Random Array generation - java

I am trying to create an array and have it filled with 0 or 1's randomly throughout the array. Below you will find the code. I am very new to java so any help would be greatly appreciated.
private static void randHouse() {
int rows = 4;
int columns = 5;
int i = 0;
int y = 0;
int [][] myList = {
{0,0,0,0,0},
{0,0,0,0,0},
{0,0,0,0,0},
{0,0,0,0,0}
};
System.out.println(Arrays.deepToString(myList)); // just prints the array
for (i : rows); {
for (y : columns);{
myList[i][y] = (int)random() * 10;
}
}
}
I am currently getting the error :
java: bad initializer for for-loop

It is easiest (imo) to use streams.
int r = 4;
int c = 5;
int[][] result = randHouse(r,c);
for (int[] row : result) {
System.out.println(Arrays.toString(row));
}
Prints something like
[1, 1, 0, 1, 1]
[0, 1, 0, 0, 1]
[1, 0, 1, 1, 1]
[1, 0, 1, 0, 0]
The IntStream iterates over the rows
the inner rand call generates each row of 1's and 0's.
then they are combined into an array of arrays.
private static int[][] randHouse(int r, int c) {
Random rand = new Random();
return IntStream.range(0, r)
.mapToObj(i -> rand.ints(c, 0, 2).toArray())
.toArray(int[][]::new);
}
Note: In your original problem, (int)Math.random()*10 will first convert the random value to 0 and then multiply by 10. So all you get are zeros. If you did the following (int)(Math.random()*10) you would get a value between 0 and 9 inclusive. Instead of 10, you should use 2.

for (int i = 0; i < rows.length; i++) {
for (int j = 0; j < columns.length; j++) {
myList[i][j] = (int)random() * 10;
}
}

Related

Filling a jagged 2d array first by columns

I want to write a function that takes an 2d array and fills it with 1...n but counting the columns first instead of the rows:
input = {{0, 0, 0, 0}, {0}, {0}, {0, 0}};
the output should be: {{1, 5, 7, 8}, {2}, {3}, {4, 6}};
if i were to loop through rows and then colums i get:
private static void fill1(int[][] input) {
int count = 1;
for (int i = 0; i < input.length; i++) {
for (int j = 0; j < input[i].length; j++) {
input[i][j] = count;
count++;
}
}
}
How do I loop through colums first?
You can do this by first transposing your input, executing your fill1 code and then transposing the output again.
See this question for how to transpose a 2 dimensional array in Java: java multi-dimensional array transposing
If you were dealing with a regular 2d matrix, where all the rows had the same number of columns, the code would be a simple modification of the code for filling the matrix row-by-row:
private static void fill1(int[][] input) {
int count = 1;
for (int j = 0; j < input[0].length; j++) {
for (int i = 0; i < input.length; i++) {
input[i][j]= count;
count++;
}
}
}
The process is basically the same for a ragged 2d array, but with a couple added twists:
You need to do some extra work to figure out how many columns there could be (i.e., the maximum row length)
You need to be prepared for the case when there's no cell at a given row/column position.
The following modification of the previous code addresses these issues:
private static void fill1(int[][] input) {
int maxCols = input[0].length;
for (int i = 1; i < input.length; ++i) {
if (input[i].length > maxCols) {
maxCols = input[i].length;
}
}
int count = 1;
for (int j = 0; j < maxCols; j++) {
for (int i = 0; i < input.length; i++) {
if (j < input[i].length) {
input[i][j]= count;
count++;
}
}
}
}
To iterate first over the columns of a jagged 2d array to fill it, you have to know the maximum number of columns beforehand, but if you don't know that, you can iterate to the Integer.MAX_VALUE and check at each step if the columns are still present or not:
int[][] arr = {{0, 0, 0, 0}, {0}, {0}, {0, 0}};
int count = 1;
for (int col = 0; col < Integer.MAX_VALUE; col++) {
boolean max = true;
for (int row = 0; row < arr.length; row++) {
if (col < arr[row].length) {
arr[row][col] = count;
count++;
max = false;
}
}
if (max) break;
}
for (int[] row : arr) {
System.out.println(Arrays.toString(row));
}
Output:
[1, 5, 7, 8]
[2]
[3]
[4, 6]
See also: How do you rotate an array 90 degrees without using a storage array?
To populate a 2d array first by columns, you can use two nested streams. In case of a jagged 2d array, when you don't know beforehand the number of the columns in each row, in an outer stream you can traverse while the columns are still present.
/**
* #param arr array that should be populated.
* #return maximum row length, i.e. columns count.
*/
private static long populate(int[][] arr) {
AtomicInteger counter = new AtomicInteger(1);
return IntStream
// traverse through the array columns
.iterate(0, i -> i + 1)
// process the array rows where
// this column is present
.mapToLong(i -> Arrays.stream(arr)
// filter those rows where
// this column is present
.filter(row -> row.length > i)
// assign a value to the element and increase the counter
.peek(row -> row[i] = counter.getAndIncrement())
// count of rows where this column is present
.count())
// while the columns are still present
.takeWhile(i -> i > 0)
// max columns count
.count();
}
public static void main(String[] args) {
int[][] arr = {{0, 0, 0, 0, 0, 0}, {0, 0}, {0}, {0, 0, 0}};
System.out.println("Max columns count: " + populate(arr));
System.out.println(Arrays.deepToString(arr));
}
Output:
Max columns count: 6
[[1, 5, 8, 10, 11, 12], [2, 6], [3], [4, 7, 9]]
See also: How to create a new List from merging 3 ArrayLists in round robin style?

