Generating a unique Random Generator in Java

  • (2 Pages)
  • +
  • 1
  • 2

17 Replies - 805 Views - Last Post: 01 May 2013 - 12:46 AM Rate Topic: -----

#1 radarmanman  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 18
  • Joined: 30-April 13

Generating a unique Random Generator in Java

Posted 30 April 2013 - 05:54 PM

Hello everyone,

I'm trying to make a random unique generator that does not repeat the same value at all and add it into a 2d array if possible. I tried using an array list, but it keeps display it in patterns. Also, the same value cannot repeat on a different row on the 2d array. Basically, I tried something like this. I got it from a guide from this site, Click here.

The problem with me is that I keep getting symbol errors and cannot even test it, even though I declared it. I'm trying to do this all on the main class so I can test it and avoid a bunch of referencing.

heres my code for reference:

for(int x=0;x<50;x++){
	Random randGen = new Random();

	int randNum = randGen.nextInt();
	}
	for(;;)/>{
	if(myNumbers.add(randNum)) break;
 
	}
	
	System.out.println(randNum);
}	



Is This A Good Question/Topic? 0
  • +

Replies To: Generating a unique Random Generator in Java

#2 Luckless  Icon User is offline

  • </luck>
  • member icon

Reputation: 292
  • View blog
  • Posts: 1,146
  • Joined: 31-August 09

Re: Generating a unique Random Generator in Java

Posted 30 April 2013 - 06:48 PM

Random needs a seed (a starting point) The algorithm gives out a sequence of numbers depending on this seed, so lets make the seed change by using the current time:

Random randGen = new Random(System.currentTimeMillis());



My guess without your error message is that your for loop runs forever. What is myNumbers? and ArrayList?
Was This Post Helpful? -1
  • +
  • -

#3 radarmanman  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 18
  • Joined: 30-April 13

Re: Generating a unique Random Generator in Java

Posted 30 April 2013 - 06:52 PM

View PostLuckless, on 30 April 2013 - 06:48 PM, said:

Random needs a seed (a starting point) The algorithm gives out a sequence of numbers depending on this seed, so lets make the seed change by using the current time:

Random randGen = new Random(System.currentTimeMillis());



My guess without your error message is that your for loop runs forever. What is myNumbers? and ArrayList?



MyNumbers is suppose to be the name of the object the numbers go in to, but I rather make that object into an array.

ArrayList was something I tried earlier that was to randomize the numbers and not repeat any of the numbers but it would end up printing on a pattern.

int count=0;
List<Integer> list=new ArrayList<Integer>();
    while(count<50){
        int num=random.nextInt(50);
            if(!list.contains(num)){
                list.add(num);
                ++count;  
            }                    
    }


I rather avoid the arraylist implementation because it gave me trouble.
Was This Post Helpful? 0
  • +
  • -

#4 Gungnir  Icon User is offline

  • Your Imaginary Friend

Reputation: 152
  • View blog
  • Posts: 527
  • Joined: 21-May 11

Re: Generating a unique Random Generator in Java

Posted 30 April 2013 - 07:01 PM

You should never, under regular circumstances, use a for loop in this fashion. You never even check whether or not you manage to break out of it.

Where is the ArrayList structure myNumbers defined?

Also, you override the instance of randGen 49 times. Declare it outside of the loop.

You don't really make an attempt to prevent duplication, either.
List<int> myNumbers = new ArrayList<int>();
Random randGen = new Random();
int randNum = 0;
int lastNum;
for(int x=0;x<50;x++){
	lastnum = randNum;
	//This will prevent your generator from repeating numbers
	while(randNum == lastNum)
	{
		randNum = randGen.nextInt(50);
	}
	//remove the for loop -- It's redundant as it's only designed to loop once (true), or an infinite amount of times (false)
	myNumbers.add(randNum);
	System.out.println(randNum);
}



EDIT
for(int x=0;x<50;x++){
	lastnum = randNum;
	//This has a longer execution time, but will prevent duplicate entries
	//Upon further inspection, I'm fairly sure that this is the structure that you want
	while(myNumbers.contains(randNum))
	{
		randNum = randGen.nextInt(50);
	}
	//remove the for loop -- It's redundant as it's only designed to loop once (true), or an infinite amount of times (false)
	myNumbers.add(randNum);
	System.out.println(randNum);
}



There's nothing wrong with using an ArrayList in this fashion. ArrayLists are just enhanced array structures that extend the List interface.

View PostLuckless, on 30 April 2013 - 06:48 PM, said:

Random needs a seed

My guess without your error message is that your for loop runs forever. What is myNumbers? and ArrayList?


Random doesn't require a seed. Please refer to the documentation for a list of Random constructors.

This infinite loop wouldn't produce an error.

ArrayList is a common array structure based off of the List interface. Please refer to the documentation for further information.

This post has been edited by Gungnir: 30 April 2013 - 07:38 PM

Was This Post Helpful? 1
  • +
  • -

#5 radarmanman  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 18
  • Joined: 30-April 13

Re: Generating a unique Random Generator in Java

Posted 30 April 2013 - 07:37 PM

View PostGungnir, on 30 April 2013 - 07:01 PM, said:

You should never, under regular circumstances, use a for loop in this fashion. You never even check whether or not you manage to break out of it.

Where is the ArrayList structure myNumbers defined?

Also, you override the instance of randGen 49 times. Declare it outside of the loop.

You don't really make an attempt to prevent duplication, either.
List<int> myNumbers = new ArrayList<int>();
Random randGen = new Random();
int randNum = 0;
int lastNum;
for(int x=0;x<50;x++){
	lastnum = randNum;
	//This will prevent your generator from repeating numbers
	while(randNum == lastNum)
	{
		randNum = randGen.nextInt(50);
	}
	//remove the for loop -- It's redundant as it's only designed to loop once (true), or an infinite amount of times (false)
	myNumbers.add(randNum);
	System.out.println(randNum);
}



There's nothing wrong with using an ArrayList in this fashion. ArrayLists are just enhanced array structures that extend the List interface.

View PostLuckless, on 30 April 2013 - 06:48 PM, said:

Random needs a seed

My guess without your error message is that your for loop runs forever. What is myNumbers? and ArrayList?


Random doesn't require a seed. Please refer to the documentation for a list of Random constructors.

This infinite loop wouldn't produce an error.

ArrayList is a common array structure based off of the List interface. Please refer to the documentation for further information.


Makes sense now. The thing is now, I'm trying to send the value of each indivdual generated value into an array I set up. Problem is, I'm trying to display each individual number 5 times through a series of 10 rows. Heres what I did.
StudentList list = new StudentList(); \\Student list is a data structure I created which contains the 10 students 
	                                     \\I created
Random gen = new Random();
	List<Integer> myNumbers = new ArrayList<Integer>();
Random randGen = new Random();
int randNum = 0;
int lastNum;
for(int x=0;x<50;x++){
	lastNum = randNum;
	
	while(randNum == lastNum)
	{
		randNum = randGen.nextInt(50)+1;
	}
	
	myNumbers.add(randNum);
	}

			for(int i=0;i<=9;i++)
			{			
			int[] grades = new int[5];		
			for(int j=0;j<=4;j++)
			{
			grades[j] = randNum;    \\Trouble Area
			}
			list.add(new Student(i+1,grades));
			}	
			System.out.println(list);
			}




My output ends up like this.

