Development/CodeWorkout
[CodeWorkout] X119: squareUp
bbubbush
2022. 4. 27. 00:10
Question
Given n >= 0, create an array of length n * n with the following pattern, shown here for n = 3 : {0, 0, 1, 0, 2, 1, 3, 2, 1} (spaces added to show the 3 groups).
Answer
반응형
package com.bbubbush.tistory;
import java.util.Arrays;
import java.util.stream.Collectors;
public class X119 {
public static void main(String[] args) {
int n;
n = 3;
System.out.printf("[n = %d]\n", n);
printArray(squareUp(n));
n = 5;
System.out.printf("[n = %d]\n", n);
printArray(squareUp(n));
n = 9;
System.out.printf("[n = %d]\n", n);
printArray(squareUp(n));
}
public static int[] squareUp(int n) {
int[] result = new int[n * n];
int value = 0;
int maxValue = n + 1;
for (int i = result.length; i > 0; i--) {
if (i % n == 0) {
value = 1;
maxValue--;
}
if (maxValue >= value) {
result[i - 1] = value++;
} else {
result[i - 1] = 0;
}
}
return result;
}
private static void printArray(int[] arr) {
String strArr = Arrays.stream(arr)
.mapToObj(String::valueOf)
.collect(Collectors.joining(", "));
System.out.println(strArr);
}
}
Ref
https://github.com/bbubbush/codeworkout/blob/master/src/com/bbubbush/tistory/X119.java
GitHub - bbubbush/codeworkout
Contribute to bbubbush/codeworkout development by creating an account on GitHub.
github.com