How to print a 2D array with random numbers - java

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
}

Related

Print random array on one line: Java

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;

Generate a random two-dimensional array of non-repeating numbers, Java

The user will type in the number for i (variant), then the number for j (elements for every variant), and finally the maximum value possible (maxElem).
Using the inputed values, the task is to generate nonrepeating random numbers (nonrepeating in a variant, meaning for i, but the numbers may repeat during the entire array).
For example, a successful output giving the input 3 (i), 5 (j), 9 (maxElem), would be:
4|8|1|7|9
3|8|2|4|5
2|6|4|8|5
As you may notice, the number 4 repeats itself during the entire array for 3 times (allowable). But, for i=0, number 4 is unique.
Please, guide me what would be the changes to this code:
static Scanner sc = new Scanner(System.in);
static int maxElem;
public static void main(String[] args) {
int[][] greatLoto;
System.out.println("Of how many variants will the ticket consist? ");
int variants = sc.nextInt();
System.out.println("Of how many elements will the variants consist? ");
int elements = sc.nextInt();
System.out.println("Which value should be considered the maximum value? ");
maxElem = sc.nextInt() + 1;
greatLoto = new int[variants][elements];
System.out.println("Initial values: ");
show(greatLoto);
System.out.println("Modifying values...");
modified(greatLoto);
System.out.println("Newest values: ");
show(greatLoto);
}
private static void show(int[][] greatLoto) {
for (int i = 0; i < greatLoto.length; i++) {
for (int j = 0; j < greatLoto[i].length; j++) {
System.out.print("|" + greatLoto[i][j] + "|");
}
System.out.println("");
}
System.out.println("");
}
private static void modified(int[][] greatLoto) {
Random r = new Random(System.currentTimeMillis());
for (int i = 0; i < greatLoto.length; i++) {
for (int j = 0; j < greatLoto[i].length; j++) {
while (Arrays.asList(greatLoto[i]).contains(r)) {
r = new Random(System.currentTimeMillis());
}
greatLoto[i][j] = r.nextInt(maxElem);;
}
System.out.println("");
}
}
This is more of a comment but too long: don't use random.next() because it forces you to check for uniqueness. Instead fill a list with the valid values and shuffle it:
List<Integer> values = new ArrayList<> ();
for (int i = 1; i <= max; i++) values.add(i);
Collections.shuffle(values);
Then you can simply iterate over the values and take the j first numbers.
Note that if j is significantly greater than i using the random approach would probably be more efficient.
The most minimal change would be:
private static void modified(int[][] greatLoto) {
Random r = new Random(System.currentTimeMillis());
for (int i = 0; i < greatLoto.length; i++) {
for (int j = 0; j < greatLoto[i].length; j++) {
do {
greatLoto[i][j] = r.nextInt(maxElem);
} while (Arrays.asList(greatLoto[i]).contains(greatLoto[i][j]));
}
System.out.println("");
}
}
But there are more elegant (but difficult to code) ways to generate unique random numbers without discarding duplicates.
You need three loops:
Loop_1: Builds an array of size j and uses Loop_1B for every field of this array.
Loop_1B: Generate an int with r.nextInt(maxElem)+1; (it has to be +1 because nextInt() is covering the 0 inclusively and the specified value exclusively). Afterwards check if the number is already used in the array, if yes, run this loop again.
Loop_2: Repeats Loop_1 i times.

Is there something wrong with my nested for-loop? counting and incrementing values of arrays

