Generating random numbers with identical pairs between 1 to 8? - java

Like my question, i need to generate random numbers that have identical pairs between a range. i have tried to generate random numbers and stored in an array but the numbers are repeating more than twice. i have 16 random numbers to be generated in the range. Any idea how to make it generate only identical pairs random number?

The following will do the job I think :
import java.util.*;
class Randoms {
public static void main(String[] args) {
List<Integer> randoms = new ArrayList<Integer>();
Random randomizer = new Random();
for(int i = 0; i < 8; ) {
int r = randomizer.nextInt(8) + 1;
if(!randoms.contains(r)) {
randoms.add(r);
++i;
}
}
List<Integer> clonedList = new ArrayList<Integer>();
clonedList.addAll(randoms);
Collections.shuffle(clonedList);
int[][] cards = new int[8][];
for(int i = 0; i < 8; ++i) {
cards[i] = new int[]{ randoms.get(i), clonedList.get(i) };
}
for(int i = 0; i < 8; ++i) {
System.out.println(cards[i][0] + " " + cards[i][1]);
}
}
}
One sample run of the above gives :
1 2
8 6
4 3
3 7
2 8
6 1
5 5
7 4
Hope that helps.

Generally, if you put the numbers you wish to generate in an array (in your case, an array of length 16 with two each of 1, 2, ..., 8), then randomly permute the array, you will get what you want. You can randomly permute the array using code here.

I believe this clearly shows you how to approach the problem:
public static List<Integer> shuffled8() {
List<Integer> list = new ArrayList<Integer>();
for (int i = 1; i <= 8; i++) {
list.add(i);
}
Collections.shuffle(list);
return list;
}
public static void main(String[] args) {
List<Integer> first = shuffled8();
List<Integer> second= shuffled8();
for (int i = 0; i < 8; i++) {
System.out.println(first.get(i) + " " + second.get(i));
}
}
shuffled8 simply returns a list of numbers 1 to 8 shuffled. Since you need two of such lists, you invoke it twice, and store it in first and second. You then pair first.get(i) with second.get(i) to get the properties that you want.
To generalize this, if you need triplets, then you just add List<Integer> third = shuffled8();, and then first.get(i), second.get(i), third.get(i) is a triplet that has the properties that you want.

I have made this way :
Random random = new Random();
List<Integer> listaCartoes = new ArrayList<Integer>();
for(int i=0; i<8;)
{
int r = random.nextInt(8) + 1;
if(!listaCartoes.contains(r))
{
listaCartoes.add(r);
listaCartoes.add(r);
++i;
}
}
Collections.shuffle(listaCartoes);
Hope it helps ^_^

Related

Duplicate entries while generating Random number [duplicate]

This question already has answers here:
Generating Unique Random Numbers in Java
(21 answers)
Closed 11 months ago.
With the below code if we try to generate random numbers from 1 to 10, I some times get duplicate values.
Below code should generate 5 unique values for random numbers between 1 to 10.
When I print the array it happens uniqueness is not guaranteed. Output was 2,1,9,10,2.
2 was repeated in this case.
Random random = new Random(System.currentTimeMillis());
random.setSeed(System.currentTimeMillis());
int[] myUniqueValues = new int[5];
for (int i = 0; i < 5; i++) {
myUniqueValues[i] = random.nextInt(10) + 1;
}
return myUniqueValues;
One way of doing this would be to create a list and pick randoms from it:
Random r = new Random();
ArrayList<Integer> list = new ArrayList<Integer>();
for(int i=0: i<10; i++){
list.add(i);
}
private int getUniqueRandom(){
int index = r.nextInt(list.size());
int number = list.get(index);
list.remove(index); // Check that it removes the Index not the value from list
return number;
}
Another way if you have a lot of numbers and dont want to store them in memory
Random r = new Random();
ArrayList<Integer> list = new ArrayList<Integer>();
for(int i=0; i<5; i++){
do{
int number = r.nextInt(10);
}while(!list.contains(number))
list.add(number);
}
The way with Set as suggested by steven7mwesigwa
This works because Sets can only contain unique values
Random r = new Random();
HashSet<Integer> list = new HashSet<Integer>();
while (list.size() < 5) {
list.add(r.nextInt(10));
}
A one liner from https://stackoverflow.com/a/31656679/11355399
int[] array = ThreadLocalRandom.current().ints(0, 10).distinct().limit(5).toArray();
We can use Set Collection here to remove duplicates inside loop itself. Set has method called contains which will check weather output of random function is already present in our result set or not. if it is present we can skip that iteration. if not we can random to our result set. please check below snippet.
Random random = new Random(System.currentTimeMillis());
random.setSeed(System.currentTimeMillis());
Set<Integer> myUniqueValues2 = new HashSet<>();
int k=0;
while(k<5) {
int test = random.nextInt(10) + 1;
if(!myUniqueValues2.contains(test)) {
myUniqueValues2.add(test);
k++;
}
}
for(int i: myUniqueValues2)
System.out.println(i+" ");

