Printing array elements at random until all elements have been printed - java

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;

Related

Operations on 1 Dimensional arrays

I am learning operations on 1 dim array.
It has three parts:
Set the 10 elements of integer array counts to zero.
Add one to each of the 15 elements of integer array bonus.
Display the five values of integer array best Scores in column format.
I have already figured out the 3. I need help in figuring out 1 and 2.
This is my code:
public class OneDimArrayOperations {
public static void main(String [] args){
// a) Set the 10 elements of integer array counts to zero.
int [] zeroArray = new int[10];
for (int i = 10; i == 0; i--) {
System.out.println("Count to zero from 10 elements" + zeroArray);
}
// b) Add one to each of the 15 elements of integer array bonus.
int [] arrayBonus = new int[15];
for (int i = 0; i <arrayBonus.length; i++) {
System.out.println("Bonus array values "+ arrayBonus[i]);
}
//c) Display the five values of integer array bestScores in column format.
int [] bestScores = {100,95,85,45,65};
System.out.printf("%n%s%12s %n", "Value", "BestScores");
for (int counter = 0; counter < bestScores.length ; counter++) {
System.out.printf( "%d%9d%n" , counter , bestScores[counter]);
}
}
}
part a:display:10,9,8,7,....1,0
for(int i=10;i>=0;i--)
part b:i havent understood your question
The line int[] zeroArray = new int[10]; will create an int array of size 10 and initialise all elements to zero. That's the default behaviour in Java.
for(int i = 0; i < arrayBonus.length; i++) { arrayBonus[i]++; } will solve your second problem.

How can I generate random numbers where each digit lies within a number range?

I am trying to figure out how to generate and store 10 random numbers in array where the numbers are two digit and each digit is in the range of 0-7. For example, 10, 23, 35, 77 are all ok, but not 1,78,89,99. And also, I want to make sure that all the numbers are unique. Here is what I have come up to so far...
import java.util.Random;
public class RandomNum{
public static void main(String[] args){
Random rand=new Random();
int[] randomFirstDigit=new int[10];
int[] randomSecondDigit=new int[10];
for(int i=0;i<10;i++){
randomFirstDigit[i]=rand.nextInt(7-1+1)+1;
}
for(int i=0;i<10;i++){
randomSecondDigit[i]=rand.nextInt(7-1+1)+0;
}
int[] randomArr=new int[10];
for(int i=0;i<10;i++){
randomArr[i]=(randomFirstDigit[i]*10)+randomSecondDigit[i];
}
for(int i=0;i<=randomArr.length;i++){
System.out.println(randomArr[i]);
}
}
}
The main issue with the above code is, sometimes, the array value is not unique. In other words, two identical numbers are stored in the array like 23,23.
Could any one please help me figure out the problem.
Thanks in advance for your help.
So the list of the possible numbers is [10, 11, 12, ..., 17, 20, ..., 76, 77] and it has a size of 7 * 8. What we need is 10 distinct random numbers that represent indices on that list, and then we can map the them to the actual numbers using i -> (i / 8 + 1) * 10 + (i % 8).
Here is a quite simple solution using ThreadLocalRandom.ints:
int[] array = ThreadLocalRandom.current()
.ints(0, 7 * 8)
.distinct()
.limit(10)
.map(i -> (i / 8 + 1) * 10 + (i % 8))
.toArray();
The simpler and less computationally expensive solution is to generate each digit one at a time, then append it to a String. You can convert it to an integer afterwards.
To generate exactly 10 unique numbers, we can add each number we generate to a HashSet, where every element must be unique. We can continue this until the HashSet has 10 elements.
import java.util.Random;
import java.util.Set;
import java.util.HashSet;
public class TwoDigitGenerator {
public static void main(String[] args) {
// Generate 10 unique random numbers with desired properties.
Set<Integer> usedNumbers = new HashSet<>();
while (usedNumbers.size() < 10)
usedNumbers.add(randomNumber());
// Convert the set of numbers to an Integer array.
Integer[] numbers = usedNumbers.toArray(new Integer[usedNumbers.size()]);
for (Integer number : numbers)
System.out.println(number);
}
public static int randomNumber() {
Random random = new Random();
String number = "";
number += 1 + random.nextInt(7); // Generate first digit between 1 and 7 inclusively
number += random.nextInt(8); // Generate second digit between 0 and 7 inclusively
return Integer.parseInt(number);
}
}
please you should loop the array again and check whether its already existing or not. this is not the best solution because some of codes are redundant but to give you some hint on how you proccess it.
import java.util.Random;
public class RandomNum{
public static void main(String[] args){
Random rand=new Random();
int[] randomFirstDigit=new int[10];
int[] randomSecondDigit=new int[10];
for(int i=0;i<10;i++){
int gen = rand.nextInt(7-1+1)+1;
Boolean flag = false;
for(int j=0; j < 10; j++)
if(randomFirstDigit[j] == gen)
flag = true
if(!flag) randomFirstDigit[i] = gen;
}
for(int i=0;i<10;i++){
int gen = rand.nextInt(7-1+1)+0;
Boolean flag = false;
for(int j=0; j < 10; j++)
if(randomSecondDigit[j] == gen)
flag = true;
if(!flag) randomSecondDigit[i] = gen;
}
int[] randomArr=new int[10];
for(int i=0;i<10;i++){
randomArr[i]=(randomFirstDigit[i]*10)+randomSecondDigit[i];
}
for(int i=0;i<=randomArr.length;i++){
System.out.println(randomArr[i]);
}
}
}

