Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Okay so I wrote this code with my friend's help to "remove the row" of a matrix, but I don't really understand whats going on with the "for" , can someone explain to me why it's done that way?
Edit: Okay so what i don't understand is the way that both loops are working
public static double [][] removeRow(double [][] m , int n){
double [][] finalm = new double [m.length-1][m[0].length];
for (int i = 0; i<finalm.length; i++) {
for (int j = 0; j<finalm[i].length; j++) {
if (i<n) {
finalm[i][j]=m[i][j];
}
if (i>=n) {
finalm[i][j]=m[i+1][j];
}
}
}
return finalm;
}
public static void main(String[] args) {
double [][] m = {{1,2,3},{1,9,2},{0,6,3}};
double [][] result = removeRow(m,0);
for (int i = 0; i<result.length; i++) {
for (int j = 0; j<result[i].length; j++) {
System.out.println(result[i][j]);
}
}
}
}
Picture the Array:
0, 0, 0, 0
1, 1, 1, 1
2, 2, 2, 2 <----- n
3, 3, 3, 3
Where n is 2.
The method constructs an empty Array with one less row:
0, 0, 0, 0
0, 0, 0, 0
0, 0, 0, 0
Then it loops for each loop, and if the index is less than n, then it copies it to the second Array. So rows one and two will be copied:
0, 0, 0, 0
1, 1, 1, 1
0, 0, 0, 0
Then if the index is equal to or more than n, it will copy the row from index + 1 to the second Array:
//Skips the row 2, 2, 2, 2
0, 0, 0, 0
1, 1, 1, 1
3, 3, 3, 3
Also note that the inner loop is not necessary since we are copying entire rows. We can simply do:
public static double [][] removeRow(double [][] m , int n){
double [][] finalm = new double [m.length-1][m[0].length];
for (int i = 0; i<finalm.length; i++) {
if (i<n) {
finalm[i]=m[i];
}
if (i>=n) {
finalm[i]=m[i+1];
}
}
return finalm;
}
Related
hello to all you code geniuses on here
ill try to explain my problem as simply as i can
image1
To produce image1, lets say an array like below is required, keeping in mind that the numbers are placed left to right in the first row, then go backwards in the second row, and if you added more numbers, it would create a third row.
int[] something = {1, 2, 3, 2, 1, 2, 1, 3, 3, 1, 1, 2}
so i want to make to make a "map" of the layout, like this desired output below.
2 1 1 3 3 1
1 2 3 2 1 2
and then from there i would want to find the total for each column, so like this.
2 1 1 3 3 1
1 2 3 2 1 2
..................
3 3 4 5 4 3
(and i then want to make store this layout and sum within another array)
hopefully that all made sense, if so,
how could i go about doing this?
thanks heaps : )
Seems like you can use a two-dimensional array data structure to solve this:
int[][] something = new int[][]{
{2, 1, 1, 3, 3, 1},
{1, 2, 3, 2, 1, 2}
};
int totalForColomn1 = something[0][0] + something [1][0];
int totalForColomn2 = something[0][1] + something [1][1];
// ...
int totoalForColomn6 = something[0][5] + something [1][5];
If you could only use one-dimensional array:
int[] something = new int[] {2, 1, 1, 3, 3, 1, 4, 2, 3, 2, 1, 2};
int row_size = 6;
int totalForColomn1 = something[0] + something[0 + row_size];
int totalForColomn2 = something[1] + something[1 + row_size];
// ...
int totalForColomn6 = something[5] + something[5 + row_size];
Remember to keep a consistant row_size by putting those undecided element to 0.
In this case, you should init your array like:
int[] something = new int[] {0, 0, 0, 0, 1, 4, 1, 2, 3, 2, 1, 1};
So If I am reading this correctly if L is the length of your array you want to add the nth and L-1-nth element of the array and store the result in an array. I through this together quickly so I did not handle what happens if the input array is of odd length (your question did not specify).
import java.util.Arrays;
public class App {
public static void main(String[] args) {
int[] something = {1, 2, 3, 2, 1, 2, 1, 3, 3, 1, 1, 2};
System.out.println(Arrays.toString(addValues(something)));
}
public static int [] addValues(int [] input){
int[] output = new int[input.length / 2];
for(int i = 0; i<input.length/2; i++){
output[i] = input[i] + input[input.length -1 - i ];
}
return output;
}
}
EDIT:
I think this will work for the case where the are an arbitrary number of rows.
The main insite into how this work is in the grid below.
0 1 2 3 4 5 :row 0
11 10 9 8 7 6 :row 1
12 13 14 15 16 17:row 2
23 22 21 20 19 18:row 3
So whether the output index is going up or down is determined by the row number and every time we hit an input index that is the same size as our output array we need to stay at the same output index.
import java.util.Arrays;
public class App {
public static void main(String[] args) {
int[] something = { 1, 2, 3, 2, 1, 2, 1, 3, 3, 1, 1, 2 };
System.out.println(Arrays.toString(addValues(something, 6)));
}
public static int[] addValues(int[] input, int row_lenth) {
int[] output = new int[row_lenth];
int output_index = 0;
for (int i = 0; i < input.length; i++) {
if (i % row_lenth != 0) {
if ((i / row_lenth) % 2 == 0) {
output_index++;
} else {
output_index--;
}
}
output[output_index] += input[i];
}
return output;
}
}
import java.util.Scanner;
public class Stckoverq {
public static void main(String args[]) {
Scanner sn = new Scanner(System.in);
System.out.print("What is the size of array? ");
int size = sn.nextInt();
System.out.print("What is length of the row?");
int len = sn.nextInt();
int ind = 0, i = 0, j = 0;
//variable 'ind' is for getting the element from arr[] array at index ind
int rac[][] = new int[size/len][len];
//variable 'i' and 'j' is for storing rows and column elements respectively in array rac[]
int arr[] = new int[size];
System.out.println("Enter array elements: ");
for(int k=0;k<size;k++)
arr[k] = sn.nextInt();
while(ind!=arr.length)
{
if(j==len) {
j=0; //Reset column index
i++; //Increase row index
}
rac[i][j] = arr[ind];
ind++;
j++; //Increase column index
}
//Now print the rows and columns................
for(int r =0;r<size/len;r++) {
for(int c=0;c<len;c++)
System.out.print(rac[r][c]+"\t");
System.out.println();
}
int sum[] = new int[len];
//this array sum[] is used to store sum of all row elements.
int s = 0;
for(int c=0;c<len;c++) {
for(int r =0;r<size/len;r++)
s += rac[r][c];
sum[c] = s;
s = 0;
}
for(int x: sum)
System.out.print(x+"\t");
}
}
I have the following array:
int [] mi_array= {9,4,0,0,4,0,3,0,1,8,0};
I want to order the numbers other than 0 on the left, and the 0s on the right, but I find that the function steps on one of the numbers.
The output must be
{9,4,4,3,1,8,0,0,0,0,0}
public class Array {
public static void main(String[] args) {
int [] mi_array= {9,4,4,3,1,8,0,0,0,0,0};
int x=0;
int y=mi_array.length-1;
for (int i=0;i<mi_array.length;i++)
if(mi_array[i]!=0) {
mi_array[x]=mi_array[i];
x++;
}
else {
mi_array[y]=mi_array[i];
y--;
}
for (int i=0;i<mi_array.length;i++)
System.out.println(mi_array[i]);
System.out.println(x);
}
}
Try this.
int[] mi_array = {9, 4, 0, 0, 4, 0, 3, 0, 1, 8, 0};
for (int i = 0, j = i + 1, s = mi_array.length; j < s;)
if (mi_array[i] == 0) {
mi_array[i] = mi_array[j];
mi_array[j] = 0;
++j;
} else if (++i >= j)
j = i + 1;
System.out.println(Arrays.toString(mi_array));
// -> [9, 4, 4, 3, 1, 8, 0, 0, 0, 0, 0]
You can use filter and IntStream.concat to merge the parts of the array that are not 0 with the parts that are.
final int[] mi_array = { 9, 4, 0, 0, 4, 0, 3, 0, 1, 8, 0 };
final int[] result = IntStream.concat(Arrays.stream(mi_array).filter(i -> i != 0),
Arrays.stream(mi_array).filter(i -> i == 0)).toArray();
System.out.println(Arrays.toString(result));
Demo!
You can also do this:
final int[] mi_array = { 9, 4, 0, 0, 4, 0, 3, 0, 1, 8, 0 };
final int[] result = new int[mi_array.length];
final AtomicInteger idx = new AtomicInteger();
Arrays.stream(mi_array).filter(i -> i != 0).forEach(val -> result[idx.getAndIncrement()] = val);
System.out.println(Arrays.toString(result));
Your primary problem here is that you overwrite numbers you haven't already covered.
if (mi_array[i] != 0) {
mi_array[x] = mi_array[i];
x++;
}
x can never exceed i in this code; it starts at 0 just like i does, and increments at most by 1 every loop (and i increments by 1 every loop). So, no problem here; at 'worst' this is mi_array[i] = mi_array[i]; which does nothing.
however...
} else {
mi_array[y]=mi_array[i];
y--;
}
This is much more problematic. Given inputs {9,4,0,0,4,0,3,0,1,8,0};, when i is 2, then mi_array[i] is 0, thus this code runs. y is still 10, so this will end up running: mi_array[10] = 0;. The second 0 occurs when i is 3, and ends up running: mi_array[9] = 0;. And at that point, the 8 at index 9? You deleted it. It cannot be recovered.
The solution
The dumb solution is to make a copy of the array; edit the copy, refer to the original (which you won't change at all). You don't actually end up needing a copy; this code will write every number back, so just make a new array of the same size and write in that.
A slightly more elegant solution will not write 0s at all. Instead, it just writes the non-zeroes (as that code cannot overwrite anything, as shown before), and then at the end, overwrite the rest with zeroes. Now you don't need a copy.
O(n), two-pointer approach:
public static void shiftZeroesRight(int[] array) {
int notZeroPos;
for (int i = 0; i < array.length; i++) {
if (array[i] != 0)
continue;
notZeroPos = i + 1;
while (notZeroPos < array.length && array[notZeroPos] == 0)
++notZeroPos;
if (notZeroPos >= array.length)
break;
array[i] = array[notZeroPos];
array[notZeroPos] = 0;
}
}
Basically my code needs to calculate the sum of the path in an nxn matrix ( starts at 0,0), and adds up the smallest sum where I'm only allowed to move right or downwards.
For example the matrix below should output 18 because the min path is 5 1 2 4 6, but I don't know how should my base case be here. I know I should stop the recursion once I reach array [n][n] though..in my code below I'm getting a stackoverflow error.
512
234
566
import java.util.*;
public class shortestpath {
public static int findminpath(int [][]c,int x,int y,int n) {
if (x==n-1 && y==n-1) {
return c[x][y];
} else {
int path1 = findminpath(c,x+1,y,n);
int path2 = findminpath (c,x,y+1,n);
return c[x][y] + Math.min(path1,path2);
}
}
public static void main (String [] args) {
Scanner sc = new Scanner (System.in);
int[][] array = new int[3][3];
for (int i=0; i<array.length; i++){
for (int j=0; j<array.length; j++){
array[i][j] = sc.nextInt();
}
}
System.out.println(findminpath(array,0,0,array.length));
}
}
The issue comes from your if statement.
if (x==n-1 && y==n-1)
Note that if you trace through your code by hand, you will have the following method calls on your stack.
findminpath(array, 0, 0, 3)
findminpath(array, 1, 0, 3)
findminpath(array, 2, 0, 3)
findminpath(array, 3, 0, 3)
findminpath(array, 4, 0, 3)
findminpath(array, 5, 0, 3)
findminpath(array, 6, 0, 3)
findminpath(array, 7, 0, 3)
....
The reason is because of the && you have in the if statement. y hasn't incremented yet, and it will never increment from this recursion because you will go until x reaches the maximum int value.
I've been working in a little Java project but I can't figure out how to overwrite the elements of an array based on the values on another array.
Basically I have two arrays: repeated[] = {1,4,0,0,0,3,0,0} and hand[] = {1,2,2,2,2,6,6,6} and I use repeated[] to count the amount of times a number appears on hand[], and if it is between 3 and 7 it should overwrite the corresponding element in hand[] with a zero but I keep getting this output {1,0,0,2,2,6,0,6} when it should give me {1,0,0,0,0,0,0,0}. What am I doing wrong?
public static void main(String[] args) {
int repeated[] = {1,4,0,0,0,3,0,0};
int hand[] = {1,2,2,2,2,6,6,6};
for(int z=0;z<repeated.length;z++){
if(repeated[z]>=3 && repeated[z]<8){
for(int f:hand){
if(hand[f]==(z+1)){
hand[f]=0;
} } } }
for(int e:hand){
System.out.print(e+",");
}
}
First, the value in repeated is offset by one (because Java arrays start at index zero). Next, you need to test if the value is >= 3 (because 6 only appears 3 times). And, you could use Arrays.toString(int[]) to print your array. Something like,
public static void main(String[] args) {
int repeated[] = { 1, 4, 0, 0, 0, 3, 0, 0 };
int hand[] = { 1, 2, 2, 2, 2, 6, 6, 6 };
for (int z = 0; z < repeated.length; z++) {
if (repeated[hand[z] - 1] >= 3) {
hand[z] = 0;
}
}
System.out.println(Arrays.toString(hand));
}
Output is
[1, 0, 0, 0, 0, 0, 0, 0]
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Does anybody know how to move "on the ones" and change them to 2? I think we need recursion, but I'm not very good at it, so I'm asking you for help.
You can only move up, down, left or right.
Here is an example:
int[][] a = {{ 0, 0, 0},
{1, 1, 0},
{1, 1, 1},
{1, 0, 1} };
recursiveFunction(a, 1, 1); // (<array you're checking>, <x of the group>, <y of the group>
/* int a now contains:
* { 0, 0, 0,
* 2, 2, 0,
* 2, 2, 2,
* 2, 0, 2 } */
int[][] b = {{0, 0, 0, 0, 1},
{1, 1, 0, 0, 1},
{1, 1, 1, 0, 1},
{1, 0, 1, 0, 1} };
recursiveFunction(b, 0, 5);
/* int b now contains:
* { 0, 0, 0, 0, 2
* 1, 1, 0, 0, 2
* 1, 1, 1, 0, 2
* 1, 0, 1, 0, 2 } */
You have defined just 1D array and its number so you should use int.
Instead of doing it recursively, try solving it easily with two for loops (1 for row and 1 for column) for 2D array as below:
int array[][] = {{0, 0, 0},
{1, 1, 0},
{1, 1, 1},
{1, 0, 1}};
for (int i = 0; i< array.length; i++) {
for (int j = 0; j< array[0].length; j++) {
if (array[i][j] == 1) {
array[i][j] = 2;
}
}
}
You dont need recursion for this .It is pretty straightforward.Also notice the way I have created a 2d array
char[][] a = { {0, 0, 0},
{1, 1, 0},
{1, 1, 1},
{1, 0, 1 }};
for(int i = 0; i < a.length; i++)
for(int j = 0; j < a[i].length; j++) {
if(a[i][j] == 1)
a[i][j] = 2;
}
}
Would this work ?
You can create a function and pass it the value that you want to replace. It will be better then recursion because you can avoid extra cost of stack that will be required during each recursive call
public static void replace(char[][] arr, char target, char replacment) {
for (int i = 0; i< arr.length; i++) {
for (int j = 0; j< arr[i].length; j++) {
if (arr[i][j] == target) {
arr[i][j] = replacment;
}
}
}
}
Then you can call it like this
replace(arr, (char)1, (char)2);
Ok, so if you want to change value of the connected component you start out in this should work.
public class Example {
public static void main(String[] args) {
int[][] b =
{
{0, 0, 0, 0, 1},
{1, 1, 0, 0, 1},
{1, 1, 1, 0, 1},
{1, 0, 1, 0, 1}
};
rec(b, 0, 4);
for (int[] row : b) {
System.out.println(Arrays.toString(row));
}
}
public static void rec(final int[][] grid, final int row, final int col) {
if (grid[row][col] != 1) return;
grid[row][col]++;
if (row-1 >= 0) rec(grid, row-1, col);
if (row+1 < grid.length) rec(grid, row+1, col);
if (col-1 >= 0) rec(grid, row, col-1);
if (col+1 < grid[0].length) rec(grid, row, col+1);
}
}
Note that depending of how big your components are you might run out of stack. Either you'd then have to manage your own stack explicitly in the code or you would need to increase the stack space available to the JVM.
Why do you think you need recursion? You could just iterate over the array and multiply every element by two (since 0 * 2 is 0 anyway, and it's faster than having to check the element):
for (int i = 0; i < a.length; ++i) {
for (int j = 0; j < a[i].length; ++j) {
a[i][j] *= 2;
}
}
If you are using Java 8 the Arrays.parallelSetAll method could be used.
public static void replace(int[][] arr, int target, int replacement) {
Arrays.parallelSetAll(arr, row -> {
Arrays.parallelSetAll(arr[row], col -> arr[row][col] == target ? replacement : arr[row][col]);
return arr[row];
});
}
It uses the Java 8 Stream API:s and offers a quite nice compact programming model. Furthermore, it uses the ForkJoinPool so performance could be better since it may be multi-threaded (depending on the CPU etc).