回答編集履歴
2
説明追加
test
CHANGED
@@ -22,13 +22,15 @@
|
|
22
22
|
|
23
23
|
```java
|
24
24
|
|
25
|
+
//list:じゃんけんするPlayerのリスト,firstRank:この組の最上位が,全体で何位か
|
26
|
+
|
25
27
|
public static void playJanken(List<Player> list, int firstRank){
|
26
28
|
|
27
29
|
|
28
30
|
|
29
|
-
//Playerでじゃんけんを行い,勝ち負けを決定する
|
31
|
+
//listにいるPlayerでじゃんけんを行い,勝ち負けを決定する
|
30
32
|
|
31
|
-
//(一人の場合には
|
33
|
+
//(一人の場合には,そのPlayerの順位がfirstRankで確定して終了)
|
32
34
|
|
33
35
|
|
34
36
|
|
@@ -44,9 +46,9 @@
|
|
44
46
|
|
45
47
|
//再帰でじゃんけん続行
|
46
48
|
|
47
|
-
playJanken(winnerList, firstRank);
|
49
|
+
playJanken(winnerList, firstRank); //勝った人でじゃんけん
|
48
50
|
|
49
|
-
playJanken(loserList, firstRank + winnerList.size());
|
51
|
+
playJanken(loserList, firstRank + winnerList.size()); //負けた人でじゃんけん.勝った人の人数分,順位が下がる
|
50
52
|
|
51
53
|
}
|
52
54
|
|
1
再帰のコードを提示
test
CHANGED
@@ -13,3 +13,55 @@
|
|
13
13
|
「じゃんけんする」という手続きは人数が変わってるだけで基本的に同じはずなので,
|
14
14
|
|
15
15
|
こう考えればコードを組みやすくなるのではないでしょうか.
|
16
|
+
|
17
|
+
---
|
18
|
+
|
19
|
+
|
20
|
+
|
21
|
+
イメージが湧きにくいかもしれないので,概要をコードで書いてみました.
|
22
|
+
|
23
|
+
```java
|
24
|
+
|
25
|
+
public static void playJanken(List<Player> list, int firstRank){
|
26
|
+
|
27
|
+
|
28
|
+
|
29
|
+
//Playerでじゃんけんを行い,勝ち負けを決定する
|
30
|
+
|
31
|
+
//(一人の場合にはじゃんけんせず終了,そのPlayerの順位が確定する)
|
32
|
+
|
33
|
+
|
34
|
+
|
35
|
+
List<Player> winnerList = new ArrayList<Player>();
|
36
|
+
|
37
|
+
List<Player> loserList = new ArrayList<Player>();
|
38
|
+
|
39
|
+
|
40
|
+
|
41
|
+
//勝ったPlayerをwinnerListに,負けたPlayerをloserListに入れる
|
42
|
+
|
43
|
+
|
44
|
+
|
45
|
+
//再帰でじゃんけん続行
|
46
|
+
|
47
|
+
playJanken(winnerList, firstRank);
|
48
|
+
|
49
|
+
playJanken(loserList, firstRank + winnerList.size());
|
50
|
+
|
51
|
+
}
|
52
|
+
|
53
|
+
```
|
54
|
+
|
55
|
+
これで何が起こるかというと,
|
56
|
+
|
57
|
+
まず全員でじゃんけんし,勝ち負けで分けます(1).
|
58
|
+
|
59
|
+
その後,勝ち組でじゃんけんします.この時,新たにplayJankenメソッドが呼ばれます.
|
60
|
+
|
61
|
+
そしてまた勝ち負けで分かれます(2)が,
|
62
|
+
|
63
|
+
この(1)のloserListと(2)のloserListは別に管理されていて,互いに干渉しません(上書きされません).
|
64
|
+
|
65
|
+
メソッドから別のメソッドのローカル変数には干渉できませんよね?それと同じです.
|
66
|
+
|
67
|
+
これを繰り返して行くといずれ最初の勝ち組の処理が終わるので,負け組の処理に入れます.
|