# Developers Planet

Bonediggerninja February 2016

### Number checking in C

(what its meant to do)

While working on a "Deal or no deal" project, I made a function check(); to check if any two cases are the same, and if they are, change one of them, then re check it again.

function deal sets random numbers for cases with the prizes, and then call on check();

``````#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void deal(void);
void check(void);

int cases[22];
int prizes[22]=1,2,3,4,5,6,8,10,15,20,25,35,50,65,85,100,105,135,165,200,250};

int main()
{   int a=0;
deal();
while (a<22){
printf("%d \n",cases[a] );
a++;
}

return 0;
}

void deal(void){

srand(time(NULL));
int r;
int n = 1;

while (n <= 22){
r = rand() % 21;
cases[n] = prizes[r];
n++;

}//Ends while loop

check();

}//Ends function

void check(void){
int i = rand() % 21;
int m = 0;
int n = 0;

srand(time(NULL));

while(m < 22){//Nested while loop

while ( n < 22){
if (m == n){
n++;
continue;
} else {
if(cases[m] == cases[n]){

cases[m] = prizes[i];
i = rand() % 21;
continue;
}else{

n++;
continue;

}

}

}//End of inside loop
m++;
n = 0;
}//End of nested loop

}//End function
``````

However it prints out the numbers unchecked, or not checked properly. I'm using code-blocks IDE

Wossname February 2016

You're nearly there, there is a simple (and quite common) algorithm or doing a scramble on an array. With one pass through the array you can randomise the positions of each value without duplicating them. The check function isn't necessary now due to the scramble function's operation.

``````#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void deal(void);
void check(void);

int cases[22];
int prizes[22] = {1,2,3,4,5,6,8,10,15,20,25,35,50,65,85,100,105,135,165,200,250};

int main()
{
srand(time(NULL));

int a = 0;
deal();

for(a = 0 ; a < 22 ; a++)
printf("%d \n", cases[a]);

return 0;
}

//this is a neat algorithm for re-ordering an array without duplication
void scramble(int* array, int length)
{
int i;
int r;
int temp;

for(i = 0 ; i < length ; i++)
{
//swap this element with a random one to it's left (or itself)
r = rand() % (i + 1);

temp = array[r];
array[r] = array[i];
array[i] = temp;
}
}

void deal(void)
{
int r;
int n = 1;

//copy the prizes across directly
for(n = 0 ; n < 22 ; n++)
cases[n] = prizes[n];

scramble(cases, 22);
}
``````

Examine the scramble() function in detail and you'll find it quite interesting.

Edited to change the algo to a single pass as per a suggestion in the comments.