Storing random values to an array

Revised question:
I want the even elements of my array to be stored in a corresponding array. My if else statements do that. Since there will always be a varying number of evens and odds each run, I want the size of the evenArray and oddArray to adjust with each iteration of my while loop. I get an error when compiling that says I'm not doing that part right.
import java.util.Arrays;
import java.util.Random;
public class randomdemo {
public static int[] randommethod()
{
int i = 0;
int[] myArray;
myArray = new int[100];
int[] evenArray;
int[] oddArray;
while(i<=99)
{
Random rand = new Random();
int n = rand.nextInt(25) + 0;
myArray[i] = n;
if(myArray[i] % 2 == 0)
{
evenArray = new int[i];
evenArray[i] = n;
}
else
{
oddArray = new int[i];
oddArray[i] = n;
}
i++;
}
return myArray;
}
public static void main(String args[])
{
int[] result = randommethod();
System.out.println(Arrays.toString(result));
randommethod();
}
}
Store the result, and maybe print it. Your could use a loop or Arrays.toString(int[]). Something like,
int[] result = randommethod();
System.out.println(Arrays.toString(result));
When I put both lines in main() and use your posted randommethod() it appears to work.
The returned array is not being used.
So the return from randommethod() is an int[] but the main method does not print it (or use it in any way).
Here is one way to use it:
int[] outputRandomAry = randommethod();
for (int elem : outputRandomAry) {
System.out.print(elem + ", ");
}
System.out.println();
Also you might want to put the Random rand = new Random(); //using the random class outside the while loop. This prevents unnecessary spinning off new objects for each rand.
And you can use int n = rand.nextInt(26); for 0(inclusive) to 26(exclusive) gives you the desired range.
If you just want to print out the array without storing, write this in the main.
100% it will work.
System.out.println(Arrays.toString(randommethod())); //print array
At this line, you returned the vaule:
return myArray; //returns the array
But you did not store it anywhere. So the return value is lost. Even though you did all the work in the method.
Store your return array as follows in the main
int[] myArray = randommethod(); //store returned value (from method)
After that, you can do anything you want with the returned array.
Other than the things mentioned by other user, if I were you, I will write your method this way:
public static int[] randommethod() //declaring method
{
Random rnd = new Random(); //using the random class
int[] myArray = new int[100]; //create and initializing array in 1 line
for(int x=0; x<myArray.length; x++) //Normally use for-loop when you know how many times to iterate
myArray[x] = rnd.nextInt(26); //0-25 has 26 possibilities, so just write 26 here
return myArray; //returns the array
}
It will do exactly the same thing, I am editing this from your original codes.
In the main..
public static void main (String[] args)
{
int[] myArray = randommethod();
}
If you want a random int between 0 and 25 inclusive, then your code should be:
int n = rand.nextInt(26); //I want a random int between 0 and 25 inclusive

