Storing random values to an array - java

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

Related

I want to declare an empty array in java and then I want do update it but the code is not working

I want to declare an empty array in java and then I want do update it but the code is not working...
public class JavaConversion
{
public static void main(String args[])
{
int array[]={};
int number = 5, i = 0,j = 0;
while (i<4) {
array[i]=number;
i=i+1;
}
while (j<4) {
System.out.println(array[j]);
}
}
}
You are creating an array of zero length (no slots to put anything in)
int array[]={/*nothing in here = array with no elements*/};
and then trying to assign values to array elements (which you don't have, because there are no slots)
array[i] = number; //array[i] = element i in the array of length 0
You need to define a larger array to fit your needs
int array[] = new int[4]; //Create an array with 4 elements [0],[1],[2] and [3] each containing an int value
Your code compiles just fine. However, your array initialization line is wrong:
int array[]={};
What this does is declare an array with a size equal to the number of elements in the brackets. Since there is nothing in the brackets, you're saying the size of the array is 0 - this renders the array completely useless, since now it can't store anything.
Instead, you can either initialize the array right in your original line:
int array[] = { 5, 5, 5, 5 };
Or you can declare the size and then populate it:
int array[] = new int[4];
// ...while loop
If you don't know the size of the array ahead of time (for example, if you're reading a file and storing the contents), you should use an ArrayList instead, because that's an array that grows in size dynamically as more elements are added to it (in layman's terms).
You need to give the array a size:
public static void main(String args[])
{
int array[] = new int[4];
int number = 5, i = 0,j = 0;
while (i<4){
array[i]=number;
i=i+1;
}
while (j<4){
System.out.println(array[j]);
j++;
}
}
So the issue is in your array declaration you are declaring an empty array with the empty curly braces{} instead of an array that allows slots.
Roughly speaking, there can be three types of inputs:
int array[] = null; - Does not point to any memory locations so is a null arrau
int array[] = {} - which is sort of equivalent to int array[] = new int[0];
int array[] = new int[n] where n is some number indicating the number of
memory locations in the array
You can't set a number in an arbitrary place in the array without telling the array how big it needs to be. For your example: int[] array = new int[4];
You can do some thing like this,
Initialize with empty array and assign the values later
String importRt = "23:43 43:34";
if(null != importRt) {
importArray = Arrays.stream(importRt.split(" "))
.map(String::trim)
.toArray(String[]::new);
}
System.out.println(Arrays.toString(exportImportArray));
Hope it helps..
You can try creating new array at every iteration with a size greater than in the previous iteration.
i.e.
public class JavaConversion
{
public static void main(String args[])
{
int array[]=new int[0];
int number = 5, i = 0,j = 0;
while (i<4) {
array = Arrays.copyOf(array, array.length + 1);
array[i]=number;
i=i+1;
}
while (j<4) {
System.out.println(array[j]);
}
}
}
It is better for that operation use ArrayList

Resizing an Integer Array with Random Numbers

