-
Notifications
You must be signed in to change notification settings - Fork 0
/
merger.java
66 lines (64 loc) · 2.26 KB
/
merger.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
public class merger{
public static void main(String[] args){
int a[][] = { {1,0,0,1},
{1,1,1,1},
{1,0,1,0},
{1,0,0,0},};
print(a);
int v[] = {0,1};
int[][] b = merger(a,v);
System.out.println("---------------");
print(b);
}
static void print(int arr[][]){
// iterating through the given array and printing the values;
for(int y = 0; y<arr.length; y++){
for(int x = 0; x<arr[y].length; x++){
System.out.print(arr[y][x] + ", ");
}
System.out.println();
}
}
static int[][] merger(int[][] a, int[] v){
// Making a copy of the input array
int arr[][] = a.clone();
for(int i = 0; i<arr.length; i++){
arr[i] = a[i].clone();
}
boolean swapped = true; // to displace again and again until all the values are displace completely
int startX, startY, endX, endY, temp;
// calculating the starting and ending value for the loop to iterate
if(v[0] < 0 || v[1] < 0){
startX = Math.abs(v[0]);
startY = Math.abs(v[1]);
endY = arr.length;
endX = arr[0].length;
}else{
startX = 0;
startY = 0;
endY = arr.length-v[1];
endX = arr[0].length-v[0];
}
while(swapped){
swapped = false;
for(int y = startY; y<endY; y++){
// recalculating the ending values for the arrays that are not perfect( i mean have different lengths)
if(v[0] < 0 || v[1] < 0){
endY = arr.length;
endX = arr[y].length;
}else{
endY = arr.length-v[1];
endX = arr[y].length-v[0];
}
for(int x = startX; x<endX; x++){
if(arr[y][x] == arr[y+v[1]][x+v[0]] && arr[y][x] != 0){
arr[y][x] = arr[y][x] + arr[y+v[1]][x+v[0]];
arr[y+v[1]][x+v[0]] = 0;
swapped = true;
}
}
}
}
return arr;
}
}