質問するログイン新規登録

回答編集履歴

1

思いつき

2020/07/25 09:41

投稿

xebme
xebme

スコア1113

answer CHANGED
@@ -53,4 +53,40 @@
53
53
  .mapToObj(Integer::valueOf)
54
54
  .collect(ArrayList<Integer>::new,(acc,x)->{acc.add(acc.size()/2,x);acc.add(acc.size()/2,x);},Collection::addAll);
55
55
  }
56
+ ```
57
+
58
+ **配列の添字を動かす**
59
+
60
+ ArrayListを使わず配列だけを使用するなら、連続した整数を与えて、添字をN-1〜0、0〜N-1へと動かせば良いことに気づいたので、メソッドを作成。`size`が配列のサイズ、`i`が連続した整数です。
61
+
62
+ ```Java
63
+ static int genIndex(int size, int i) {
64
+ return i%(2*size) - ((i/size)%2) * (2*(i%size)+1);
65
+ }
66
+ ```
67
+
68
+ 以下のように添字が動きます。Nは配列のサイズ。
69
+
70
+ - 0 <= i < 2*N
71
+ 0, 1, … N-1, N-1, … 1, 0
72
+ - N <= i < 3*N
73
+ N-1, … 1, 0, 0, 1, … N-1
74
+
75
+ テストケース。
76
+
77
+ ```Java
78
+ @Test
79
+ void testGenIndex() {
80
+
81
+ BiFunction<Integer,Integer,Integer> genIdx = list::genIndex;
82
+ Function<Integer,UnaryOperator<Integer>> supplyGen = size -> i -> genIdx.apply(size,i);
83
+ int size = 5;
84
+ UnaryOperator<Integer> gen = supplyGen.apply(size);
85
+
86
+ String result = IntStream.range(0,6*size).map(i -> gen.apply(i)).mapToObj(String::valueOf).collect(Collectors.joining(","));
87
+ assertEquals("0,1,2,3,4,4,3,2,1,0,0,1,2,3,4,4,3,2,1,0,0,1,2,3,4,4,3,2,1,0",result);
88
+
89
+ result = IntStream.range(size,7*size).map(i -> gen.apply(i)).mapToObj(String::valueOf).collect(Collectors.joining(","));
90
+ assertEquals("4,3,2,1,0,0,1,2,3,4,4,3,2,1,0,0,1,2,3,4,4,3,2,1,0,0,1,2,3,4",result);
91
+ }
56
92
  ```