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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值