using System;
using System.Collections.Generic;
using System.Linq;
namespace _2021___Day_03
{
class Program
{
static void Main(string[] args)
{
int counter = 0;
string line;
string[] fileBuffer = new string[1000];
// Read the file and display it line by line.
System.IO.StreamReader file =
new System.IO.StreamReader(@"../../../../Input.in");
while ((line = file.ReadLine()) != null)
{
fileBuffer[counter] = line;
counter++;
}
file.Close();
string gamma = "";
double gammaDec = 0;
string epsilon = "";
double epsilonDec = 0;
for (int i = 0; i < 12; i++)
{
if (GetMostCommonDigit(i, fileBuffer) == '0')
{
gamma += "0";
epsilon += "1";
}
else
{
gamma += "1";
epsilon += "0";
}
//gamma += fileBuffer[i][0];
//epsilon += fileBuffer[i][fileBuffer[i].Length-1]; //Maybe Length-1
}
gammaDec = BinToDec(gamma);
epsilonDec = BinToDec(epsilon);
Console.WriteLine("Gamma is: " + gammaDec.ToString());
Console.WriteLine("Epsilon is: " + epsilonDec.ToString());
Console.WriteLine("Sought value is: " + (gammaDec * epsilonDec).ToString());
List<string> bins = fileBuffer.ToList();
char comp;
int k;
int size = bins.Count;
for (int i = 0; i < 12; i++)
{
comp = GetMostCommonDigit(i, bins);
k = 0;
while (k < size)
{
if (bins[k][i] != comp)
{
}
else
{
bins.Add(bins[k]);
}
k++;
}
for (int p = 0; p < size; p++)
{
bins.RemoveAt(0);
}
if (bins.Count == 1)
{
break;
}
}
double oxyRat = BinToDec(bins[0]);
bins = fileBuffer.ToList();
size = bins.Count;
for (int i = 0; i < 12; i++)
{
comp = GetMostCommonDigit(i, bins);
k = 0;
while (k < size)
{
if (bins[k][i] == comp)
{
}
else
{
bins.Add(bins[k]);
}
k++;
}
for (int p = 0; p < size; p++)
{
bins.RemoveAt(0);
}
if (bins.Count == 1)
{
break;
}
}
double co2Rat = BinToDec(bins[0]);
Console.WriteLine("Oxygen Rating is: " + oxyRat.ToString());
Console.WriteLine("CO2 Rating is: " + co2Rat.ToString());
Console.WriteLine("Sought value is: " + (oxyRat * co2Rat).ToString());
}
static char GetMostCommonDigit(int index, string[] file)
{
var zerCount = 0;
var oneCount = 0;
for (int j = 0; j < file.Length; j++)
{
if (file[j][index] == '0')
{
zerCount++;
}
if (file[j][index] == '1')
{
oneCount++;
}
}
if (zerCount>oneCount)
{
return '0';
}
else
{
return '1';
}
}
static char GetMostCommonDigit(int index, List<string> file)
{
var zerCount = 0;
var oneCount = 0;
for (int j = 0; j < file.Count; j++)
{
if (file[j][index] == '0')
{
zerCount++;
}
if (file[j][index] == '1')
{
oneCount++;
}
}
if (zerCount > oneCount)
{
return '0';
}
else
{
return '1';
}
}
static double BinToDec(string bin)
{
double thing = 0;
for (int i = bin.Length-1; i > -1; i--)
{
thing += int.Parse(bin[i].ToString()) * Math.Pow(2, bin.Length-i-1);
}
return thing;
}
}
}