loops in a two-dimensional array - java

import java.util.Random;
public class arrayClass
{
public static void main(String [] args)
{
int [][] array = new int [5][5];
Random gen = new Random();
for(int x = 0; x < array.length; x++)
{
array[x][2]= gen.nextInt(15) + 1;
}
}
}
I know the code is brief but it might be enough for you to understand
Okay so my goal right now is to put random numbers into each cell without "brute forcing" it(so using loops). I was wondering if there is a way to manipulate two variables in a for loop. Also, how could I make it so that the first row will increase one cell when the cells within the row is done in a loop (in this case cell 0 through 4 in one row)
And is there a way to output a specific range of cells?
thanks and sorry I know this might be pretty confusing

I think you really should use a double for loop here:
for (int x=0; x < array.length; x++) {
for (int y=0; y < array[x].length; ++y) {
array[x][y]= gen.nextInt(15) + 1;
}
}
You could use a single for loop to populate the 2D array, but it would require an external loop counter, and in the end would be functionally similar to a double loop.

Related

Fill array with zero in random places

So, what I am trying to do is to fill a 2D array with zeros in random places a specific amount of times. Let's say that it has to be 20 zeros in an array of 90 places. What I have done so far is to declare a 2D array and fill it with random numbers. And my next thought was to simply choose random positions and replace them with zeros. Any idea how I could do that?
int[][] myboard = new int[9][9];
for (int i = 0; i < myboard.length; i++) {
for (int j = 0; j < myboard[i].length; j++) {
myboard[i][j] = (int) (Math.random() * 10);
}
}
It is a rather simple way to achieve the goal, but it should do the job. So you need to get the length of each row. After you have done that you can call a function that will give you a random number between some start point and the length of the row. Here is some code sample to show you what I mean:
import java.util.concurrent.ThreadLocalRandom;
import java.util.Arrays;
public class Example {
public static void main(String []args) {
int[][] myboard = new int[9][9];
for (int i = 0; i < myboard.length; i++) {
for (int j = 0; j < myboard[i].length; j++) {
// fill the row with random vals
myboard[i][j] = GetRandomNumber(0, myboard[i].length);
}
// sneak as much zeros as your heart content
int random = GetRandomNumber(0, myboard[i].length);
myboard[i][random] = 0;
}
System.out.println(Arrays.deepToString(myboard));
}
private static int GetRandomNumber(int min, int max) {
/*
min is the start point
max is the curr row len
*/
return ThreadLocalRandom.current().nextInt(min, max);
}
}
A pseudo code would look like:
while (num_zeros_filled < 20):
row = random()%total_rows
col = random()%total_cols
if (arr[row][col] == 0): # already filled in with 0
continue
else:
arr[row][col] = 0
num_zeros_filled += 1
This, however, could take infinite time theoretically if only those cells are generated which have already been filled with 0. A better approach would be to map the two-dimensional array into a 1-d array, and then sample out only from those cells which haven't been filled with 0 yet.

How to iterate through a fixed tridimensional matrix efficiently (java)

As part of a program I'm building I need to iterate through all the points in a tridimensional matrix.
On each point I need to execute a method that takes int x, int y, int z as parameters.
The tridimensional matrix always has the same width(16) length(16) & height(256).
What is the most performant way of doing the iteration?(i'm specially concerned about CPU, not so concerned about ram usage)
Based on what i know , I think this are the most efficient methods, but I'm open to other suggestions if they are faster.
A. Iterate directly:
public void doSomethingForAllPointsInMatrix(Matrix matrix){
for(int x= 0; x<16; x++){
for(int z = 0; z<16; z++){
for(int y = 0; y<256; y++){
matrix.doSomething(x,y,z);//A method out of my control without any alternatives
}
}
}
}
B. Iterate an array containing the coordinates
private static final int[] zeroToFifteen; //Contains every number from 0 to 15
private static final int[] zeroToTwoHundredFiftyFive; //Contains every number from 0 to 255
public void doSomethingForAllPointsInMatrix(Matrix matrix){
for(int x: zeroToFifteen){
for(int z: zeroToFifteen){
for(int y: zeroToTwoHundredFiftyFive){
matrix.doSomething(x,y,z);//A method out of my control without any alternatives
}
}
}
}
Thanks in advance for any help you can provide!
A counting loop is already one of the most efficient iteration mechanisms.
Your idea to incorporate an array indicates that you are not aware that the for-each loop over an array is just syntactic sugar for a counting loop over the indices from zero to the array length.
In other words, your
public void doSomethingForAllPointsInMatrix(Matrix matrix){
for(int x: zeroToFifteen){
for(int z: zeroToFifteen){
for(int y: zeroToTwoHundredFiftyFive){
matrix.doSomething(x,y,z);//A method out of my control without any alternatives
}
}
}
}
is basically equivalent to
public void doSomethingForAllPointsInMatrix(Matrix matrix){
for(int index1 = 0; index1 < zeroToFifteen.length; index1++){
int x = zeroToFifteen[index1];
for(int index2 = 0; index2 < zeroToFifteen.length; index2++){
int z = zeroToFifteen[index2];
for(int index3 = 0; index3 < zeroToTwoHundredFiftyFive.length; index3++){
int y = zeroToTwoHundredFiftyFive[index3];
matrix.doSomething(x,y,z);//A method out of my control without any alternatives
}
}
}
}
differing from the counting loop of your first approach only by doing additional array operations, which is very unlikely to improve the performance.
Since your bounds are powers of two, you could do the entire operation with a single loop
public void doSomethingForAllPointsInMatrix(Matrix matrix) {
for(int coord = 0; coord < 0x10000; coord++) {
matrix.doSomething(coord >> 12, coord & 0xff, (coord >> 8)&0xf);
}
}
reducing the number of conditionals. However, the actual performance depends on what the JVM’s optimizer makes out of it and it might be that it can deal better with the nested loops.
So you can only try and benchmark the approaches, to find “the best”, whereas “the best” may be different, depending on the system and the JVM implementation/version.
As said in the comments, the performance is likely dominated by whatever doSomething does and if the processing order is not important for your program logic, you should try with alternative iteration orders, as it may affect how the caches are utilized.

Two dimentional array printing rows

Okay, so I need to print 10 rows from 1 to 10 and 15 columns in every row from 1 to 15 with lines in between numbers. The second subroutine runs on its own, but only prints 0's and the first subroutine is me trying to give value to rows and columns, but I know I'm doing it very wrong. Any help is appreciated
static int ROWS = 10;
static int COLUMNS = 15;
static int[][] myArray = new int[10][15];
static int i; // loops through the number of rows
static int j; // loops through the number of columns
static int num1 = 0;
static int num2 = 0;
public static void vlueArray() {
for (i = 1; i < ROWS; i++) {
myArray[i][j]= num1++;
for (j = 1; j < COLUMNS; j++) {
myArray[i][j] = num2++;
System.out.print(myArray[i][j]);
}
System.out.println("");
}
}
public static void display2DArray() {
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLUMNS; j++) {
System.out.print(myArray[i][j] + " | ");
}
System.out.println("");
System.out.println("_____________________________________________________________");
}
}
you have not initialized elements in array and that is why you are getting zero displayed because int values are always initialized by the compiler even if you don't initialize them. The default value of int is 0.
Initialize your 2D array like this:
int[][] myArray = new int[10][15]{{2,3},{3,5},..........};
Hope this helps.
There are two issues here. First, you don't have very good syntax, while the way you have this set up does work, let me give you a couple of tips about settings this up, and then we can fix your problem fairly easily.
Some general rules here:
You don't have to initialize loop variables in the class variables, just initialize them in the loop structure (I'll show you this below).
Use the ROW and COLUMN in declaring your array, it helps make sure the array length values are the same throughout.
Your loop for creating the values in vlueArray is incorrect. I'll show you some correct formatting for placing these values below.
When you array is initialized, each place in the array (if it is an integer array) is automatically given a value of zero. You can change this, but since the first method doesn't run correctly, printing the values in the array without changing them will give the array of zeros.
Now, it seems like you want to just have 1 - 15 on 10 different rows. To do this, you only need one variable, so my response code will only have one variable, but if this isn't what you want, I'd be glad to help you get a different setup.
So now that you have a little bit of background information, let's get you some working code.
static int ROWS = 10; //Your row count.
static int COLUMNS = 15; //Your column count.
static int num = 0; //Our number.
//Using the constants to make sure rows and columns values match everywhere.
static int[][] myArray = new int[ROWS][COLUMNS];
public static void fillArray() {
//Initializing the loop variables in the loop is the common practice.
//Also, since the first index is zero, the loop needs to start at 0, not 1.
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLUMNS; j++) {
//If you want 0 - 14, use `num++`.
//If you want 1-15, use `++num`.
myArray[i][j] = num++;
}
num = 0; //This sets num back to zero after cycling through a whole row.
}
//Your display method works just fine.
public static void display2DArray() {
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLUMNS; j++) {
System.out.print(myArray[i][j] + " | ");
}
System.out.println("");
System.out.println("_____________________________________________________________");
}