I'm trying to create an Integer[] that is increased by a multiple of 10 for each loop. Once the Integer[] size is set I'd like it to fill up the array with random ints. I'm able to get the size of the array to increase, but the values stored within it are null.
To me this means the array is resizing correctly, but they elements aren't being assigned to anything. I'm trying a double for-loop, with the inner loop assigning the random values. If there is a better way to do this(which I'm sure there is b/c mine isn't running!) could you please help?
this is my creation of the Int[]
public class TimeComplexity {
Integer[] data;
public TimeComplexity()
{
Random random = new Random();
for (int N = 1000; N <= 1000000; N *= 10)
{
N = random.nextInt(N);
data = new Integer[N];
//checking to see if the random numbers were added.
//array size is okay but locations aren't taking a
//random number
System.out.println(Arrays.toString(data));
}
}
In case you're interested in the output for it my main class. (this isn't part of the question but if you have suggestions I'd love them!)
public class TimeComplexityApp {
private static int MAXSIZE = 1000000;
private static int STARTSIZE = 1000;
public TimeComplexityApp()
{
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
TimeComplexity time = new TimeComplexity();
System.out.println(time);
System.out.printf("%-6s %13s %13s\n\n\n","ARRAY","int","INTEGER");
for (int N = STARTSIZE; N <= MAXSIZE; N *= 10)
{
double d = 1.0;
System.out.printf("\n%-6d %15.2f %15.2f\n", N, d, d);
}
}
}
In the first source code that shows lack initialize the elements of array of integers.
data = new Integer [N]; only creates the array of integers of size N, lack include the elements in each cell of the array.
So, just need a loop to complete each element or cell array:
for (int i = 0; i <N; i ++)
    data [i] = random.nextInt (N);
Now this array is complete and will not return NULL on each item.
On every iteration of your loop, you are creating a new array of random (int size) length. But you are never putting anything into it. The right way to do this is:
int[] vals = ...;
for (int i = 0; i < end - start; i++) {
if (vals.length < i; i++) {
//1. create new larger int[]
//2. copy the old array into the new array
//3. vals = yourNewArray
}
vals[i] = random.nextInt();
}

How do i input all the values from one array into random indexes of another array?

I cant figure out how to input all the money amounts,which is stored in the array (case_value), into the other array, (cases).I am trying to do this randomly. My program does run but never finishes. This is what i have so far. In case you couldn't guess, I am trying to copy the format of deal or no deal. Also, if there is any way to make my code more efficient, I would appreciate it. Thank you for the help.
import java.util.Scanner;
import java.lang.Math;
public class DOND
{
public static void main (String [] args)
{
Scanner sc = new Scanner (System.in);
int [] cases=new int [26]; //array for the cases
int [] case_value=new int [26]; //array for the money amounts
int b=0;
case_value[0]=1; // all the money amounts
case_value[1]=2;
case_value[2]=5;
case_value[3]=10;
case_value[4]=25;
case_value[5]=50;
case_value[6]=75;
case_value[7]=100;
case_value[8]=200;
case_value[9]=300;
case_value[10]=400;
case_value[11]=500;
case_value[12]=750;
case_value[13]=1000;
case_value[14]=5000;
case_value[15]=10000;
case_value[16]=25000;
case_value[17]=50000;
case_value[18]=75000;
case_value[19]=100000;
case_value[20]=200000;
case_value[21]=300000;
case_value[22]=400000;
case_value[23]=500000;
case_value[24]=750000;
case_value[25]=1000000;
for (int i=0;i<26;i++) //distributing the money
{
while (cases[b]==0); //checks if case is filled
{
int r=(int)(Math.random()*26); //randomizes money amounts in case
if (cases[r]==0)
{
b=r;
cases[r]=case_value[i]; //inserts money amount in case
}
}
}
for (int i=0;i<26;i++) //outputs value in cases
{
System.out.println(cases[i]);
}
}
}
If you just want the input shuffled, why not use the built in Collection.shuffle method?
// Fill up array with input
final List<Integer> list = new ArrayList<>(array.length);
for (int i = 0; i < array.length; i++) {
list.add(array[i]);
}
Collections.shuffle(list);
// Work with this shuffled list
Since you need to shuffle the contents in your array and need to store those in other array. I suggest you to use the below method.
Step1) Put data into one array.
Step2) shuffle the contents in that array.
Step3) for each item now add that into different array.
To shuffle the contents you can use.
// Implementing Fisher–Yates shuffle
static void shuffleArray(int[] ar)
{
Random rnd = new Random();
for (int i = ar.length - 1; i > 0; i--)
{
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
You can find this in Random shuffling of an array
Please don't duplicate questions. This is a possible duplicate.

Java - Using the output of one method in the statement body of another method is not producing the expected result

I have 2 classes, LotSelection and LotGen, in a package called lotterynumberselector. LotSelection has 2 methods: LotPool() and WinningSequence(). LotPool() is meant to return an ArrayList of 50 integers from 0 to 49 and scramble it. WinningSequence() is meant to create a 6-element array containing the first 6 integers from the ArrayList generated in LotPool().
This is the code for LotSelection.
package lotterynumberselector;
import java.util.ArrayList;
import java.util.Collections;
public class LotSelection {
ArrayList<Integer> LotPool() {
ArrayList<Integer> sequencedraw = new ArrayList<Integer>();
for(int i = 0; i < 49; i++) {
sequencedraw.add(i);
}
Collections.shuffle(sequencedraw);
return sequencedraw;
}
int[] WinningSequence() {
int[] WinningSequence = new int[6];
int j = 0;
while (j < 6) {
WinningSequence[j] = LotPool().get(j);
j++;
}
return WinningSequence;
}
}
The purpose of LotGen is to test if the outputs created by LotSelection were doing their expected tasks. However, the output from WinningSequence() didn't match the first six numbers created from LotPool() and I'm wondering why. I'm not sure if it's because the code in LotGen or LotSelection is creating an unexpected result. I suspect it's because LotPool() is producing one 50-element ArrayList and WinningSequence() is creating ANOTHER LotPool() so it's making it's array from a DIFFERENT 50-element ArrayList, but I'm not sure.
Here is the code for LotGen:
package lotterynumberselector;
import java.util.ArrayList;
import java.util.Arrays;
public class LotGen {
public static void main(String [] args) {
LotSelection a = new LotSelection();
ArrayList<Integer> LotPool = new ArrayList<Integer>();
LotPool = a.LotPool();
System.out.println(LotPool);
int[] WinSeq = new int[6];
WinSeq = a.WinningSequence();
System.out.println(Arrays.toString(WinSeq));
}
}
In your winning sequence method you call LotPool() method. LotPool creates a new ArrayList every time.
I would refactor your code to initialize the 50 integers in the constructor and never do it again. Make LotPool() a simple getter method to return the arraylist.
The reason for this is very simple: each time you pick a new number for the list returned by WinningSequence, you call LotPool again. You need to call it once, store the result in a variable, and use it again for each time through the loop.
The single argument version of Collections.shuffle will produce a different random sequence each time you call it. In order to get repeatable results, you need to pass in your own random generator, and handle seeding appropriately.
You could do it something like this, though as noted by the other posters, this is still horribly inefficient.
public class LotSelection {
ArrayList<Integer> LotPool(long seed) {
ArrayList<Integer> sequencedraw = new ArrayList<Integer>();
for(int i = 0; i < 49; i++) {
sequencedraw.add(i);
}
Collections.shuffle(sequencedraw, new Random(seed));
return sequencedraw;
}
int[] WinningSequence(long seed) {
int[] WinningSequence = new int[6];
int j = 0;
while (j < 6) {
WinningSequence[j] = LotPool(seed).get(j);
j++;
}
return WinningSequence;
}
}
Here is the problem in your WinningSequence method:
WinningSequence[j] = LotPool().get(j);
You are getting the list everytime you add to your array. This will cause only the first element of the list to be fetched. You need to do this out of your loop just once.
Here is how you can update your WinningSequence method:
int[] WinningSequence() {
int[] WinningSequence = new int[6];
int j = 0;
ArrayList<Integer> LotPool = LotPool().get(j)
while (j < 6) {
WinningSequence[j] = LotPool .get(j);
j++;
}
return WinningSequence;
}

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;

Categories

Resources