Dividing a 1D array into a 2D array

So I have homework that asked me to:
Write a method that takes two parameters: an array of integers and an integer that represents a number of elements. It should return a two-dimensional array that results from dividing the passed one-dimensional array into rows that contain the required number of elements. Note that the last row may have less number of elements if the length of the array is not divisible by the required number of elements. For example, if the array {1,2,3,4,5,6,7,8,9} and the number 4 are passed to this method, it should return the two-dimensional array {{1,2,3,4},{5,6,7,8},{9}}.
I tried to solve it using this code:
public static int[][] convert1DTo2D(int[] a, int n) {
int columns = n;
int rows = a.length / columns;
double s = (double) a.length / (double) columns;
if (s % 2 != 0) {
rows += 1;
}
int[][] b = new int[rows][columns];
int count = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
if (count == a.length) break;
b[i][j] = a[count];
count++;
}
}
return b;
}
But I had a problem which is when I try to print the new array this is the output:
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 0, 0, 0]]
So how can I remove the 3 zeros at the end? Just a note that I can't use any method from java.util.* or any built-in method to do this.
Change the 2D array's initialization to not contain the second dimension: new int[rows][]. Your array now has null arrays inside it. You have to initialize those in your loop: b[i]=new int[Math.min(columns,remainingCount)]; where remainingCount is the amount of numbers outside the 2d array.
Populating a 2d array with values from a 1d array as long as they are present:
public static int[][] convert1DTo2D(int[] arr, int n) {
// row count
int m = arr.length / n + (arr.length % n == 0 ? 0 : 1);
// last row length
int lastRow = arr.length % n == 0 ? n : arr.length % n;
return IntStream.range(0, m)
.mapToObj(i -> IntStream.range(0, i < m - 1 ? n : lastRow)
.map(j -> arr[j + i * n])
.toArray())
.toArray(int[][]::new);
}
public static void main(String[] args) {
int[] arr1 = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int[][] arr2 = convert1DTo2D(arr1, 4);
System.out.println(Arrays.deepToString(arr2));
// [[1, 2, 3, 4], [5, 6, 7, 8], [9]]
}
See also: How to populate a 2d array with values from a 1d array?
It may be better to switch arguments in the method:
int[][] convert1DTo2D(int cols, int... arr)
to allow use of vararg.
Also, it is possible to iterate on the input array (single loop) instead of nested loops.
Example implementation:
public static int[][] convert1DTo2D(int cols, int... a) {
int lastRowCols = a.length % cols;
int rows = a.length / cols;
if (lastRowCols == 0) {
lastRowCols = cols;
} else {
rows++;
}
int[][] b = new int[rows][];
for (int i = 0; i < a.length; i++) {
int r = i / cols;
int c = i % cols;
if (c == 0) { // start of the row
b[r] = new int[r == rows - 1 ? lastRowCols : cols];
}
b[r][c] = a[i];
}
return b;
}
Adding this if-condition to your code will shorten the final array should it not be the right size:
...
final int[][] b = new int[rows][columns];
if ((a.length % columns) != 0) {
b[rows - 1] = new int[a.length % columns];
}
int count = 0;
...
% is the Modulo operator which gives you the remainder of a division of the first and second number.
9 % 4 would return 1, the exact size needed for our final array.
We then merely have to replace the final array with a new one of that size.

How to get all possible combinations of elements of one (int) array?

