今何行目ですか
文字の白黒判定はi % 2
これに今何行目かを加えるとよい (i + i/4) % 2
行に含まれる文字数を変えたければ4を任意の数n
に変える
ただしnが偶数の場合のみ行i/n
を加える
改行は(i+1)%n == 0
素朴案
1行の文字数が偶数、奇数どちらの場合でもチェッカーボードになるよう除数d
を調整しました。
Java
1 345
6 static void pattern(int l, int n) {
7 int d = (l%2==0) ? l : l * n;
8 for (int i = 0; i < l * n; ++i) {
9 if ((i+i/d)%2 == 0) {
10 System.out.print('□');
11 } else {
12 System.out.print('■');
13 }
14 if ((i+1)%l == 0) {
15 System.out.println();
16 }
17 }
18 System.out.println();
19 }
関数化案
文字の判定、改行の判定をそれぞれ関数化しました。
Java
1import java.util.function.Function;
2import java.util.stream.Collectors;
3import java.util.stream.IntStream;
4
5public class CheckerBoard {
6
7 static Function<Integer,String> letter = x -> (x%2 == 0) ? "□" : "■";
8 static Function<Integer,Function<Integer,String>> supp1 = l -> (l%2 == 0) ? x -> letter.apply(x + x/l): x -> letter.apply(x);
9 static Function<Integer,Function<Integer,String>> supp2 = l -> x -> ((x+1)%l == 0) ? "\r\n" : "";
10
11 static void pattern(int l, int n) {
12 Function<Integer,String> bw = supp1.apply(l); // "□""■"判定
13 Function<Integer,String> cr = supp2.apply(l); // "\r\n"判定
14 System.out.println(
15 IntStream.range(0,l * n)
16 .mapToObj(i -> bw.apply(i) + cr.apply(i))
17 .collect(Collectors.joining())
18 );
19 }
20}