Sequential filling of a jagged array. How does this code work? - java

I was going through one of the solutions on the jagged array and could not follow a few of the below lines. Can anyone help me in understanding the below-the-line how the count is being utilized here. I do understand basics of Java but not getting a vision why count is exactly used here.
Program to demonstrate 2-D jagged array in Java:
int arr[][] = new int[2][];
// Making the above array Jagged
// First row has 3 columns
arr[0] = new int[3];
// Second row has 2 columns
arr[1] = new int[2];
// Initializing array
int count = 0;//why do we need count
for (int i = 0; i < arr.length; i++)
for (int j = 0; j < arr[i].length; j++)
arr[i][j] = count++; //how this line of code will work

You can add output to this code. The count variable is needed to sequentially fill the array with integers from 0 and so on.
int[][] arr = new int[2][];
arr[0] = new int[3];
arr[1] = new int[2];
int count = 0;
// iterate through the rows of the array
for (int i = 0; i < arr.length; i++)
// iterate through the columns of the array
for (int j = 0; j < arr[i].length; j++)
// set the array element and increment the counter
arr[i][j] = count++;
// output
for (int[] row : arr) System.out.println(Arrays.toString(row));
Output:
[0, 1, 2]
[3, 4]

Related

How to traverse diagonally through two dimensional array in Java?