Generate 10 Random Integers storing them in an Array and then calling a Method to display the Array

so i need to generate 10 random integers in the range 1-20 but i have to store them in an array
called numbers. Then I have to call a method called displayArray which displays the contents of the
array and for the assignment i have to use a for loop to traverse the array.
The method header for the displayArray method is:
public static void displayArray(int[] array)
This is what I have done
public class RandomIntegers {
static int numbers = 0;
public static void displayArray(int[] array) {
System.out.println(numbers + "Numbers Generated");
}
}//end class
and
public class Random_Integers{
public static void main(String[] args) {
RandomIntegers[] numbers = new RandomIntegers[10];
//Generates 10 Random Numbers in the range 1 -20
for(int i = 0; i < numbers.length; i++) {
numbers[i] = (int)(Math.random() * 20);
RandomIntegers Numbers = new RandomIntegers();
numbers[i] = Numbers;
}//end for loop
for (int i = 0; i < numbers.length; i++) {
numbers Numbers = numbers[i];
Numbers[i].displayArray;
System.out.println();
}//end for loop
}//end main method
}//end class
An error appears on the lines
Type mismatch cannot convert from int to RnadomIntegers
numbers[i] = (int)(Math.random() * 20);
numbers cannot be resolved to a type
numbers Numbers = numbers[i];
Syntax error enter 'AssignmentOperator Expression' to complete expression
Numbers[i].displayArray;
I realize I need to assign an instance of the RandomIntegers class to the slot in the array to fix the first problem but i don't know how, could someone show me how do to so
and i don't know how to fix the other 2 problems i'm only learning how to use java so could someone please guide me in the right direction
You only have to use a single for loop - like this:
public static void main(String[] args)
{
int[] numbers = new int[10];
//Generates 10 Random Numbers in the range 1 -20
for(int i = 0; i < numbers.length; i++) {
numbers[i] = (int)(Math.random()*20 + 1);
}//end for loop
System.out.println("Numbers Generated: " + Arrays.toString(numbers));
}
To generate a random integer, you're best off using this:
Random rand = new Random();
numbers[i] = rand.nextInt(20)+1;
The rand.nextInt(20) call will give a random number from 0 to 19, so adding 1 makes it from 1 to 20.
In practice, you don't need to create a new Random() every time; you'd put this
Random rand = new Random();
at the beginning of your loop, and then
numbers[i] = rand.nextInt(20)+1;
inside it.
Since you've got several errors, I'd suggest you start again, write your code bit by bit, and check at each stage that it compiles and does what you want. For instance, start by printing a single random number out, and check that that works.
you have created an array of type RandomIntegers use this it will work int[] numbers = new int[10];
there is no problem with the code
From Java 8 onwards you can use following:
public static void main(String[] args) {
int[] numbers = new Random().ints(1, 21).limit(10).toArray();
System.out.println("Numbers generated: " + Arrays.toString(numbers));
}
Output:
Numbers generated: [4, 14, 8, 14, 19, 16, 13, 2, 3, 1]
Here in ints(randomNumberOrigin, randomNumberBound) randomNumberOrigin is inclusive and randomNumberBound is exclusive. So you might want to increase randomNumberBound number by 1.

Generating random numbers with identical pairs between 1 to 8?

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 ^_^

Categories

Resources