954,504 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

help About Random

i have a class with 10 object and each object have a random position like (x,y)
now i wand a code that do not put object in same position
please complete my code

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

class chess{

public :
	chess();
private :
	int x;
	int y;
};



chess::chess()
{
x=rand()%15+1;    //rand()%max+min will give values from min to min+max-1
y=rand()%15+1;
}

main()
{
chess a[10];
}
aminpost
Newbie Poster
2 posts since Feb 2009
Reputation Points: 10
Solved Threads: 0
 

You need to set the rand seed value, use srand() . Unlike Java and C# the seed value, when not set, is the same every time it is run. I suggest using the current time to set the seed value.

nmaillet
Posting Whiz in Training
236 posts since Aug 2008
Reputation Points: 69
Solved Threads: 53
 
You need to set the rand seed value, use srand() . Unlike Java and C# the seed value, when not set, is the same every time it is run. I suggest using the current time to set the seed value.

now what should i do?

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

class chess{

public :
	chess();
private :
	int x;
	int y;
};



chess::chess()
{
x=rand()%15+1;    //rand()%max+min will give values from min to min+max-1
y=rand()%15+1;
}

main()
{
srand((unsigned)time(NULL));
chess a[10];
}
aminpost
Newbie Poster
2 posts since Feb 2009
Reputation Points: 10
Solved Threads: 0
 

You can run it through a loop to check the other pieces to ensure that the randomly generated square is not already occupied.

nmaillet
Posting Whiz in Training
236 posts since Aug 2008
Reputation Points: 69
Solved Threads: 53
 

Help yes. Writing code for others, no, sorry ;P

Thanx...
Sean

seanhunt
Light Poster
40 posts since Oct 2008
Reputation Points: 13
Solved Threads: 6
 

Create a static member in your class which is a bool type 2D array (call it say,current_pos) of 8X8 elements.
Each time you assign a Position to the object, be sure to mark the current_pos[x][y]=TRUE;
So, now you can keep track of what all postition are been ocupied.
Hence, as soon as your random() generates a new position, check whether that position is already occupied or not. If it is, tell him to generate another number and so on.

Since the array will be a static member, its value will be same for all the object of the class.

siddhant3s
Practically a Posting Shark
816 posts since Oct 2007
Reputation Points: 1,486
Solved Threads: 140
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You