using System;
using System.Collections;
namespace Hamming
{
class Program
{
static void Input(BitArray ba, int[] control, string input)
{
int count = 0;
for (int i = 0; i < ba.Length; i++)
{
if ((!Array.Exists<int>(control, element => element == i)) && (input[count++] == '1')) ba[i] = true;
}
}
static bool Value(BitArray ba, int ControlIndex)
{
int ind = ControlIndex;
int temp = 0;
while (ind < ba.Length)
{
for (int i = ind; i <= ind + ControlIndex; i++)
{
if ((i < ba.Length) && (ba[i])) temp++;
}
ind = ind + ControlIndex * 2 + 2;
}
if (temp % 2 == 1) return true;
return false;
}
static void ControlValue(BitArray ba, int[] control)
{
foreach (int i in control)
{
ba[i] = Value(ba, i);
}
}
static void FindError(BitArray ba, int[] control)
{
string result = "";
ControlValue(ba, control);
for (int i = ba.Length - 1; i >= 0; i--)
{
if (Array.Exists<int>(control, element => element == i))
{
if (ba[i])
{
result += 1;
ba[i] = false;
}
else result += 0;
}
}
int IndexOfError = Convert.ToInt32(result, 2);
ba[IndexOfError - 1] = !ba[IndexOfError - 1];
ControlValue(ba, control);
Console.WriteLine("Ошибка была в {0} разряде", IndexOfError);
}
static void Output(BitArray ba)
{
for (int i = 1; i <= ba.Length; i++)
{
Console.Write("{0}\t|", i);
}
Console.WriteLine();
foreach (bool b in ba)
{
if (b) Console.Write("1\t|");
else Console.Write("0\t|");
}
Console.WriteLine();
}
static void Main(string[] args)
{
string input;
do
{
Console.Write("Введите 8 бит кодируемой информации: ");
input = Console.ReadLine();
} while (input.Length != 8);
int[] control = { 0, 1, 3, 7 };
BitArray ba = new BitArray(12);
Input(ba, control, input);
ControlValue(ba, control);
Console.WriteLine("Информация с контрольными битами:");
Output(ba);
Console.Write("Введите разряд, в который хотите добавить ошибку (не выбирайте разряд, в котором находится контрольное значение): ");
int IndexOfError = Convert.ToInt32(Console.ReadLine());
ba[IndexOfError - 1] = !ba[IndexOfError - 1];
Console.WriteLine("Информация с добавленной ошибкой:");
Output(ba);
FindError(ba, control);
Console.WriteLine("Информация с исправленной ошибкой:");
Output(ba);
}
}
}