Eat. Sleep. Code: The Computer Programming Thread, Ver. 010

Yeah, what you are going to want to do instead of just printfing each string immediately you want to put them into a char[] and then print the whole array at the end. and again, you can use those arrays of literals to make those if elses much shorter/less ugly.

Would you mind showing me a small sample to get me started please? I’m kind of having trouble picturing this right now. I know it involves


char* first20[] = {“zero”, “one”, “two”, “three”, “four”, “five”,“six”, “seven”, “eight”, “nine”, “ten”, “eleven”, “twelve”, “thirteen”, “fourteen”, “fifteen”, “sixteen”, “seventeen”, “eighteen”,“nineteen”};
char* tens[] = {“twenty”, “thirty”, “forty”, “fifty”, “sixty”,“seventy”, “eighty”, “ninety”};

And shoutouts to juggling this and studying for my last math and physics midterms. :sad:

So you have those arrays of strings. Zero is in the 0th position, One is in the 1st position.

Instead of



switch(int)
{
case 1:
  printf("one");
.....
 case 20:
 printf("twenty");
}


you just do this



char* first20[] = {“zero”, “one”, “two”, “three”, “four”, “five”,“six”, “seven”, “eight”, “nine”, “ten”, “eleven”, “twelve”, “thirteen”, “fourteen”, “fifteen”, “sixteen”, “seventeen”, “eighteen”,“nineteen”};
int ones = number - (hundreds * 100) - (tens * 10);
prinf(first20[ones]);


One line eliminates the entire switch or if/else than logic

You just need to make sure you change your logic so you get a number that is really one of the first twenty since those are represented in the array. Then you can output whole words easily; then you have to make sure your logic makes the english read properly

Okay I think I get it now thanks!

So I’m working on my last project of the semester and it’s a text-based Minesweeper game. I’m pretty sure I’m on the right path to completing it, but I’m on my way to work now so I’m going to have to call it quits for the night. If you guys don’t mind could I post my code up tomorrow and see what you guys think after I work on it a little more, I have the field creation all finished, just working on taking in user input and bomb-checking now. Which are the harder things to get right I think.

Another question, what is everybody’s approach to doing something like this? I thought about it a little bit before I started coding, but I’m sure I could have been better prepared.

Well there’s essentially two things you need to store per square, what the player can see(the number 1-however many bombs are next to it, a blank space, a flag, or unchecked) and whether or not it’s a bomb. There’s a lot of ways to set up that information. I’d prolly make a square class that would have an int that held the number of bombs near a square(-1 if it is a bomb), and a display character(defaulting to unchecked). That’s a fairly light class and has all the information that I can think of. Then just store a bunch of those in an array.

There’s only two real inputs, a check input and a flag input. Check should reveal the square, and you lose it’s a bomb, if it’s not a bomb You change the display character to whatever the number of bombs around it is, minesweeper also then reveals a ton of stuff around that number(though I’m not sure how that mechanic works). If it’s a flag I’d just change the display character to flag(or back to unchecked if it’s already a flag). I’d probably keep integers counting the number of flags and the number of bombs, and only check to see if they’ve won when the flag count changes to be equal to the number of bombs. As far as actually checking if they’ve won, probably just iterate through the array and break out of the iteration as soon as you find a bomb that’s not flagged(again only running through this iteration when they click the flag button and only when numFlags == numBombs).

The real interesting part is map generation. You could just hard code a map, or you could keep a bunch of premade maps in files and load 'em. But I like things to be interesting so I’d probably try and think of a generation algorithm. I’d probably generate the map on the first click, or generate when it loads and remove a bomb if the first click is a bomb so that they don’t blow up on first click(or give like a 1% chance to be a dick). The simplest way would just be to iterate through the list with X% chance that a square is a bomb. There should probably be some simple rules to this IE, you probably don’t want a square completely surrounded in bombs since there’d be no way to figure out what that square was. We could do some crazy stuff like weighting how likely a bomb is to be in a square based on how many bombs are already around it(either to promote or prevent clusters or maybe promoting clusters based on a difficulty setting etc…).

Definitely a class/struct for each square. Create a 2D array of these structs.
Unless required, I’d just do a simple random operation followed by a check to ensure all squares and bombs are reasonably placed. If it violated some simple rules, I’d do something really dumb to fix it. I think the simple rules would have to do with how many bombs are surrounding a square.

ASCII command line, hmm I’ve honestly never programmed anything that will resize the terminal window and refresh over itself, similar to how ‘top’ operates. The UI is where I’d spend most of my time, mostly because I’ve never done anything like that before. Since it is texted based, I suppose they shouldn’t use the mouse, in this case I’d somehow make the arrow keys and the enter key the way the user interacts with it.

This habit I have of mistyping “appendChild” as “appendChile” is getting on my nerves. I don’t want a South American country in my DOM.

So my final for Compe 160 is this Saturday, wish me luck! Anyway my professor gave us a Practice Final for us so we have an idea what it’s going to be like and if you want to, give it a go and see how you do, I’ll post the solutions later.

[details=Spoiler]1. Write a program that will prompt the user to enter a list of 10 integers and then print the average of the integers. The average should include the fractional part. Print the average with 2 digits to the right of the decimal point. Use a for loop. A sample run is shown below:

Enter 10 integers:
1 2 3 4 5 6 7 8 9 10
Average = 5.50


Answer

  #include <stdio.h>
 main()

{



2. Repeat exercise 1, but use a while loop instead of a for loop.


Answer

  #include <stdio.h>
 main()

{


***3. Read the program below and show exactly what will be printed when the program executes. ***


main()
{
** int a[] = {7, -2, 0, 3, -4, -6, 9, 4, -5, 8};**
** int i;**
** for (i=0; i<10; i++)**
** {**
** if (a* < 0)******
** a* = -a*;**********
** }**
** for (i=9; i>=0; i–)**
** printf(“a[%d] = %d
”, i, a*);******
}


Answer


4***. Read the program below and show exactly what will be printed when the program executes. ***

int fun(int b, int e);


main()
{
** int x = 2, y = 6;**
** printf(“fun(%d, %d) = %d
”, x, y, fun(x, y));**
}


int fun(int b, int e)
{
** int i, p;**
** i = 0;**
** p = 1;**
** while(i < e)**
** {**
** p = p * b;**
** i++;**
** }**
** return p;**
}

Answer


5. Write a program that will prompt the user to enter 10 integers and then will print out the integers in two lists: a list of the odd numbers, and a list of the even numbers. A sample run is shown below.


Enter 10 integers:
1 2 3 4 5 6 7 8 9 10
Even integers: 2 4 6 8 10
Odd integers: 1 3 5 7 9


Answer

  #include &lt;stdio.h&gt;
  main()

{



6. Write a function with prototype
void init_rand(int x[], int size, int min, int max);
The function should assign a random integer between min and max to each variable of the array x. The parameter size is the number of variables in array x. Assume that the srand function has already been called to seed the random number generator.

Answer

void init_rand(int x[], int size, int min, int max)
{


7. Write a function with prototype
void init_rand(float x[], int size, float min, float max);
The function should assign a random real number between min and max to each variable of the array x. The parameter size is the number of variables in array x. Assume that the srand function has already been called to seed the random number generator.

Answer

void init_rand(float x[], int size, float min, float max)
{













8. Write a function with prototype
float stats(int x[], int size, int* pMin, int* pMax);
***The function should find the most positive and the most negative integers in array x and store them in the variables pointed to by pMin and pMax. Also, it should compute the average of the integers in array x and return that value. The fractional part of the average should be retained. For example, if the array is {3, -5, -3, 6, 5}***, then the min, max and average are -5, 6 and 1.2.


Answer


float stats(int x[], int size, int* pMin, int* pMax)
{











9. Write a program that you can use to test the function stats of the previous problem. The program should prompt the user to enter a list of integers, terminating the list by entering q. Then call the stats function to find the minimum, maximum and average of these numbers, and print these values. A sample run should look as follows:

Enter 10 integers, q to quit:
55 33 66 99 44 11 22 33 88 77 q
Minimum = 11
Maximum = 99
Average = 52.80000

Answer

  #include &lt;stdio.h&gt;

float stats(int x[], int size, int* min, int* max);
main()
{


***10. Write a function with prototype ***
*** *void myStrcat(char s1, char s2);
The function should add the string s2 to the end of the string s1 (like the library function strcat). You may not call any library functions.
***For example, the following code, ***
char a[80] = “I like “;
char b[80] = “ice cream.”;
myStrcat(a, b);
printf(”%s
”, a);
will print
I like ice cream.


Answer
void myStrcat(char* s1, char* s2)
{



***11. Write a function with prototype ***
*** ***int LCM(int x, int y);
***The function should find the Least Common Multiple of integers x and y. ***
***For example, the statement, ***
printf(“LCM(8, 12) = %d
”, LCM(8, 12));
will print
LCM(8, 12) = 24


Answer
int LCM(int x, int y);
{[/details]****

I hate questions like 3, if you want someone to debug code tell them to debug code. I’m also not a fan of three questions that ask you to program something on paper that all have the exact same first chunk of code, if the question is about that first chunk of code only ask it once, if it’s about other stuff don’t make 'em write the stupid first chunk.

ROFL Well for question 3, absolutely nothing will be printed when the program executes, because that code won’t compile.

Allow me to fix it for extra credit:



main()
{
int a[] = {7, -2, 0, 3, -4, -6, 9, 4, -5, 8};
int i;
for (i=0; i<10; i++)
{
if (a* < 0)
a* = -a*;
}
for (i=9; i>=0; i--)
printf("a[%d] = %d
", i, a*);
}
 


Nah it’s not about debugging, it’s about making sure you know exactly what each line of code means. In the real world it’s not good, but for a test it’s a damn good question.

3 is weird though, I’m guessing that if the formatting isn’t off, that it is kind of just supposed to be a trick question. And I’m guessing that accessing an array without an index (i.e. a) is the same as accessing an array with index 0. So a[0] = 7, and also a = 7. But it’s not something I ever use day to day so I’m not sure. Makes the whole loop do nothing since a is never less than 7 since he never says a* < 0 *
Edit: Ah so you can’t access it with just A? That’s what I was wondering I thought it was a trick question and not just bad formatting lol but I had the same thoughts

Yup just tried compiling, you can’t access an array without an index. Awesome I thought it was some unique trick that only gets asked on a test

Nah accessing an array without an index is a point operation so it’ll be the address of the first element of the array without a dereference. I don’t actually remember if pointer < int is a valid operator, it’d either compare the address(which will never be less than 0) and go through the loop doing nothing or it won’t compile. You absolutely can mess around with A without dereferencing or given it an index, I just don’t remember if < is valid with type int(I’m pretty sure you can do pointer < otherPointer though considering subtraction between two pointers is valid).

edit: IMO for question 3 it should say it doesn’t work. When you’re programming in the real world you know what something spits out or if it doesn’t compile just by running it. I personally never felt like I learn anything from those style of questions, I much prefer the “large chunk of code with some correct and some incorrect, find the bugs” style, you can put run time/logic errors and compile errors in that and you actually know what your looking for. I generally assume code does what it looks like it’s supposed to unless it’s known to be broken.

I generally assume all code is broken unless I personally just wrote/fixed it and no one else has had a chance to break it yet :wink:

Also for question 10, instead of answering it I would fill the provided space with an essay why that question is a bad idea and explanation of “buffer overrun”.

Part of me hates when I change a file (in this case, a global defines file) and it triggers a recompile of everything in the project.

The other part of me loves Compile Time! Though working from home, 90% of my time is like compile time

I was having a problem with a very large code base(10ish gigs) not working on machines without visual studio, for a few days my job was essentially installing and uninstalling visual studios(the first time I had to remove 2003, 2005, AND 2008) and moving around a 10 gig file, I also had to get some fresh checkouts of the project during that. My job for DAYS was essentially watching progress bars!

Sucks and rocks all at the same time. But don’t you just need the Visual Studio Redist? and not visual studio itself

Yeah that’s essentially what it ended up being, although the redist pack from MSDN wasn’t working, I had to use one that was packed with visual studio 2008 service pack 1. It’s a solution/code base written by someone else for 2003 that I was updating to 2008.

Dammit I’m stuck. I need to check for bombs around a user’s input on a 3x3 grid. I have two 2D arrays (one is int[10][10] with ten 1’s acting as bombs, the other is a String[][] with "?"s until the user flags or uncovers whichever cell.)

This is the pseudo code version of what I’m trying to do but I can’t seem to get it right.


int[][] grid = new int[10][10];
x=input.nextInt();
y=input.nextInt();
bombCount = 0;
temp = y;
for(int i =0; i < 3; i++)
{
    y = temp;
    for(int j = 0; j < 3; j++)
    {
        if(grid[x-1][y-1] == 1) /*This is what I'm having trouble with. I don't know how to thoroughly check surrounding cells*/
          bombCount++;
        y++;
    }
    x++;
}
        

Try writing out the problem, and use diagrams. That’s what I usually do when I need to figure out something.

Does that code compile, or does it give any “array out of bounds” error at runtime? I’m curious as to what the x and y values are.