Merge pull request #7352 from Thabo08/loop-through-array
t.ntsoko@gmail.com - Demo code for looping diagonally through a square 2D array
This commit is contained in:
commit
352ea88a7b
|
@ -0,0 +1,45 @@
|
||||||
|
package com.baeldung.array.looping;
|
||||||
|
|
||||||
|
public class LoopDiagonally {
|
||||||
|
|
||||||
|
|
||||||
|
public String loopDiagonally(String[][] twoDArray) {
|
||||||
|
|
||||||
|
int length = twoDArray.length;
|
||||||
|
int diagonalLines = (length + length) - 1;
|
||||||
|
int itemsInDiagonal = 0;
|
||||||
|
int midPoint = (diagonalLines / 2) + 1;
|
||||||
|
StringBuilder output = new StringBuilder();
|
||||||
|
|
||||||
|
for (int i = 1; i <= diagonalLines; i++) {
|
||||||
|
|
||||||
|
StringBuilder items = new StringBuilder();
|
||||||
|
int rowIndex;
|
||||||
|
int columnIndex;
|
||||||
|
|
||||||
|
if (i <= midPoint) {
|
||||||
|
itemsInDiagonal++;
|
||||||
|
for (int j = 0; j < itemsInDiagonal; j++) {
|
||||||
|
rowIndex = (i - j) - 1;
|
||||||
|
columnIndex = j;
|
||||||
|
items.append(twoDArray[rowIndex][columnIndex]);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
itemsInDiagonal--;
|
||||||
|
for (int j = 0; j < itemsInDiagonal; j++) {
|
||||||
|
rowIndex = (length - 1) - j;
|
||||||
|
columnIndex = (i - length) + j;
|
||||||
|
items.append(twoDArray[rowIndex][columnIndex]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (i != diagonalLines) {
|
||||||
|
output.append(items).append(" ");
|
||||||
|
} else {
|
||||||
|
output.append(items);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return output.toString();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,20 @@
|
||||||
|
package com.baeldung.array.looping;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
public class LoopDiagonallyTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void twoArrayIsLoopedDiagonallyAsExpected() {
|
||||||
|
|
||||||
|
LoopDiagonally loopDiagonally = new LoopDiagonally();
|
||||||
|
String[][] twoDArray = {{"a", "b", "c"},
|
||||||
|
{"d", "e", "f"},
|
||||||
|
{"g", "h", "i"}};
|
||||||
|
|
||||||
|
String output = loopDiagonally.loopDiagonally(twoDArray);
|
||||||
|
assertEquals("a db gec hf i", output);
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue