[JAVA-616] core-java-arrays-multidimensional
* Creation * Moved code from https://www.baeldung.com/java-jagged-arrays * Moved code from https://www.baeldung.com/java-loop-diagonal-array
This commit is contained in:
@@ -5,7 +5,6 @@ This module contains articles about Java arrays
|
||||
## Relevant Articles
|
||||
|
||||
- [Extending an Array’s Length](https://www.baeldung.com/java-array-add-element-at-the-end)
|
||||
- [Looping Diagonally Through a 2d Java Array](https://www.baeldung.com/java-loop-diagonal-array)
|
||||
- [Converting Between Stream and Array in Java](https://www.baeldung.com/java-stream-to-array)
|
||||
- [Convert a Float to a Byte Array in Java](https://www.baeldung.com/java-convert-float-to-byte-array)
|
||||
- [Array Operations in Java](https://www.baeldung.com/java-common-array-operations)
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package com.baeldung.array.looping;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class LoopDiagonallyUnitTest {
|
||||
|
||||
@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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user