Created
March 14, 2014 19:15
-
-
Save dgritsko/9554733 to your computer and use it in GitHub Desktop.
Naive bijective function in C#. http://stackoverflow.com/questions/742013
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
namespace Alphabet | |
{ | |
public class AlphabetTest | |
{ | |
public static readonly string Alphabet = "abcdefghijklmnopqrstuvwxyz0123456789"; | |
public static readonly int Base = Alphabet.Length; | |
public static string Encode(int i) | |
{ | |
if (i == 0) return Alphabet[0].ToString(); | |
var s = string.Empty; | |
while (i > 0) | |
{ | |
s += Alphabet[i % Base]; | |
i = i / Base; | |
} | |
return string.Join(string.Empty, s.Reverse()); | |
} | |
public static int Decode(string s) | |
{ | |
var i = 0; | |
foreach (var c in s) | |
{ | |
i = (i * Base) + Alphabet.IndexOf(c); | |
} | |
return i; | |
} | |
public static void Main(string[] args) | |
{ | |
// Simple test of encode/decode operations | |
for (var i = 0; i < 10000; i++) | |
{ | |
if (Decode(Encode(i)) != i) | |
{ | |
System.Console.WriteLine("{0} is not {1}", Encode(i), i); | |
break; | |
} | |
} | |
} | |
} | |
} |
update to use string builder and reverse in one step
public string Encode(int i)
{
if (i == 0) return Alphabet[0].ToString();
var s = new StringBuilder();// string.Empty;
while (i > 0)
{
s.Insert(0, Alphabet[i % Base]);
i = i / Base;
}
return s.ToString();
}
I did a small modificated version with fixes from comments (:
https://github.com/MrModest/LinkShortener/blob/master/LinkShortener/ServiceImpls/ShortenerService.cs
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@suren2k44 But the idea is that it doesn't encode free text string ... it encodes Integer - e.g. the generated ID in database table where you store that link. So the result of the encoding is a proper string and it can be decoded back to that integer. So after decoding you get your ID in database and go retrieve it.