math - Custom number system in C# -
this question has answer here:
i have requirement custom number system in c# goes following:
a - 1 b - 2 ... z - 26 aa - 27 ab - 28
i've made function converts arbitrary strings numbers this:
private const int min = 'a'; private const int max = 'z'; private const int base = max - min + 1; private static int getcharvalue(char c) { if (c < min || c > max) throw new argumentoutofrangeexception(nameof(c), c, $"character needs between '{min}' , '{max}', '{c}'."); return c - min + 1; } public static int getstringvalue(string s) { char[] chars = s.tochararray(); int[] values = new int[chars.length]; (var = 0; < chars.length; i++) { values[i] = getcharvalue(chars[i]); } int position = 1; int value = 0; (var = values.length - 1; >= 0; i--) { value += position * values[i]; position *= base; } return value; }
i've tested working aaa
(not rigorously, skimming on output of printing them all). however, can't life of me figure out how write reverse function. in other words, need 1
return a
, 26
return z
, 27
return aa
. "problem" number system has no 0, doesn't convert base. instance, if a
0, aa
0, it's not. how solve this?
you can generate this....
public static ienumerable<string> generate() { long n = -1; while (true) yield return tobase26(++n); } public static string tobase26(long i) { if (i == 0) return ""; i--; return tobase26(i / 26) + (char)('a' + % 26); } public static void buildquery() { ienumerable<string> lstexcelcols = generate(); try { string s = lstexcelcols.elementatordefault(1) ; } catch (exception exc) { } }
Comments
Post a Comment