Array Multiplication

new programmer here and I am a little confused on this code sample I'm working on. Basically I'm taking arrayA and passing it down to my method, I would then like my method to take and multiply each adjacent numbers, therefore my total should come out to 962, return it back to main and sopln it out.
public class 8a
{
public static void main(String [] args)
{
int [] arrayA = {10,5,100,3,6,2,30,20};
int result = sumOfProducts(arrayA);
}
public static int sumOfProducts(int [] a)
{
int counter = 1;
for(int x = 0; x < a.length; x++)
}
}
Are you sure 962 is the correct result? If you multiply each adjacent number and sum up the results, your return value should be 1540. You seem to take only every other pair into consideration:
10*5 ok
5*100 not
100*3 ok
3*5 not
...etc.
If you want to sum up of the results of every adjacent pair multiplication (also the ones marked with 'not'), you can simply go through the array like this:
int sum= 0;
for(int x = 0; x < arrayA.length-1; x++)
sum+=(arrayA[x]*arrayA[x+1]);
On the other hand, if you are REALLY 100% sure you want to leave out every other pair and get to the 962 result:
int sum= 0;
for(int x = 0; x < arrayA.length-1; x+=2)
sum+=(arrayA[x]*arrayA[x+1]);
However, this only works for arrays with an even number of entries. And since this is part of an exercise, i would consider the first solution to be far more likely to be the indended one.

how to iterate on array[...][i] (columns) in java

There is a really easy way to access the rows of a 2D array in java
for (int i = 0 ; i < integer2D.length ; i++)
getMyArray(integer2D[i]);
But, I searched in the web to find such easy way to iterate on columns of the 2D-array, like
for (int j = 0 ; j < integer2D[0].length ; j++)
getMyArray(integer2D[][i]);
or
for (int j = 0 ; j < integer2D[0].length ; j++)
getMyArray(integer2D[...][i]);
which works in some programming languages. I just found the class RealMatrix and MatrixUtils that I can convert my array2D to a real matrix and then transpose it and again convert it to an array and iterate on it. But I suppose that there exist a simpler way?
Edit: iterating on rows as I noted in the first piece of code is easy but the main question is how to iterate on columns like the second and third codes work in some other programming languages.
Edit2: As I mentioned in the last paragraph of the main question, the easiest way that I know is transposing the matrix and the iterating on its rows.
If I understand your question, you could use a for-each as an easy way to get each row like
for (int[] row : integer2D) { // <-- for each int[] in the int[][]
for (int val : row) { // <-- for each int in the int[] row
// ...
}
}
For this, you can use the BigMatrixImpl Class of the commons math library. It has a getColumnAsDoubleArray() method which will return the specified column as an array.
Delivering only one index will give you the whole row, so:
integer2D[5] // returns an int[]
will give you an integer array, which is the 6th row in your matrix.
If you supply both indexes directly you get the value of the "cell"
integer2D[5][1] // returns an int
will give you the value of the second column of the 6th row.
This is direct access to your matrix, if you want to iterate through the rows the answer from Elliott is what you are looking for.
Edit: Transposing:
int width = array.length;
int height = array[0].length;
int[][] array_new = new int[height][width];
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
array_new[y][x] = array[x][y];
}
}

Categories

Resources