Skip to content

Instantly share code, notes, and snippets.

@Xmerr
Last active November 29, 2016 17:50
Show Gist options
  • Save Xmerr/4c31b8dc3323db34fa349b14af7d4ab2 to your computer and use it in GitHub Desktop.
Save Xmerr/4c31b8dc3323db34fa349b14af7d4ab2 to your computer and use it in GitHub Desktop.
Simplify Fractions
4 8
1536 78360
51478 5536
46410 119340
7673 4729
4096 1024
using System;
using System.IO;
using System.Threading;
namespace Simplifying_Fractions
{
class Program
{
static void Main(string[] args)
{
//Gets input files (this example only has one)
string[] files = Directory.GetFiles("inputs", "*.txt");
//Loops through files
for (int i = 0; i < files.Length; i++)
using (StreamReader file = new StreamReader(files[i]))
{
string line;
//Each line of this file is a new fraction
while ((line = file.ReadLine()) != null)
{
int spaceLocation = line.IndexOf(' ');
//Threads because why not
Fraction frac = new Fraction(Convert.ToInt32(line.Substring(0, spaceLocation)), Convert.ToInt32(line.Substring(spaceLocation + 1)));
new Thread(new ThreadStart(frac.Simplify)).Start();
}
}
Console.ReadKey();
}
}
/// <summary>
/// Attempts to simplify fractions
/// </summary>
class Fraction
{
int num { get; set; }
int den { get; set; }
int numSimp { get; set; }
int denomSimp { get; set; }
/// <summary>
/// Sets the numerator and denominator
/// </summary>
/// <param name="numerator">
/// The numerator of the fraction
/// </param>
/// <param name="denominator">
/// The fractions denominator
/// </param>
public Fraction(int numerator, int denominator)
{
num = numerator;
den = denominator;
}
/// <summary>
/// Quickly simplifies the fraction using the mod operator
/// </summary>
public void Simplify()
{
if(num == den)
numSimp = denomSimp = 1;
else
{
numSimp = (num / Modder(num, den));
denomSimp = (den / Modder(num, den));
}
Console.WriteLine(string.Format("{0} / {1} Becomes: {2} / {3}", num, den, numSimp, denomSimp));
}
/// <summary>
/// Tests the two passed in integers
/// for the highest common denominator
/// </summary>
/// <param name="a">
/// First integer to test
/// </param>
/// <param name="b">
/// Second integer to test
/// </param>
int Modder(int a, int b)
{
if (b == 0)
return a;
else
return Modder(b, a % b);
}
}
}
@Xmerr
Copy link
Author

Xmerr commented Nov 29, 2016

For the reddit coding challenge #277

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment