java problem
/*the program prints out a few random
nbrs between (1-9).
the program shoud not prints out the same nbr.
ex: 5-7-7-6-8-4-4-9 is wrong
5-7-1-6-8-4-2-9 is ok
my problem: first for loop prints out a random nbr(temp)
I try to compare temp with v[] elemnts if the temp and
an element av v[] are not the same, I put it into a new array s[];
but the program prints out just 0, 0,0......
*/
import java.util.Random;
class RandomNbr{
publicstaticvoid main(String[]args){
int k=10;
int []v=newint[k];
int []s=newint[k];
Random r =new Random( );
for(int i=0; i<k; i++)
{
int temp = r.nextInt(9)+1;
System.out.println("temp: "+temp);
for(int b=0; b><v.length; b++)
{
if(v[temp]!=v[b])
s[b]=temp;
}
}
for(int i=0; i><v.length; i++)
System.out.println(s[i]);
}
}
>
[1908 byte] By [
peter0001a] at [2007-11-26 13:35:56]

The contents of array "v" is never altered, so "v[temp]!=v[ b ]" will always be false as both elements will alway be 0.As a result, "s[ b ]=temp" is never executed.
The arrays v and s are both initialized to hold zeroes. You haven't loaded anything into either array yet.Do you mean to load the array with the random values between 1 and some maximum, with no zeroes?%
I want to put random nbrs in to an array and prints out an array witout repeating any nbr.
This does it. It's a slight refactoring of your code to make it more generic and move the work out of the main method.
package cruft;
import java.util.Random;
class RandomNbr
{
private static final int MAX_ELEMENTS = 10;
public static void main(String[] args)
{
int [] values = loadRandomArray(MAX_ELEMENTS);
for (int i = 0; i < values.length; i++)
{
System.out.print(values[i] + ",");
}
}
public static int [] loadRandomArray(int maxElements)
{
int [] values = new int[maxElements];
Random random = new Random();
for (int i = 0; i < maxElements; ++i)
{
System.out.println("setting value " + i);
int temp;
boolean notSet = true;
do
{
temp = random.nextInt(maxElements)+1;
if (!containsValue(values, temp))
{
values[i] = temp;
notSet = false;
}
} while (notSet);
}
return values;
}
public static boolean containsValue(int [] values, int value)
{
boolean hasValue = false;
for (int i = 0; i < values.length; i++)
{
if (values[i] == value)
{
hasValue = true;
break;
}
}
return hasValue;
}
}
This is the output I get from it:
C:\bea\jdk150_04\bin\java -Didea.launcher.port=7533 "-Didea.launcher.bin.path=C:\Program Files\JetBrains\IntelliJ IDEA 6.0.2\bin" -Dfile.encoding=windows-1252 -classpath "C:\bea\jdk150_04\jre\lib\charsets.jar;C:\bea\jdk150_04\jre\lib\deploy.jar;C:\bea\jdk150_04\jre\lib\jce.jar;C:\bea\jdk150_04\jre\lib\jsse.jar;C:\bea\jdk150_04\jre\lib\plugin.jar;C:\bea\jdk150_04\jre\lib\rt.jar;C:\bea\jdk150_04\jre\lib\ext\dnsns.jar;C:\bea\jdk150_04\jre\lib\ext\localedata.jar;C:\bea\jdk150_04\jre\lib\ext\sunjce_provider.jar;C:\bea\jdk150_04\jre\lib\ext\sunpkcs11.jar;C:\Documents and Settings\Michael\My Documents\Projects\Java\Forum\classes\test\Forum;C:\Documents and Settings\Michael\My Documents\Projects\Java\Forum\classes\production\Forum;C:\Documents and Settings\Michael\My Documents\Projects\Java\Forum\lib\activation.jar;C:\Documents and Settings\Michael\My Documents\Projects\Java\Forum\lib\hsqldb.jar;C:\Documents and Settings\Michael\My Documents\Projects\Java\Forum\lib\jdom.jar;C:\Documents and Settings\Michael\My Documents\Projects\Java\Forum\lib\junit-3.8.1.jar;C:\Documents and Settings\Michael\My Documents\Projects\Java\Forum\lib\mail.jar;C:\Documents and Settings\Michael\My Documents\Projects\Java\Forum\lib\mailapi.jar;C:\Documents and Settings\Michael\My Documents\Projects\Java\Forum\lib\mysql-connector-java-3.0.17-ga-bin.jar;C:\Documents and Settings\Michael\My Documents\Projects\Java\Forum\lib\ocrs12.jar;C:\Documents and Settings\Michael\My Documents\Projects\Java\Forum\lib\ojdbc14.jar;C:\Documents and Settings\Michael\My Documents\Projects\Java\Forum\lib\poi-2.0-final-20040126.jar;C:\Documents and Settings\Michael\My Documents\Projects\Java\Forum\lib\postgresql-8.1-404.jdbc3.jar;C:\Documents and Settings\Michael\My Documents\Projects\Java\Forum\lib\testng-4.7-jdk15.jar;C:\Tools\spring-framework-2.0\dist\spring.jar;C:\Tools\spring-framework-2.0\dist\spring-mock.jar;C:\Tools\spring-framework-2.0\dist\spring-aspects.jar;C:\Tools\hibernate-annotations-3.2.0.GA\hibernate-annotations.jar;C:\Tools\hibernate-annotations-3.2.0.GA\lib\ejb3-persistence.jar;C:\Tools\lucene-2.0.0\lucene-core-2.0.0.jar;C:\Documents and Settings\Michael\My Documents\Projects\Java\Forum\config;C:\bea\weblogic91\server\lib\weblogic.jar;C:\Program Files\JetBrains\IntelliJ IDEA 6.0.2\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMain cruft.RandomNbr
setting value 0
setting value 1
setting value 2
setting value 3
setting value 4
setting value 5
setting value 6
setting value 7
setting value 8
setting value 9
5,6,4,8,10,7,2,1,3,9,
Process finished with exit code 0
Study how I did it and ask questions.
%
hi !thank you very much for your help.
duffymo, I just feel the need to tell him that the
solution you provided is very prone to spin off into a
near-infinite loop especially as it fills in the elements
towards the end of the array. The checking for dups
can end up checking over and over again as it keeps
generating numbers which are already taken.
Why not just create an N-element List, fill it with
the numbers 1-N (or 0 to N-1, etc), and simply shuffle
it?
Hi u can use the following method. it gives u random numbers(equal to freq) between 0 an d n.
/**
* This method returns a an array of random numbers between 0(inclusive) and n(exclusive).
* @param n The bound on the random number to be returned. Must be positive.
* @param freq The number of random numbers needed.Must be less than n.
*/
public static final int[] multipleRandomGenerator(int n, int freq) throws Exception {
int[] randNumbers = new int[freq];
Random rand = new Random();
if(n == freq) {
throw new Exception("Frequency equal to bound");
}
for(int i=0;i<freq;i++) {
int temp = rand.nextInt(n);
boolean flag = false;
for(int j=i;j>=0;j--) {
if(randNumbers[j] == temp) {
flag = true;
}
}
if(flag == true) {
i--;
continue;
}else {
randNumbers = temp;
}
}
return randNumbers;
}//end of method
Message was edited by:
Nistelrooy
warnerja, you're spot on. I like your method far better than the one I posted.
I did a little time comparison:
shuffle took 4234 ms for 1 million repetitions
my way took 5515 ms for 1 million repetitions
The shuffle solution takes 76% of the time that my original solution does. This is an improvement that's not to be taken lightly. I think warnerja's solution is more elegant, too. Thanks so much for pointing out my faux pas.
Here's the code I used to compare. Just change the argument to the method call to switch between the two implementations.
Thanks, warnerja. Sincerely, %
package cruft;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
class RandomNbr
{
private static final int MAX_ELEMENTS = 10;
private static final int REPETITIONS = 1000000;
public static void main(String[] args)
{
int [] values = new int[MAX_ELEMENTS];
long totalTime = 0;
for (int m = 0; m < REPETITIONS; ++m)
{
long begTime = System.currentTimeMillis();
values = loadRandomArray(MAX_ELEMENTS);
long endTime = System.currentTimeMillis();
totalTime += (endTime-begTime);
}
for (int i = 0; i < values.length; i++)
{
System.out.print(values[i] + ",");
}
System.out.println();
System.out.println("total cpu time: " + totalTime + " ms");
}
public static int [] loadRandomArray(int maxElements)
{
int [] values = new int[maxElements];
Random random = new Random();
for (int i = 0; i < maxElements; ++i)
{
int temp;
boolean notSet = true;
do
{
temp = random.nextInt(maxElements)+1;
if (!containsValue(values, temp))
{
values[i] = temp;
notSet = false;
}
} while (notSet);
}
return values;
}
public static int [] loadRandomArray(int maxElements, boolean allowZero)
{
List<Integer> values = new ArrayList<Integer>(maxElements);
for (int i = 0; i < maxElements; ++i)
{
values.add(new Integer(i+1));
}
Collections.shuffle(values, new Random());
int [] valuesArray = new int[maxElements];
for (int i = 0; i < valuesArray.length; i++)
{
valuesArray[i] = values.get(i);
}
return valuesArray;
}
public static boolean containsValue(int [] values, int value)
{
boolean hasValue = false;
for (int i = 0; i < values.length; i++)
{
if (values[i] == value)
{
hasValue = true;
break;
}
}
return hasValue;
}
}
