Working on building an array that can generate random integer values inside an array. It prints the random numbers but it prints it like this
[10][2][5][7][6][2][4][7][2][10][0]--->(down the side)--------> and want it to print like this [10,7,5,9,4,3,4,7,2,3] (one line).
public class ArrayLab
{
//array instance variable
private int[] array1 = new int[10];
//array constructor
public ArrayLab(int integer)
{
//class parameter = 10
int[] array1 = new int[]{integer};
}
public void initialize()
{
//allow randomization of numbers inside the array field.
System.out.println(Arrays.toString(array1));
//prints [0,0,0,0,0,0,0,0,0,0] which is ok
System.out.println();
for (int iteration = 0; iteration < array1.length; iteration ++)
{
Random number = new Random();
number.nextInt(10);
int n = number.nextInt(11);
int[] array1 = new int[]{n};
System.out.println(Arrays.toString(array1));
//prints down the side. Want on one line?
}
}
}
Just change
System.out.println(Arrays.toString(array1));
//new output
System.out.print(Arrays.toString(array1));
another way you can get this done is by using a for loop to iterate through the array in similar fashion
for( int i = 0; i < array1.length; i++ ){
System.out.print(array1[i]+" ");
}
for the random numbers
Random ran = new Random();
for( int i = 0; i < array1.length; i++ ){
int number = ran.nextInt((max - min) + 1) + min;
//insert the maximum and min values for your generator
array1[i] = number;
Related
I'm looking to create a dynamic amount of arrays of random integers and then put them into an array list. Later I want to use each of these arrays separately to test for quick sort functionality. I'm having problems with adding the object List[] into the ArrayList.
//Create dynamic amount of random arrays
public static ArrayList<int[]> Randomizer(int arrays, int size, int seed){
ArrayList<int[]> Tests = new ArrayList<int[]>(arrays);
int[] List = new int[size];
for (int j = 0; j < arrays; j++){
Random r = new Random(seed+j);
for(int i = 0; i < size; i++){
List[i] = r.nextInt(5*size);//Multiplier for how big the numbers get
System.out.print(List[i] + ",");
}
System.out.println();
Tests.add(j, List);
}
return Tests;
}
public static void main(String[] args) {
int tests = 5;
int size = 4;
ArrayList<int[]> Test = Randomizer(tests,size,10); //1st = Number of Tests
//2nd = Number of Digits
//3rd = seed for Randomizer
for(int i = 0; i < Test.size(); i++){
System.out.println(Test.get(i));
}
}
}
The problem with your code was that you were storing the same array 5 times into the ArrayList, so when printing during generation it printed correct numbers, but later you couldn't get them out. Each iteration of the for loop was overwriting the values generated earlier.
Here is the corrected code:
private static ArrayList<int[]> randomizer(int arrays, int size, int seed){
ArrayList<int[]> tests = new ArrayList<>(arrays);
for (int j = 0; j < arrays; j++) {
int[] list = new int[size];
Random r = new Random(seed + j);
for(int i = 0; i < size; i++) {
list[i] = r.nextInt(5 * size); // Multiplier for how big the numbers get
}
tests.add(j, list);
}
return tests;
}
public static void main(String[] args) {
int tests = 5;
int size = 4;
ArrayList<int[]> arrays = randomizer(tests, size, 10);
for (int i = 0; i < arrays.size(); i++){
int[] ints = arrays.get(i);
for (int j = 0; j < ints.length; j++) {
System.out.print(ints[j] + ",");
}
System.out.println();
}
}
Basically you needed to move the int[] list = new int[size]; line inside the for loop, so that you are actually creating new arrays instead of using the same one each time.
You can now replace the printing loop in the main() method with whatever you like, like your quick sort tests. Let me know if anything still doesn't work.
I'm building a class that takes an array of numbers and has methods to output their min, max and average values as a string representation of the numbers. Here's my constructor for the class:
public RandomArray(int sizeOfArray)/*Constructor: gets array size and populates array with
random numbers*/
{
Random generator = new Random();
size = sizeOfArray;
for (int i = 0;i < size;i++)
{
numbers[i] = generator.nextInt(size + 1);
}
}
I'm getting the array out of bounds exception message when I test this class with a driver program and this constructor is the one causing it. I'm not able to understand how I'm going beyond the size of the array here. Please help! Thanks.
Edit - So just to clear up any confusion I'm posting the entire class below for reference:
public class RandomArray
{
/*A class that contains an array of random numbers and methods that output
the numbers' minimum, maximum and average values. Also includes a method
that outputs a string representation of the numbers.*/
int size, min, max;
String array;
int[] numbers = new int[size];
public RandomArray(int sizeOfArray)/*Constructor: gets array size and populates array with
random numbers*/
{
Random generator = new Random();
size = sizeOfArray;
for (int i = 0;i < size;i++)
{
numbers[i] = generator.nextInt(size + 1);
}
}
public int min_value()
{
for (int i = 0;i < size - 1;i++)
{
min = numbers[i];
for (int k = 1;k < size; k++)
{
if (numbers[k] < min)
{
min = numbers[k];
}
else
{
min = numbers[i];
}
}
}
return min;
}
public int max_value()
{
for (int i = 0;i < size - 1;i++)
{
max = numbers[i];
for (int k = 1;k < size; k++)
{
if (numbers[k] > max)
{
max = numbers[k];
}
else
{
max = numbers[i];
}
}
}
return max;
}
public double average()
{
double avg;
int sum = 0;
for (int i = 0;i < size;i++)
{
sum = sum + numbers[i];
}
avg = sum/size;
return avg;
}
public String toStringArray()//Outputs a string representation of all the numbers in the array
{
for (int i = 0; i < size;i++)
{
array = Integer.toString(numbers[i]) + " ";
}
return array;
}
}
You are initializing the array before you initialize the size variable. The size variable has a default value which is passed into the array constructor and sets the array to that size. to fix the problem just move the initialization of the array into the constructor after the size variable is set.
public class RandomArray
{
/*A class that contains an array of random numbers and methods that output
the numbers' minimum, maximum and average values. Also includes a method
that outputs a string representation of the numbers.*/
int size, min, max;
String array;
int[] numbers;
public RandomArray(int sizeOfArray) {
Random generator = new Random();
size = sizeOfArray;
numbers = new int[size];
for (int i = 0;i < size;i++)
{
numbers[i] = generator.nextInt(size + 1);
}
}
Also I've noticed a bug with the string output method. The array would be overwritten on each iteration. To solve this you must add the array to itself.
public String toStringArray()//Outputs a string representation of all the numbers in the array
{
for (int i = 0; i < size;i++)
{
array = array + Integer.toString(numbers[i]) + " ";
}
return array;
}
Your method is passed the size of the array, but the array definition is not present in your code.
If you need to create the array in the RandomArray method, do something like :
public int[] RandomArray(int sizeOfArray)/*Constructor: gets array size, create and populates array with random numbers*/
{
int[] randomArray = new int[sizeOfArray];
for (int i = 0;i < randomArray.length();i++)
{
numbers[i] = generator.nextInt(size + 1);
}
return randomArray;
}
As you did not provide the entire class code it is hard to see whats going on. However I think you did not initialize the array correctly. If you have a private variable for an array, you should still 'make space' for it, as follows.
private int[] myIntArray; // As class member
myIntArray = new int[3]; // To allocate memory for the array
See the following link, for more info regarding arrays.
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
I am trying to write a program that prints a 2d array with random numbers ranging from 100-10000 and prints out the max number in the array,average,and min. The program will ask the user for the number of rows and column and print random numbers in that array.
Here is my code:
Random rand = new Random();
int randomnumber = rand.nextInt(9901) + 100;
Scanner console = new Scanner(System.in);
System.out.println("Enter row");
int n = console.nextInt();
System.out.println("Enter column");
int y = console.nextInt();
int[][] array = new int[n][y];
array[n][y] = randomnumber;
int k;
for (int i = 0; i <= array.length; i++) {
for (k = 0; k <= array[i].length; k++) {
System.out.print(array[i][k]);
}
}
If you want to fill the array with random values, you need to generate random values in a loop, and then write them to the array in that loop. So far you are only generating one value (and putting it in an invalid location).
Additionally, since arrays are 0-based, your loops should be for(i=0; i<arr.length; i++);, not <=.
Here's some code:
// don't declare k here
for(int i=0;i<array.length;i++){
for(int k=0;k<array[i].length;k++){
array[i][k]=rand.nextInt(9901)+100;
System.out.print(array[i][k]);
}
System.out.println(); // separate rows
}
I would like to generate 6 numbers inside an array and at the same time, having it compared so it will not be the same or no repeating numbers. For example, I want to generate 1-2-3-4-5-6 in any order, and most importantly without repeating. So what I thought is to compare current array in generated array one by one and if the number repeats, it will re-run the method and randomize a number again so it will avoid repeating of numbers.
Here is my code:
import javax.swing.*;
public class NonRepeat
{
public static void main(String args[])
{
int Array[] = new int [6];
int login = Integer.parseInt(JOptionPane.showInputDialog("ASD"));
while(login != 0)
{
String output="";
for(int index = 0; index<6; index++)
{
Array[index] = numGen();
for(int loop = 0; loop <6 ; loop++)
{
if(Array[index] == Array[loop])
{
Array[index] = numGen();
}
}
}
for(int index = 0; index<6; index++)
{
output += Array[index] + " ";
}
JOptionPane.showMessageDialog(null, output);
}
}
public static int numGen()
{
int random = (int)(1+Math.random()*6);
return random;
}
}
I've been thinking it for 2 hours and still cant generate 6 numbers without repeating.
Hope my question will be answered.
Btw, Im new in codes so please I just want to compare it using for loop or while loop and if else.
You can generate numbers from, say, 1 to 6 (see below for another solution) then do a Collections.shuffle to shuffle your numbers.
final List<Integer> l = new ArrayList<Integer>();
for (int j = 1; j < 7; j++ ) {
l.add( j );
}
Collections.shuffle( l );
By doing this you'll end up with a randomized list of numbers from 1 to 6 without having twice the same number.
If we decompose the solution, first you have this, which really just create a list of six numbers:
final List<Integer> l = new ArrayList<Integer>();
for (int j = 1; j < 7; j++ ) {
l.add( j );
}
So at this point you have the list 1-2-3-4-5-6 you mentioned in your question. You're guaranteed that these numbers are non-repeating.
Then you simply shuffle / randomize that list by swapping each element at least once with another element. This is what the Collections.shuffle method does.
The solutions that you suggested isn't going to be very efficient: depending on how big your list of numbers is and on your range, you may have a very high probability of having duplicate numbers. In that case constantly re-trying to generate a new list will be slow. Moreover any other solution suggesting to check if the list already contains a number to prevent duplicate or to use a set is going to be slow if you have a long list of consecutive number (say a list of 100 000 numbers from 1 to 100 000): you'd constantly be trying to randomly generate numbers which haven't been generated yet and you'd have more and more collisions as your list of numbers grows.
If you do not want to use Collections.shuffle (for example for learning purpose), you may still want to use the same idea: first create your list of numbers by making sure there aren't any duplicates and then do a for loop which randomly swap two elements of your list. You may want to look at the source code of the Collections.shuffle method which does shuffle in a correct manner.
EDIT It's not very clear what the properties of your "random numbers" have to be. If you don't want them incremental from 1 to 6, you could do something like this:
final Random r = new Random();
final List<Integer> l = new ArrayList<Integer>();
for (int j = 0; j < 6; j++ ) {
final int prev = j == 0 ? 0 : l.get(l.size() - 1);
l.add( prev + 1 + r.nextInt(42) );
}
Collections.shuffle( l );
Note that by changing r.nextInt(42) to r.nextInt(1) you'll effectively get non-repeating numbers from 1 to 6.
You have to check if the number already exist, you could easily do that by putting your numbers in a List, so you have access to the method contains. If you insist on using an array then you could make a loop which checks if the number is already in the array.
Using ArrayList:
ArrayList numbers = new ArrayList();
while(numbers.size() < 6) {
int random = numGen(); //this is your method to return a random int
if(!numbers.contains(random))
numbers.add(random);
}
Using array:
int[] numbers = new int[6];
for (int i = 0; i < numbers.length; i++) {
int random = 0;
/*
* This line executes an empty while until numGen returns a number
* that is not in the array numbers yet, and assigns it to random
*/
while (contains(numbers, random = numGen()))
;
numbers[i] = random;
}
And add this method somewhere as its used in the snippet above
private static boolean contains(int[] numbers, int num) {
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == num) {
return true;
}
}
return false;
}
Here is the solution according to your code -
You just need to change the numGen method -
public static int numGen(int Array[])
{
int random = (int)(1+Math.random()*6);
for(int loop = 0; loop <Array.length ; loop++)
{
if(Array[loop] == random)
{
return numGen(Array);
}
}
return random;
}
Complete code is -
import javax.swing.*;
public class NonRepeat
{
public static void main(String args[])
{
int login = Integer.parseInt(JOptionPane.showInputDialog("ASD"));
while(login != 0)
{
int Array[] = new int [6];
String output="";
for(int index = 0; index<6; index++)
{
Array[index] = numGen(Array);
}
for(int index = 0; index<6; index++)
{
output += Array[index] + " ";
}
JOptionPane.showMessageDialog(null, output);
}
}
public static int numGen(int Array[])
{
int random = (int)(1+Math.random()*6);
for(int loop = 0; loop <Array.length ; loop++)
{
if(Array[loop] == random)
{
return numGen(Array);
}
}
return random;
}
}
Use List instead of array and List#contains to check if number is repeated.
you can use a boolean in a while loop to identify duplicates and regenerate
int[] array = new int[10]; // array of length 10
Random rand = new Random();
for (int i = 0 ; i < array.length ; i ++ ) {
array[i] = rand.nextInt(20)+1; // random 1-20
boolean found = true;
while (found) {
found = false;
// if we do not find true throughout the loop it will break (no duplicates)
int check = array[i]; // check for duplicate
for (int j = 0 ; j < i ; j ++) {
if ( array[j] == check ) {
found = true; // found duplicate
}
}
if (found) {
array[i] = rand.nextInt(20)+1 ; // replace
}
}
}
System.out.println(Arrays.toString(array));
You may use java.util.Random. And please specify if you want any random number or just the number 1,2,3,4,5,6. If you wish random numbers then , this is a basic code:
import java.util.*;
public class randomnumber
{
public static void main(String[] args)
{
Random abc = new Random();
int[] a = new int[6];
int limit = 100,c=0;
int chk = 0;
boolean y = true;
for(;c < 6;)
{
int x = abc.nextInt(limit+1);
for(int i = 0;i<a.length;i++)
{
if(x==a[i])
{
y=false;
break;
}
}
if(y)
{
if(c!=0)if(x == (a[c-1]+1))continue;
a[c]=x;
c++;
}
}
for (Integer number : a)
{
System.out.println(number);
}
}
}
if you don't understand the last for loop , please tell , i will update it.
Use List and .contains(Object obj) method.
So you can verify if list has the random number add before.
update - based on time you can lost stuck in random loop.
List<Integer> list = new ArrayList<Integer>();
int x = 1;
while(x < 7){
list.add(x);
x++;
}
Collections.shuffle(list);
for (Integer number : list) {
System.out.println(number);
}
http://docs.oracle.com/javase/7/docs/api/java/util/List.html#contains(java.lang.Object)
Use the Random class to get numbers from 0 to 99 and store them into the array. Use a for loop to get each random number, store each into the array, and print each value.
Then use the bubble sort to sort the array, and print out the stored array.
here is my program
import java.util.Random;
public class Randomness
{
public static void main(String[] args)
{
Random randomNum = new Random();
for (int number = 0; number <= 99; ++number)
{
int num = randomNum.nextInt(100);
System.out.print(num + " ");
int numValues = num;
int [] values = new int[numValues];
boolean swap;
do
{
swap = false;
int temp;
for (int count = 0; count < numValues-1; count++)
if (values[count] > values[count+1])
{
temp = values[count];
values[count] = values[count+1];
values[count+1] = temp;
swap = true;
}
} while (swap);
System.out.print(values[count] + " ");
}
}
}
i get error
System.out.print(values[count] + " "); array required, but Random found.
please help!
You aren't creating any random values in your array. You are creating an array of random length (between 0 to 99). You need to initialize each element of your array with a random:
Random randomNum = new Random();
int numValues = 100;
int[] values = new int[numValues];
for (int number = 0; number < numValues; ++number)
{
int num = randomNum.nextInt(100);
System.out.print(num + " ");
values[number] = num;
}
Then do the bubble sort.