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:
rpvilao 2019-07-21 20:51:03 +02:00 committed by GitHub
commit 352ea88a7b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 65 additions and 0 deletions

View File

@ -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();
}
}

View File

@ -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);
}
}