Categories
Visual C# Телерик

Решение на задача – Encode and Encrypt

using System;
using System.Text;

namespace EncodeAndEncrypt {
  class Program {
    static void Main() {
      string message = Console.ReadLine();
      string cypher = Console.ReadLine();
      Console.WriteLine(Encode(Encrypt(message, cypher) + cypher) + cypher.Length);
    }

    static string Encrypt(string message, string cypher) {
      char[] cypherText = new char[message.Length];
      int index = 0;
      if (cypher.Length < message.Length) {
        for (int i = 0; i < message.Length; i++) {
          if (index == cypher.Length) {
            index = 0;
          }
          cypherText[i] = (char)((FindLetterIndex((message[i])) ^ FindLetterIndex(cypher[index])) + 65);
          index++;
        }
      } else {
        for (int i = 0; i < cypher.Length; i++) {
          if (index == message.Length) {
            index = 0;
          }
          if (i >= message.Length) {
            cypherText[index] = (char)((FindLetterIndex((cypherText[index])) ^ FindLetterIndex(cypher[i])) + 65);
          } else {
            cypherText[index] = (char)((FindLetterIndex((message[index])) ^ FindLetterIndex(cypher[i])) + 65);
          }
          index++;
        }
      }
      string encryptedText = string.Join(string.Empty, cypherText);
      return encryptedText;
    }

    static string Encode(string message) {
      string letters = string.Format("{0}*", message);
      char currentLetter = letters[0];
      int count = 1;
      StringBuilder sb = new StringBuilder();
      for (int i = 1; i < letters.Length; i++) {
        if (letters[i] == currentLetter) {
          count++;
        } else {
          switch (count) {
          case 1:
            sb.Append(currentLetter);
            break;
          case 2:
            sb.Append(currentLetter);
            sb.Append(currentLetter);
            break;
          default:
            sb.Append(count);
            sb.Append(currentLetter);
            break;
          }
          currentLetter = letters[i];
          count = 1;
        }
      }
      return sb.ToString();
    }
    static int FindLetterIndex(char letter) {
      int index = (letter < 97 ? letter - 64 : letter - 96) - 1;
      return index;
    }
  }
}