I have a m x n matrix mat and I need to return an array of all the elements of the array in a diagonal order.
Input: mat = [[1,2,3],
[4,5,6],
[7,8,9]]
Output: [1,2,4,7,5,3,6,8,9]
public int[] findDiagonalOrder(int[][] mat){
int rows = mat.length;
int cols = mat[0].length;
int[] result = new int[rows * cols];
for(int i = 0; i <= rows - 1; i++){
for (int j = 0; j <= cols - 1; j++) {
while(i >= 0) {
i = i - 1;
j = j + 1;
from this point I dont know what should I do. Do you have any tips / advices how to continue to solve it myself?
I'm trying to figure out how to solve this problem by myself.
I'm trying to start from the first row and first column and then continue to traverse the array diagonally.

How to create an array from a pre-existing array?

New to java and am trying to create a program/method that will take an int array, and return another int array but it replaces the values of the indexes with the value of the elements. (Example {2,1,3} will return {0,0,1,2,2,2}
public static void main(String[] args) {
int[] pracArray = {2, 1, 3};
int sum = 0;
for (int i = 0; i < pracArray.length; i++)
{
sum = sum + pracArray[i];
}
System.out.println("Amount of array indexes: " + sum);
int[] newArray = new int[sum];
System.out.println(Arrays.toString(pracArray));
for (int i = 0; i < pracArray.length; i++)
{
for (int j = 0; j < pracArray[i]; j++)
{
newArray[j] = i;
}
}
System.out.println(Arrays.toString(newArray));
}
}
Currently I am getting [2,2,2,0,0,0]. I have tried changing the how many times each for loop iterates with no avail. I have also tried to make the elements of newArray equal to a counter ( int count = 0; and having count++ in the for loop) since the values of the new array will always be 0 - however many runs.
Given the length of your array is 3, your outer 'i' loop is iterating through the values 0,1,2. That means your inner 'j' loop never writes to index 3,4,5 (hence why they are 0 in the output), and why the first 3 indexes are set to '2' (2 is the last indexed processed in the 'i' loop). Try this instead...
int h = 0;
for (int i = 0; i < pracArray.length; i++)
{
for (int j = 0; j < pracArray[i]; j++)
{
newArray[h] = i;
h++;
}
}

Adding jagged arrays beginner

I'm a beginner at java at struggling with this:
I am trying to sum two jagged arrays ( n and m, both double [][]) of the same size (each is length 3 at the first level, then of length x-1,x and x-1 respectively at the second level).
The problem I'm having is to specify the length that each array within the jagged array should be, at the moment my code is producing an n x n array because I've specified the length as n[1] rather than as a parameter, but if I try and use sum[i].length=n[i].length I get the error, "cannot assign value to final variable". So I know this part is wrong but I don't know what is right...
Thanks for the help!
My code:
else if (isValidTridiagonal(m)== true && isValidTridiagonal (n) == true)
{
int size = n[1].length; /** specifying all lengths to be x where they shouldnt be*/
sum = new double[3][size];
for (int i = 0; i < n.length; i++)
{
for(int j = 0; j< n[i].length; j++)
{
sum [i][j]= n[i][j] + m [i][j];
}
}
return sum;
}
There is some missing information. As far as I can tell there are two things you need to fix. You seem to have "sum" as a final variable already defined in your code.
Secondly, you are declaring a new array that is 3xsize big. If you want a jagged array in that sence, you must leave one of the brackets empty and in the first loop insert a new array of the wanted size.
double[][] sum = new double[3][]; //Make sure this is unique within the scope
for(int i = 0; i < 3; i++) { //if you want dynamic scaling you'll need to replace 3 in the array as well.
int size = n[i].length; //size of the new row
sum[i] = new double[size]; // Inserting a new array of the wanted size
for(int j = 0; j< sum[i].length; j++)
{
sum[i][j]= n[i][j] + m[i][j];
}
}
return sum;
The problem is probably with this line:
sum = new double[3][size];
Here you create an incorrect, non-jagged array of size [3][2]
When you try to set sum[1][2] (2nd, 3rd index), you will not be able to.
Otherwise, the code looks correct and I got a sum to work using this:
public static void main(String[] args) {
int[][] n = new int[3][];
n[0] = new int[2];
n[0][0] = 1;
n[1] = new int[3];
n[2] = new int[2];
int[][] m = new int[3][];
m[0] = new int[2];
m[1] = new int[3];
m[1][2] = 1;
m[2] = new int[2];
int[][] sum = new int[3][];
sum[0] = new int[2];
sum[1] = new int[3];
sum[2] = new int[2];
for (int i = 0; i < n.length; i++) { // n.length will be 3
for (int j = 0; j < n[i].length; j++) { // n[i].length will be 2, 3 and 2
sum[i][j] = n[i][j] + m[i][j];
}
}
System.out.println("Sum: ");
for (int i = 0; i < sum.length; i++) {
for (int j = 0; j < sum[i].length; j++) {
System.out.print(sum[i][j] + "|");
}
System.out.println();
}
}
This will print off:
Sum:
1|0|
0|0|1|
0|0|

Trouble populating 2d array

I'm trying to populate a 2d array in java for a sudoku board. The numbers come from a csv file. The issue is the code just reads the first four numbers, then restarts at 0 again for a new row. How do I stop this from happening, and get it to continue to the end of the numbers?
String[] lines = Cell.toCSV().split(",");
int[] intArray = new int[lines.length];
for (int i = 0; i < intArray.length; i++) {
intArray[i] = Integer.parseInt(lines[i]);
} //convert string to int
int[][] dataArray = new int[4][4]; //4x4 sudoku game
for (int col = 0; col < size; col++) {
for (int row = 0; row < dataArray[col].length; row++) {
dataArray[col][row] = intArray[row];
}
You need a separate counter for the original array :
int index = 0;
for (int col = 0; col < dataArray.length; col++) {
for (int row = 0; row < dataArray[col].length; row++) {
dataArray[col][row] = intArray[index++];
}
This is assuming the intArray has enough values to populate the 2D array. You should probably validate that prior to this loop.
BTW, the first dimension of a 2D array is usually considered as the row, not the column, so your loop variable names are a bit confusing.

Java: create array with random int's (int's can only be used once)

I have an array called arr, with place for 15 elements.
I need to place the numbers 1 through 15 in a random order into that array.
Here is what I have tried:
int[] arr = new int[15];
int i,j,k,n;
for (i = 0; i<15; i++) {
for (j=0; j<15; j++) {
n = (int)(Math.random() * 14 + 1);
if (rij[j] != n) {
rij[i] = n;
break;
}
}
}
Thanks! :)
Use an ArrayList and fill it up with numbers 1 to 15.
Shuffle the list.
Convert it to an array.
This seems like homework (or an interview question?). If that's the case and you are required to use arrays rather than the built in methods with the Java Collection Objects, (or even if not, really), the answer is the Fisher-Yates Shuffle algorithm
The modern in-place shuffle is:
To shuffle an array a of n elements (indexes 0..n-1):
for i from n − 1 downto 1 do
j ← random integer with 0 ≤ j ≤ i
exchange a[j] and a[i]
(I'd have to check, but I suspect this is what Java uses under the hood for its shuffle() methods).
Edit because it's fun to implement algorithms:
In java, this would be:
public static void main(String[] args) {
int[] a = new int[15];
for (int i = 1; i <= 15; i++)
{
a[i-1] = i;
}
Random rg = new Random();
int tmp;
for (int i = 14; i > 0; i--)
{
int r = rg.nextInt(i+1);
tmp = a[r];
a[r] = a[i];
a[i] = tmp;
}
for (int i = 0; i < 15; i++)
System.out.print(a[i] + " ");
System.out.println();
}
And ... this can be further optimized using the inside-out version of the algo since you're wanting to insert a known series of numbers in random order. The following is the best way to achieve what you stated as wanting to do as there are no extra copies being made such as when creating an ArrayList and having it copy back out to an array.
a = new int[15];
Random rg = new Random();
for (int i = 0; i < 15; i++)
{
int r = rg.nextInt(i+1);
a[i] = a[r];
a[r] = i+1;
}
Do it like this
// Create an ordered list
List<Integer> list = new ArrayList<Integer>();
for (int i = 1; i < 16; i++) {
list.add(i);
}
// Shuffle it
Collections.shuffle(list);
// Get an Integer[] array
Integer[] array1 = list.toArray(new Integer[list.size()]);
// Get an int[] array
int[] array2 = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
array2[i] = list.get(i);
}
This will leave the elements randomly shuffled in a Integer[], if that's fine with you:
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 15; i++)
list.add(i + 1);
Collections.shuffle(list);
Integer[] arr = list.toArray(new Integer[0]);
I will do something like this:
First create a temporary arraylist filled with numbers from start to end, then using random select a number, copy it into array and remove it from the temp arraylist, repeat until the arraylist is empty...
ArrayList<Integer> arr = new ArrayList<Integer>();
int[] arr2 = new int[15];
int i,j,k,n;
for (i=0;i<15;i++) arr.add(i+1);
i=0;
while(arr.size()>0){
n = (int)(Math.random() * (14 + 1 - i));
arr2[i]=arr.get(n);
arr.remove(n);
i++;
}

Categories

Resources