Skip to content

Instantly share code, notes, and snippets.

@Blizzardo1
Last active May 28, 2016 07:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Blizzardo1/7ddad9398e4a13b8616e9f5cbbe3a293 to your computer and use it in GitHub Desktop.
Save Blizzardo1/7ddad9398e4a13b8616e9f5cbbe3a293 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static ToasterNotes.Conditioner;
namespace ToasterNotes
{
public class BinaryDecoder
{
private string q;
private List<string> result;
/*
class BinaryCode:
def decode(self, message):
self.q = message
#assuming first digit is 0
self.p = "00"
result = []
try:
for i in xrange(0,len(self.q)):
if int(self.p[i])+int(self.p[i+1])+1==int(self.q[i]):
self.p=str(self.p)+"1"
elif int(self.p[i])+int(self.p[i+1])+0==int(self.q[i]):
self.p=str(self.p)+"0"
except:
self.p = "NONE"
result.append(self.p[1:-1]) if self.p!="NONE" else result.append(str(self.p))
#assuming first digit is 1
self.p = "01"
try:
for i in xrange(0,len(self.q)):
if int(self.p[i])+int(self.p[i+1])+1==int(self.q[i]):
self.p=str(self.p)+"1"
elif int(self.p[i])+int(self.p[i+1])+0==int(self.q[i]):
self.p=str(self.p)+"0"
except:
self.p = "NONE"
result.append(self.p[1:-1]) if self.p!="NONE" else result.append(str(self.p))
return tuple(result)
*/
/// <summary>
///
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
public Tuple<string [ ]> Decode ( string message )
{
Tuple<string [ ]> tuple;
result = new List<string> ( );
q = message;
// Assuming first digit is 0
Binary ( "00" );
Binary ( "01" );
tuple = new Tuple<string [ ]> ( result.ToArray ( ) );
return tuple;
}
private void Binary ( string v )
{
TraceLine ( "Begin Binary", "Binary Method" );
string p = v;
TraceLine ( $"x = {p}" );
try
{
TraceLine ( "Begin Forloop" );
Indent ( );
for ( int i = 0; i < q.Length; i++ )
{
TraceLine ( $"len(p) = {p.Length}" );
TraceLine ( $"len(q) = {q.Length}" );
if ( CheckDigit ( p, i, 1 ) )
p += "1";
else if ( CheckDigit ( p, i, 0 ) )
p += "0";
TraceLine ( $"Currently p = {p}" );
}
Unindent ( );
p = p.ToString ( );
TraceLine ( "End Forloop" );
}
catch ( Exception ex )
{
Unindent ( );
TraceLine ( $"{ex.Message}", "Binary Error" );
p = "NONE";
TraceLine ( "Broken Forloop" );
}
TraceLine ( $"x = {p}" );
result.Add ( p != "NONE" ? p.Substring ( 1, p.Length - 2 ) : p );
}
public string Encode(string binaryString)
{
string x = string.Empty;
string y = $"0{binaryString}0";
for(int i = 0; i < y.Length; i++ )
{
TraceLine ( $"x = {x}" );
TraceLine ( $"i - 1 = {i - 1}; i = {i}; i + 1 = {i + 1}" );
x += cAsI ( y [ ( i - 1 ) < 0 ? 0 : i - 1 ] ) + cAsI ( y [ i ] ) + cAsI ( y [ ( i + 1 ) > y.Length - 1 ? y.Length - 1 : i + 1 ] );
}
return x.Substring ( 1, x.Length - 2 );
}
private bool CheckDigit(string str, int position, int digit)
{
TraceLine ( $"if p[{position}] + p[{position + 1}] + {digit} == q[{position}]" );
Indent ( );
TraceLine ( $"{str [ position ]} + {str [ position + 1 ]} + {digit} == {q [ position ]}" );
Unindent ( );
return ( ( cAsI ( str [ position ] ) + cAsI ( str [ position + 1 ] ) + digit ).Equals ( cAsI ( q [ position ] ) ) );
}
private int cAsI(char c)
{
return int.Parse ( new string ( c, 1 ) );
}
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
// For Trace Output, Compile with DEBUG
namespace ToasterNotes
{
public class Options : IList<Options.Option>
{
List<Option> _options;
public int Count => _options.Count;
public bool IsReadOnly => false;
public Option this [ int index ]
{
get
{
return _options [ index ];
}
set
{
_options [ index ] = value;
}
}
public Option this [string index] => _options.Find ( ( o ) => o.Switch == index );
public class Option
{
private string _switch;
public string Switch => _switch;
private string _desc;
public string Description => _desc;
private bool _requiresArg;
public bool ReguiresArgument => _requiresArg;
private Action<string> _function;
public Action<string> Invoke => _function;
public Option ( string @switch, string description, bool requiresArgument, Action<string> function )
{
_switch = @switch;
_desc = description;
_requiresArg = requiresArgument;
_function = function;
}
}
public Options()
{
_options = new List<Option> ( );
}
public int IndexOf ( Option item ) => _options.IndexOf ( item );
public void Insert ( int index, Option item ) => _options.Insert ( index, item );
public void RemoveAt ( int index ) => _options.RemoveAt ( index );
public void Add ( Option item ) => _options.Add ( item );
public void Clear ( ) => _options.Clear ( );
public bool Contains ( Option item ) => _options.Contains ( item );
public void CopyTo ( Option [ ] array, int arrayIndex ) => _options.CopyTo ( array, arrayIndex );
public bool Remove ( Option item ) => _options.Remove ( item );
public IEnumerator<Option> GetEnumerator ( ) => _options.GetEnumerator ( );
IEnumerator IEnumerable.GetEnumerator ( ) => _options.GetEnumerator ( );
}
public class Program
{
public const string AppName = "Toaster Network Binary Decoder";
public const string AppVersion = "1.0 beta";
public const string AppCopy = "Blizzardo1, 2016";
public static readonly string [ ] AppCopyW = {
"The BinaryDecoder class was originally developed in Python, and was converted into C# for testing.",
"It was originally solved by SaSoGeek and can be found here:",
@" ""https://sasothegenius.wordpress.com/2016/05/27/decoding-the-binary-code-srm-144-div-1-300/""",
"All credit goes to SaSoGeek.",
"",
"For help, type :h"
};
private static Options options;
private static List<string> results;
private static BinaryDecoder binaryDecoder = new BinaryDecoder ( );
public static void Main ( string [ ] args )
{
Header ( );
CreateArguments ( );
results = new List<string> ( );
string ins = string.Empty;
int x = 3; // position
while ( true )
{
Prompt ( "Command> " );
ins = Console.ReadLine ( );
if ( ins.StartsWith ( ":" ) )
{
string z = string.Empty;
try
{
z = ins.Substring ( 1, ins.IndexOf ( ' ' ) - 1 ).ToLower ( );
} catch ( Exception )
{
z = ins.Substring ( 1 );
}
try
{
/*
if ( !options.Any ( ( o ) => o.Switch == z ) )
options [ "h" ].Invoke ( null );
if ( ins.Split(' ').Length > 1 )
options [ z ].Invoke ( ins.Substring ( x, ins.Length - x ) );
else
options [ z ].Invoke ( null );*/
if ( ins.Split ( ' ' ).Length > 1 )
ParseAndExecute ( z, ins.Substring ( x, ins.Length - x ) );
else
ParseAndExecute ( z, null );
}
catch (Exception)
{
Console.WriteLine ($"Error with command :{z}");
}
}
}
}
private static void ParseAndExecute(string commands, string arguments)
{
Queue<string> args = null;
if(!string.IsNullOrEmpty( arguments ) )
args = MakeList ( arguments );
foreach ( char c in commands )
{
Options.Option op;
if ( !options.Any ( ( o ) => o.Switch == c.ToString ( ) ) )
{
Console.WriteLine ( $"Unknown Command \"{c}\"" );
options [ "h" ].Invoke ( null );
break;
}
op = options [ c.ToString ( ) ];
if ( args != null )
{
if ( op.ReguiresArgument )
{
// Console.WriteLine ( $"Argument for {c}: { args.Dequeue ( )}" );
op.Invoke ( args.Dequeue ( ) );
}
}
else
{
op.Invoke ( null );
}
}
}
private static Queue<string> MakeList ( string arguments )
{
Queue<string> x = new Queue<string> ( );
Regex r = new Regex ( @"(?<digit>(?:\d*)?)?(?<literal>\"".*?\"")*", RegexOptions.Compiled );
MatchCollection mc = r.Matches ( arguments );
foreach(Match m in mc)
{
if(m.Groups["digit"].Length > 0)
{
x.Enqueue ( m.Groups [ "digit" ].Value );
}
if(m.Groups["literal"].Length > 0)
{
x.Enqueue ( m.Groups [ "literal" ].Value.Trim ( '"' ) );
}
}
return x;
}
private static void CreateArguments ( )
{
if ( options != null )
return;
options = new Options ( );
options.Add ( new Options.Option ( "h", "Shows this help file", false, ( x ) => Usage ( ) ) );
options.Add ( new Options.Option ( "?", "Alias to :h", false, ( x ) => Usage ( ) ) );
options.Add ( new Options.Option ( "b", "Like :e, but Translates Text into a binary string for encryption", true, ( x ) => Encode(x, true ) ) );
options.Add ( new Options.Option ( "c", "Clears the Screen", false, ( x ) => Console.Clear ( ) ) );
options.Add ( new Options.Option ( "d", "Decodes a given string. e.g. -> :d 123210122", true, ( x ) => Decode ( x ) ) );
options.Add ( new Options.Option ( "e", "Encodes a given string. e.g. -> :e 011100011", true, ( x ) => Encode ( x ) ) );
options.Add ( new Options.Option ( "q", "Quits the Program", false, ( x ) => Environment.Exit ( 0x00 ) ) );
options.Add ( new Options.Option ( "w", "Writes the results to file", false, ( x ) => Write( results.ToArray() ) ) );
options.Add ( new Options.Option ( "x", "Prints the Header", false, ( x ) => Header ( ) ) );
options.Add ( new Options.Option ( "z", "Clears the Results List", false, ( x ) => results.Clear ( ) ) );
}
private static void Write ( string[] data )
{
StreamWriter w = new StreamWriter ( $"Results-{DateTime.Now:yyyyMMMdd-HHmmss}.txt" );
foreach(string x in data)
{
w.WriteLine ( x );
w.Flush ( );
}
w.Close ( );
}
private static void Usage ( )
{
foreach(Options.Option o in options)
{
Console.WriteLine ( $":{o.Switch}\t- {o.Description}" );
}
Console.WriteLine ( "Commands can also be combined on one line such as, :bbdwz \"Test String 1\" \"Test String Two\" 123210122" );
}
private static void Encode ( string input, bool translateToBinary = false )
{
string encoded = input;
if(translateToBinary)
{
encoded = ToBinary ( input );
Console.WriteLine ( $"Binary: {encoded}" );
}
encoded = binaryDecoder.Encode ( encoded );
Console.WriteLine ( $"Input: {input}" );
Console.WriteLine ( $"Input Length: {input.Length}\r\n" );
Console.WriteLine ( $"Encoded Message: {encoded}" );
Console.WriteLine ( $"Encoded Length: {encoded.Length}" );
AddResult ( "encoded", $"{input}, {encoded}" );
Console.WriteLine ();
}
private static void AddResult ( string type, string message )
{
results.Add ( $"{type} - {message}" );
}
public static string ToBinary ( string data, bool spaced = false ) {
byte [ ] bytes = Encoding.UTF8.GetBytes ( data );
return string.Join ( spaced ? " " : "", bytes.Select ( byt => Convert.ToString ( byt, 2 ).PadLeft ( 8, '0' ) ) );
}
private static void Header()
{
Console.WriteLine ($"{AppName} Version {AppVersion}");
Console.WriteLine ($"Copyright {AppCopy}\r\n");
Console.WriteLine ($"{AppCopyW.Aggregate((x,y) => $"{x}\r\n{y}")}\r\n");
}
private static void Prompt ( string prompt = "String> " )
{
Console.Write ( prompt );
}
private static void Decode(string input)
{
ToasterStringArray decoded = new ToasterStringArray ( binaryDecoder.Decode ( input ).Item1 );
Console.WriteLine ( $"Input: {input}" );
Console.WriteLine ( $"Input Length: {input.Length}\r\n" );
Console.WriteLine ( $"Decoded Message: {decoded}" );
Console.WriteLine ( $"Decoded Length: {decoded.Length}" );
Console.WriteLine ( $"Decoded Array Length: {decoded.Size}" );
AddResult ( "decoded", $"{input}, {decoded}" );
Console.WriteLine ();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ToasterNotes
{
public class ToasterStringArray
{
private string [ ] array;
public ToasterStringArray ( string [ ] array )
{
this.array = array;
}
public override string ToString ( )
{
string rsx = "( ";
foreach(string s in array)
{
rsx += $"{s}, ";
}
rsx = $"{rsx.TrimEnd ( ',', ' ' )} )";
return rsx;
}
/// <summary>
/// Returns a Length of every string
/// </summary>
public int Length => array.Aggregate ( ( x, y ) => $"{x}{y}" ).Length;
/// <summary>
/// Returns the Size of the Array
/// </summary>
public int Size => array.Length;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment