Jump to content

HELP! 3x3 array random number 1-9 no repeat

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
3 replies to this topic

#1
siren

siren

    Newbie

  • Members
  • PipPip
  • 11 posts
Hello! I'm new to programming, and currently having trouble with a C program. In essence, I am suppose to make a magic square program, and in order to do so I thought that I would have to create a 3x3 matrix, then randomize the numbers in each slot, without any overlapping, and keep looping that until every row, column and diagnals equals one another. I'm sure there are other more efficient ways, but this is all I could think of. So far I have

#include <stdio.h>

#include<stdlib.h>


#define N 3

int main(void)

{

  srand((unsigned)time(NULL));

  int b[N][N], int i, int j;


  for(               ){

    /* need to randomize numbers 1-9 here in matrix but I don't know how*/



    if(b[0][0]+b[1][0]+b[2][0]=b[0][1]+b[1][1]+b[2][1]=b[0][2]+b[1][2]+b[2][2]=b[0][0]+b[0][1]+b[0][2]=b[1][0]+b[1][1]+b[1][2]=b[2][0]+b[2][1]+b[2][2]=b[0][0]+b[1][1]+b[2][2]=b[2][0]+b[1][1]+b[0][2])

      printf("/* how do you print the current matrix?*/");

    break;


    else continue;}

}



and simply want the result to be something like

% ./a.out
4 3 8
9 5 1
2 7 6

Please help me!

#2
kkelly

kkelly

    Learning Programmer

  • Members
  • PipPipPip
  • 49 posts
That would require a nested for loop.

#3
v0id

v0id

    Retired

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,936 posts
It's right what kkelly is saying. You need a nested loop, and it's fairly easy to make, and use. You can use it to both print you matrix, and put in random values.

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

int GetRandom(int Max)
{
	/* Returns a value between 0 and Max-1 */
	return (rand() % Max);
}

int main()
{
	int X, Y;
	int MaximumValue = 10;
	int X_Axis = 3, Y_Axis = 3;
	int Matrix[X_Axis][Y_Axis];
	
	/* Use the time to get random values */
	srand((unsigned int)time(NULL));
	
	/* Fill the array with random values */
	for(X = 0; X < X_Axis; X++)
		for(Y = 0; Y < Y_Axis; Y++)
			Matrix[X][Y] = GetRandom(MaximumValue);
	
	/* Print all the values to the user */
	for(X = 0; X < X_Axis; X++)
	{
		for(Y = 0; Y < Y_Axis; Y++)
			printf("%d ", Matrix[X][Y]);
		putchar(10);
	}
	
	return 0;
}


#4
felixme86

felixme86

    Newbie

  • Members
  • PipPip
  • 11 posts
kkelly I want to warn you that this method may not work. there are a few combinations of randomly set numbers that will make your puzzle impossible to solve. if this is a problem you may want to investigate what those are or think of another way to randomize your numbers.