Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

number distribution  RSS feed

 
seema pal
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i have a one problem
if i have a 6 numbers and i want to distribute it in randomly 2 numbers(like 1 2,3 4,5 6)
means
first =1,2
second =3,4
third=5,6
plz give reply with some example
 
Campbell Ritchie
Marshal
Posts: 55717
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Put the numbers into an array (or better still, an ArrayList as Integer objects).
Use an object of the java.util.Random class to get an int between 0 and count.
Remove your number with each random digit. That is why an ArrayList is better; evry time you remove an element its count gets smaller.

And BTW: only use one single Random object in your code. You can get the same number repeated if you create 2 Random objects at the same time.
 
Christian Nash
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, Hope this helps


Random randomValue=new Random();

ArrayList randomNumbersList= new ArrayList();//this ArrayList hols the 6 random numbers which u want
randomNumbersList.clear();//first clear (optional)
int countOfNumbers=6;
do{
if(randomNumbersList.isEmpty()){
randomNumbersList.add(new Integer(randomValue.nextInt(6)));//gets a random integer value between 0 and 6
}
else{
int randCheck=randomValue.nextInt(6);
if(!(randomNumbersList.contains(new Integer(randCheck)))){//check if arraylist already contains the random value
randomNumbersList.add(new Integer(randCheck));
}
}


}while(randomNumbersList.size()<countOfNumbers);


ArrayList oneTwoThree = new ArrayList();// this arraylist contains your pair of values
for(int i=0;i<randomNumbersList.size()/2;i++){
String first=randomNumbersList.get(i).toString()+","+randomNumbersList.get(i+1).toString();
oneTwoThree.add(first);
System.out.println("OneTwoThreeValue[" + i+ "]= " +oneTwoThree.get(i));
}


[ June 23, 2006: Message edited by: Christian Nash ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!