C#练习题答案: 猫和狗的数组矩阵【难度:2级】--景越C#经典编程题库,1000道C#基础练习题等你来挑战

猫和狗的数组矩阵【难度:2级】:

答案1:

using System;
using System.Linq;
using System.Collections.Generic;
    public static class Kata
    {
        public static int Solve(List<char> xk, int n)
        {
            List<char> xs = new List<char>();
            xs = xk.ToList();
            int res = 0;
            for (int i = 0; i < xs.Count(); i++)
            {
                if (xs[i] == 'D')
                {
                    int check = 0;
                    for (int j = i - n; j < i; j++)
                    {
                        if (j > -1 &amp;&amp; xs[j] == 'C')
                        {
                            res++;
                            xs[j] = 'P';
                            check++;
                            break;
                        }
                    }
                    if (check == 0)
                    {
                        for (int j = i + 1; j <= i + n; j++)
                        {
                            if (j < xs.Count() &amp;&amp; xs[j] == 'C')
                            {
                                res++;
                                xs[j] = 'P';
                                break;
                            }
                        }
                    }
                }
            }
            return res;
        }
    }

答案2:

using System;
using System.Collections.Generic;
using System.Linq;
public static class Kata
{
  public static int Solve(List<char> xs, int n)
  {
      if (xs.Count < 2 || n == 0) return 0;
            var dog = 'D';
            var cat = 'C';
            var result = new List<int>();
            var cats = new List<int>();
            for (var i = 0; i < xs.Count; i++)
            {
                if(xs[i] == cat) cats.Add(i);
            }
            for (var i = 0; i < xs.Count; i++)
            {
                if (xs[i] == dog)
                {
                    var allowCats = cats.Where(x => !result.Contains(x) &amp;&amp; Math.Abs(x - i) <= n).ToList();
                    if(!allowCats.Any()) continue;
                    var catIndex = allowCats.First();
                    result.Add(catIndex);
                }
            }
            return result.Count;
  }
}

答案3:

using System;
using System.Collections.Generic;

public static class Kata
{
  public static int Solve(List<char> input, int n)
  {
     //To indicate whether each cat has been caught
     var caughtCats = new bool[input.Count];
     var caughtCount = 0;
     for (int i = 0; i < input.Count; i ++)
     {
        if (input[i] == 'D')
        {
            var startCatchableRange = Math.Max(0, i - n); 
            var endCatchableRange = Math.Min(input.Count - 1, i + n);
            for (int j = startCatchableRange; j <= endCatchableRange; j++)
            {
                if (input[j] == 'C' &amp;&amp; !caughtCats[j])
                {
                  caughtCount++;
                  caughtCats[j] = true;
                  break;
                }
            }
        }  
     }
     return caughtCount;
  }
}

答案4:

using System;
using System.Collections.Generic;

public static class Kata
{
  public static int Solve(List<char> xs, int n)
  {
     //To indicate whether each input has been used
     var usedXs = new bool[xs.Count];
     var count = 0;
     for (int i = 0; i < xs.Count - 1; i ++)
     {
        if (usedXs[i])
        {
          continue;
        }          
          
       for (int j = i + 1; j <= i + n; j++)
       {
          if (j >= xs.Count)
          {
            break;
          }
          else if (usedXs[j])
          {
            continue;
          }
          else if (xs[i] != xs[j])
          {
             count++;
             usedXs[i] = true;
             usedXs[j] = true;
             break;
          }
       }
     }
     return count;
  }
}

答案5:

using System;
using System.Collections.Generic;

public static class Kata
{
public static int Solve(List<char> input, int n)
{
  input = new List<char>(input);
  var count = 0;
  for (int i = 0; i < input.Count; i++)
  {
    for (int c = 1; c <= n; c++)
    {
      if ((i + c) >= input.Count) break;
      if (input[i] == 'C')
      {
        if (input[i + c] == 'D')
        {
          input[i + c] = 'X';
          count++;
          break;
        }
      }
      else if (input[i] == 'D')
      {
        if (input[i + c] == 'C')
        {
          input[i + c] = 'X';
          count++;
          break;
        }
      }
    }                    
  }
  return count;
  }
}

答案6:

using System;
using System.Collections.Generic;

public static class Kata
{
  public static int Solve(List<char> xs, int n)
  {
    var used_dogs = new HashSet<int>();  
    for (int i = 0; i < xs.Count; i++)
    {
      if (xs[i] == 'D') continue;
      for (int k = (i - n) < 0 ? 0 : i - n; k <= i + n &amp;&amp; k < xs.Count; k++)
      {
        if (used_dogs.Contains(k)) continue;
        if (xs[k] == 'D')
        {
          used_dogs.Add(k);
          break;
        }
      }
    }
    return used_dogs.Count;
  }
}

答案7:

