Showing posts with label chapter 10 exercise. Show all posts
Showing posts with label chapter 10 exercise. Show all posts

Thursday, 20 February 2020

Chapter 10 // 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 10 // Exercise 11

 Write a program that produces the sum of all the whitespace separated integers in a text file. For example, bears: 17 elephants 9 end should output 26.


I was going to leave this last exercise for the night but seeing as how it was the last one of the chapter I decided to just get it done and ended up doing it in 5 minutes. This was very easy if you just read everything into a vector, sort it and then convert the string to an int using stoi(). If it's not an int then we've run out of numbers and the program breaks out of the for loop and prints the sum.

It's funny, I remember almost 3 years ago now when I was starting the second semester of my first year at uni and in the programming exam we had coming up, we had to read in from text files and output to them. I froze and started freaking out because I had only done up to around chapter 5 by then. I thought the task was impossible and I'd never be able to do it; that I wasn't good enough or smart enough to be able to remember all these coding conventions. Progress takes time and patience; not all of us are born as geniuses. Just keep working at it and don't give up.

And with that I have FINALLY finished Chapter 10. I originally started this chapter in June 2017 and it's crazy to think I'm just now moving onto a fresh chapter. I remember giving this a read through a few years ago but it's all new content from here on out. I'm excited to start the graphics chapters though and he starts to introduce templates and inheritance. I hate these constructs but I work with Unreal and UE4 loves object oriented programming...and I mean, it really fucking loves it. Personally, I detest OOP but that's what the job requires so I need to understand it better so I can undo it and replace it with faster data orientated code.

Wednesday, 19 February 2020

Chapter 10 // 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 10 // Exercise 10

         Add a command from x to the calculator from Chapter 7 that makes it take input from a file x. Add a command to y to the calculator that makes it write its output (both standard output and error output) to file y. Write a collection of test cases based on ideas from section 7.3 and use that to test the calculator. Discuss how you would use these commands for testing.


I cheated slightly on this one and modified the calculator to only take input from a file and then output to a file; if there is an error it will ask you to press ';' to continue. This was pretty simple as you can continue to use cin.get() and cin.unget() on ifstreams. If you run the txt file I provided, you'll notice that it just keeps going forever because it gets stuck in a loop on 'a';. This isn't broken, it expects you to input a correct definition however, 'a' keeps getting putback and then being re-read. If I wasn't feeling lazy I would stick a command in that would switch to regular calculator code and allow you to start inputting your own stuff.

Tuesday, 18 February 2020

Chapter 10 // 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 10 // Exercise 8

Write a program that takes two files containing sorted whitespace separated words
and merges them, preserving order.


At first I completely missed the word "sorted" and thought this was the exact same exercise as the on before. After that I changed the program slightly to output every word into a vector and then sorted it; outputting it back into another file. Easy peasy.

Monday, 17 February 2020

Chapter 10 // 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 10 // Exercise 8

Write a program that accepts two file names and produces a new file that is the contents of the first file followed by the contents of the second; that is, the program concatenates the two files.


Ah, a nice and easy one. I also really love using substr(), it has so many useful applications, like checking to see if a certain part of a string matches another string. I also found that you can easily copy files into another by using the .rdbuf() function. It contains a pointer to the contents of the file for easy access.

Saturday, 15 February 2020

Chapter 10 // 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 10 // Exercise 7

Make a version of the calculator from Chapter 7 that accepts Roman Numerals rather than the usual Arabic ones, for example, XXI + CIV == CXXV.


When I first tried this I realised we needed a way to convert Roman Numeral to Ints so went back to the previous exercise and added a new function that does that. Then it became as simple as adding the class to the file and checking input for roman numerals. Once they are all added, they are then converted to an int, the calculations are done and then the resulting int is converted back to a Roman Numeral.

Saturday, 18 January 2020

Chapter 10 // 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 10 // Exercise 6

Define a Roman_int class for holding Roman numerals (as ints) with a << and >>. Provide Roman_int with an as_int() member that returns the int value, so that if r is a Roman_int , we can write cout << "Roman" << r << " equals " << r.as_int() << '\n';


This exercise was quite confusing. He mentions to store the values in Roman_int as ints but then use a member function called as_int() to return the integer value of the int??? Surely it would make more sense to input the values as chars like C or M and then use the as_int() function to output 100 or 1000.

Eventually I decided upon a class that stores an int but when using cout<< it returns the roman numeral comversion. This turned out to be harder than I thought. The main problem comes from the adding/subtracting depending what side of the main number you're on. My first few attempts ended up with a lot of ifs and switches but if there's one thing I've learnt in my job as an engine programmer, it's to avoid branching as much as possible. So I scoured the internet in search of a more optimal solution.


This smartly uses modulo and divide to correctly determine where the number is in the number table. For example if you input 618, the divide will be 0 for the first 2 loops (and therefore there will be nothing to print). However 618 / 500 is 1, therefore the corresponding symbol will be printed that matches the index of the table. This is what I was trying to attempt but I kept messing up the division and remainders.

.....*sometime later*

When attempting the next exercise I quickly realised that the class needed a way to convert roman numerals to ints. I thought that this would be pretty simple however there is the rule that if the following number is greater than the previous then you subtract. Numerous examples on the internet were either in Python (eurgh) or contained a great deal of branching. I'm quite proud of the small function that I came up with.

Wednesday, 15 January 2020

Chapter 10 // 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 10 // Exercise 5

Write the function print_year() mentioned in section 10.11.2.


