Original Post
🔒 Locked
String generator
Advertisement
Well, here's what I'm at now.
I've started over and over on this one.
(Sorry, I don't know how yo put code in one of those boxes.)
public static string GetUniqueCode(int number)
{
int iNumber = number;
if (iNumber <= 0)
throw new ArgumentOutOfRangeException();
int counter = 1;
string returnString = "";
const int UPPERCHARPOSITION = 65;
while (true)
{
if (Math.Pow(26, counter) > iNumber)
{
for(int i = 0;i < counter; i++)
{
returnString = Convert.ToChar((int)(iNumber % Math.Pow(26, i)) + UPPERCHARPOSITION).ToString() + returnString;
}
break;
}
counter++;
}
return returnString;
}
private void button1_Click(object sender, EventArgs e)
{
label1.Text = GetUniqueCode(Convert.ToInt32(textBox1.Text));
}
I've started over and over on this one.
(Sorry, I don't know how yo put code in one of those boxes.)
public static string GetUniqueCode(int number)
{
int iNumber = number;
if (iNumber <= 0)
throw new ArgumentOutOfRangeException();
int counter = 1;
string returnString = "";
const int UPPERCHARPOSITION = 65;
while (true)
{
if (Math.Pow(26, counter) > iNumber)
{
for(int i = 0;i < counter; i++)
{
returnString = Convert.ToChar((int)(iNumber % Math.Pow(26, i)) + UPPERCHARPOSITION).ToString() + returnString;
}
break;
}
counter++;
}
return returnString;
}
private void button1_Click(object sender, EventArgs e)
{
label1.Text = GetUniqueCode(Convert.ToInt32(textBox1.Text));
}
1. Start with 0 instead of 1, that makes life easier
2. Use recursion:
f(x) = string consisting of the x-th character, if x < 26
f(x) = f(x / 26 - 1) + f(x % 26), else
Or even better recursion (I like trivial base cases):
f(x) = empty string, if x < 0
f(x) = f(x / 26 - 1) + (x % 26)-th character, else
non-optimized C++ code:
2. Use recursion:
f(x) = string consisting of the x-th character, if x < 26
f(x) = f(x / 26 - 1) + f(x % 26), else
Or even better recursion (I like trivial base cases):
f(x) = empty string, if x < 0
f(x) = f(x / 26 - 1) + (x % 26)-th character, else
non-optimized C++ code:
#include <iostream>#include <string>std::string unique_code(int x){ return x < 0 ? "" : unique_code(x / 26 - 1) + char('A' + (x % 26));}int main(){ std::cout << unique_code(0) << std::endl; std::cout << unique_code(25) << std::endl; std::cout << unique_code(26) << std::endl; std::cout << unique_code(27) << std::endl; std::cout << unique_code(26*26) << std::endl; std::cout << unique_code(27*26) << std::endl;}
Quote:
Original post by C3rial
when I try to transer it to c#-code it's getting messed up.
Well, show us the code then.
Quote:
Original post by C3rial
I get a "StackOverFlow".
A StackOverflow is usually an indication that you forgot your base case and thus never stop the recursion. Again, show us the code.
Topic Locked
This topic has been locked by a moderator. New replies are not allowed.
Sign in to reply to this topic.
Advertisement