Student1: [I@8746d23 
Student2: [I@13a9192b 
Student3: [I@42b36022 
Student4: [I@e6c7a64 
Student5: [I@73d742a1 
Student6: [I@39579371 
Student7: [I@2490fd20 
Student8: [I@2ada52a1 
Student9: [I@6366de01 
Student10: [I@767946a2 



I'm trying to display 5 numbers for each row of student. I'm assuming that the array cannot display all the values properly. I'm gonna keep trying to find a way to connect it to here. Thanks for your initial help so far Gungnir. You really helped me out so far.
Was This Post Helpful? 0
  • +
  • -

#6 Gungnir  Icon User is offline

  • Your Imaginary Friend

Reputation: 152
  • View blog
  • Posts: 527
  • Joined: 21-May 11

Re: Generating a unique Random Generator in Java

Posted 30 April 2013 - 07:52 PM

Your deepest code at the end there is improperly tabbed, and hard to read -- but I'll make do.

You can't print a list from its toString like that, because you'll just get an incomprehensible stream. You also don't need to make your own List structure.

You want something more along the lines of
public class Student
{
    private int grades, num;
    public Student(int num, int grades)
    {
        this.grades = grades;
        this.num = num;
    }

    public int getGrades()
    {
        return this.grades;
    }
    public int getNumber()
    {
        return this.num;
    }
}

//... Skipping ahead
List<Student> list = new ArrayList<Student>();

//Populate the list
list.add(new Student(1, 15));
//etc...

//...Skipping ahead
for(Student student : list)
    //This gives you much more control over the output
    println("Student" + student.getNumber() +": " + student.getGrade());



Quote

I'm trying to display each individual number 5 times through a series of 10 rows


So, like...
{1, 1, 1, 1, 1, 2, 2, 2, 2, 2},
{3, 3, 3, 3, 3, 4, 4, 4, 4, 4},
{5, 5, 5, 5, 5, 6, 6, 6, 6, 6}; //etc...



Obviously, that's oversimplified, but is that what you're trying to achieve? With a RANDOM number generator?

EDIT: I seem to have missed a part of your question in my answer, which was the multidimensional ArrayList structure.

Well, if a multidimensional array is just an array of arrays, you can apply this same structural rule to ArrayLists.

//A 2D ArrayList structure of Integers
ArrayList<ArrayList<Integer>> myNumbers = new ArrayList<ArrayList<Integer>>();


This post has been edited by Gungnir: 30 April 2013 - 08:17 PM

Was This Post Helpful? 0
  • +
  • -

#7 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8328
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Generating a unique Random Generator in Java

Posted 30 April 2013 - 08:11 PM

View PostLuckless, on 30 April 2013 - 09:48 PM, said:

Random needs a seed (a starting point) The algorithm gives out a sequence of numbers depending on this seed, so lets make the seed change by using the current time:

Random randGen = new Random(System.currentTimeMillis());


This is exactly what Random does.....

Only if you want different runs of your program to generate the same "random" number you should use a seed

// for debug purpose let generates always the same numbers
Random randGen = new Random(123456789L);

To generate random numbers (not repeating) between 1-N simply fill an ArrayList of these number and randomly remove out of it

ArrayList<Integer> al = new ArrayList<Integer>();
for(int i = 1; i <= N; ++i)
   al.add(i);

Random ran = new Random();

// removing 10 numbers
for(int i = 0; i < 10; ++i) {
   int index = ran.nextInt(al.size());
   System.out.prinln("" + al.remove(index));


Was This Post Helpful? 0
  • +
  • -

#8 radarmanman  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 18
  • Joined: 30-April 13

Re: Generating a unique Random Generator in Java

Posted 30 April 2013 - 08:17 PM

View PostGungnir, on 30 April 2013 - 07:52 PM, said:

Your deepest code at the end there is improperly tabbed, and hard to read -- but I'll make do.

You can't print a list from its toString like that, because you'll just get an incomprehensible stream. You also don't need to make your own List structure.

You want something more along the lines of
public class Student
{
    private int grades, num;
    public Student(int num, int grades)
    {
        this.grades = grades;
        this.num = num;
    }

    public int getGrades()
    {
        return this.grades;
    }
    public int getNumber()
    {
        return this.num;
    }
}

//... Skipping ahead
List<Student> list = new ArrayList<Student>();

//Populate the list
list.add(new Student(1, 15));
//etc...

//...Skipping ahead
for(Student student : list)
    //This gives you much more control over the output
    println("Student" + student.getNumber() +": " + student.getGrade());



Quote

I'm trying to display each individual number 5 times through a series of 10 rows


So, like...
{1, 1, 1, 1, 1, 2, 2, 2, 2, 2},
{3, 3, 3, 3, 3, 4, 4, 4, 4, 4},
{5, 5, 5, 5, 5, 6, 6, 6, 6, 6}; //etc...



Obviously, that's oversimplified, but is that what you're trying to achieve? With a RANDOM number generator?

EDIT: I seem to have missed a part of your question in my answer, which was the multidimensional ArrayList structure.

Well, if a multidimensional array is just an array of arrays, you can apply this same structural rule to ArrayLists.

//A 2D ArrayList structure of Integers
ArrayList<ArrayList<int>> myNumbers = new ArrayList<ArrayList<int>>();



That still leaves with the pattern that remains. I want the answer to print out a non repeating values 5 times each row but without having each random sequence be the same as the last. With some modifications to my iteration, My output now looks like this

Student1: 27 27 27 27 27 
Student2: 27 27 27 27 27 
Student3: 27 27 27 27 27 
Student4: 27 27 27 27 27 
Student5: 27 27 27 27 27 
Student6: 27 27 27 27 27 
Student7: 27 27 27 27 27 
Student8: 27 27 27 27 27 
Student9: 27 27 27 27 27 
Student10: 27 27 27 27 27 


This is possibly the hardest part for me. I tried other methods of non-duplicated generation but it always ends up repeating at a pattern. Should I try the duplication check while using a random generator that is defined within a range(for instance, through each loop within the array or a row, generate a random between 1-5, then list them while checking for duplication and keep going for the remaining 9 students. 5 numbers for 10 students so it'll end up with 50 numbers total. Lord, how to implement that.
Was This Post Helpful? 0
  • +
  • -

#9 Gungnir  Icon User is offline

  • Your Imaginary Friend

Reputation: 152
  • View blog
  • Posts: 527
  • Joined: 21-May 11

Re: Generating a unique Random Generator in Java

Posted 30 April 2013 - 08:32 PM

Your issue is here
grades[j] = randNum;



Since you never re-roll your random number, it will always return the same value. Why don't you try:
grades[j] = randGen.nextInt(4)+1;
//OR
randNum = randGen.nextInt(4)+1;
grades[j] = randNum;



Remember to re-roll your random generator whenever you desire a new outcome. An integer (in this case, randNum) will never change its value on its own.

This post has been edited by Gungnir: 30 April 2013 - 08:40 PM

Was This Post Helpful? 0
  • +
  • -

#10 radarmanman  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 18
  • Joined: 30-April 13

Re: Generating a unique Random Generator in Java

Posted 30 April 2013 - 09:55 PM

Well I made a lot of progress but here is what I got now. Basically, the generator you setup works fine without duplication, Gungir. I now know that its fine on that end. I also tried the re-roll condition, which elimated the patterns, but still gives me duplication. I think I have to change an parameter in my linked list to read an arraylist rather than array and display the results through there instead of trying to reference it to a regular array which probably doesn't end up directly referencing the values in the arraylist that was created.

 
	 List<Integer> myNumbers = new ArrayList<Integer>();
Random randGen = new Random();
int randNum=0;
int lastNum;
for(int x=0;x<50;x++){
	lastNum = randNum;
 
	while(myNumbers.contains(randNum))
	{
		randNum = randGen.nextInt(50);
	}
	 
	myNumbers.add(randNum);
	System.out.println(randNum);
}

 
            
				     
	
	
			
			for(int i=0;i<=9;i++)
			{
			
			int[] grades = new int[5];
				for(int j=0;j<=4;j++)
				{
				grades[j] = randGen.nextInt(50)+1;
				}
				list.add(new Student(i+1,grades));
			}
			
			System.out.println(list);
		 
			
			
		 	
		
	
	
	}



0
35
34
19
15
47
31
7
23
16
3
26
28
12
13
6
46
5
4
8
14
9
21
29
37
24
48
40
1
38
42
11
36
49
33
25
45
18
10
2
30
39
41
20
22
27
44
43
32
17
Student 1: 16 32 11 44 28 
Student 2: 27 36 22 4 39 
Student 3: 19 21 43 7 34 
Student 4: 42 25 34 30 32 
Student 5: 16 40 49 22 50 
Student 6: 1 41 39 38 43 
Student 7: 7 16 28 44 10 
Student 8: 4 14 6 46 29 
Student 9: 6 17 19 22 37 
Student 10: 6 19 22 26 46 


Was This Post Helpful? 0
  • +
  • -

#11 Gungnir  Icon User is offline

  • Your Imaginary Friend

Reputation: 152
  • View blog
  • Posts: 527
  • Joined: 21-May 11

Re: Generating a unique Random Generator in Java

Posted 30 April 2013 - 10:34 PM

I think I understand now. I figured that those two parts of your program were inert, and not affected by eachother at all.
You want your grades to draw from the myNumbers array, without duplication? You could do something like:
	List<Integer> myNumbers = new ArrayList<Integer>();
	Random randGen = new Random();
	int randNum=0;
	int lastNum;
	for(int x=0;x<50;x++)
	{
		lastNum = randNum;
		while(myNumbers.contains(randNum))
		{
			randNum = randGen.nextInt(50);
		}
		 
		myNumbers.add(randNum);
		System.out.println(randNum);
	}	
		for(int i=0;i<=9;i++)
		{
		
			int[] grades = new int[5];
			for(int j=0;j<=4;j++)
			{
				//v- these lines have changed -v
				grades[j] = myNumbers.get(randGen.nextInt(myNumbers.length() - 1));
				myNumber.remove(grades[j]);
				//^- these lines have changed -^
			}
			list.add(new Student(i+1,grades));
		}
	
		System.out.println(list);	
	}



Does that suit your needs better?

This post has been edited by Gungnir: 30 April 2013 - 10:36 PM

Was This Post Helpful? 2
  • +
  • -

#12 radarmanman  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 18
  • Joined: 30-April 13

Re: Generating a unique Random Generator in Java

Posted 30 April 2013 - 10:57 PM

At first I was getting Symbol errors, so I changed it to this because I was assuming the max length was trying to be found


grades[j] = myNumbers.get(randGen.nextInt(myNumbers.size() - 1));
myNumbers.remove(grades[j]);



Now I get Indexoutofbounds exception cases now.
Was This Post Helpful? 0
  • +
  • -

#13 Gungnir  Icon User is offline

  • Your Imaginary Friend

Reputation: 152
  • View blog
  • Posts: 527
  • Joined: 21-May 11

Re: Generating a unique Random Generator in Java

Posted 30 April 2013 - 11:11 PM

Which of those lines are you getting the error on?

EDIT: Found it.
for(int x=0;x<50;x++)
//^CHANGE THIS TO:
for(int x=0;x<51;x++)


This post has been edited by Gungnir: 30 April 2013 - 11:13 PM

Was This Post Helpful? 0
  • +
  • -

#14 radarmanman  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 18
  • Joined: 30-April 13

Re: Generating a unique Random Generator in Java

Posted 30 April 2013 - 11:14 PM

View PostGungnir, on 30 April 2013 - 11:11 PM, said:

Which of those lines are you getting the error on?



Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 47, Size: 47
	at java.util.ArrayList.rangeCheck(ArrayList.java:604)
	at java.util.ArrayList.remove(ArrayList.java:445)
	at StudentProject.main(StudentProject.java:32)


I get the error at line 32 with the "myNumbers.size() operation. When I tried using myNumbers.length()-1, I would get this error

StudentProject.java:31: error: cannot find symbol
			grades[j] = myNumbers.get(randGen.nextInt(myNumbers.length() - 1));
			                                                   ^
  symbol:   method length()
  location: variable myNumbers of type List<Integer>
1 error



Isn't length an operation that works with Array and Arraylist? It seems like I have to initialize it somewhere.
Was This Post Helpful? 0
  • +
  • -

#15 Gungnir  Icon User is offline

  • Your Imaginary Friend

Reputation: 152
  • View blog
  • Posts: 527
  • Joined: 21-May 11

Re: Generating a unique Random Generator in Java

Posted 30 April 2013 - 11:29 PM

Please read my above answer. It's changed.

length is a public field of array.
size() is a public method of the List interface that returns the private field length*.

There is no difference, but ArrayList.length can't be called publicly (and rightly so), so you have to use ArrayList.size().

* It mightn't be called length, but it's to that effect

You need to change
grades[j] = myNumbers.get(randGen.nextInt(myNumbers.length() - 1));


to
grades[j] = myNumbers.get(randGen.nextInt(myNumbers.size() - 1));



List.size() implementation:
//Method descriptor #25 ()I
public abstract int size();



Further Reading:
- Oracle Docs > ArrayList Documentation (optional)

This post has been edited by Gungnir: 30 April 2013 - 11:38 PM

Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2