Oh I detested this exercise. It wasn't necessarily hard; the format just made it very confusing. Also, having a vector, in a vector, in a vector almost blew my brains out. I honestly think he made this more complicated than it needed to be just to make you think. The problem is though that you will probably see code like this "in the wild". 

In the first chapters of this book, Bjarne mentions the importance of avoiding magic numbers. However, if you check out PrimitiveComponent.cpp in Unreal Engine 4.10, you'll find this magical snippet:

 int32 UPrimitiveComponent::CurrentTag = 2147483647 / 4;

On a code review a senior thought I had done this; I didn't, it was already there. I asked my manager why they would do this and he asked me why that number was special; I had no clue. He then informed me it was the largest number you can fit in an int32. However, he was confused as to why they didn't just use MAX_INT or const instead of some ridiculous magic number.

Tuesday, 14 January 2020

Chapter 10 // 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 10 // Exercise 4

Modify the store_temps.cpp program from exercise 2 to include a temperature suffix c for Celsius or f for Fahrenheit temperatures. Then modify the temp_stats.cpp program to test each temperature, converting the Celsius reasdinfs to Fahrenheit before putting them in the vector.


It was in this exercise that I realised I had goofed the median bit and accidentally left in out of bounds errors (I also forgot to add a check for if the vector contained 1 value). I decided to add some more error checking as well as whilst re-doing the book I became quite lax and focused more on getting the exercises done than adding code that was actually robust.

I also prefer my new "isNumber()" function over the previous one that I used to use all the time. I think allowing cin to fail and then clearing it is a lot more of a hassle than just reading into a string. Cin will never go bad and you can just use the extremely handy "find_first_not_of()" function found in the std library. I love that function. This also allows for some easy parsing to extract numbers and characters.

Another thing I learnt whilst doing this exercise is that when using while(!file.eof) and ctrl+z, the last line will actually be read twice before the eof is read. This is not great if you are pushing things back into vectors. I kept getting an extra value and wondered where it was coming from. Instead, I'll remember to always start the while loop with while(cin >> value) as the eof will be read immediately. 

Monday, 13 January 2020

Chapter 10 // 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 10 // Exercise 3

Write a program that reads the data from raw_temps.txt created in exercise 2 into a vector and then calculates the mean and median temperatures in your data set. Call this program temp_stats.cpp

GitHub: https://github.com/l-paz91/principles-practice/blob/master/Chapter%2010/Exercise%203

I initially had the median messed up when I first uploaded it (as you can see in the file history...I should've done GitHub sooner). I always forget how to code the median.

These programs may seem a little confusing as I bundled them all into one to read/write/create raw_temps.txt based on what you want to do.

This though is officially the first new exercise I've done since September  2019 (and restarting the entire book). It was actually a little scary when I realised that there were no more exercises for me to compare against anymore, everything from here on out is new territory. I will say though that it's been eye opening. I remember spending 6+ hours on one exercise from Chapter 4 when I first started this book back in 2016. Now I can do entire chapters in 1 day.

Friday, 6 September 2019

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

Chapter 10 // Exercise 2

Write a program that creates a file of data in the form of the temperature Reading type defined in section 10.5. For testing, fill the file with at least 50 "temperature readings". Call this program store_temps.cpp and the file it creates raw_temps.txt.

Main.cpp

//--------------------------------------------//
//main.cpp
//--------------------------------------------//
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <conio.h>
using namespace std;
struct Reading
{
 int hour;
 double temperature;
};
int main()
{
 vector<Reading> temps;
 int hour;
 double temperature;
 cout << "Please enter temperatures in format HOUR TEMP. Example: 1 32.65    Press Ctrl+Z to stop.\n";
 while (cin >> hour >> temperature)
 {
  if (hour < 0 || hour > 23)
   cout << "Error. Hour out of range.\n" << endl;
  temps.push_back(Reading{ hour, temperature });
 }
 ofstream readOut{ "raw_temps.txt" };
 for (uint32_t i = 0; i < temps.size(); ++i)
  readOut << temps[i].hour << " " << temps[i].temperature << "\n";
 cout << "\nPress any key..."; _getch();
 return 0;
}




EDIT: 13/01/2020
New version on GitHub. This one has more error checking and actually parses the weird format instead of changing it. https://github.com/l-paz91/principles-practice/blob/master/Chapter%2010/Exercise%202

Thursday, 5 September 2019

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

Chapter 10 // Exercise 1

Write a program that produces the sum of all the numbers in a file of whitespace-separated integers.

Main.cpp
//--------------------------------------------//
//main.cpp
//--------------------------------------------//
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <conio.h>
using namespace std;
//create a file with white-space separated integers
void createFile()
{
 ofstream readOut{ "integers.txt" };
 if (!readOut)
  cout << "Error opening file" << endl;
 string integers;
 cout << "Enter a list of whitespace separated integers: (press enter when done)\n>>";
 getline(cin, integers);
 readOut << integers;
}
//read in from a file
vector<int> readInIntegersFromFile()
{
 vector<int> integers;
 ifstream readIn{ "integers.txt" };
 if(!readIn)
  cout << "Error opening file" << endl;
 int temp;
 while (!readIn.eof())
 {
  readIn >> temp;
  integers.push_back(temp);
 }
 return integers;
}
//add numbers together
int sumOfIntegers(vector<int>& v)
{
 int sum = 0;
 for (uint32_t i = 0; i < v.size(); ++i)
  sum += v[i];
 return sum;
}
int main()
{
 createFile();
 vector<int> integers = readInIntegersFromFile();
 int sum = sumOfIntegers(integers);
 cout << "Sum: " << sum << endl;
 cout << "\nPress any key..."; _getch();
 return 0;
}




EDIT: 13/01/2020