So, I generate a 100 numbers between the range of 0 and 9. I store these 100 numbers in an array called 'array'. Then I have the array called 'count'. It has 10 elements, and I wanted to check the following: for each element in 'array' if it equals to 0-9 then count[0-9] increments by 1, count[0] = how many times number 0 appears and so on count[1] = 1, count[2] = 2... . I just keep getting the output of around 20k numbers and i suppose? the sum of each element?, no idea why. I was wondering if there is something major wrong with my for loop?
import java.util.*;
class RandomInt {
public static void main(String[] args) {
int size = 100;
int max = 10;
int[] array = new int[size];
int[] count = new int[max]; //count[0,0,0,0,0,0,0,0,0,0]
int loop = 0;
Random generator = new Random();
for (int i = 0; i < size; i++) {
array[i] = generator.nextInt(max); // Generates 100 random numbers between 0 and 9 and stores them in array[]
System.out.print(array[i]);
for (int x = 0; x < size; x++) {// loop through 10 elements in count
for(int j = 0; j < 10; j++){ //loop through 100 elements in array
if (array[x] == j) {// loop through each 100 elements of array[x] and if element array[x] = value
count[j] += 1; // then count[x] = x + 1
System.out.print(count[j]);
}
}
}
}
System.out.println("0 appears " + count[0] + " times.");
}
}
Your Login is Perfect only mistake which i found u made is with the brackets........!
Generate the numbers using first loop and then count the number of occurrence using different for loop.
Here is your code's modified version which generates 10 numbers and counts the individual number occurrence count.....
public class RandomInt {
public static void main(String[] args) {
int size = 10;
int max = 10;
int[] array = new int[size];
int[] count = new int[max]; //count[0,0,0,0,0,0,0,0,0,0]
int loop = 0;
Random generator = new Random();
for (int i = 0; i < size; i++)
{
array[i] = generator.nextInt(max); // Generates 100 random numbers between 0 and 9 and stores them in array[]
System.out.print(array[i]+" ");
}
for (int x = 0; x < size; x++)
{// loop through 10 elements in count
for(int j = 0; j < 10; j++)
{ //loop through 100 elements in array
if (array[x] == j)
{// loop through each 100 elements of array[x] and if element array[x] = value
count[j] += 1; // then count[x] = x + 1
//System.out.print(count[j]);
}
}
}
System.out.println("3 appears " + count[3] + " times.");
}
}
There's a simpler way to do this without nested loops, so forgive me for suggesting this as a fix rather than finding the issue in the loop.
for(int i=0; i<size; i++){
int num = generator.nextInt(max);
array[i] = num;
count[num]++;
}
One loop, incrementing the count for each number as it appears. You may need to ensure all the entries in count start at 0, but even then an additional loop through 10 entries is MUCH faster.
To increment your counter, you don't need to have two nested for loops. Instead, you can use the value of array[x] as your counter.
for (int i = 0; i < size; i++) {
count[array[i]]++
}
You've nested your counting loop inside of your random number generating loop. Move the counting part outside.
Edit: The reason you're getting like 20k or whatever instances of zero is because when you set array[0] with a random value, you also check how many instances of 0 are in array[1] to array[99].
You probably shouldn't do your count until you have finished assigning your numbers, but here is how you could. Note that you want the value at array[i] to be your index to count.
for (int i = 0; i < size; i++) {
array[i] = generator.nextInt(max); // Generates random numbers
count[array[i]]++;
}
System.out.println(Arrays.toString(array));
System.out.println(Arrays.toString(count));

Out of bounds exception multiplying arrays

