C#狼追兔子问题
一只兔子躲進了 10 個環形分布的洞的某一個,狼在第一個洞沒有找到兔子,就隔一個洞,到第三個洞去找,也沒有找到,就隔兩個洞,到第六個洞去找,以后每次多隔一個洞 去找兔子……這樣下去,結果一直找不到兔子,請問:兔子可能躲在哪個洞中?
算法思想:
| (1) | 1 |
| (2) | (1)+2=3 |
| (3) | (2)+3=6 |
| (4) | (3)+4=10 |
| (5) | (4)+5=10+5 |
| (6) | (5)+6=2*10+1 |
| (7) | (6)+7=2*10+8 |
| (8) | (7)+8=3*10+6 |
| (9) | (8)+9=4*10+5 |
| (10) | (9)+10=5*10+5 |
C#代碼實現:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections;namespace 狼追兔子問題 {class Program{static void Main(string[] args){int x1 = 1;int x2 = 0;int yushu; //狼可以去的洞口int[] a = new int[] {0,1,2,3,4,5,6,7,8,9,10};for (int i = 2; i < 100; i++){if (x1 % 10 == 0){yushu = x1 % 10 + 10; //第10個洞口}else{yushu = x1 % 10 ;}//Console.Write(yushu + " ");for (int j = 0; j < a.Length; j++){if (yushu == j) {a[j] = 0; //經過的洞口號碼在數組中置0}}x2 = x1 + i;x1 = x2;}Console.WriteLine("兔子可能躲的洞是:");for (int i = 0; i < a.Length; i++) //數組用a.Length的方法來界定長度,最不容易數組越界{if (a[i] != 0) //去掉數組中已經置0的成員{Console.Write(a[i] + " ");} }Console.ReadKey();}} }輸出的結果是:
兔子可能躲的洞是:
2 4 7 9
總結
- 上一篇: 互联网公司面试经历(转载)
- 下一篇: C#冒泡排序算法