Generating random Numbers , but it must be Generated with Unique numbers without replications

int[] drawNumbers = new int[10];//Array With 10 Random Numbers USED for DRAWN NUMBERS
String x = "Drawn Numbers: ";
List<Ticket> ticketWon ;
do{
//GENERATING 10 Random Numbers
for (int i = 0; i <= drawNumbers.length -1 ; i++) {
Random r = new Random();
drawNumbers[i] = r.nextInt(99) + 1;
x += drawNumbers[i] + " ";
}
}
I'm trying to generate 10 random numbers that must be random generated and Unique. My problem is that with Random r = new Random() there are times that replicated numbers are shown. How can i generate 10 random numbers from range 1 to 99 without replications?
Problem is for a Lottery System
I would like to use Collection.Shuffle but I'm not that sure how it should be implemented.
Here is an alternative way to achieve your desired result. We populate a list with values 1 to 99. Then we shuffle the list and grab the first 10 values:
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i=1; i<100; i++) {
list.add(new Integer(i));
}
Collections.shuffle(list);
for (int i=0; i<10; i++) {
System.out.println(list.get(i));
}
}
You won't have to import/directly deal with Random, which is a plus. However, as pointed out by #Voicu (in the comments), shuffle does indeed utilize random:
public static void shuffle(List<?> list) {
if (r == null) {
r = new Random();
}
shuffle(list, r);
}
private static Random r;
You can broadly think of this problem as having a deck of cards numbered from 1 to 99, and you want to pick 10 of those cards. The solution would be to, programmatically, create that deck and then randomly select from that deck and remove from the deck.
We can model the deck as a List of Integers and populate that List with entries from 1 to 99 with something like this:
List<Integer> deck = new ArrayList<Integer>();
for( int i=1; i<=99; i++ ){
deck.add( i );
}
We then need to pick a random card between the 0th card (lists are numbered starting at 0) and the number of elements in the list:
int draw = r.nextRandom( deck.size() );
Integer card = deck.remove( draw );
And repeat that 10 times, doing something with the "card" (say, putting it into an array, or another list, or whatever:
int drawNumbers = new int[10];
for( int co=0; co<10; co++ ){
int draw = r.nextRandom( deck.size() );
Integer card = deck.remove( draw );
drawNumbers[co] = card;
}
Use Set<Integer>.
Set<Integer> set = new HashSet<Integer>();
int[] drawNumbers = new int[10];
Random r = new Random();
for(int i=0; i<10; i++)
{
drawNumbers[i] = r.nextInt(99) + 1;
while(set.contains(drawNumbers[i]))
drawNumbers[i] = r.nextInt(99) + 1;
set.add(drawNumbers[i]);
}
I'd generate random numbers and save them to a Set until I get 10 numbers. Then create a list from it, shuffle it, and then take numbers from it.
final int NUMBERS_TO_DRAW = 10;
Random r = new Random();
// Generate NUMBERS_TO_DRAW random numbers
Set<Integer> randoms = new HashSet<>();
while (randoms.size() < NUMBERS_TO_DRAW) {
randoms.add(r.nextInt(99) + 1);
}
// Now shuffle them:
List<Integer> shuffledRandom = new ArrayList<>(randoms);
Collections.shuffle(shuffledRandom);
EDIT:
As #MarkPeters noted in the comments, using a LinkedHashSet would eliminate the need to shuffle:
final int NUMBERS_TO_DRAW = 10;
Random r = new Random();
// Generate NUMBERS_TO_DRAW random numbers
LinkedHashSet<Integer> randoms = new LinkedHashSet<>();
while (randoms.size() < NUMBERS_TO_DRAW) {
randoms.add(r.nextInt(99) + 1);
}
It would be easier to use a list so you could check if it already contains the number and re-generate if it does.
List<Integer> drawNumbers = new ArrayList<Integer>();
Random r = new Random();
int newNumber = -1;
do
{
newNumber = r.nextInt(99) + 1;
} while(drawNumbers.contains(newNumber); //Make sure the number is not already in the list.
Then put this in a loop to repeat 10 times.

don't random number that are being random before

I know how to random number using java Random class.
This will random a number between 0-13 13 times;
public static void main(String[] args) {
int ctr = 13;
int randomNum = 0;
while(ctr != 0) {
Random r = new Random();
randomNum = r.nextInt(13);
ctr--;
System.out.println(ctr +": " + randomNum);
}
}
Question
-I would like to random a number between 0-13 for 13 times
-If the first random number is e.g(5),then my second random number will random any number from 0-13 again EXCLUDING 5;
If the second random number is e.g(4),then my third random number will random any number from 0-13 again EXCLUDING 5 and 4;
etc..
is there a way to do it?
Do this:
Create a List of size 13
Fill it with numbers 0-12
Shuffle the List using the JDK Collections utility method
Use the numbers in the shuffled order (by just iterating over the List)
In code:
List<Integer> nums = new ArrayList<Integer>();
for (int i = 0; i < 13; i++)
nums.add(i);
Collections.shuffle(nums);
for (int randomNum : nums)
System.out.println(randomNum); // use the random numbers
I'd fill a list, shuffle it, and then iterate it, guaranteeing a different number each time:
public static void main(String[] args) {
int ctr = 13;
List<Integer> list = new ArrayList<>(ctr);
for (int i = 0; i < ctr; ++i) {
list.add(i);
}
Collections.shuffle(list);
for (int i = 0; i < ctr; ++i) {
System.out.println(ctr + ": " + list.get(i));
}
}
Question -I would like to random a number between 0-13 for 13 times
I would start with a List and Collections.shuffle(List) and a Random with something like -
Random rand = new Random();
List<Integer> al = new ArrayList<>();
for (int i = 0; i < 14; i++) {
al.add(i);
}
Collections.shuffle(al, rand);
System.out.println(al);
Or, if using Java 8+, an IntStream.range(int, int) to generate the List. And you could use a forEachOrdered to display (and in either version, you cold use the Collections.shuffle with an implicit random) like
List<Integer> al = IntStream.range(0, 13).boxed().collect(Collectors.toList());
Collections.shuffle(al);
al.stream().forEachOrdered(System.out::println);
The answers recommending shuffle show the right way, as it is elegant and fast.
Just for the sake of completeness: you can also slightly alter your code. Add any random number found to an array. Then check the next random number if it is already in the array. If yes, drop the number and get a new one. Do this until the array is filled with 13 numbers.
Like this:
List<Integer> numbers = new ArrayList<Integer>();
Random r = new Random();
while (numbers.size() < 14) {
randomNum = r.nextInt(13);
if (!numbers.contains(randomNum)) {
numbers.add(randomNum);
}
}
you can use Set to avoid having duplicate
Code:
Set<Integer> set1 = new LinkedHashSet<>();
int ctr = 13;
int randomNum = 0;
while (ctr == 13) {
Random r = new Random();
randomNum = r.nextInt(13);
set1.add(randomNum);
System.out.print(randomNum + " ");
if (set1.size() >= 13) {
ctr = 12;
}
}
System.out.println("");
set1.forEach(i -> System.out.print(" " + i));
output:
4 11 11 11 5 1 9 12 5 7 5 2 9 10 1 7 10 3 11 8 9 3 12 9 2 6 7 10 12 3 11 1 10 3 6 2 0
4 11 5 1 9 12 7 2 10 3 8 6 0
ArrayList<Integer> nums = new ArrayList<Integer>();
Random generator = new Random();
for (int i = 0; i < 14; i++) {
nums.add(i);
}
for (int i = 0; i < 14; i++) {
int size = nums.size();
int chosen = generator.nextInt(size);
System.out.println(nums.get(chosen) + " ");
nums.remove(chosen);
}

Printing array elements at random until all elements have been printed

I'm trying to create a method that takes in 3 int arrays and prints out one element from each array until all the elements of all three arrays have been printed at least once. The first array has 10 elements, the second has 7, and the third has 2. The elements are selected and printed at random. Any help would be appreciated. The idea is to see how many iterations it would take to print out all the elements at least once. I don't know the conditions to set for
a large scale iteration like this. My code so far (with just one array as a parameter):
import java.util.*;
public class calculateAverage{
private static int[] x = new int[]{1,2,3,4,5,6,7,8,9,10};
private static int[] y = new int[]{1,2,3,4,5,6,7};
private static int[] z = new int[]{1,2};
public static void main(String[] args){
calculate(x);
}
public static void calculate(int a[]){
Random random = new Random();
for(int i = 0;i < a.length; i++){
System.out.print(a[random.nextInt(a.length)] + " ");
}
System.out.println();
}
}
code output:
7 2 4 1 8 10 3 10 7 3
Solution for one array:
public static int calculate(int a[]){
Random random = new Random();
HashSet<Integer> remaining = new HashSet<Integer>();
for (int i = 0; i < a.length; i++) {
remaining.add(i);
}
int i = 0;
while (!remaining.isEmpty()) {
int index = random.nextInt(a.length);
System.out.print(a[index] + " ");
remaining.remove(index);
i++;
}
System.out.println();
System.out.println("Finished after " + i + " iterations.");
return i;
}
You could use a collection like Set to keep track of indexes that were already picked. Each time you generate a random number you would first check if it already exist in the Set. If not, print the value in array and add the index number to the set.
Your loop would end when size of that set equals size of the array.
int a[] = {4, 6, 3, 2, 9, 1, 5};
Set<Integer> set = new TreeSet<Integer>();
int counter = 0;
Random rand = new Random();
while(set.size() != a.length){
set.add(a[rand.nextInt(a.length)]);
counter ++;
}
System.out.println("Total Iterations : "+counter);
return counter;

How to return 5 random "Powerball" numbers in Java

Trying to return 5 random numbers between 1 and 42 in Java.
I currently have logic to return a single number (putting it into an ArrayList, but I'd like to do away with that.) I'm stumped on implementation to return 5 random numbers. Would I need 5 for loops?
for (int i = 0; i < 10; i++) {
int r = (int) (Math.random() * 42 + 1);
}
I've seen some other related examples here and they seem more complex than what my needs dictate. However, I could be wrong.
Simply place each random number into an array and return the array...
public int[] powerBalls() {
int[] balls = new int[5];
for (int index = 0; index < 5; index++) {
balls[index] = (int) (Math.random() * 42) + 1;
}
return balls;
}
You can use the Set to generate 5 Unique Random numbers.
Random random = new Random();
Set randomNumbers = new HashSet<Integer>();
while(randomNumbers.size()< 5) {
randomNumbers.add(random.nextInt(42)+1);
}
Since you've mentioned that you're using an ArrayList which will hold all the random numbers, you could just add all the elements present in randomNumbers set to your ArrayList.
Update:-
To suit your needs, you need to do something like this:-
Random random = new Random();
Set<String> set = new HashSet<String>();
while(set.size()< 5) {
set.add(String.valueOf(random.nextInt(42)+1));
}
fortuneList3.addAll(set);
Be careful! Each number can be taken only one time. With your solution it is possible to get same number more than one time.
Other solution (and here you can't have same numer more than one time) is to create array with all numbers, shuffle it and take first 5:
public int[] powerBalls() {
// create array with all numbers
List<Integer> balls = new ArrayList<Integer>(42);
for (int i = 1; i <= 42; i++)
balls.add(i);
// shuffle
Collections.shuffle(balls);
// take first 5
int[] result = new int[5];
for (int i = 0; i < 5; i++)
result[i] = balls.get(i);
return result;
}
Try it like this:
IntArray = new int[5]; //Create an array
for (int i = 0; i < 5; i++) {
IntArray[i] = (int) (Math.random() * 42 + 1);
}
Store the numbers in array and return that array.
int []randArray;
randArray = new int[5];
for (int i = 0; i < 5; i++) { //for 5 random numbers
randArray[i] = (int) (Math.random() * 42 + 1);
}
//now return this array "randArray"
It's a straight forward approach.
List<Integer> generated = new ArrayList<Integer>();
for (int i = 0; i < 5; i++)
{
while(true)
{
int r = (int) (Math.random() * 42 + 1);
if (!generated.contains(r))
{
generated.add(r);
break;
}
}
}
Just throwing my 2 cents in. I recently made a jQuery Plugin, appropriately named "Powerball". I'll share with ya the formula i'm using as well as link ya my plugin. Not sure why anyone would really need this. I did it just for fun! LoL!
The Function
function getNumbers() {
var a=[]; // array to return
for(i=1;5>=i;i++){ // for loop to get first 5 numbers
var b = Math.floor(Math.random()*59)+1; // set #
while (a.indexOf(b) > -1) { b = Math.floor(Math.random()*59)+1; } // reset # if already used
a.push(b); // add number to array
}
a.push(Math.floor(35*Math.random())+1); // add ball 6 number
return a; // 0 index array will have a length of 6, [0-4] being whiteball numbers, [5] being the red ball
}
The Plugin
jsFiddle
Contains the plugin between comment lines
Shows example use
Use is as easy as $("element").powerball(). However, only one method exist for it at the moment, $("element").powerball("setNumbers"). That method simply resets the numbers shown in the p tags.
Style: a note!
All styling is done through a style tag added to the header upon initialization. This means there's no need for extra files to add, but it also gives the ease of custom styling. See more about styling in the jsFiddle!

Categories

Resources