JAVA程式討論

2009-05-04 5:38 am
今天有10個人漂流到1個食人族的島嶼
酋長抓到他們後跟他們說
我是很仁慈的 我會放你們其中一個人回去
你們坐著排一圈 編號1-10
我們每次會吃掉第3個人
1 2 吃掉3號
4 5 吃掉6號
7 8 吃掉9號
10 1 吃掉2號
這樣的規則

請用一個有陣列的程式
算出誰沒有被吃掉

我嘗試過了
這是我的想法
先設定一個陣列
int[] people={1,1,1,1,1,1,1,1,1,1,1};
每數到一次就把裡面的數-1
再用if判斷 被吃過就跳過去 沒被吃過就吃他
再用陣列裡面的值的加總來判斷迴圈是否要繼續跑
最後印出陣列裡還有1的編號
例如:int[] people = {0,0,0,1,0,0,0,0,0,0};
就印出 4號沒被吃
更新1:

最後陣列總數剩1的時候要停止程式 用IF判斷一下

回答 (4)

2009-05-04 10:09 pm
✔ 最佳答案
參考一下我的方法吧!!省掉允長的程式碼

import java.util.LinkedList;
import java.util.List;

public class Token {
public static void main(String args[]) {
int[] number = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
List<Integer> list = new LinkedList<Integer>();
for (int i : number) {
list.add(i);
}
int step = 2;
int i = 0;
while (list.size() != 1) {
i = i + step;
i = (i >= list.size()) ? i % list.size() : i;
list.remove(i);
}
for (int j : list) {
System.out.println(j);
}
}
}

參考: mySelf
2009-05-04 6:10 pm
public class Test {
public static void main(String[] args) {
final int NumOfPeople=10;
final int Step=2;
Test t = new Test();

int[] a = new int[NumOfPeople];
int i, k, n=0;
int num=NumOfPeople;

for ( i=0; i < num; i++ ) {
a[i] = 0;
}
i = Step;
a[i] = 1;
System.out.print(( i + 1 ) + " " );
k = 1;
while ( k < num-1 ) {
i = t.find_next( a, i, num, Step );
a[i] = 1;
System.out.print(( i + 1 ) + " " );
k++;
}
System.out.println();

i = 0;
while (( i < num ) && ( a[i] == 1 )) {
i++;
}
System.out.println("The last one to stand is " + (i + 1));
}

public static int find_next( int[] a, int n, int num, int step ) {
int i=n;
int k=0;

while ( a[i] == 1 ) {
i++;
i %= num;
}
while ( k < step ) {
i++;
i %= num;
while ( a[i] == 1 ) {
i++;
i %= num;
}
k++;
}
return i;
}
}

// The Step and NumOfPeople are tunable. You can play with them a bit.
// Don't have much time to debug but I think this should work ok.

2009-05-04 8:47 am
妳那個加總設為<=1時停止程式看看
2009-05-04 8:01 am
不知道是我的問題還是題目的問題
我程式跑出來是顯示全部都被吃掉跟本沒有一個人是活的
大大你能不能算一下最後會不會剩一個人
如果是剩一個人我在算看看= =


收錄日期: 2021-04-30 13:26:00
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20090503000010KK10470

檢視 Wayback Machine 備份