I've been writing code to get all combinations of elements from array, but I couldn't figure out how to do it. Can you guys give me some advice?
This is what I'm trying to do...
int[] num = {1, 2, 3, 4, 5};
int n = num.length;
int length = (n * (n - 1)) / 2;
int[] list = new int[length];
for (int j = 0; j < n - 1; j++) {
for (int p = 4;p < n; p--) {
for (int i = 0; (I < length); i++) {
list[i] = Math.abs(num[j] - num[j + p]);
}
p++;
}
}
My result list would look like this..
list = {1, 2, 3, 4, 1, 2, 3, 1, 2, 1};
Thank you in advance.
edit: I'm really sorry that I didn't post my question clearly. What I was trying to do is get the absolute value of subtracting each values from array.
ex) 1-2 , 1-3, 1-4, 1-5, 2-3, 2-4, 2-5, 3-4, 3-5, 4,5
for (int v : list) {
System.out.println(v);
}
output:
1
2
3
4
1
2
...
Do it as follows:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] num = { 1, 2, 3, 4, 5 };
int n = num.length;
int length = (n * (n - 1)) / 2;
int[] list = new int[length];
// Index counter for list[]
int c = 0;
for (int i = n - 1; i >= 0; i--) {
for (int j = 0; j < i; j++) {
list[c++] = num[j];
}
}
// Display
System.out.println(Arrays.toString(list));
}
}
Output:
[1, 2, 3, 4, 1, 2, 3, 1, 2, 1]
For any value n the following should work. The key is to base the termination point of the inner loop on the outer loop's termination point.
System.out.println(string);
int n = 5;
int[] num = {1, 2, 3, 4, 5};
int length = (n * (n - 1)) / 2;
int m = 0;
int[] list = new int[length];
for (int i = 1; i<n ; i++) {
for (int k = 1; k <= n-i; k++) {
list[m++] = num[k-1];
}
}
System.out.println(Arrays.toString(list));
Prints
1 2 3 4 1 2 3 1 2 1

How to pass result from an array to another method without 0 numbers in java? [duplicate]

This question already has answers here:
Remove all zeros from array
(11 answers)
Closed 4 years ago.
Can you please advise how can I pass results from an array to another array without some numbers? In this case without zero numbers. Here is my code, I'm stuck.
Result is: [0, 1, 2, 3, 0, 5, 0, 7, 0, 0, 0, 11] - all I want to do, is to create another array and pass there numbers from above without 0's.
Thanks.
public class SieveOfEratosthenes {
public static void main(String[] args) {
int[] myArray = new int[12];
fillArrayWithNumbers(myArray);
System.out.println(Arrays.toString(sieve(myArray)));
}
private static void fillArrayWithNumbers(int[] myArray) {
for (int i = 0; i < myArray.length; i++) {
myArray[i] = i;
}
}
public static int[] sieve(int[] maximumNumber) {
for (int j = 2; j < maximumNumber.length; j++) {
for (int i = j * 2; i < maximumNumber.length; i += j) {
maximumNumber[i] = 0;
}
}
return maximumNumber;
}
}
You can convert your Int[] to a Stream and filter out the zero values.
Code
public static void main(String[] args) {
int[] arr = new int[]{0, 1, 2, 3, 0, 5, 0, 7, 0, 0, 0, 11};
int[] ints = Arrays.stream(arr)
.filter(i -> i != 0)
.toArray();
Arrays.stream(ints).forEach(System.out::println);
}
Output
1
2
3
5
7
11
The solution is above as what infinitezero said to write a for loop that has you array length. Then copy items in the array as length.
for(int i = 0; i < arr.length; i++){
if(arr[i] == 0){
}
else{
arr[i] = arr2[i];
}
I think you can create a new array and fill it with above zero value:
What you want to do it to omit all even numbers (except 2). Then it should be done like this:
public static int[] sieve(int[] maximumNumber) {
int[] result = new int[maximumNumber.length];
int index= 0;
for (int i = 1; i < maximumNumber.length; i++) {
if (i == 2 || i % 2 != 0) { // i is 2 or odd
result[index] = i;
index++; // This will store the real length of the array
}
}
return Arrays.copyOfRange(result, 0, index);
}

Expanding an array to represent an index as many times as the magnitude of original value

Example: expand(new int[]{3, 2, 5}) -> {0, 0, 0, 1, 1, 2, 2, 2, 2, 2}
I am trying to have it make a a new array to print the index of say 3, 3 times. So 3 would be 0,0,0.
public static int[] expand(int[] input) {
int c = 0;
int[] myArray = new int[sum(input)];
if(input.length == 0){
return new int[0];
}
for(int i = 0; i < input.length; i++) {
int a = input[i];
for(int j = c; j < a; j++) {
c += j;
myArray[j] = i;
}
}
return myArray;
}
Currently this only partially works and I cant seem to figure out how to go through the full array properly. In addition, index zero seems to get skipped.
You were close! It seems that you just need to modify your nested for-loop slightly:
for (int j = 0; j < a; j++) {
myArray[c++] = i;
}
Seeing as you're using c to keep track of the current index, this simply sets the element at index c to i and increments c. You can also remove a and use input[i] in place of it.
Note: It is easier to start j from 0 rather than from c.
Functional method
public class Main {
public static void main(final String... args) {
int[] items = expand(new int[]{3, 2, 5});
System.out.println(Arrays.toString(items));
}
public static int[] expand(int[] input) {
return IntStream.range(0, input.length)
.flatMap(p -> IntStream.generate(() -> p).limit(input[p]))
.toArray();
}
}
This makes a stream of the index, and for each item takes that many of the index, putting all of them into an array

Categories

Resources