Showing posts with label 11. Show all posts
Showing posts with label 11. Show all posts

Tuesday, 10 March 2020

Chapter 11 // Exercise 16 - Principles & Practice Using C++

In this exercise I am using Visual Studio Community 2017 and the header file "std_lib_facilities.h" which can be found here:

http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h

Chapter 11 // Exercise 16

Write a program to read a file of whitespace-separated numbers and output
them in order (lowest value first), one value per line. Write a value only
once, and if it occurs more than once write the count of it's occurrences on
it's line. For example, 7 5 5 7 3 117 5 should give
3
5 3
7 2
117
This one took me a stupid amount of time. It could've been done quite quickly with some brute force and a lot of if statements but I knew there had to be a better way (that didn't involve using maps). I also didn't want to rely on output trickery to get the data and eventually settled on a custom struct that holds a number and how many times it appears. There is a function that sorts the vector, then removes an extra values whilst increasing the count of the number.

Monday, 9 March 2020

Chapter 11 // Exercise 15 - Principles & Practice Using C++

In this exercise I am using Visual Studio Community 2017 and the header file "std_lib_facilities.h" which can be found here:

http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h

Chapter 11 // Exercise 15

 Write a program that reads a file of whitespace-separated numbers and outputs
 a file of numbers using scientific format and precision 8 in four fields of 
 20 characters per line.
.

Sunday, 8 March 2020

Chapter 11 // Exercise 14 - Principles & Practice Using C++

In this exercise I am using Visual Studio Community 2017 and the header file "std_lib_facilities.h" which can be found here:

http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h

Chapter 11 // Exercise 14

 Write a program that reads a text file and writes out how many characters of each character classification are in the file.
.

Saturday, 7 March 2020

Chapter 11 // Exercise 13 - Principles & Practice Using C++

In this exercise I am using Visual Studio Community 2017 and the header file "std_lib_facilities.h" which can be found here:

http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h

Chapter 11 // Exercise 13

Reverse the order of words (defined as whitespace-separated strings) in a file. For example, Norwegian Blue Parrot becomes parrot Blue Norwegian. You are allowed to assume that all the strings from the file will fit into memory at once.
.

Friday, 6 March 2020

Chapter 11 // Exercise 12 - Principles & Practice Using C++

In this exercise I am using Visual Studio Community 2017 and the header file "std_lib_facilities.h" which can be found here:

http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h

Chapter 11 // Exercise 12

Reverse the order of characters in a text file. For example, asdfghjkl becomes
 lkjhgfdsa. Warning: There is no really good, portable, and efficient way of
 reading a file backward.
This one was pretty simple. I did originally do it with just an fstream as we're reading and writing the same file however, it appears an fstream, by default, appends new text rather than overwrite. I tried using ios::trunc to make it overwrite but it didn't work so I just switched to if/ostream.

Thursday, 5 March 2020

Chapter 11 // Exercise 11 - Principles & Practice Using C++

In this exercise I am using Visual Studio Community 2017 and the header file "std_lib_facilities.h" which can be found here:

http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h

Chapter 11 // Exercise 11

Write a function vector<string> split(const string& s, const string& w) that
returns a vector of whitespace-separated substrings from the argument s, where
whitespace is defined as "ordinary whitespace" plus the characters in w.
Again, on this one I'm assuming that he means add a break at whitespace and the string w? Eg if w is "break" and the line "I like to eat donuts on my break everyday" is entered; the following would be entered in the vector:
[0] I
[1]
[2] like
[3]
[4] to
[5]
[6] eat
[7]
[8] donuts
[9]
[10] on
[11]
[12] my
[13]
[14] everyday




Wednesday, 4 March 2020

Chapter 11 // Exercise 10 - Principles & Practice Using C++

In this exercise I am using Visual Studio Community 2017 and the header file "std_lib_facilities.h" which can be found here:

http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h

Chapter 11 // Exercise 10

 Write a function vector<string> split(const string& s) that returns a vector of whitespace-separated substrings from the argument s.
On this one I'm assuming he just meant "read in the entire thing push back single words and spaces". So that's what I did. It's a vector that goes "word", " ", "word", " ", etc.

Tuesday, 3 March 2020

Chapter 11 // Exercise 9 - Principles & Practice Using C++

In this exercise I am using Visual Studio Community 2017 and the header file "std_lib_facilities.h" which can be found here:

http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h

Chapter 11 // Exercise 9

Split the binary I/O program from section 11.3.2 into two; one program that
converts an ordinary text file into binary and one program that reads binary
and converts it to text. Test these programs by comparing a text file with
what you get by converting it to binary and back.
When just running the code given in the book on a random file, I noticed that when reading it out to a new file, it cut off the last two characters. They weren't special ones just 'e' and '.'...After staring at the code and the book for a good 15 minutes I realised that I truly am an idiot because the program in the book is designed to read in integers...

After changing int to char it worked as expected, however I'm now wondering what was so different about 'e' compared to the other letters.




Monday, 2 March 2020

Chapter 11 // Exercise 8 - Principles & Practice Using C++

In this exercise I am using Visual Studio Community 2017 and the header file "std_lib_facilities.h" which can be found here:

http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h

Chapter 11 // Exercise 8

         Use the program from the previous exercise to make a dictionary (as an alternative to the approach in section 11.7). Run the result on a multi-page text file, look at the result, and see if you can improve the program to make a better dictionary.
Make a dictionary? Is this guy having a giraffe? Also what is a multi-page text file? A txt document doesn't have pages. Also, having read over section 17 again I think he just wants us to run the previous program on a text file and remove all punctuation and contractions, whilst displaying each word on a new line. I can do that easy however that's not a dictionary. A dictionary has definitions of what each word means.

Also, most dictionaries allow some forms of contractions; but they do tend to differ on what is allowed depending on the country. The same applies to hyphenated words as some are common enough to be included in dictionaries. So I decided to allow contractions, hyphens and remove any other form of punctuation and numbers and then output each word on a separate line after being sorted. I started getting a bit pedantic about things as well like removing duplicated words.

Sunday, 1 March 2020

Chapter 11 // Exercise 7 - Principles & Practice Using C++

In this exercise I am using Visual Studio Community 2017 and the header file "std_lib_facilities.h" which can be found here:

http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h

Chapter 11 // Exercise 7

Modify the program from the previous exercise so that it replaces don't with
do not, can't with cannot, etc.; leaves hyphens within words intact (so that
we get " do not use the as-if rule "); and converts all characters to lower 
case.
Eurgh. He just had to say 'etc'  on the contraction words. There are 17 common words that use the 't contraction and only one of them doesn't have a space (cannot). I'm super lazy, so there is no way I'm checking to see if the second to last character is a single quote and then checking if that word is equal to 1 of 17 contractions. 

I ended up putting the contractions and their counterparts into a text file, then reading them into vectors at the start of the program. When a user comes along and then inputs 'don't' it will then just compare the string against the vector of contractions, if there is a match, the index will be used to return the matching 'normal phrase'. You can find the contractions.txt in the main section of Chapter 11 on the git.

That wasn't even the hardest part. I spent the longest ensuring that hyphens were only removed when not wrapped in quotes and were by themselves.

Saturday, 29 February 2020

Chapter 11 // Exercise 6 - Principles & Practice Using C++

In this exercise I am using Visual Studio Community 2017 and the header file "std_lib_facilities.h" which can be found here:

http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h

Chapter 11 // Exercise 6

 Write a program that replaces punctuation with whitespace. Consider .(dot),
 ; (semicolon), ,(comma), ? (question mark), - (dash), ' (single quote)
 punctuation characters. Don't modify characters within a pair of double
 quotes ("). For example "-don't use the as-if rule." becomes " don t use the
 as if rule ".
I'm sure there's a more elegant way to do this than if's and counting quotes but it isn't too ugly to I'll allow it.

Friday, 28 February 2020

Chapter 11 // Exercise 5 - Principles & Practice Using C++

In this exercise I am using Visual Studio Community 2017 and the header file "std_lib_facilities.h" which can be found here:

http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h

Chapter 11 // Exercise 5

 Write a program that reads strings and for each string outputs the character
 classification of each character, as defined by the character classification
functions presented in section 11.6. Note that a character can have several
 classifications (e.g, x is both a letter and an alphanumeric).


This was suspiciously easy and it makes me wonder if I did it correctly.

Thursday, 27 February 2020

Chapter 11 // Exercise 4 - Principles & Practice Using C++

In this exercise I am using Visual Studio Community 2017 and the header file "std_lib_facilities.h" which can be found here:

http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h

Chapter 11 // Exercise 4

Write a program called multi_input.cpp that prompts the user to enter several
integers in any combination of octal, decimal, or hexadecimal, using the 0
and 0x base suffixes; interpret the numbers correctly; and converts them to
decimal form. Then your program should output the values in properly spaced
columns like this:
0x43 hexadecimal converts to 67 decimal
0123 octal converts to 83 decimal
  65         decimal converts to 65 decimal


The useful item I learnt from this exercise is that stoi() takes in 3 parameters, the first is the string, the second is a size_t pointer (used for finding the next value) and last is a number which indicates the base. I noticed that when you use stoi() on an int, the base is default set to 10 (deicmal), therefore it cut off the 0 and 0x, even if the cout stream was set to oct and hex. To convert the number correctly, set the base to 0 as this will check for all 3 bases.

If you just want to check for oct, set the base to 8 and hex to 16. Other than that, the hardest part was getting it to output with all the fields lined up. I really hate that setw().

Wednesday, 26 February 2020

Chapter 11 // Exercise 3 - Principles & Practice Using C++

In this exercise I am using Visual Studio Community 2017 and the header file "std_lib_facilities.h" which can be found here:

http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h

Chapter 11 // Exercise 3

Write a program that removes all vowels from a file ("disemvowels"). For example, Once upon a time! becomes nc pn tm!. Surprisingly often, the result is still readable; try it on your friends. 


Once again the find functions on a string come to the rescue. I think I'm becoming a bit addicted to using find_first_not_of and find_first_of; they're just so god damn handy. I know these functions haven't been introduced in the book yet but this isn't prior knowledge I already had. I only learnt about them when googling how to solve problems like "find a character in a string" so I don't think it's cheating. Also rdbuf() and stringstreams are definitely ones I'll have to remember.

Tuesday, 25 February 2020

Chapter 11 // Exercise 2 - Principles & Practice Using C++

In this exercise I am using Visual Studio Community 2017 and the header file "std_lib_facilities.h" which can be found here:

http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h

Chapter 11 // Exercise 2

Write a program that given a file name and a word outputs each line that contains that word together with the line number. Hint: getline().


.

Monday, 24 February 2020

Chapter 11 // Exercise 1 - Principles & Practice Using C++

In this exercise I am using Visual Studio Community 2017 and the header file "std_lib_facilities.h" which can be found here:

http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h

Chapter 11 // Exercise 1

Write a program that reads a text file and converts its input to all lower case, producing a new file.


.

Sunday, 23 February 2020

Chapter 11 // Drill 10 - Principles & Practice Using C++

In this exercise I am using Visual Studio Community 2017 and the header file "std_lib_facilities.h" which can be found here:

http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h

Chapter 11 // Drill 10

Make a small table including last name, first name, telephone number and email address for yourself and at least five of your friends. Experiment with different field width until you are satisfied that the table is presented well.


This drill seemed a little pointless to me seeing as how I don't see how setw() can be useful outside of the console window. And unfortunately DOS isn't all that popular anymore. You can still use it with user defined streams like ostream but whatever. Handy to know when I start making all my console window games...

Saturday, 22 February 2020

Chapter 11 // Drill 9 - Principles & Practice Using C++

In this exercise I am using Visual Studio Community 2017 and the header file "std_lib_facilities.h" which can be found here:

http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h

Chapter 11 // Drill 9

Write some code to print the number 1234567.89 three times, first using defaultfloat, then fixed, then scientific forms. Which output form presents the user with the most accurate representation? Explain why.


This exercise made me wonder why anyone would use float if they need precision from floating point numbers. Sure float is smaller than double so you would be saving bytes however you lose precision.

Wednesday, 3 August 2016

Chapter 4 // Exercise 11, 12, 13, 14, 15 - Principles & Practice Using C++

In all these exercises I am using Visual Studio Community 2015 and the header file "std_lib_facilities.h" which can be found here:


http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h


My version is spelt differently so adjust the code accordingly if copying and pasting.


Chapter 4 Exercise // 4.11

Create a program to find all the prime numbers between 1 and 100. One way to do this is to write a function that will check if a number is a prime (i.e., see if the number can be divided by a prime smaller than itself) using a vector of primes in order (so that if the vector is called primes, primes[0]==2, primes[1]==3, primes[2]==5, etc). Then write a loop that goes from 1 to 100, checks each number to see if it is a prime, and stores each prime found in a vector. Write another loop that lists the primes you found. You might check your result by comparing your vector of prime number with primes. Consider 2 the first prime.

#include "stdafx.h"
#include "std_lib_facilities_new_version.h"
using namespace std;

vector<int> user_primes; // vector to put found primes into
vector<int> primes{ 2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,}; // to compare against

bool isItPrime(int n) 
{
for (int p = 0; p < user_primes.size(); ++p)
{
if (n % user_primes[p] == 0)
return false;
}
return true;

}

int main()
{
user_primes.push_back(2);

for (int i = 3; i <= 100; ++i)
{
if (isItPrime(i))
user_primes.push_back(i);
}

for (int i = 0; i < primes.size(); ++i)
{
cout << primes[i] << '\t' << user_primes[i] << '\n';
}

keep_window_open();

return 0;
}

I spent so many hours trying to solve this one, so many hours scouring the internet but they all solved it using methods that hadn't been taught yet. I then even found Bjarne himself answer this question using methods he had fucking taught yet (talk about not even reading your own book). The way the question is written it sounds like he is implicitly asking you to check all numbers from 1 to 100 are prime by dividing them by a smaller number from within another vector called primes containing primes numbers from 1 - 100. Talk about misleading. He actually wants you to just write a function that finds a prime and then returns that number into a vector. 

So basically I had to end up using a bool function which I still don't fully understand. In chapters 1 - 4 all he has said is that a bool is true or false. I also had to start at 3 otherwise it would never work (even though he says to start at 1 in the book, his own website solves this starting at 3. I was rage quitting for hours). So it checks to see if the number is divisible by any primes already pushed back (so obviously, primes smaller than itself).

For a better understanding of bool values, look here. This is the website I use when Bjarne makes no fucking sense. The author Alex, makes things much easier to understand. 

This was a terribly written exercise.

Chapter 4 Exercise // 4.12

Modify the program described in the previous exercise to take an input value max and then find all the prime numbers from 1 to max.

#include "stdafx.h"
#include "std_lib_facilities_new_version.h"
using namespace std;

vector<int> user_primes; // vector to put found primes into
vector<int> primes{ 2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,}; // to compare against

bool isItPrime(int n)
{
for (int p = 0; p < user_primes.size(); ++p)
{
if (n % user_primes[p] == 0)
return false; // n divided
}
return true; // n couldn't be divided

}

int main()
{
user_primes.push_back(2);

cout << "Please give a maximum number the computer should stop finding primes at:\n";
int max;
cin >> max;

for (int i = 3; i <= max; ++i)
{
if (isItPrime(i))
user_primes.push_back(i);
}

for (int i = 0; i < user_primes.size(); ++i)
{
cout << '\n' << user_primes[i];
}

cout << '\n';
keep_window_open();

return 0;
}



Chapter 4 Exercise // 4.13

Create a program to find all the prime numbers between 1 and 100. there is a classic method for doing this, called the "Sieve of Eratosthenes." Write your program using this method.

At this point in my programming knowledge, I honestly don't know how to do this using only methods he has shown us so far in the book. I've looked everywhere and I just don't understand whats going on. If someone could perhaps explain it to me in dunce terms that would be greatly appreciated but until I'm a more proficient programmer the answer to this one (and below) will have to wait.

EDIT 17/09/2019 - 3 years later I have now completed exercises 13 & 14. You can find the code for them at my git repository: https://github.com/l-paz91/principles-practice/tree/master/Chapter%204

I followed the pseudocode given on Wikipedia here: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Algorithmic_complexity

This time is took me around 30 minutes to solve and I'm quite happy to see just how much my ability to read other code (pseudo or not) has progressed. It also is very possible to do this exercise using methods only shown up to chapter 4 but my problem solving skills were not as developed. I still have a long way to go but I've improved. 

Basically though, this method is quite a contrived way of doing it but I understand why he made us do it. I don't fully understand how it works, but the pseudocode is simple enough to follow to get it working.

Chapter 4 Exercise // 4.14

Modify the program described in the previous exercise to take an input value max and then find all the prime numbers from 1 to max.



Chapter 4 Exercise // 4.15

Write a program that takes an input value n and then finds the first n primes.


#include "stdafx.h"
#include "std_lib_facilities_new_version.h"
using namespace std;

vector<int> user_primes; // vector to put found primes into
vector<int> primes{ 2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,}; // to compare against

bool isItPrime(int n)
{
for (int p = 0; p < user_primes.size(); ++p)
{
if (n % user_primes[p] == 0)
return false; // n divided
}
return true; // n couldn't be divided

}

int main()
{
user_primes.push_back(2);

cout << "What number do you want to find primes from?: \n";
int countFrom;
cin >> countFrom;

double maxPrime = countFrom * 100;

for (int i = 3; i <= maxPrime; ++i)
{
if (isItPrime(i))
user_primes.push_back(i);
}

int countTo = countFrom*2;

for (int i = countFrom-1; i <= countTo-2; ++i) //this starts at n and continues n times
{
cout << '\n' << user_primes[i];
}

cout << '\n';
keep_window_open();

return 0;
}

I was a little confused on this one for a while as I thought he meant enter a number (n) and then find that many primes starting from the beginning. But then I realised that was exactly the same as 4.12, so he actually meant start at 'n' and then find the next 'n' numbers from 'n'. 

After some messing around it wasn't too hard, the function to find primes doesn't actually need to be tinkered all that much, you just need to make sure that it finds enough primes to print out.