Skip to main content
gamedev.net
🔒 Locked

String generator

Started by C3rial 5 replies 900+ views
Original Post
C3rial
C3rial
Hi! I need to make every number a string. They go: 1 = "A" 26 = "Z" 27 = "AA" 28 = "AB" and so on. Any idea? I'm stuck. All I've gotten untill now has been un-useable! I apprechiate any help! Regards!
CrazyPoly
C3rial
C3rial
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));
}

CrazyPoly
DevFred
DevFred
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:
#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;}
C3rial
C3rial
I can see it working with your c++ code, but when I try to
transer it to c#-code it's getting messed up.
I can't make a call for a function in that same function.
I get a "StackOverFlow".

Any ideas?:)
Btw - thanks for all your help so far!:)
CrazyPoly
DevFred
DevFred
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.
C3rial
C3rial
Hi again!
I got it working eventually:D
Sorry about forgetting the code and all.

Thanks alot for all your help! Recursion is great:D

Regards!
CrazyPoly

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.