Created
December 2, 2016 13:47
-
-
Save Xmerr/be9a74bf93c34839950b8dabcd211098 to your computer and use it in GitHub Desktop.
For Reddit Easy Challenge 287
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq; | |
namespace Kaprekars_Routine | |
{ | |
class Program | |
{ | |
const int KAPREKAR_CONSTANT = 6174; | |
static void Main(string[] args) | |
{ | |
string input = Console.ReadLine(); | |
Validate(input); | |
while(input.Length < 4) | |
input += "0"; | |
Console.WriteLine(LargestDigit(input)); | |
Console.WriteLine(DescDigits(input)); | |
Console.WriteLine(Kaprekars(input)); | |
Console.ReadKey(); | |
} | |
/// <summary> | |
/// Returns the largest digit from the passed in string | |
/// </summary> | |
static int LargestDigit(string input) | |
{ | |
return (int)Char.GetNumericValue( | |
input.ToArray() | |
.OrderByDescending(x => x) | |
.Take(1).Single()); | |
} | |
/// <summary> | |
/// Returns the digits in descending order | |
/// </summary> | |
static int DescDigits(string input) | |
{ | |
return Convert.ToInt16( | |
new string(input | |
.ToArray() | |
.OrderByDescending(x => x) | |
.ToArray())); | |
} | |
/// <summary> | |
/// Returns the digits in ascending order | |
/// </summary> | |
static int AscDigits(string input) | |
{ | |
return Convert.ToInt16( | |
new string(input | |
.ToArray() | |
.OrderBy(x => x) | |
.ToArray())); | |
} | |
/// <summary> | |
/// Validates the input | |
/// </summary> | |
static void Validate(string input) | |
{ | |
if (input.Length > 4 || input.ToArray().Distinct().Count() < 2) | |
throw new Exception("Invalid Input"); | |
} | |
/// <summary> | |
/// Determines how long it'll take to get to Kaprekar's Constant | |
/// </summary> | |
static int Kaprekars(string input) | |
{ | |
int counter = 0, | |
test = Convert.ToInt16(input); | |
while(test != KAPREKAR_CONSTANT) | |
{ | |
test = DescDigits(test.ToString()) - AscDigits(test.ToString()); | |
counter++; | |
while (test.ToString().Length < 4) | |
test = Convert.ToInt16(test.ToString() + "0"); | |
} | |
return counter; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For reddit easy challenge #287