C#练习题答案: 字母战争 - 核打击【难度:3级】--景越C#经典编程题库,1000道C#基础练习题等你来挑战

字母战争 - 核打击【难度:3级】:

答案1:

using System;
using System.Text.RegularExpressions;
using System.Linq;
public class Kata
{
    public static string AlphabetWar(string b)
    => !b.Contains('#') ? Regex.Replace(b,@"[\[\]]","") :
       string.Concat(Regex.Matches(b, @"(?<=([a-z#]*))\[([a-z]+)\](?=([a-z#]*))").Cast<Match>().Where(g => (g.Groups[1].Value + g.Groups[3].Value).Count(c => c == '#') < 2).Select(g => g.Groups[2].Value));
}

答案2:

using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

public class Kata {
    public static string AlphabetWar( string battleField ) {
        const char strike = '#';
        var underAttack = battleField.Contains( strike );
        if ( !underAttack ) {
            return battleField.Replace( "[", string.Empty ).Replace( "]", string.Empty );
        }
        var survivors = new StringBuilder();
        var shelterAreaRegex = new Regex( @"(?'s1'[^\]]*)\[(?'s'[a-z]+)\](?'s2'[^\[]*)" );
        while ( shelterAreaRegex.IsMatch( battleField ) ) {
            var m = shelterAreaRegex.Match( battleField );
            var shelterPopulation = m.Groups [ "s" ].Value;
            var frontStrikesCount = m.Groups [ "s1" ].Value.Count( c => c == strike );
            var behindStrikesCount = m.Groups [ "s2" ].Value.Count( c => c == strike );
            if ( frontStrikesCount + behindStrikesCount < 2 ) {
                survivors.Append( shelterPopulation );
            }
            battleField = battleField.Replace( m.Value, m.Groups [ "s2" ].Value );
        }
        return survivors.ToString( );
    }
}

答案3:


using System.Linq;
using System.Collections.Generic;
public class Kata
{
    static IEnumerable<string> War(string input)
    {
        bool bunkerFlag = true;
        var groups = input.Split('[', ']').Select(x => (letters: x, isBunker: bunkerFlag = !bunkerFlag, bombNum: x.Count(y => y == '#')));
        var linkedList = new LinkedList<(string letters, bool isBunker, int bombNum)>(groups);
        for (var node = linkedList.First; node != null; node = node.Next)
            if (!input.Contains('#') || node.Value.isBunker &amp;&amp; (node.Previous?.Value.bombNum ?? 0) + (node.Next?.Value.bombNum ?? 0) < 2)
                yield return node.Value.letters;
    }
    public static string AlphabetWar(string input) => string.Concat(War(input));
}

答案4:

using System.Text.RegularExpressions;

public class Kata {
  public static string AlphabetWar(string b) {
    bool ripOutside = Regex.Matches(b, "#").Count > 0;
    if (!ripOutside) return b.Replace("[", "").Replace("]", "");
    string[] areas = Regex.Split(b, @"\[|\]");
    string survivors = "";
    for (int i = 0; i < areas.Length; i++) {
      if (i % 2 == 1) {
        int bombCount = 0;
        try {bombCount += Regex.Matches(areas[i - 1], "#").Count;} catch {}
        try {bombCount += Regex.Matches(areas[i + 1], "#").Count;} catch {}
        if (bombCount < 2) survivors += areas[i];
      }
    }
    return survivors;
  }
}

答案5:

 using System;
 using System.Linq;
 using System.Text.RegularExpressions;
 
 public class Kata
 {
    public static string AlphabetWar(string b)
    {
        var now = Regex.Replace(b, @"(\w*#\w*)", "#");
        return string.Concat(Regex.Matches(now,
              @"(?=^[^#]*$).*|((?<!#{2,})\[\w+\](?!#))|((?<!#)\[\w+\](?!#{2,}))")
            .Cast<Match>()
            .Select(m => m.Value.Replace("[", "").Replace("]", "") ));
    }
}

