-
Incorrect Output
Hi,
My following code is suppose to generate 20 random numbers and store them in an array. But if the number duplicates then that array element is replaced by a zero instead of that number. However my code only outputs one random number but all remaining numbers are zeros.........but i don't see why.... pls help
thnx in advance
Code:
/* Prints only random numbers generated */
#include <stdio.h>
int main()
{
int i, array[ 20 ], smallestSize = 0, num, j;
srand( time( NULL ) );
for ( i = 0; i < 20; i++ ) {
num = 1 + rand() % 20;
for ( j = 0; j <= i; j++ )
if ( array[ j ] == num )
array[ i ] = 0;
else
array[ i ] = num;
if ( array[ i ] != 0 )
++smallestSize;
}
for ( i = 0; i < 20; i++ )
printf( "%d", array[ i ] );
return 0;
}
-
OK....
This could do with some optimising, but I think it works....
Code:
#include <stdio.h>
int main()
{
int i, array[ 20 ], smallestSize = 0, num, j, flag = 0, total = 0;
srand( time( NULL ) );
for ( i = 0; i < 20; i++ ) {
flag = 0; // Reset flag
num = 1 + rand() % 20;
for ( j = 0; j <= i; j++ ) {
if ( array[ j ] == num ){
--i; // If number already selected count down by 1
flag = 1; // Do not select number
}
}
if(!flag){ // If number is selectable
array[ i ] = num; // Assign it a place in the array
} // Else start again with i 1 value less that it should
}
for ( i = 0; i < 20; i++ ) {
printf( "%d\t", array[ i ] );
total += array[i]; // Check: sum of all values between 1 & 20 = 210
}
printf( "\nTotal of all numbers = %i", total ); // Is it 210??
return 0;
}
The "total" thing is a check. I wanted to make sure that the total of all elements of the array totalled 210 (1+2+3.......+19+20 = 210)
It seems to work, but its just me messing with your code...there should be better algorithms on this board if you look.....
-
Hi,
thnx , problem solved. Here is my final code:
Code:
/* Generate 20 random numbers and prints them only if it's unique in the array. */
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
void noDuplicate( int [], int );
int main()
{
int i, array[ 20 ], smallestSize = 0, num, j;
srand( time( NULL ) );
for ( i = 0; i < 20; i++ ) {
num = 1 + rand() % 20;
if ( i == 0 ) {
array[ i ] = num;
continue;
}
for ( j = 0; j < i; j++ )
if ( array[ j ] == num )
num = 0;
array[ i ] = num;
if ( array[ i ] != 0 )
++smallestSize;
}
noDuplicate( array, smallestSize );
return 0;
}
void noDuplicate( int array[], int smallestSize )
{
int j;
int smallestArray[ smallestSize ];
printf( "Random-numbered array with no duplicates: \n" );
for ( j = 0; j < smallestSize; j++ ) {
if ( array[ j ] != 0 ) {
smallestArray[ j ] = array[ j ];
printf( "%d ", smallestArray[ j ] );
}
}
}