String Encoder

CSharp · Console

/Program.cs

using System;
using System.Collections.Generic;
					
public class Program
{
	public void Main()
{
	// Sets inputs
	// the double[] input will eventually be the id's of the questions in the database
	double[] input = {123, 893, 4, 12394};
	double toBase = 47;
	string encodedString = encodeString(toBase, input);
	Console.WriteLine(encodedString);
}

// Encodes the string
public string encodeString(double baseNum, double[] input)
{
	if (baseNum > 62) {
		throw new Exception("Can't use base higher that 62");
	}
	string finalResult = "";
	List<string> finalEncodedString = new List<string>();
	
	// Loops through each number in the input list
	foreach (double num in input)
	{
		// sets variables to convert between bases
		double quotient = num;
		double remainder;
		List<double> remainders = new List<double>();
			int i = 0;
			while (quotient >= baseNum)
			{
			// base conversion
			// Example:
			// converting 113 from base 10 to base 13
			// 743 / 13 = 57 r 2
			// 57 / 13 = 4 r 5
			// 4 / 13 = 0 r 4
			// the answer is the remainders read bottom to top, so its 452.
			// this vvv does what I just typed out above
			remainder = quotient % baseNum;
			quotient = Math.Floor(quotient / baseNum);
			remainders.Add(remainder);
			i++;
		}
		remainder = quotient % baseNum;
		remainders.Add(remainder);
		
		// The remainders are stored in the wrong direction so this reverses them
		List<string> encodedString = new List<string>();
		List<double> reverseRemainders = new List<double>();
		for (var z = remainders.Count - 1; z >= 0; z--)
		{
			reverseRemainders.Add(remainders[z]);
		}
		
		// converts remainders to the baseX versions
		foreach (double r in reverseRemainders)
		{
			int z = Convert.ToInt32(r);
			if (z > 9 && z <= 35) {
				char character = Convert.ToChar(z + 55);
				encodedString.Add(character.ToString());
			}
			else if (z >= 36 && z < 62)
			{
				char character = Convert.ToChar(z + 61);
				encodedString.Add(character.ToString());
			}
			else if (z <= 9)
			{
				encodedString.Add(r.ToString());
			}
		}
		
		// adds all strings together
		string result = String.Join("", encodedString);
		finalEncodedString.Add(result);
		finalResult = String.Join(",", finalEncodedString);
	}
	return finalResult;
}
}
;