答案6:

 using System;
 using System.Linq;
 public class Kata
 {
    public static string AlphabetWar(string b)
    {
        if (!b.Contains('#')) return string.Concat(b.Where(char.IsLetter));
        var sections = b.Split('[', ']');
        var nukeCounts = sections.Select(s => s.Count(c => c == '#')).ToArray();
        for (int i = 0; i < sections.Length; i++)
        {
            // even sections are outdoors, odd are inside shelters
            if (i % 2 == 0 || nukeCounts[i - 1] + nukeCounts[i + 1] > 1)
            {
                sections[i] = string.Empty;
            }
        }
        
        return string.Concat(sections);
    }
}

答案7:

using System.Text.RegularExpressions;
public class Kata
{
    public static string AlphabetWar(string b) => Regex.Replace((!b.Contains('#') ? b : Regex.Replace( 
      string.Concat(Regex.Matches(b, @"\[(\w*)\]|(#)")), @"(?<=##)\[(\w*)\]|(?<=#)\[(\w*)\](?=#)|\[(\w*)\](?=##)", "")), @"[^\w]","");
}

答案8:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
 
 public class Kata
 { 
 
 // The worst code ever written... should have used Regex
    private static List<char> temp;
    public static string AlphabetWar(String b)
    { 
        int s = 0;
        temp = new List<char>();
        foreach (char c in b)
        {
          temp.Add(c);
        }
        if (b.Contains("#")){
          bool inShelter = false;
          bool bomb;
          for(int i = 0; i < temp.Count(); i++)
          {
            bomb = false;
            switch(temp[i])
            {
            case '[':
              inShelter = true;
              break;
            case ']':
              inShelter = false;
              continue;
              //break;
            case '#':
              bomb = true;
              break;
            default:
              break; 
            }
            if (!(inShelter || bomb))
            {
              temp.RemoveAt(i);
              i--;
            }
          }
        }
        
        
        int leftBomb = 0;
        int rightBomb = 0;
        int shelter = 0;
        for (int i = 0; i < temp.Count(); i++)
        {
          if(temp[i] == '[')
          {
            if(shelter == 0)
            {
              shelter = 1;
            }
            else
            {
              i = elimate(ref leftBomb,ref rightBomb, i, ref shelter);
            }
            
          }
          else if(temp[i] == '#')
          {
            if (shelter != 0) 
            {
              rightBomb++;
            }
            else leftBomb++;        
          }
          
        }
        elimate(ref leftBomb, ref rightBomb, temp.Count() - 1, ref shelter);
        
        return String.Join("", String.Join("", temp).Where(Char.IsLetter));
        
    }
    
    private static int elimate(ref int left, ref int right, int index, ref int side)
    {
        if(left > 1)
        {
          index = deleteLeftShelter(index);
          left = right;
          right = 0;
        }
        else if(left == 1)
        {
          if (right > 0) 
          {
           index = deleteLeftShelter(index); 
          }
          left = right;
          right = 0;
        }
        else if(right > 1) 
        {
          index = delteLeftAndRightShelter(index);
          left = 0;
          right = 0;
          side = 0;
        }
        else 
        {
          left = right;
          right = 0;
        }
        return index;
    }
    
    private static int deleteLeftShelter(int index)
    {
      bool found = false;
      for (int i = index; i > 0; i--)
      {
        if (temp[i] == ']')
        {
          i--;
          if (i >= 0) temp.RemoveAt(i);
          index--;
          found = true;
        }
        else if(found)
        {
          if (temp[i] != '[')
          {
            temp.RemoveAt(i);
            index--;
          }
          else i = 0;
        }
      }
      
      return index;
    }

    private static int delteLeftAndRightShelter(int index)
    { 
      for (int i = index + 1; i < temp.Count() - 1;i++)
      {
        if(temp[i] == ']') i = temp.Count();
        else 
        {
          temp.RemoveAt(i);
          i--;
        }
      }
      return deleteLeftShelter(index);
    }
}

