Bay 12 Games Forum

Please login or register.

Login with username, password and session length
Advanced search  
Pages: 1 [2]

Author Topic: Pathetic Attempts at Programming(A month of learning self-challenge)  (Read 2753 times)

alexandertnt

  • Bay Watcher
  • (map 'list (lambda (post) (+ post awesome)) posts)
    • View Profile
Re: Pathetic Attempts at Programming(A month of learning self-challenge)
« Reply #15 on: March 05, 2015, 08:12:19 am »

So I decided to start over. Scrap everything, because apparently I've done it all wrong according to the above 2 posters. I'm going to be working out of a book, called C++ Primer 5th Edition, I'm still going to treat this like a job, but it will be more lesson oriented. I'll be honest, being told, a lot of the stuff you guys told me, discouraged me for a few days. Contemplated giving it up entirely, contemplated a lot of things. But I'm not going to let depression win. As such, I've started going through the C++ Primer 5th Edition, which covers things like C++11, and is a bit slower than Accelerated C++ is. It also clocks in at a massive 1000+ pages. I'm skipping posting a few things, because well, some of the things are boring for you guys. But I will do them, however updates will be a bit slower.

I'm sorry if what I said sounded harsh, I did not mean it to come off as that. Please, keep in mind that the only way you will learn is by being given an opportunity to learn from your mistakes. As a new person to anything, you will make mistakes, this is a normal part of the learning process. It's clear to me you are willing to listen to people's advice and criticism and learn from it, you can't ask much more than that from anyone. Your doing fine, keep it up!


Quote
Does that mean, when you cout something, and you are chaining things together with << operators, each link in the chain, is basically including all of the previous ones because the operator is returning everything to the left of it? If so, would it be smarter/more efficient for the compiler to write it out as

using std::cout << calls the operator<< function.

You can also write it as

Code: [Select]
std::cout.operator<<("Hello").operator<<("world");

This is my hunch, but....

The compiler is pretty good at optimising incredibly trivial things like this. If improving performance was as simple as seperating chained << operator calls to cout (an incredibly common pattern), it would probably do so. I can not verify this, however.

Quote
This is just a curiosity. Not something I'm planning on incorporating, literally just a random fit of interest in how it works, but a lack of ability to test it. Though, later on the same page it mentions something about how endl flushes the buffer, and that it's best to flush the buffer, so that if a program crashes it doesn't leave bits hanging around in memory. Hrm, is \n equivalent to an endl, I doubt it. This is rather interesting. A little googling suggested that the third one is more efficient because of how long it takes flush the buffer. So in cases of messing around with pure text, and needing highly performent code, you'd not use std::endl. Because it is the largest reason why C++ IO is generally slower than that of C.

In most cases, stdout in C is also buffered.

Outputting a '\n' character will not necessarily flush the output. If you use \n instead of std::endl, you run the risk of not flushing the output if your program crashes.

Quote
The code in 1.6 is fine barring the semicolon placement, removing the semicolons makes it print correctly. Alternatively and this is possibly the answer they are looking for, adding std::cout in front of each line would make it work. Here's the code in question they wanted you to state if it would work, what it was supposed to do and how to fix it if it didn't.
Code: [Select]
std::cout<< "The sum of "  << v1;
<< " and " << v2;
<< " is " << v1 + v2 << std::endl;

I believe adding std::cout was the answer they were looking for. You can remove the semicolons to get

Code: [Select]
std::cout<< "The sum of "  << v1
<< " and " << v2
<< " is " << v1 + v2 << std::endl;

Which is equivalent to

Code: [Select]
std::cout<< "The sum of "  << v1 << " and " << v2 << " is " << v1 + v2 << std::endl;

As whitespace is ignored. Just removing the semicolons is not how I think they expected you to go about it, but it is still perfectly valid all the same.

Quote
1.7 is just inputting and viewing an error for nested comments, that error looked like this,
Code: [Select]
1>d:\users\tyler\documents\visual studio 2013\projects\c++primer5th\chapter1\comments.cpp(1): warning C4138: '*/' found outside of comment
1>d:\users\tyler\documents\visual studio 2013\projects\c++primer5th\chapter1\comments.cpp(1): error C2059: syntax error : '/'

Yes, nested block comments do not work, unfortunately. Only a few languages I can think of support such a feature.

Code: [Select]
/*

  /*

    hello

  */

*/

The compiler will see the first /* and start a comment. It will ignore the next /* as it is inside a comment. the first */ terminates the comment, leaving a stray */ to cause a syntax error.

Quote
1.8 is a bit more interesting,
Code: [Select]
Exercise 1.8: Indicate which, if any, of the following output statements are
legal:

std::cout << "/*";
std::cout << "*/";
std::cout << /* "*/" */;
std::cout << /*  "*/" /* "/*"  */;
After you’ve predicted what will happen, test your answers by compiling a
program with each of these statements. Correct any errors you encounter.
I think the first and second ones are the only ones that work. The first one is the definite might, which the second will definitely work. 

The fourth ones possibly working. Let's actually figure that out, following along, open comment, close comment, within quotation marks,  one quotation mark visible to the program, open comment, invisible because it is within quotations, followed by an open comment within quotation. Will work I think, because it closes the quotes then begins the next set of comments.  But very tricky and maybe wrong.

The third definitely won't work, because it's calling cout without closing the output's quotes.

Time to check if those actually were right answers.

First and second worked, third tossed these errors,
Code: [Select]
1>d:\users\tyler\documents\visual studio 2013\projects\c++primer5th\chapter1\comments.cpp(10): error C2001: newline in constant
1>d:\users\tyler\documents\visual studio 2013\projects\c++primer5th\chapter1\comments.cpp(12): error C2143: syntax error : missing ';' before 'return'

The fourth amazingly works, I was really guessing hard on that one. But I guess I should have guessed easier because of how the first one passed. On to chapter 1.4.

The first ", does not indicate the start of a string as it is inside a quote block, and as such the first */ (which not in a string) terminate the comment block.

So

Code: [Select]
std::cout << /*  "*/" /* "/*"  */;

turns into

Code: [Select]
std::cout << " /* "/*"  */;

The next " starts a string, it is not inside a quote block. The next /* is part of a string, and as such does not start a quote block. The second " ends a string. Now the second /* is not in a string and starts a quote block. The third " does not start a string as it is in a quote block. The last */ ends the quote block. It then becomes

Code: [Select]
std::cout << " /* ";
Logged
This is when I imagine the hilarity which may happen if certain things are glichy. Such as targeting your own body parts to eat.

You eat your own head
YOU HAVE BEEN STRUCK DOWN!

Dakorma

  • Bay Watcher
    • View Profile
Re: Pathetic Attempts at Programming(A month of learning self-challenge)
« Reply #16 on: March 05, 2015, 05:34:05 pm »

Code: [Select]
#include <iostream>

void print50To100() {
int value = 50;
int moving = 50;
while (moving <= 100){
value += moving;
++moving;
}
std::cout << "The sum of 50 to 100 is: " << value << '\n';
}

void printDownFrom10() {
int number = 10;
while (number > 0) {
std::cout << number << ' ';
--number;
}
}

void printUserSpecifiedRange() {
int grab1 = 0;
int grab2 = 0;
std::cout << std::endl;
std::cout << "Enter 2 numbers seperated by a space." << '\n';
std::cin >> grab1;
std::cin >> grab2;
while (grab1 <= grab2) {
std::cout << grab1 << ' ';
++grab1;
}
}


int main(){
print50To100();
printDownFrom10();
printUserSpecifiedRange();
system("pause");

return 0;
}

So following along in this book, I got to while loops, and loops in general, Here's the exercises that that code is responding to,
Code: [Select]
ExercisesSection 1.4.1
Exercise1.9: Write a program that uses a while to sum the numbers from
50 to 100.

Exercise 1.10: In addition to the ++operator that adds 1 to its operand,
there is a decrement operator (--) that subtracts 1. Use the decrement
operator to write a while that prints the numbers from ten down to zero.

Exercise 1.11: Write a program that prompts the user for two integers.
Print each number in the range specified by those two integers.

The output of this looks something like this,
Spoiler (click to show/hide)

No real questions about loops, they are kinda easily understandable, especially while loops. I did also bloat the line count on the second EDIT:third one to be sure it worked as I intended it, and that I didn't have any lines merged together. I've decided to incorporate the \n within single quotes, because well, it looks cleaner to me. Afterall if you are defining a character, like a linebreak technically is, '\n' is the most correct way to do it.
« Last Edit: March 05, 2015, 05:36:59 pm by Dakorma »
Logged

Dakorma

  • Bay Watcher
    • View Profile
Re: Pathetic Attempts at Programming(A month of learning self-challenge)
« Reply #17 on: March 07, 2015, 03:20:03 am »

Replying to do the for loop exercises and some more, the first one was just a demonstration of knowledge, and math skills. They wanted you to look at a loop that summed all values from -100 to 100, and tell what it did, and what the result of sum would be, in this case, because all those numbers cancel out. It is 0, because sum is initially declared as 0.

Then they wanted me to rewrite, the while loops as for loops. Made them a bit shorter when I did, because all of the while loops can be reduced to the same pattern that for was invented to deal with easier anyway.

Code: [Select]
#include <iostream>

void print50To100() {
int value = 50;
for (int i = 50; i <= 100; ++i){
value += i;
}
std::cout << "The sum of 50 to 100 is: " << value << '\n';
}

void printDownFrom10() {
for (int i = 10; i > 0; --i) {
std::cout << i << ' ';
}
}

void printUserSpecifiedRange() {
int grab1 = 0;
int grab2 = 0;
std::cout << std::endl;
std::cout << "Enter 2 numbers seperated by a space." << '\n';
std::cin >> grab1;
std::cin >> grab2;
for (int i = grab1; i <= grab2; ++i) {
std::cout << i << ' ';
}
}


int main(){
print50To100();
printDownFrom10();
printUserSpecifiedRange();
system("pause");

return 0;
}

Done and done.

Then it wanted you to compare and contrast for and while, and provide the advantages and disadvantages of using either. And I will say, I find for loops easier to deal with, because the logic of the loop in so far as how much to repeat itself is contained in the initial loop declaration, where as with the while, some of the logic is normally within the loop.

Then it wanted me to make a bunch of errors again, generally common ones to deal with cout. But I'm skipping that, because I've made those mistakes before and don't want to deliberately make them again. Namely missing semicolon, missing quotes around a string literal, and missing semi-colon on a return statement.

I chose to modify the next bits exercises a bit, to have a little fun, and because I don't want to have the user input ctrl-z to end input, but rather I wanted them to hit enter to end the input and moreover I know how to do that. So blagh. And it doesn't specify that I have to use the while(std::cin >> input1) structure. So I'll be using getline and stringstream instead. So after trying that, and failing, I decided to just say fuck it, and make it with just the cin. I wanted to try and use stringstreams because I could then not worry about a wrong input(IE them inputting a non-integer value) fucking everything up. But meh, that leads to you not having an easy way to terminate the loop. And every way I tried to end it when a condition is met, either added a restriction on and/or an amount of numbers that had to be met, or was buggy, in the infinite loop sort of way, or was suboptimal compared to just using cin, because it suffered the same issues and just added 6 extra lines of code for type conversions through sstreams. I have learned not to be Fancy just for the sake of sounding like a pop star.

Quote
Exercise 1.16: Write your own version of a program that prints the sum of
a set of integers read from cin.
Code: [Select]
#include <iostream>

int main() {

int inputInt = 0;
std::cout << "Enter numbers seperated by spaces, and stop by entering a non-integer value";
int sum = 0;

while (std::cin >> inputInt){
sum += inputInt;
inputInt = 0;
std::cout << "Total so far" << sum << '\n';
}


system("pause");

return 0;


}


Anyway, I went to sleep for a little bit after doing that, waking up 2 hours later was unexpected, and as I have an appointment unwanted, I'm gonna exhaust my brain with some Pathetic Attempts at Programming.
 

As far as the next chapter and set of exercises which are designed to introduce the if statement, another odd departure from most books on programming, which introduce the if statement well before they attempt to teach you looping.

 
Quote
Exercises Section 1.4.4
Exercise 1.17: What happens in the program presented in this section if the
input values are all equal? What if there are no duplicated values?
I'm assuming that it'll work fine, with every value returning 1 for no dupes and as many as you enter if you enter all equal input values, but the next question has you test it. So I imagine my theories will be tested there.
Exercise 1.18: Compile and run the program from this section giving it only
equal values as input. Run it again giving it values in which no number is
repeated.
Code: [Select]
#include<iostream>

int main()
{
// currVal is the number we're counting; we'll read new values into val
int currVal = 0, val = 0;
// read first number and ensure that we have data to process
if (std::cin >> currVal) {
int cnt = 1;  // store the count for the current value we're processing
while (std::cin >> val) { // read the remaining numbers
if (val == currVal)  // if the values are the same
++cnt;  // add 1 to cnt
else { // otherwise, print the count for the previous value
std::cout << currVal << " occurs "
<< cnt << " times" << std::endl;
currVal = val;  // remember the new value
cnt = 1;  // reset the counter
}
}  // while loop ends here
// remember to print the count for the last value in the file
std::cout << currVal << " occurs "
<< cnt << " times" << std::endl;
} // outermost if statement ends here
system("pause");
return 0;
}
That was odd, it worked completely different than expected, and I think the code was a little broken. Because it wouldn't cancel the loop, and when I closed it, caused the debugger to spit a kernel32 error at me, that I forgot to screenshot. Granted that coulda been due to it not freeing the ram as it closed because I force closed it. I ran it again after that, and it worked if I canceled out of the loop by giving it improper input. Like a string rather than an int. After running it again, for both it kinda behaved as expected but the first one didn't work as completely expected, it didn't list it's value until I canceled out of the loop. And the second didn't list the last value until the very end. Ie both didn't list their values until after the loop was canceled, which I suppose could be expected.
Exercise 1.19: Revise the program you wrote for the exercises in § 1.4.1(p.
13) that printed a range of numbers so that it handles input in which the first
number is smaller than the second, I think they are talking about the counting down one, this is solved easily by checking if the first is less than the second, then placing the variables depending on the results.

Think I'm gonna work on my own for a bit tomorrow today was a break day. I may or may not post the results. Also I kinda accidentally tried Smite, which is like video game heroin for me.
Logged

Dakorma

  • Bay Watcher
    • View Profile
Re: Pathetic Attempts at Programming(A month of learning self-challenge)
« Reply #18 on: March 10, 2015, 05:34:14 am »

So Smite is like heroin even though I keep losing, I keep playing.
Code: [Select]
#include <iostream>
#include <string>
#include <sstream>
#include <numeric>
#include <algorithm>

void loopDownAndUp(int rangeStart, int rangeEnd) {
  int first = 0;
  int last  = 0;
  int spc = 9;
  if(rangeStart < rangeEnd){
    first = rangeEnd;
    last = rangeStart;
  }else{
    first = rangeStart;
    last = rangeEnd;
  }
  for(int i = 0; i <= 1; ++i){
    if (i == 0) {
      for(int a = first; a > last; --a, --spc) {
        std::cout << a << ' ';
        if(spc == 0) {std::cout << '\n'; spc = 10;}
      }
    }else if(i==1){
      for(int a = last; a < first; ++a, --spc) {
        std::cout << a << ' ';
        if(spc == 0) {std::cout << '\n'; spc = 10;}
      }
    }
  }
}

void helloWeirdness() {


}

void fizzbuzz(int range) {
  for (int i = 0; i <= range; ++i) {
    if (i % 15 == 0) std::cout << "fizzbuzz" << '\n';
    else if (i % 5 == 0) std::cout << "buzz" << '\n';
    else if (i % 3 == 0) std::cout << "fizz" << '\n';
    else{std::cout << i << '\n';}
  }
}

//
// void fizzbuzzCounter(int range) {
//   int A = 3;
//   int B = 5;
//   int C = 15;
//
//   for(int i = 1; i <= range; ++i) {
//     if(A > 0){--A;}
//     else{std::cout << " fizz "; A = 3;}
//     if(B > 0){--B;}
//     else{std::cout << " buzz "; B = 5;}
//     if(C > 0){--C;}
//     else{std::cout << " fizzbuzz "; C = 15;}
//     if(A > 0 && C > 0 && B > 0) std::cout << ' ' << i << ' ';
//   }
// }
//
void outOfNumber(int range) {
  std::ostringstream intStream;
  int modifiedValue = range;
  int sum = 0;
  int iter = 0;
  std::string intString;

for(int i = 10; i >= 0; --i){
      intStream << modifiedValue;
      intString = intStream.str();
      std::for_each(intString.begin(), intString.end(), [] (char c) { std::cout << c << std::endl;});

      sum = std::accumulate(intString.begin(), intString.end(), 0) -
                           (intString.size() * int('0'));
      std::cout << "Initial sum is " << sum << std::endl;
      iter = sum;
      if(iter >= 10) {

        intStream.str("");
        intStream.clear();
        intStream << iter;
        intString = intStream.str();

        std::for_each(intString.begin(), intString.end(), [] (char c) { std::cout << c << std::endl;});

        sum = std::accumulate(intString.begin(), intString.end(), 0) -
                             (intString.size() * int('0'));
        std::cout << "Second Sum is " << sum << "\n\n";

      }
    iter = sum;
    if(iter >= 10) {

      intStream.str("");
      intStream.clear();
      intStream << iter;
      intString = intStream.str();

      std::for_each(intString.begin(), intString.end(), [] (char c) { std::cout << c << std::endl;});

      sum = std::accumulate(intString.begin(), intString.end(), 0) -
                           (intString.size() * int('0'));
      std::cout << "Third Sum is " << sum << "\n\n";
    }
    intStream.str("");
    intStream.clear();
    int result = 0;
    result = modifiedValue / sum;
    std::cout << "It took " << result << " Units of " << sum << " To reach " << modifiedValue << "\n\n";
    if(result <= 9 || sum <= 1) break;
    modifiedValue = result;
  }
}


int main() {
  int c = 0;
  std::cout << "Enter a number:\n";
  std::cin >> c;
  outOfNumber(c);

  system("pause");
  return 0;
}

So this was my last days project, the file is called FunLoops, I basically made any "easy" loop I could think of, just to try and figure it out. I made a loop that counts down and then counts up, basically bouncing between 2 numbers, and also, every 10 digits had a line break. Creating a kind of pseudo block of numbers. The second one, is one solution to fizz buzz, the commented code under that was another I thought up but didn't pan out, but I didn't want to erase it, the helloWeirdness, was going to take an input split it into letters and move those +1 on the ascii table then print it out again. But I didn't actually write it, I do have notes in my head for how I thought I would accomplish it though. Most of them are probably wrong.

Then I made the thing that I spent most of yesterday and all of today so far(only been up 3 hours) on. My friend challenged me, to take a number, say 123456, and then split that into it's component parts( 1 2 3 4 5 6), and add those together(1 + 2 + 3 + 4 + 5 + 6). Then to take that result(21) and continue the process(2 + 1) all the way down, until you get to the point where you have a single digit number( 3 ), then take that number, and test to see how many times it went into the original number(123456/3). Then another friend challenged me to go one step further, and make it a loop that continued that process until it either reaches 1 and can't go any further, or the next number it would reach would be a single digit number.

In the case of 123456 the result looks a bit like this,
Logged
Pages: 1 [2]