Numbers 1 -4 (or 0-3) put into a random order. HELP PLEASE!

Put your problem here if it does not fit any of the other categories.

Numbers 1 -4 (or 0-3) put into a random order. HELP PLEASE!

Postby HarryH » Mon Aug 03, 2009 7:11 pm

Hello, I'm still quite new to Java and Android but now I'm stuck (again).

I would like to have an ArrayList (placement) to have the numbers 0-3 in a random order. I can get 4 numbers between 0 and 3 into the ArrayList EASILY but what I've been stuck on for the last 5 hours is making sure there are no duplicates. I've tried everything and then came across for loops on the web but still couldn't do it.

This is the code I have so far but will give results like 3312 and 2311.

private void placements(){
Random randomnumber = new Random();
int suggested = 0;
int places = 0;
for ($suggested = randomnumber.nextInt(4); places < 4; suggested = randomnumber.nextInt(4)) {

placement.add(suggested);
places =$places + 1;
}
}


Please could someone have a look at my code and propose how I can change it?
Any help would be appreciated.

Thankyou!
Harry
HarryH
Junior Developer
Junior Developer
 
Posts: 22
Joined: Sun Mar 29, 2009 6:50 pm

Top

Postby Jompe71 » Wed Aug 05, 2009 12:25 pm

I'm sure you've solved it by now, but anyway this should do the trick.

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.        
  2.  
  3. public static void randomizer( ArrayList<Integer> list, int from, int to ) {
  4.  
  5.        
  6.  
  7.     Random rand = new Random( System.currentTimeMillis() );    
  8.  
  9.     list.clear();
  10.  
  11.     list.add( from );
  12.  
  13.  
  14.  
  15.     for( int i = from + 1; i <= to; i++ ) {
  16.  
  17.         list.add( rand.nextInt( list.size() ), i );    
  18.  
  19.     }
  20.  
  21. }
Parsed in 0.032 seconds, using GeSHi 1.0.8.4
There is no school like old school gaming.
Jompe71
Experienced Developer
Experienced Developer
 
Posts: 69
Joined: Sat Oct 25, 2008 2:21 pm
Location: Stockholm Sweden

Postby HarryH » Sun Aug 09, 2009 12:25 am

Thankyou very much but yes, I have found a solution.

I just used:

Collections.shuffle(nameofarraylist);

Annoyingly simple grrr.
HarryH
Junior Developer
Junior Developer
 
Posts: 22
Joined: Sun Mar 29, 2009 6:50 pm

Top

Return to Other Coding-Problems

Who is online

Users browsing this forum: MSNbot Media and 20 guests