I have an one-dimensional table with degrees:
double tabledegrees[10]={0.2,3.4,4.3,1.2,4.6,4.5,3.8,1.5,3.4,3.7};
The degrees are always in the interval [0,5].
I want to count the number of thermometers whose degree belong in each of the intervals [0,1), [1,2),[2,3), [3,4),[4,5] and store these values in an array of integers of size 5, in which cell 0 belongs to degrees belonging to the interval [0,1), cell 1 to degrees belonging to the interval [1,2), and so on.
I want to use floor function and not a sequence of if commands.
The following program:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
double tabledegrees[10]={0.2,3.4,4.3,1.2,5.6,4.5,3.8,1.5,3.4,3.7};
double tabledegreesfloored[10];
for (int i=0;i<10;i++){
tabledegreesfloored[i] = floor(tabledegrees[i]);
}
for (int j=0;j<10;j++){
printf("%.f \n", tabledegreesfloored[j]);
}
}
returns:
0 3 4 1 5 4 3 1 3 3
How to achive this?
You create an array of thermometers and use the interval to index into the array as you count them:
#include <math.h>
#include <stdio.h>
#define LEN(a) sizeof(a) / sizeof(*a)
int main() {
double tabledegrees[10]={0.2,3.4,4.3,1.2,5.6,4.5,3.8,1.5,3.4,3.7};
size_t thermometers[5] = {0};
for (size_t i=0; i < LEN(tabledegrees); i++) {
if(tabledegrees[i] < 0 || tabledegrees[i] >= LEN(thermometers)) {
printf("skip data out of range %lf\n", tabledegrees[i]);
continue;
}
thermometers[(int) floor(tabledegrees[i])]++;
}
for (size_t i=0; i < LEN(thermometers); i++)
printf("%zu: %zu\n", i, thermometers[i]);
}
and here is example output:
skip data out of range 5.600000
0: 1
1: 2
2: 0
3: 4
4: 2
Related
I want to shuffle an array of containing a list of cities to generate a result. The requirement for this shuffling is that same city can only appear again after at least six different cities have appeared. The same city must appear only twice.
I messed up using a different scenario before but I am new on here and getting used to how to post codes that I am struggling with. Any help would be appreciated. Array5 is the array to be shuffled.
Cities to be shuffled:
Boston, Durban, Melbourne, Paris, Denver, Algiers, Freetown, Sydney, Colorado, Oslo, Melbourne, Brussels
I have included my code below:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int i,j,count;
char array1[3][10]={"Denver","Boston","Colorado"};
char array2[3][10]={"Melbourne","Sydney","Canberra"};
char array3[3][10]={"Paris","Brussels","Oslo"};
char array4[3][10]={"Durban","Algiers","Freetown"};
char array5[12][10];
for (i=0;i<3;i++){
strcpy(array5[i],array1[i]);
}
for (i=0;i<3;i++){
strcpy(array5[i+3],array2[i]);
}
for (i=0;i<3;i++){
strcpy(array5[i+6],array3[i]);
}
for (i=0;i<3;i++){
strcpy(array5[i+9],array4[i]);
}
for (i=0;i<12;i++)
printf("%s\t\n",array5[i]);
}
The problem can be solved in two steps.
1) We shuffle the auxiliary array to obtain initial placement of the cities.
We can use FisherYates shuffle algorithm for shuffling the initial array.
2) We randomly decide which city we want to duplicate. We have to be mindful of the restrictions. City can be doubled only one time. If the city is doubled then there are at least 6 cities between them.
More explanations in the code:
// The requirement for this shuffling is that same city can only appear again after at least six different cities have appeared.
// A city can only appear twice.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define STR_LEN 16
#define NR_OF_ROWS 3
#define NR_OF_SMALL_ARRAYS 4
#define NR_OF_ROWS_IN_BIG_ARRAY NR_OF_ROWS*NR_OF_SMALL_ARRAYS
#define DOUBLE_COUNTER 12 // number of tries to double the city
void copy(char dest[][STR_LEN], char source[][STR_LEN], size_t displacement)
{
size_t i;
for (i=0; i<NR_OF_ROWS; i++){
strcpy(dest[i+displacement], source[i]);
}
}
void init_shuffle(size_t array[], size_t size)
{
size_t i;
for (i=0; i<size; i++){
array[i] = i;
}
}
void print_array(char array[][STR_LEN], size_t size)
{
size_t i;
for (i=0; i<size; i++){
printf("%s ",array[i]);
}
printf("\n");
}
void print_shuffle(size_t array[], size_t size)
{
size_t i;
for (i=0; i<size; i++){
printf("%zu ",array[i]);
}
printf("\n");
}
void print_corresponding_cities(char array[][STR_LEN], size_t *shuffle, size_t size)
{
size_t i;
size_t j;
for (i=0; i < size; i++){
j = shuffle[i];
printf("%s ", array[j] );
}
printf("\n");
}
int check_for_repeats(size_t *arr, size_t size, size_t value)
{
size_t i;
size_t counter = 0;
for (i=0; i<size; i++){
if(arr[i] == value){
counter++;
if(counter > 1)
return 1; // repeats found
}
}
return 0; // no repeats
}
int check_for_number_of_repeats(char array[][STR_LEN], size_t *arr, size_t size)
{
size_t i, j;
size_t counter = 0;
size_t value;
int repeats = 0;
for (j=0; j<size; j++){
value = j;
counter = 0;
for (i=0; i<size; i++){
if(arr[i] == value){
counter++;
if(counter > 1){
repeats++; // repeats found
printf("%s ", array[j]); // print the city
break;
}
}
}
}
return repeats;
}
void FisherYatesShuffle(size_t *arr, int n) {
size_t i, j; // indexes
size_t tmp; // create local variables to hold values for shuffle
for (i = n - 1; i > 0; i--) { // shuffle
j = rand() % (i + 1); // randomise j for shuffle
tmp = arr[j];
arr[j] = arr[i];
arr[i] = tmp;
}
}
int main()
{
size_t i;
int no_yes;
size_t double_index;
time_t t;
size_t shuffle[NR_OF_ROWS_IN_BIG_ARRAY]; // keep the results
char array1[NR_OF_ROWS][STR_LEN]={"Denver0","Boston1","Colorado2"};
char array2[NR_OF_ROWS][STR_LEN]={"Melbourne3","Sydney4","Canberra5"};
char array3[NR_OF_ROWS][STR_LEN]={"Paris6","Brussels7","Oslo8"};
char array4[NR_OF_ROWS][STR_LEN]={"Durban9","Algiers10","FreeTown11"};
char array5[NR_OF_ROWS_IN_BIG_ARRAY][STR_LEN];
init_shuffle(shuffle, NR_OF_ROWS_IN_BIG_ARRAY);
// Initial arrangement:
copy(array5, array1, 0*NR_OF_ROWS);
copy(array5, array2, 1*NR_OF_ROWS);
copy(array5, array3, 2*NR_OF_ROWS);
copy(array5, array4, 3*NR_OF_ROWS);
printf("Initial arrangement:\n");
print_shuffle(shuffle, NR_OF_ROWS_IN_BIG_ARRAY);
print_array(array5, NR_OF_ROWS_IN_BIG_ARRAY);
printf("\n");
// Algorithm:
// Note:
// The shuffling will be done on the auxilliary shuffle array
// Once the shuffling is done we can print the cities base on shuffle array values
// Steps.
// 1. We shuffle existing cities.
// 2. We randomly decide if we want to repeat the city.
// 3. If yes, we choose a random city
//
// 4. Now we have to repeat that city. The requirement is that if we repeat the city
// then we have have at least 6 cities between them.
// E.g. We want to repat city from index 0 then duplicated city can only be placed at index 7 to 11
// Index Next city placement:
//
// 0 7-11 range 5 [7,8,9,10,11]
// 1 8-11 range 4
// 2 9-11 range 3
// 3 10-11 range 2
// 4 11 fixed position
// 5 no placement
// x if (x > 4) no placement possible
// else placement possible in the range [x+7, 11]
// size of the range is 5-x
// 5. we can repeat that procees a few times (DOUBLE_COUNTER). Restriction: A given city can be repeated only 1 time.
/* Intializes random number generator */
srand((unsigned) time(&t));
// 1. Shuffle
printf("After the shuffle:\n");
FisherYatesShuffle(shuffle, NR_OF_ROWS_IN_BIG_ARRAY);
print_shuffle(shuffle, NR_OF_ROWS_IN_BIG_ARRAY);
print_corresponding_cities(array5, shuffle, NR_OF_ROWS_IN_BIG_ARRAY);
printf("\n");
// 2. Add cities
for(int i=0; i < DOUBLE_COUNTER; i++)
{
no_yes = rand() % 2; // add? YES OR NO
if(no_yes == 0) // NO
continue;
double_index = rand() % NR_OF_ROWS_IN_BIG_ARRAY; // which city
if(double_index > 4)
continue; // NO placement possible
// check for repeats
int rep = check_for_repeats(shuffle, NR_OF_ROWS_IN_BIG_ARRAY, shuffle[double_index]);
if(rep)
continue; // city under this index has a double already
//-------------------------------------------------------
// OK we need to repeat the city
if(double_index == 4)
{
shuffle[11] = shuffle[double_index];
continue;
}
// now we have a choice:
int choice = rand() % (5 - double_index);
// random placement within the range:
shuffle[double_index +7 + choice] = shuffle[double_index];
//-------------------------------------------------------
}
// Results:
printf("Final arrangement after adding double city/cities:\n");
print_shuffle(shuffle, NR_OF_ROWS_IN_BIG_ARRAY);
print_corresponding_cities(array5, shuffle, NR_OF_ROWS_IN_BIG_ARRAY);
// Stats:
printf("\nThese cites occure two times:\n");
int nr_rep = check_for_number_of_repeats(array5, shuffle, NR_OF_ROWS_IN_BIG_ARRAY);
printf("\nNumber of repeated cities = %d\n", nr_rep);
return 0;
}
Output:
Initial arrangement:
0 1 2 3 4 5 6 7 8 9 10 11
Denver0 Boston1 Colorado2 Melbourne3 Sydney4 Canberra5 Paris6 Brussels7 Oslo8 Durban9 Algiers10 FreeTown11
After the shuffle:
5 9 3 11 6 8 4 0 7 2 1 10
Canberra5 Durban9 Melbourne3 FreeTown11 Paris6 Oslo8 Sydney4 Denver0 Brussels7 Colorado2 Boston1 Algiers10
Final arrangement after adding double city/cities:
5 9 3 11 6 8 4 0 5 2 1 6
Canberra5 Durban9 Melbourne3 FreeTown11 Paris6 Oslo8 Sydney4 Denver0 Canberra5 Colorado2 Boston1 Paris6
These cites occure two times:
Canberra5 Paris6
Number of repeated cities = 2
**This was a deleted question but I remade it so it easier for this community to understand what I'm asking
Here is my code:
#include <stdio.h>
#include <stdbool.h>
int main()
{
int row;
int col;
int x;
int y;
int i = 9;
int count[i];
printf("Enter the size of your array: ");
scanf("%d %d", &row, &col);
int arr[row][col];
//This will read the rows
for (int x = 0; x < row; ++x) {
for (int y = 0; y < col; ++y) {
printf("Enter row %d: ", x);
scanf("%d", &arr[x][y]);
}
}
//This will create a count for the rows
for (x = 0; x < row; ++x) {
for (y = 0; y < col; ++y) {
++count[arr[x][y]];
}
}
//This will count if digits repeat in the rows and print it
printf("\nTotal count for each digit:\n");
for (int j = 0; j < 10; ++j) {
printf("Digit %d occurs %d time%s\n", j, count[j], count[j] > 1 ? "s" : "");
}
return 0;
}
Notes on the code
I made i = 9 because the max number the user should enter is 9
On the "This will read the rows" there should be two printf's
"Enter Row 0"
"Enter Row 1"
How would I go and make it so the user would enter a set of numbers for the user to enter in both the rows. When I compile it just keeps saying "enter row 0: enter row 0: enter row 0". The program should find out how many times a number between 0 and 9 was entered. The final result should look like this
Enter the size of your array: 2 6
Enter row 0: 0 1 2 3 4 5
Enter row 1: 0 1 6 7 8 9
Total count for each digit:
Digit 0 occurs 2 times
Digit 1 occurs 2 times
Digit 2 occurs 1 time
Digit 3 occurs 1 time
ect. This would keep going until it the program hits "Digit 9 occurs however many times.
When I compile without the printf it runs through 3 rows when it should be 2 and most of the numbers that the compiler gives out are wack except for 2 digits
Ex The Digit 1 occurs 3 times
Digit 2 occurs -343589435 times
Thanks for any help!
There are ten digits 0-9. So the array count should have ten elements. Also the array need to be initialized.
Either use an array with the size specified by a constant expression and initialize it in a declaration like
#define N 10
//...
int count[N] = { 0 };
Or use a variable length array and initialize it using the function memset declared in the header <string.h>
For example
#include <string.h>
//...
int i = 10;
int count[i];
memset( count, 0, i * sizeof( int ) );
Otherwise if the array is not initialized it will have indeterminate values.
I have 2D array of size m*m with element values either 0s or 1s. Furthermore, each column of the array has a contiguous block of 1s (with 0 outside that block). The array itself is too large to be held in memory (as many as 10^6 rows), but for each column I can determine the lower bound, a, and the upper bound, b, of the 1s in that column. For a given n, I need to find out those n consecutive rows which have the maximum number of 1s. I can easily do it for smaller numbers by calculating the sum of each row one by one, and then choosing n consecutive rows whose sum comes out to be maximum, but for large numbers, it is consuming too much time. Is there any efficient way for calculating this? Perhaps using Dynamic Programming?
Here is an example code fragment showing my current approach, where successive calls to read_int() (not given here) provide the lower and upper bounds for successive columns:
long int harr[10000]={0}; //initialized to zero
for(int i=0;i<m;i++)
{
a=read_int();
b=read_int();
for(int j=a;j<=b;j++) // for finding sum of each row
harr[j]++;
}
answer=0;
for(int i=0;i<n;i++)
{
answer=answer+harr[i];
}
current=answer;
for(int i=n;i<m;i++)
{
current=current+harr[i]-harr[i-n];
if(current>answer)
{
answer=current;
}
}
For example (with m = 6 and n = 3)
Here the answer would be row 1 to row 3 with a total 1-count of 13 in those rows. (Row 2 to row 4 also maximizes the sum as there is a tie.)
Here is a different approach. Think of each pair a, b as defining an interval of the form [a,b+1). The task is to find the n consecutive indices which maximizes the sum of the parenthesis depth of the numbers in that interval. Every new a bumps the parenthesis depth at a up by 1. Every new b causes the parenthesis depth after b to go down by 1. In the first pass -- just load these parentheses depth deltas. Then one pass gets the parenthesis depths from these deltas. The following code illustrates this approach. I reduced m to 6 for testing purposes and replaced calls to the unkown read_int() by accesses to hard-wired arrays (which correspond to the example in the question):
#include <stdio.h>
int main(void){
int a,b,answer,current,lower,upper;
int n = 3;
int lower_bound[6] = {0,1,2,3,1,2};
int upper_bound[6] = {3,4,3,5,2,4};
int m = 6;
int harr[6]={0};
//load parenthesis depth-deltas (all initially 0)
for(int i=0;i<m;i++)
{
a = lower_bound[i];
b = upper_bound[i];
harr[a]++;
if(b < m-1)harr[b+1]--;
}
//determine p-depth at each point
for(int i = 1; i < m; i++){
harr[i] += harr[i-1];
}
//find optimal n-rows by sliding-window
answer = 0;
for(int i=0;i<n;i++)
{
answer = answer+harr[i];
}
current =answer;
lower = 0;
upper = n-1;
for(int i=n;i<m;i++)
{
current = current+harr[i]-harr[i-n];
if(current>answer)
{
answer = current;
lower = i-n+1;
upper = i;
}
}
printf("Max %d rows are %d to %d with a total sum of %d ones\n", n,lower,upper,answer);
return 0;
}
(Obviously, the loop which loads harr can be combined with the loop which computes answer. I kept it as two passes to better illustrate the logic of how the final harr values can be obtained from the parentheses deltas).
When this code is compiled and run its output is:
Max 3 rows are 1 to 3 with a total sum of 13 ones
I'm not sure how the following will scale for your 10^6 rows, but it manages the the trailing sum of x consecutive rows in a single pass without function call overhead. It may be worth a try. Also insure you are compiling with full optimizations so the compiler can add its 2 cents as well.
My original thought was to find some way to read x * n integers (from your m x n matrix) and in some fashion look at a population of set bits over that number of bytes. (checking the endianness) and taking either the first or last byte for each integer to check whether a bit was set. However, the logic seemed as costly as simply carrying the sum of the trailing x rows and stepping through the array while attempting to optimize the logic.
I don't have any benchmarks from your data to compare against, but perhaps this will give you another idea or two.:
#include <stdio.h>
#include <stdlib.h>
#ifndef CHAR_BIT
#define CHAR_BIT 8
#endif
#ifndef INT_MIN
#define INT_MIN -(1U << (sizeof (int) * CHAR_BIT - 1))
#endif
int main (int argc, char **argv) {
/* number of consecutive rows to sum */
size_t ncr = argc > 1 ? (size_t)atoi (argv[1]) : 3;
/* static array to test summing and row id logic, not
intended to simulate the 0's or 1's */
int a[][5] = {{1,2,3,4,5},
{2,3,4,5,6},
{3,4,5,6,7},
{4,5,6,7,8},
{3,4,5,6,7},
{0,1,2,3,4},
{1,2,3,4,5}};
int sum[ncr]; /* array holding sum on ncr rows */
int sumn = 0; /* sum of array values */
int max = INT_MIN; /* variable holding maximum sum */
size_t m, n, i, j, k, row = 0, sidx;
m = sizeof a / sizeof *a; /* matrix m x n dimensions */
n = sizeof *a / sizeof **a;
for (k = 0; k < ncr; k++) /* initialize vla values */
sum[k] = 0;
for (i = 0; i < m; i++) /* for each row */
{
sidx = i % ncr; /* index for sum array */
if (i > ncr - 1) { /* sum for ncr prior rows */
for (k = 0; k < ncr; k++)
sumn += sum[k];
/* note 'row' index assignment below is 1 greater
than actual but simplifies output loop indexes */
max = sumn > max ? row = i, sumn : max;
sum[sidx] = sumn = 0; /* zero index to be replaced and sumn */
}
for (j = 0; j < n; j++) /* compute sum for current row */
sum [sidx] += a[i][j];
}
/* output results */
printf ("\n The maximum sum for %zu consecutive rows: %d\n\n", ncr, max);
for (i = row - ncr; i < row; i++) {
printf (" row[%zu] : ", i);
for (j = 0; j < n; j++)
printf (" %d", a[i][j]);
printf ("\n");
}
return 0;
}
Example Output
$./bin/arraymaxn
The maximum sum for 3 consecutive rows: 80
row[2] : 3 4 5 6 7
row[3] : 4 5 6 7 8
row[4] : 3 4 5 6 7
$./bin/arraymaxn 4
The maximum sum for 4 consecutive rows: 100
row[1] : 2 3 4 5 6
row[2] : 3 4 5 6 7
row[3] : 4 5 6 7 8
row[4] : 3 4 5 6 7
$ ./bin/arraymaxn 2
The maximum sum for 2 consecutive rows: 55
row[2] : 3 4 5 6 7
row[3] : 4 5 6 7 8
Note: if there are multiple equivalent maximum consecutive rows (i.e. two sets of rows where the 1's add up the the same number), the first occurrence of the maximum is selected.
I'm not sure what optimizations you are choosing to compile with, but regardless which code you use, you can always try the simple hints to the compiler to inline all functions (if you have functions in your code) and fully optimize the code. Two helpful ones are:
gcc -finline-functions -Ofast
Say I have the following raw data:
5 6
1 4 5
2 4 5
2 3 4
3 4 6
where first line represents: [number of vertices] [number of edges] and the subsequent lines represent: [index of vertex1] [index of vertex2] [weight]. I was thinking of doing %3 and dividing data into 3 strings as vertices1, vertices2 and weights, but I cant find a proper way to arrange this data into an adjacency matrix. Any suggestions?
Probbaly you need this:
#include <stdio.h>
#define MAXVERTICES 10
int main(void)
{
int matrix[MAXVERTICES][MAXVERTICES];
for (int i = 0; i < MAXVERTICES; i++)
for (int j = 0; j < MAXVERTICES; j++)
matrix[i][j] = 0;
int nbvertices, nbedges;
scanf("%d %d", &nbvertices, &nbedges);
for (int i = 0; i < nbvertices; i++)
{
int v1, v2;
int weight;
scanf("%d %d %d", &v1, &v2, &weight);
matrix[v2][v1] = matrix[v1][v2] = weight;
}
return 0;
}
It's very basic, no error checking is done and the maximum number of vertices is 10 (MAXVERTICES).
So the question is to develop a [5][5] table, each containing unique numbers from 1-100 (no duplicates)
so here's what I came up with:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int outerLoop;
int innerLoop;
int board[5][5]; /* Array Name And Size*/
/* seeds the random number generator*/
srand(time(NULL));
int number;
number = rand() % 101;
/* Start a loop to generate a random integer between 1 and 100 and
assign it into the array. The loop runs 25 times*/
for ( outerLoop = 0 ; outerLoop <= 25 ; outerLoop++ ) /* loop 25 times*/
{
for ( innerLoop = 0 ; innerLoop <= 4 ; innerLoop++ ) /* <=4 due to 5
columns*/
{
board[outerLoop][innerLoop] = rand() % 100 + 1;
}
printf( "%d \n", board[outerLoop][innerLoop] );
}
So I pretty much got stuck here.I'm not really sure about this:
board[outerLoop][innerLoop] = rand() % 100 + 1;
I simply made it up :/ Any idea guys?
What you want is a shuffle algorithm
Shuffle array in C
To get your 25 element array of unique #s from 1 to 100; just create a 100 element array with the numbers 1..100, shuffle the 1st 25 from the pool of 100, and use the 1st 25.
$ cat test.c
#include <stdio.h>
#include <stdlib.h>
void shuffle(int *array, size_t array_size, size_t shuff_size)
{
if (array_size > 1)
{
size_t i;
for (i = 0; i < shuff_size - 1; i++)
{
size_t j = i + rand() / (RAND_MAX / (array_size - i) + 1);
int t = array[j];
array[j] = array[i];
array[i] = t;
}
}
}
int main(int argc, char * argv[]) {
int a[100];
int b[5][5];
int i,j,k=0;
for(i=0; i<100;++i)
a[i]=i;
shuffle(a,100,25);
for(i=0;i<5;++i)
for(j=0;j<5;++j) {
b[i][j] = a[k++];
printf("%d ",b[i][j]);
}
printf("\n");
}
$ gcc -o test test.c
$ ./test
0 14 76 47 55 25 10 70 7 94 44 57 85 16 18 60 72 17 49 24 53 75 67 9 19
Think of it like a deck of 100 cards.
Create a 100 element array holding the card numbers (1..100)
Shuffle the array (=deck). (see #koodawg's answer and #Steve314's comment)
"Deal" yourself the first 25 cards off the deck, into your 5x5 array.
Just create array of boolean of size 100 : bool numberUsed[100]. Then in cycle:
1.Generate random number r
2.If numberUsed[r] is true, dont add that r anywhere and continue in loop
3.numberUsed[r] = true
Note that you need to use WHILE cycle with this approach, not FOR cycle.
Here is some pseudo code to solve it:
Create a "list" of length 100 containing the numbers 1...100 called "numbersAvailable"
In your inner loop set index = (int)rand() * numbersAvailable; and the take the number numbersAvailable.get(index); and then do numbersAvailable.remove(index);
In Java creating a list is easy. If you like to stick to C you have to emulate this via arrays. (I can write down the solution, but this looks like a homework, so I leave something for you).
Note: In contrast to a trial-and-reject solution, this solution has the advantage of a fixed amount of time needed to construct the result.
Since int board[5][5]; allocates a continuous amount of memory you can initialise it with just
for (i = 0; i < sizeof(board)/sizeof(int); i++)
board[0][i] = rand() % 100 + 1;
Or use a double loop like you did, but then you only need to loop 5 times in the other loop, or use sizeof to set the iteration count automatically:
for ( outerLoop = 0 ; outerLoop < sizeof(board)/sizeof(board[0]) ; outerLoop++ ) {
for ( innerLoop = 0 ; innerLoop < sizeof(board[0])/sizeof(board[0][0]) ; innerLoop++ ) {
board[outerLoop][innerLoop] = rand() % 100 + 1;
}
}
Please keep in mind that sizeof will only work on arrays in this way when the length of the array is known at compile time like it is in your example.
C stores arrays in row-major order, i.e, the elements of row 0 comes first , followed by the elements of row 1, and so forth.
We can take advantage of this by viewing int board[5][5] as int board[5*5].
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 5
int main()
{
int i, outerLoop = 1;
int board[N*N];
srand(time(NULL));
int number;
board[0] = rand() % 100 + 1; //initializing the first element
while(1)
{
number = rand() % 100 + 1 ;
if(outerLoop == N*N)
break;
else
{
//Cheking the previous elements for no duplicacy
for ( i = 0; i < outerLoop; i++)
{
if(number == board[i])
break;
}
//confirming whether all the elements are checked or not and the assigning number to the array element and then increment the counter outerLoop
if(i == outerLoop)
{
board[outerLoop] = number;
outerLoop++;
}
else
continue;
}
}
//Printing the elements of array board[N*N]
for ( outerLoop = 0 ; outerLoop < N*N ; outerLoop++ )
{
printf( "%d\t", board[outerLoop] );
if(outerLoop % N == 4)
printf("\n\n");
}
}