As far as my knowledge goes, this program is done correctly. However, given the exception it appears not. I am to make 2 arrays of length x (user inputted) and the user is to input the elements. Done. Next multiply each element by its corresponding element in the other array and add the sum total.
Ex, array1[0]*array2[0] + array1[1]*array2[1]...
Precise error is : Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
I have done many different loops, the last loop below that I have spaced extra to identify is what I think is closest to correct but not. I would much appreciate some advice, thank you in advance.
System.out.println("This program will multiply 2 one dimension arrays of any length. \n The length and contents of the array is entered from the keyboard.");
System.out.println("Enther the data for the first array. ");
System.out.println("Enther the length of the array (remember arrays being counting at 0, not 1:");
int a = 0;
Scanner keyboard = new Scanner(System.in);
a = keyboard.nextInt();
int[] firstArrayLength = new int[a];
System.out.println("Enter the elements of the first array(remember arrays begin counting at 0, not 1");
double arrayElements = 0;
for (int elements = 0; elements <= firstArrayLength.length; elements++) {
arrayElements = keyboard.nextInt();
}
System.out.println("Enter the data for the second array. ");
System.out.println("Enter the elements of the second array(remember arrays begin counting at 0, not 1");
int[] secondArrayLength = new int[a];
double secondArrayElements = 0;
for (int elements = 0; elements <= secondArrayLength.length; elements++) {
secondArrayElements = keyboard.nextInt();
}
double [] thirdArray = new double [a];
for (int i =0; i <=firstArrayLength.length; i++)
{
thirdArray[a] = firstArrayLength[i]*secondArrayLength[i];
}
System.out.println(thirdArray);
}
Change your <= symbols to < when you are accessing de array. For instance:
for (int elements = 0; elements < firstArrayLength.length; elements++)
...
Remember if the length is 4, you can access elements as:
array[0], array[1], array[2], array[3] // 4 elements
array[4] doesn't exist, that cause the IndexOutOfBounds exception.
Edit
The strange output [I#756a7c99 (for instance) is because you are printing an array as:
int a[] = new int[4];
System.out.println(a);
Instead, you may want to print elements of that array:
int a[] = new int[4];
for (int i = 0; i < 4; i++) {
System.out.println(a[i]);
}
Edit 2
public static void main(String[] args) {
System.out
.println("This program will multiply 2 one dimension arrays of any length. \n The length and contents of the array is entered from the keyboard.");
System.out.println("Enther the data for the first array. ");
System.out
.println("Enther the length of the array (remember arrays being counting at 0, not 1:");
int a = 0;
Scanner keyboard = new Scanner(System.in);
a = keyboard.nextInt();
int[] firstArray = new int[a];
System.out
.println("Enter the elements of the first array(remember arrays begin counting at 0, not 1");
for (int elements = 0; elements < firstArray.length; elements++) {
firstArray[elements] = keyboard.nextInt();
}
System.out.println("Enter the data for the second array. ");
System.out
.println("Enter the elements of the second array(remember arrays begin counting at 0, not 1");
int[] secondArray = new int[a];
for (int elements = 0; elements < secondArray.length; elements++) {
secondArray[elements] = keyboard.nextInt();
}
double[] thirdArray = new double[a];
for (int i = 0; i < firstArray.length; i++) {
thirdArray[i] = firstArray[i]*secondArray[i];
}
for (int i = 0; i < thirdArray.length; i++)
System.out.println(thirdArray[i]);
}
elements <= firstArrayLength.length ==> elements < firstArrayLength.length
arrayElements = keyboard.nextInt(); ==>> firstArrayLength[elements] = keyboard.nextInt();
secondArrayElements = keyboard.nextInt(); ==>> secondArrayLength[elements] = keyboard.nextInt();

Array of counter in Processing

I have to pass two arrays
1) that are filled with 1000 int's between 0-100
2) that contains ten bins to sort the 1000 numbers.
How do I create the counter to sort numbers into ten bins such as 0-9, 10-19, 20-29, 30-39, 40-49,50-59 and so on to 90-99...
Would it be with an if/else that sorts them? If so, how do I add values into each bin? Would it be something like this?
This is what I have so far:
//initialize array of 1000 elements
int[] numbers = new int[1000];
int i = 0;
//initialize array of 10 bins
int[] bins = new int[10];
void setup() {
// Populate array with random number
for (int i = 0; i < numbers.length; i++) {
numbers[i] = ceil(random(0,99));
}
}
//function that sorts random numbers into bins
void counter(int[] numbers, int[] bins) {
}
If you want every number from numbers in the right bin then I would use an array of 10 ArrayLists as the datastructure for your bins.
int[] numbers = new int[1000];
ArrayList[] bins = new ArrayList[10];
void setup() {
for(int i = 0; i<bins.length; i++) {
bins[i] = new ArrayList();
}
for (int i = 0; i < numbers.length; i++) {
numbers[i] = floor(random(0,100));
}
}
void counter(int[] numbers, ArrayList[] bins) {
for (int i = 0; i < numbers.length; i++) {
bins[floor(float(numbers[i])/10.0)].add(numbers[i]);
}
}
You then get a bin with (for example the first bin consisting of numbers with values 0-9):
int sizeBin = bins[0].size();
for(int i=0; i<sizeBin; i++) {
println(bins[0].get(i));
}
If you want the count of numbers in a bin you can get it with (again an example with the bin 0-9)
bins[0].size();
the simplest way a can think of is to use a for loop to cycle through the numbers[] and then a series of if statements to evaluate whether the number is <= 9 , <= 19 etc
void counter(int[] numbers, int[] bins){
int count = 0;
int length = numbers.length;
for(int i = 0; i< length; i++){
if(numbers[i] <= 9){
bins[count] = numbers[i];
count++;
}
//and the same for 10-19 etc...
}
something like this maybe? not very eloquent but since the array is only 1000 elements it should suffice

Categories