using System.Collections.Generic;
using System.Diagnostics;
using System.IO.Compression;
const int c_INPUT_SIZE_BYTES = 100000;
const int c_REPEATED_SEQUENCE_MIN_LENGTH = 50;
const int c_REPEATED_SEQUENCE_MAX_LENGTH = 100;
public static void Main(string[] args)
byte[] inputBytes = new byte[c_INPUT_SIZE_BYTES];
byte[] inputBits = new byte[c_INPUT_SIZE_BYTES * 8];
for (int experiment = 0; experiment < 10; ++experiment)
bool[] repeatedSequence = new bool[c_REPEATED_SEQUENCE_MAX_LENGTH];
for (int i = 0; i < c_REPEATED_SEQUENCE_MAX_LENGTH; ++i)
repeatedSequence[i] = r.Next(100) < 50;
int repeatedSequenceLastIndex = 0;
int repeatedSequenceCurrentIndex = 0;
for (int byteIndex = 0; byteIndex < c_INPUT_SIZE_BYTES; ++byteIndex)
for (int bitInByte = 0; bitInByte < 8; ++bitInByte)
++repeatedSequenceCurrentIndex;
if (repeatedSequenceCurrentIndex >= repeatedSequenceLastIndex)
repeatedSequenceLastIndex = r.Next(c_REPEATED_SEQUENCE_MAX_LENGTH - c_REPEATED_SEQUENCE_MIN_LENGTH) + c_REPEATED_SEQUENCE_MIN_LENGTH;
repeatedSequenceCurrentIndex = r.Next(repeatedSequenceLastIndex - c_REPEATED_SEQUENCE_MIN_LENGTH);
bool bit = repeatedSequence[repeatedSequenceCurrentIndex];
inputBits[bitIndex++] = (byte)(bit ? 1 : 0);
inputBytes[byteIndex] = currentByte;
Console.WriteLine("Experiment #" + experiment.ToString());
ShowCompressedSize("\tCompressing bits\t\t", inputBits);
ShowCompressedSize("\tCompressing bytes\t", inputBytes);
private static void ShowCompressedSize(string prefixToWrite, byte[] input)
using (Stream stream = new MemoryStream())
long beginning = stream.Position;
using (Stream compressedStream = new DeflateStream(stream, CompressionLevel.Optimal, true))
compressedStream.Write(input, 0, input.Length);
length = stream.Position - length;
Console.WriteLine("{0}: Original Length = {1}\tCompressed Length = {2}", prefixToWrite, input.Length, length);