Jump to content

Recommended Posts

Posted

Thought I'd start a thread dedicated to my failings in C and my questions, which hopefully people can answer!!

 

I'm working on CS50 PSET3 - Game of 15. I have to code a search function. Which is fine. Just linear search for now.

 

Here is my code:

#include 
#include "helpers.h"


/**
* Returns true if value is in array of n values, else false.
*/
bool search(int value, int values[], int n);
{
   if (n <= 0)
   return false;

// TODO: implement a searching algorithm

   for (int i = 0; i < n; i++)
   {
       if (value == values[i])
       {
       return true;
       }
       
   }
   return false;
}

 

Here is my error:

 

~/workspace/pset3/find/ $ make

clang -ggdb3 -O0 -std=c11 -Wall -Werror -o find find.c helpers.c -lcs50 -lm

helpers.c:18:1: error: expected identifier or '('

{

 

So when you are coding functions... do you use normal parentheses () as opposed to curly brackets {}?

Posted

I'll expand on that :p

 

If you're doing it your way, you need to re-do the function as all you're doing is declaring it.

 

bool search(int value, int values[], int n); 


int main () {
   Do search blah blah
  return 0;
}



bool search(int value, int values[], int n) {
   if (n <= 0)
   return false;

   for (int i = 0; i < n; i++)
   {
       if (value == values[i])
       {
       return true;
       }
       
   }
   return false;
}

 

First one is declaring a function, second one is the code linked to it.

 

If you want you can do it all together as you are, but you can't end the function first line with ; as you cut the rest out.

 

int main () {
   Do search blah blah
  return 0;
}

bool search(int value, int values[], int n) {
   if (n <= 0)
   return false;

   for (int i = 0; i < n; i++)
   {
       if (value == values[i])
       {
       return true;
       }
       
   }
   return false;
}

 

If that makes sense?

 

Steve

  • Thanks 1
Posted

On another side note :p I'm guessing from the way you did your include CS50, the original idea might have been with the declaring is you declare the function locally, but the actual function is in another file.

 

So you could have like:

 

bool search(int value, int values[], int n); 

int main () {
   Do search blah blah
  return 0;
}

 

In your main file, and then the big one in the CS50 as an example which is included :

 

bool search(int value, int values[], int n) {
   if (n <= 0)
   return false;

   for (int i = 0; i < n; i++)
   {
       if (value == values[i])
       {
       return true;
       }
       
   }
   return false;
}

 

Obviously not sure what they asked, but just a heads up :)

 

Steve

Posted

today I am trying to draw a board like this

 

8 7 6

5 4 3

2 1 _

 

I think I need a counter to count to d and then when it does, print a new line.

 

#include 
#include 
#include 

int main (void)
{
int d = 3;

int grid[d][d];
   int row, col, val;
   row = 0;
   val = 1;
   //populate grid by row, move along columns
   for (row = 0; row < d; row++)
   {
   for (col = 0; col < d; col++)
       {
       grid[col][row] = (d * d) - val;
       val = val + 1;
       printf("%2d",grid[col][row]);
       printf("\n");
       
       }
       
   }
}

 

This code just prints one number per line....

Posted

   for (row = 0; row < d; row++)
   {
   for (col = 0; col < d; col++)
       {
       grid[col][row] = (d * d) - val;
       val = val + 1;
       printf("%2d",grid[col][row]);
 [color="#FF0000"]      printf("\n");
       
       }[/color]
       
   }
}

 

This code just prints one number per line....

 

In terms of your one per line issue, check where you're adding the new line.

 

You're adding a newline per "column" not per "row" :p

So 10 newline 9 newline etc, you want 10 9 8 newline

 

In terms of the entire thing though do you need it in an array for another part of it? You could get rid of a lot of the process if you don't need the array. (As in is it just printing out that box? or is it for use in something like tic tac toe etc)

 

Steve

  • Thanks 1
Posted

Yeah I need the array, it's basically going to be a function in a much bigger program. Kinda think if I can't even do something as simple as this, I shouldn't even bother!!

 

Got a last minute class support to go to now :mad:

 

I appreciate the help! (y)

Posted

You have done it lol :p Don't bring yourself down. Literally move one line on yours and it'll work.

 

  #include 
#include 
#include 

int main (void)
{
int d = 3;

int grid[d][d];
   int row, col, val;
   row = 0;
   val = 1;
   //populate grid by row, move along columns
   for (row = 0; row < d; row++)
   {
   for (col = 0; col < d; col++)
       {
       grid[col][row] = (d * d) - val;
       val = val + 1;
       printf("%2d",grid[col][row]);
       
       
       }
       [color="#FF0000"]printf("\n");[/color]
   }
}

 

That red one, moved it down one line and boom you have a square :p

 

 

 

Personally though one thing you might want to do is skip the counter, and use a function that works for any number you put into the array size. (Also has the benefit of dropping the requirement for the Val counting etc)

 

int main()
{
int ArraySize = 3;
int Array[ArraySize][ArraySize];
int RowNumber, ColNumber;

for (RowNumber = 0; RowNumber < ArraySize; RowNumber++) {
   for (ColNumber = 0; ColNumber < ArraySize; ColNumber++) {
           Array[ColNumber][RowNumber] = (ArraySize * (ArraySize - RowNumber)) - ColNumber ;
           printf("%2d",Array[ColNumber][RowNumber]);
       }
    printf("\n");
   }
}

 

As an example (Wasn't sure if you wanted it to end on 1 or 0 but that's just one extra part :p)

 

