View Full Version : Trouble generating array of unique random numbers
uniquity
06-09-2009, 03:18 AM
I'm trying to generate an array of 128 unique random numbers using Random. However, after debugging, I found that some strange stuff happens. Here's my code so far (with debugging println's still in it), can someone help me out?
public Dictionary( String fileName, boolean sorted, long seed )
throws java.io.FileNotFoundException, java.io.IOException
{
dictionary = new ArrayList<String>();
String decryptWord = new String();
int ctr = 1;
int ctr2 = 0;
Random rand = new Random( seed );
int[] randArray = new int[128];
randArray[0] = rand.nextInt( 128 );
while( ctr != 128 )
{
int temp = rand.nextInt( 128 );
System.out.println( "Random number: " + temp );
for( ctr2 = 0; ctr2 < ctr; ctr2++ )
{
if( temp == randArray[ctr2] )
{
System.out.println( "Already found at index " + ctr2 + "." );
break;
}
else if( ctr2 == ctr - 1 )
{
randArray[ctr] = temp;
System.out.println( "Added #: " + randArray[ctr] );
ctr++;
}
} //end for
System.out.println( "Number at index" + ctr + ": " + randArray[ctr] );
} //end while
Fou-Lu
06-09-2009, 04:24 AM
Are you meaning to only allow random numbers between 0 and 128?
If this is the case, and you're wanting a unique array of 128 of these numbers between 0 and 128, you'd be better off simply using a loop to write the incrementing value and than running shuffle on it. Any Collection's have shuffle written into them, and then you can output toArray to get the primitive again if necessary. Don't forget that random runs from 0 to x inclusive, so you may want to use 127 and add one to the result.
uniquity
06-10-2009, 02:07 AM
well the point of generating a random array of unique characters is part of a bigger problem i'm trying to solve, which is posted here: http://www.codingforums.com/showthread.php?t=168407 pretty much i have to generate the same array of int's as the test case coming in to decrypt a file, so i don't know if the proposed solution would give me the answer i need.
Fou-Lu
06-10-2009, 03:38 AM
Ok, I see. It just needs to be a particular sequence of numbers, but should still be from 0 - 128.
With this and the other thread you have, I suspect you're just asking for just the numbers?
Like so:
// No idea what the seed is, it says that was given to you
Random r = new Random(seed);
// I'm lazy:
List<Number> intList = new LinkedList<Integer>();
Integer iTemp = null;
while (intList.size() < 127)
{
iTemp = new Integer(r.nextInt(128));
if (!intList.contains(iTemp))
{
// Not currently in the list
intList.add(iTemp);
}
}
Methinks you'll need to reverse that after as well, which is why I suggest a list.
List<Number> reverseIntList = Collections.Reverse(intList);
I doubt you'll need an actual array out of this, just use the list.get(index) method instead of the array[index].
uniquity
06-10-2009, 04:03 AM
i think your solution would have probably work, but we're not allowed to use the Collections class in our solution :rolleyes:
Fou-Lu
06-10-2009, 04:37 AM
Why not? I see you're using an arraylist in there, is there a reason you can't use the collection for the numbers? You can always just use an arrayList instead of a LinkedList.
If you're just meaning the static reverse, you can get around that by a standard reversal. LinkedList class itself will actually allow you to addFirst on it. That is the same as the reverse since you create a stack instead of a queue.
This sounds like an assignment now though, so I'm not sure how much more I can help before its no longer considered you're work.
uniquity
06-10-2009, 07:58 AM
yes this is for an assignment (last one for the quarter, bleh). if possible, i'm not asking for code snippets, but just for some pointers in the logic of the code and maybe some pointers on where i should start lookin to debug to fix this thing up.
heres some modified code of the same thing i have for you to look at:
/**
* This class will represent a Dictionary, with the ability to look up words and to write the
* the contents of the dictionary to a text file.
*
* @author Bryan Chan
* @version Program 8
* @version CPE102-01
* @version Spring 2009
*/
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Random;
import java.util.Iterator;
public class Dictionary implements Iterable<String>
{
//variables
private ArrayList<String> dictionary;
//constructor
public Dictionary( String fileName, boolean sorted ) throws java.io.FileNotFoundException
{
dictionary = new ArrayList<String>();
try
{
FileInputStream fis = new FileInputStream( fileName );
Scanner sc = new Scanner( fis );
while( sc.hasNextLine() )
{
dictionary.add( sc.nextLine() );
}
if( !sorted )
{
sort();
}
sc.close(); //close scanner
try
{
fis.close(); //close file
}
catch( java.io.IOException ioe )
{
System.out.println( "An IO Exception occurred." );
}
}
catch( java.io.FileNotFoundException fnfe )
{
System.out.println( "Invalid file name." );
}
} //end constructor Dictionary( fileName, sorted )
public Dictionary( String fileName, boolean sorted, long seed )
throws java.io.FileNotFoundException, java.io.IOException
{
dictionary = new ArrayList<String>();
String decryptWord = new String();
int ctr = 1;
int ctr2 = 0;
Random rand = new Random( seed );
int[] randArray = new int[128];
boolean alreadyExists = false;
randArray[0] = rand.nextInt( 128 );
while( ctr != 128 )
{
int temp = rand.nextInt( 128 );
for( ctr2 = 0; ctr2 < ctr; ctr2++ )
{
if( temp == randArray[ctr2] )
{
alreadyExists = true;
break;
}
else
{
alreadyExists = false;
}
}
if( !alreadyExists )
{
randArray[ctr] = temp;
}
// if( ctr2 != (ctr - 1) )
// {
// if( temp == randArray[ctr2] )
// {
// System.out.println( "Already found at index " + ctr2 + "." );
// break;
// }
// }
//
// else if( ctr2 == (ctr - 1) )
// {
// randArray[ctr] = temp;
// System.out.println( "Added #: " + randArray[ctr] );
// ctr++;
// }
// } //end for
} //end while
try
{
FileInputStream fis = new FileInputStream( fileName );
while( fis.available() != 0 )
{
int tempEncrypted = fis.read();
System.out.println( tempEncrypted );
for( int j = 0; j < randArray.length; j++ )
{
if( (char)tempEncrypted == '\n' )
{
dictionary.add( decryptWord );
System.out.println( "Word added to dictionary." );
}
else if( tempEncrypted == randArray[ctr] )
{
decryptWord += (char)randArray[tempEncrypted];
}
// if( temp == '\n' )
// {
// dictionary.add( decryptWord );
// System.out.println( decryptWord );
// }
// else if( randArray[j] == (int)temp )
// {
// decryptWord += (char)randArray[j];
// }
}
}
//String s += (char)randArray[ctr]????
if( !sorted )
{
int n = dictionary.size();
boolean swapped;
do
{
swapped = false;
n -= 1;
for( int i = 0; i <= n - 1; i++ )
{
if( dictionary.get( i ).compareTo( dictionary.get( i + 1 ) ) > 0 )
{
swap( i, i + 1 );
swapped = true;
}
}
}
while( swapped );
}
}
catch( java.io.FileNotFoundException fnfe )
{
System.out.println( "Invalid file name." );
}
} //end constructor Dictionary( fileName, sorted, seed )
//methods
public Iterator<String> iterator()
{
return dictionary.iterator();
}
public boolean lookUp( String word )
{
int low = 0;
int high = dictionary.size() - 1;
while( low < high )
{
int mid = ( low + high ) / 2;
if( ( dictionary.get( mid ).compareTo( word ) ) < 0 )
{
low = mid + 1;
}
else if( ( dictionary.get( mid ).compareTo( word ) ) > 0 )
{
high = mid - 1;
}
else
{
return true;
}
}
System.out.println( "Word not found." );
return false;
} //end method lookUp( word )
public void write( String fileName )// throws java.io.FileNotFoundException
{
try
{
FileOutputStream fos = new FileOutputStream( fileName );
ObjectOutputStream oos = new ObjectOutputStream( fos );
for( int ctr = 0; ctr < dictionary.size(); ctr++ )
{
oos.writeObject( dictionary.get( ctr ) );
}
}
catch( java.io.IOException ioe )
{
System.out.println( "An I/O error occurred." );
}
catch( java.lang.SecurityException se )
{
System.out.println( "An untrusted subclass is trying to override methods." );
}
catch( java.lang.NullPointerException npe )
{
System.out.println( "Cannot output 'null'." );
}
}
//sort method
private void sort()
{
int n = dictionary.size();
boolean swapped;
do
{
swapped = false;
n -= 1;
for( int i = 0; i <= n - 1; i++ )
{
if( dictionary.get( i ).compareTo( dictionary.get( i + 1 ) ) > 0 )
{
swap( i, i + 1 );
swapped = true;
}
}
}
while( swapped );
}
private void swap( int one, int two )
{
String temp = dictionary.get( one );
dictionary.set( one, dictionary.get( two ) );
dictionary.set( two, temp );
}
} //end class Dictionary
at this point, when a Dictionary with a seed is constructed, it seems the array never actually fills with 128 unique characters for some reason and I can't figure out why. any help would be appreciated.
uniquity
06-10-2009, 07:38 PM
problem solved...forgot to update ctr in while loop :rolleyes:
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.