答案9:

 using System;
 using System.Collections.Generic;
 using System.Linq;
 
 public class Kata
 {
    private static int CountBombs(IEnumerable<char> chars, 
      int pos,
      int length,
      bool forward)
    {
      IEnumerable<char> xs;
      char end;
      if(!forward)
      {
        xs = chars.Reverse();
        pos = length - 1 - pos;
        end = ']';
      }
      else
      {
        xs = chars;
        end = '[';
      }
      
      return xs
        .Skip(pos + 1)
        .TakeWhile(c => c != end)
        .Count(c => c == '#');
    }
    
    public static string AlphabetWar(string b)
    {
      var chars = b.ToCharArray();
      if(chars.Any(c => c == '#'))
      {
        bool shelter = false;
        for(int i = 0; i < chars.Length; i++)
        {
          var c = chars[i];
          
          if(c == '#')
            continue;
            
          if(c == '[')
          {
            // TODO: Check for double bombs
            int bombs = CountBombs(b, i, chars.Length, true)
                      + CountBombs(b, i, chars.Length, false);
            
            shelter = bombs < 2;
            continue;
          }
          
          if(c == ']')
          {
            shelter = false;
            continue;
          }
          
          if(shelter)
            continue;
          
          chars[i] = '_';
        }
      }
      
      var survived = chars
        .Where(c => c != '_')
        .Where(c => c != '[')
        .Where(c => c != ']')
        .Where(c => c != '#')
        .ToArray();
      
      return string.Concat(survived);
    }
}

答案10:

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

 public class Kata
 {
    public static string AlphabetWar(string b) {
            Battlefield bf = new Battlefield(b);
            return bf.Survivers();
    }
  }
    
        public class Battlefield
    {
        private List<Lettergroup> lettergroups = new List<Lettergroup>();
        public string BattlefieldDesc { get; set; }

        public Battlefield(string battlefieldDesc) {
            this.BattlefieldDesc = battlefieldDesc;
            ParseGroups();
        }

        private void ParseGroups() {
            Lettergroup current = new Lettergroup();

            for (int i = 0; i < this.BattlefieldDesc.Length; i++) {

                if (this.BattlefieldDesc[i] == '[') {
                    // End previous group
                    if (current.Length > 0) {
                        lettergroups.Add(current);
                        current = new Lettergroup();
                    }
                    current.HasShelter = true;
                } else if (this.BattlefieldDesc[i] == ']') {
                    lettergroups.Add(current);
                    current = new Lettergroup();
                } else if (this.BattlefieldDesc[i] == '#') {
                    current.Bomb();
                } else {
                    current.Letter(BattlefieldDesc[i]);
                }
            }

            if (current.Length > 0) {
                lettergroups.Add(current);
            }
        }

        public string Survivers() {
            // Did bombs drop?
            if (this.lettergroups.Any(l => l.NumberOfBombs > 0)) {
                this.lettergroups.Where(l => !l.HasShelter).ToList().ForEach(l => l.IsDead = true);
            }

            // Were any shelters destroyed?
            int neighbouringBombs = 0;
            for (int i = 0; i < lettergroups.Count; i++) {
                if (lettergroups[i].HasShelter) {
                    neighbouringBombs += i > 0 ? this.lettergroups[i - 1].NumberOfBombs : 0;
                    neighbouringBombs += this.lettergroups[i].NumberOfBombs;
                    neighbouringBombs += i + 1 < this.lettergroups.Count ? this.lettergroups[i + 1].NumberOfBombs : 0;

                    if (neighbouringBombs >= 2) {
                        lettergroups[i].NukeShelter();
                    }

                    neighbouringBombs = 0;
                }
            }

            string survivors = "";
            this.lettergroups.Where(l => !l.IsDead).ToList().ForEach(l => survivors += l.Letters);

            return survivors;
        }

        public override string ToString() {
            return string.Join(Environment.NewLine, this.lettergroups);
        }
    }

public class Lettergroup
    {
        public bool HasShelter { get; set; }
        public int NumberOfBombs { get; private set; }
        public string Letters { get; private set; }
        public int Length { get; private set; }
        public bool IsDead { get; set; }

        public Lettergroup() {
            this.IsDead = false;
        }

        public void Letter(char letter) {
            this.Letters += letter;
            Length++;
        }

        public void Bomb() {
            this.NumberOfBombs++;
            Length++;
        }

        public void NukeShelter() {
            this.HasShelter = false;
            this.IsDead = true;
        }

        public override string ToString() {
            StringBuilder s = new StringBuilder();
            s.Append(Letters);

            if (this.HasShelter) {
                s.Insert(0, '[');
                s.Append(']');
            }

            if (this.NumberOfBombs > 0) {
                s.Append(" (");
                for (int i = 0; i < NumberOfBombs; i++) {
                    s.Append('#');
                }
                s.Append(')');
            }

            return s.ToString();
        }
    }



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值