Steve

  • Thanks 1
Posted

Thanks Steve. I'm getting some strange output!!

 

Capture.PNG

 

I'm thinking perhaps I need to use a float instead of an int to do precise maths.

 

I had a look at your formula above too. It wouldn't give me the numbers I wanted though. It would populate the first number as 9 (in a 3x3 grid) and I need it to be 8. Also to complicate matters, if the grid is an even number (like 16) the 1 and 2 have to be switched! ie -

 

15 14 13 12

11 10 9 8

7 6 5 4

3 1 2 _

Posted

What code are you using that's giving you the odd figures? As the above you posted works fine for me. Counts 8-0 in a 3x3

 

And on my one if you wanted 8-0 would just need to add a -1 to my line.

 

And on a 4x4 why would those last numbers change around? Just trying to work out what the process you're doing is :)

 

Steve

Posted

I'm doing this - Problem Set 3: Game of Fifteen

 

Although other configurations are possible, we shall assume that this game begins with the board’s tiles in reverse order, from largest to smallest, left to right, top to bottom, with an empty space in the board’s bottom-right corner. If, however, and only if the board contains an odd number of tiles (i.e., the height and width of the board are even), the positions of tiles numbered 1 and 2 must be swapped, as in the below. The puzzle is solvable from this configuration.

 

download.png

Posted

Ah ok :)

 

Basically in regards to your ending with 8-0 on mine, Just take the one off the end:

 

Array[ColNumber][RowNumber] = (ArraySize * (ArraySize - RowNumber)) - ColNumber - 1;

 

In regards to the swapping the end around, I'd personally do a check If the Arraysize squared is even, and value to print = 2, swap to 1 (and if value to print = 1 swap to 2) etc if that makes sense?

 

Steve

  • Thanks 1
  • 2 weeks later...
Posted
I'm thinking perhaps I need to use a float instead of an int to do precise maths.

 

To a programmer, that line reads very oddly. Floats are intrinsically imprecise and are specialist things. You definitely don't want one here.

Posted (edited)
To a programmer, that line reads very oddly. Floats are intrinsically imprecise and are specialist things. You definitely don't want one here.

 

Not sure how you find that. A float is just with a decimal place so is required for any advanced maths (even divisions etc) if you want an accurate reading that will accept all outcomes without needing additional error checking.

 

While the individual element may be more precise as a variable due to limited 4 byte rounding etc (Thus going Double wise now), In her context doing precise maths is better to have a float not int. Else what do you work out 4/3 to be as an int? (Random example).

 

Steve

Edited by Steve21
  • Thanks 1
Posted
Not sure how you find that. A float is just with a decimal place so is required for any advanced maths (even divisions etc) if you want an accurate reading that will accept all outcomes without needing additional error checking.

I suspect jwinters is alluding to the fact that floats are problematic at either extreme (measuring very small values or measuring very large values) and in combination, (arithmetic in which both extremes are involved) floats can be hugely imprecise. So, you would never want to model financial transactions using floats.

Posted
I suspect jwinters is alluding to the fact that floats are problematic at either extreme (measuring very small values or measuring very large values) and in combination, (arithmetic in which both extremes are involved) floats can be hugely imprecise. So, you would never want to model financial transactions using floats.

 

No you'd use Decimal. Neither of what's been talked about or financial work :p The point being Int can't be used for any precise maths in the scenario and coding that's linked here.

 

Steve

Posted

If it makes anyone feel better, I got it working without floats or doubles. I'm going to sit down and try and do the next 2 parts of this problem today,

 

swapping values in the array and a check for winning.

 

It sounds so simple when I put it like that!!

  • Thanks 1
Posted (edited)
Not sure how you find that. A float is just with a decimal place

 

Ah, yes - you'd expect it to be implemented like that but alas it isn't and it's an area which often catches out beginner programmers. You expect floats to be just the same as real numbers, but the underlying implementation means they are in fact only an approximation.

 

Any integer can be represented exactly as a float, but most non-integers are only approximate. This leads to really surprising results like:

 

1.0 - 0.87 != 0.13

 

(Incidentally, I'm not saying that that particular calculation will show the issue, but it is a real issue and you need to be aware of it when programming with floating point numbers.)

 

A classic mistake is to think that financial values should be stored in floats because they appear to have two digits after the decimal point. Their intrinsic imprecision then leads to wrong answers. The correct approach is to store your amounts of money as integer numbers of pence, and then add the decimal point at the presentation stage.

 

Some years ago I did some work interfacing to the London Stock Exchange, who required all values to be reported exactly to 8 decimal places. Naive attempts to do this using floats or doubles were doomed to fail. What you actually had to do was use 64 bit ints and use them to store values x 10^-8

 

As a general rule when programming, avoid the use of floats and double unless you actively need the imprecision they provide - e.g. for statistics calculations. Definitely never for anything like calculating indices into arrays.

Edited by jwinters
Posted
Some years ago I did some work interfacing to the London Stock Exchange, who required all values to be reported exactly to 8 decimal places. Naive attempts to do this using floats or doubles were doomed to fail. What you actually had to do was use 64 bit ints and use them to store values x 10^-8

 

Might want to read up as I already phrased that above :p As I said financial things are nothing to do with this post, and you'd still use Decimal at 128bit for them. And none of that post changes the fact that even a simple divide calculation would need a type other than Int :p

 

Anyway, don't want to de-rail Jo's thread anymore than it is :)

 

Steve

  • Thanks 1

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now



×
×
  • Create New...