Tuesday, December 23, 2008

Unscramble the words (Mission 1)

This is my first (crude) attempt to mission 1.

http://www.hackthissite.org/missions/prog/1/


using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
StreamReader sr1 = new StreamReader("C:\\scrambled.txt");
string the_word;

string[] output = new string[10];
int t = 0;

while ((the_word = GetWords(sr1)) != null)
{
StreamReader sr2 = new StreamReader("C:\\wordlist.txt");
string word_2;

while ((word_2 = GetWords(sr2)) != null)
{
the_word = CleanUp(the_word);
word_2 = CleanUp(word_2);

if (CompareSize(the_word, word_2) == true)
{
string result1 = Convert2CharNSort(the_word);
string result2 = Convert2CharNSort(word_2);

bool itmatches = CompareWords(result1, result2);
if (itmatches == true)
{
output[t] = word_2;
}
else
{
Console.WriteLine("No match");
}
}
else
Console.WriteLine("No match");
}
t++;
}

StreamWriter writer = File.CreateText("c:\\challenge1.txt");

for (int f = 0; f < output.Length; f++)
{

if (f != 0)
{
writer.Write(",");
}
writer.Write(output[f]);
}

writer.Close();
}

public static string CleanUp(string to_be_cleaned)
{
to_be_cleaned = Regex.Replace(to_be_cleaned, @"\s", "");
to_be_cleaned = Regex.Replace(to_be_cleaned, "#", "");
return to_be_cleaned;
}

public static bool CompareWords(string to_be_compared1, string to_be_compared2)
{

if (to_be_compared1 == to_be_compared2)
return true;
else
return false;
}

public static string Convert2CharNSort(string to_be_converted)
{
char[] buffer = new char [to_be_converted.Length];

for (int i = 0; i < to_be_converted.Length; i++)
{
buffer[i] = to_be_converted[i];
}

//Start the bubble sort
char tmp;
int m, n;

for (m = 0; m < to_be_converted.Length; m++)
{
for (n = m + 1; n < to_be_converted.Length ; n++)
{
if (buffer[m] > buffer[n])
{
tmp = buffer[m];
buffer[m] = buffer[n];
buffer[n] = tmp;
}
}
}

//converting from char[] to string
string result_s = "";
result_s = new string(buffer);
return result_s;
}

public static bool CompareSize(string theword, string word2)
{
if (theword.Length == word2.Length)
return true;
else
return false;
}

public static string GetWords(StreamReader sr)
{
return sr.ReadLine();
}
}
}