using System;
using System.Collections.Generic;
using System.Linq;


    public static class Kata
    {
        public static int Solve(List<char> xs, int n)
        {
            var dogs = new List<Dog>();
            var cats = new List<Cat>();
            var catsCaught = 0;

            var index = 0;

            //Get positions
            foreach (var item in xs)
            {
                if (item == 'D')
                {
                    dogs.Add(new Dog { Position = index });
                }
                if( item == 'C')
                {
                    cats.Add(new Cat { Position = index });
                }
                index++;
            }

            //Find cats
            foreach (var dog in dogs)
            {
                var cat = cats.Where(w => !w.Caught)
                            .FirstOrDefault(c => (n > 0) &amp;&amp; (Math.Abs(dog.Position - c.Position) <= n));

                if (cat  !=null )
                {
                    cat.Caught = true;
                    catsCaught++;                    
                }
            }


            return catsCaught;
        }

        public class Dog
        {
            public int Position;
        }

        public class Cat
        {
            public int Position;
            public bool Caught;
        }
    }

答案8:

using System;
using System.Collections.Generic;
using System.Linq;

public static class Kata
{
  public class AnimalUsed
  {
      public char Animal { get; set; }
      public bool Used { get; set; }

      public AnimalUsed(char animal, bool used = false)
      {
          Animal = animal;
          Used = used;
      }
  }

  public static int Solve(List<char> xs, int n)
  {
    //a cat cannot be caught more than once
    //a dog cannot catch more than one cat
    //iterate through each can and see if it can be caught

    int caught = 0;
    List<AnimalUsed> list = new List<AnimalUsed>();
    foreach(char c in xs)
    {
        list.Add(new AnimalUsed(c));
    }

    for(int i = 0; i < list.Count(); ++i)
    {
        //get elements at index i +- n, is a cat and hasn't been caught
        if (list[i].Animal == 'D')
        {
            try
            {
                int matchedindex = list.Select((animal, index) => new { index, animal })
                            .Where(x => x.index >= i - n
                                     &amp;&amp; x.index <= i + n
                                     &amp;&amp; x.animal.Animal == 'C'
                                     &amp;&amp; !x.animal.Used)
                             .First().index;

                //mark both as used
                list[i].Used = true;
                list[matchedindex].Used = true;
                ++caught;
            }
            catch(Exception e)//none found
            {

            }
        }

    }

    return caught;
  }
}

答案9:

using System;
using System.Collections.Generic;
using System.Linq;

public static class Kata
{
  public static int Solve(List<char> xs, int n)
  {
      //convert to the helper class
      Animal[] newField = xs.AsParallel().Select(x => new Animal(x)).ToArray();
     
      for (int a = 0; a < newField.Length; a++)
      {      
        if (newField[a].IsUsed)
        {
           continue;
        }

        //count and correct range edges for the helper function
        int from = (a - n < 0) ? 0 : a - n;
        int to = (a + n >= newField.Length) ? newField.Length - 1 : a + n;

        Check(newField, from, to, a);
      }

      return newField.Count(x => x.IsCat &amp;&amp; x.IsUsed);
  }
  
  //checks the actual range of animals from our current animal into negative and positive directions
  private static void Check(Animal[] field, int from, int to, int it)
  {  
     //check the given range
     for (int i = from; i < to+1; i++)
     {
       if (i == it)
       {
         continue;
       }

       //not already catched a cat or has been catched by a dog and
       //the ivestigated pair of animals are a dog and a cat
       if (!field[i].IsUsed &amp;&amp; field[i].IsCat == !field[it].IsCat)
       {
         field[i].IsUsed = true;
         field[it].IsUsed = true;
         break;
       }
     }
  }

  //helper inner class to follow the already checked elements and the result of check
  class Animal
  {
     public Animal(char mark)
     {
        IsCat = mark.Equals('C');

        if (!IsCat &amp;&amp; !mark.Equals('D'))
        {
           throw new Exception("Neither Cat or Dog has been given!");
        }

        IsUsed = false;
     }

     public bool IsUsed { get; set; }
     public bool IsCat { get; set; }
  }
}

答案10:

using System;
using System.Collections.Generic;
using System.Linq;

public static class Kata
{
  public static int Solve(List<char> xs, int n)
  {
      //convert to the helper class
      Animal[] newField = xs.AsParallel().Select(x => new Animal(x)).ToArray();
     
      for (int a = 0; a < newField.Length; a++)
      {      
        if (newField[a].IsUsed)
        {
           continue;
        }

        //count and correct range edges for the helper function
        int from = (a - n < 0) ? 0 : a - n;
        int to = (a + n >= newField.Length) ? newField.Length - 1 : a + n;

        Check(newField, from, to, a);
      }

      return newField.Count(x => x.IsCat &amp;&amp; x.IsUsed);
  }
  
  //checks the actual range of animals from our current animal into negative and positive directions
  private static void Check(Animal[] field, int from, int to, int it)
  {  
     //check the given range
     for (int i = from; i < to+1; i++)
     {
       if (i == it)
       {
         continue;
       }

       //not already catched a cat or has been catched by a dog and
       //the ivestigated pair of animals are a dog and a cat
       if (!field[i].IsUsed &amp;&amp; field[i].IsCat == !field[it].IsCat)
       {
         field[i].IsUsed = true;
         field[it].IsUsed = true;
         break;
       }
     }
  }

  //helper inner class to follow the already checked elements and the result of check
  class Animal
  {
     public Animal(char mark)
     {
        IsCat = mark.Equals('C');

        if (!IsCat &amp;&amp; !mark.Equals('D'))
        {
           throw new Exception("What is this???");
        }

        IsUsed = false;
     }

     public bool IsUsed { get; set; }
     public bool IsCat { get; set; }
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值