Skip to content

Instantly share code, notes, and snippets.

@oerpli
Created January 19, 2015 21:37
Show Gist options
  • Save oerpli/6f540f60ac3bca181d26 to your computer and use it in GitHub Desktop.
Save oerpli/6f540f60ac3bca181d26 to your computer and use it in GitHub Desktop.
Arithmetic Encoding
using System;
using System.Collections.Generic;
using System.Linq;
namespace Encoding {
class Program {
static double sum;
static Dictionary<char, double> Val, Low, High;
static string Input;
static void Main(string[] args) {
if(false) {
Val = new Dictionary<char, double>() { { 't', 3 }, { 'e', 3 }, { 's', 2 }, { 'i', 1 }, { 'n', 1 } };
Low = new Dictionary<char, double>() { { 't', 0 }, { 'e', 3 }, { 's', 6 }, { 'i', 8 }, { 'n', 9 } };
High = new Dictionary<char, double>() { { 't', 3 }, { 'e', 6 }, { 's', 8 }, { 'i', 9 }, { 'n', 10 } };
Input = "teststeine";
} else {
Val = new Dictionary<char, double>() { { 'd', 7 }, { 'u', 5 }, { 's', 4 }, { 'a', 3 }, { 'r', 2 }, { 'e', 1 } };
Low = new Dictionary<char, double>() { { 'd', 0 }, { 'u', 7 }, { 's', 12 }, { 'a', 16 }, { 'r', 19 }, { 'e', 21 } };
High = new Dictionary<char, double>() { { 'd', 7 }, { 'u', 12 }, { 's', 16 }, { 'a', 19 }, { 'r', 21 }, { 'e', 22 } };
Input = "dudadsusdrausredausdud";
}
sum = Val.Values.Aggregate(0.0, (a, b) => a + b);
var x = new Intervall(0, 1);
Console.WriteLine("Start: " + x);
foreach(char c in Input) {
x = newIntervall(x, c);
Console.WriteLine(string.Format("{0}: {1}", c, x));
}
Console.ReadKey(false);
}
static Intervall newIntervall(Intervall i, char c) {
var r = new Intervall(0, 0);
r.Lower = i.Lower + i.Length * (Low[c] / sum);
r.Higher = i.Lower + i.Length * (High[c] / sum);
return r;
}
private class Intervall {
public double Lower, Higher;
public double Length { get { return Higher - Lower; } }
public Intervall(double l, double h) {
Lower = l;
Higher = h;
}
public override string ToString() {
return "(" + Lower + "," + Higher + ")";
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment