import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class Kata { public static int findIndex (int[] array, int target) { return Arrays.stream(array).boxed().collect(Collectors.toList()).indexOf(target); } }
import org.apache.commons.lang3.ArrayUtils;- import java.util.Arrays;
- import java.util.List;
- import java.util.stream.Collectors;
- public class Kata {
- public static int findIndex (int[] array, int target) {
return ArrayUtils.indexOf(array, target);- return Arrays.stream(array).boxed().collect(Collectors.toList()).indexOf(target);
- }
- }
Arrays
Data Types
Given a 2D integer matrix, format it to print the matrix with each character occupying a minimum width.
import java.lang.StringBuilder;
import java.util.Arrays;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.stream.Collectors;
public class Kata {
public static String stringify2dArray(int[][] array, int width) {
String pattern = "%" + width + "s";
return Arrays.stream(array)
.map(formatRow(pattern))
.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
.toString();
}
private static Function<? super int[], ? extends String> formatRow(String pattern) {
return row -> Arrays.stream(row)
.mapToObj(formatCell(pattern))
.collect(Collectors.joining(" ")) + "\n";
}
private static IntFunction<? extends String> formatCell(String pattern) {
return cell -> String.format(pattern, cell);
}
}
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class SolutionTest {
@Test
void testStringify() {
assertEquals(" 1 2\n 2 3\n", Kata.stringify2dArray(new int[][] {{1, 2}, {2, 3}}, 3));
assertEquals(" 10 9\n 21 3\n", Kata.stringify2dArray(new int[][] {{10, 9}, {21, 3}}, 3));
assertEquals(" 123 19\n 21 413\n 156 546\n 46 465 456 451\n",
Kata.stringify2dArray(new int[][] {{123, 19},{21, 413}, {156, 546}, {46, 465, 456, 451}}, 4));
}
@Test
void testEdgeCases() {
assertEquals(" 1 0\n 1 0\n 0 0\n 0 1 0 1\n",
Kata.stringify2dArray(new int[][] {{1, 0},{1, 0}, {0, 0}, {0, 1, 0, 1}}, 3));
assertEquals(" -1 0\n -1 0\n 0 -1\n 0 0 0 0\n",
Kata.stringify2dArray(new int[][] {{-1, 0},{-1, 0}, {0, -1}, {0, 0, 0, 0}}, 4));
assertEquals("16164 16164\n",
Kata.stringify2dArray(new int[][] {{16164, 16164}}, 4));
}
}