Library of Babel

This is more of a conceptual thread because I don't know how to approach this.

In base 10 if you want to know what index the number 'n' as you can just look at the number and add 1, obviously. 10 is at position 11 (because we include 0), 101 is at position 102 etc.

Well, can we convert this to strings? if I want to know what the index of 'hello' is can we look at the base 26 set and see? I'm not including capitals for simplicity but also capital letters don't exist in the middle or ends of words. For example, the index of 'a' is 0, 'aa' is 26 and so on each time adding a new 26sths place and 'counting' from 'a' to 'z'.

Does anyone know how to approach this? I already made a converter from base 10 to 26 and vice versa but it's not really working as it starts at 0 - 9 then enters the alpha set. Also, it skips some letters... but that's probably just my bad programming.

I assume the way to calculate the index would be to count up from 'a' all the way to the string and have a counter counting the entire time. I feel like there's a super elegant way to do this in only a couple of lines.
Last edited on
To be consistent, wouldn't you want 26 to be "ba"? Or am I misunderstanding something (or I'm just being dumb, I'm kinda tired)?
0 --> 10
a --> ba

0 --> 00
a --> aa ?

a = 0
b = 1
z = 25
ba = 26 * 1 + 0 = 26
bz = 26 * 1 + 25 = 51
ca = 26 * 2 + 0 = 52

a = 0
b = 1
z = 25
aa = 26 * (0 + 1) = 26
ab = 27 = 26 * (0+1) + 1
az = 51 = 26 * (0+1) + 25
ba = 52 = 26 * (1+1) + 0 (I guess this is still OK, but everything is offset by 26)

Anyway, yes, it sounds possible. Need to subtract 'a' from the input character, and multiply by 26 every time you go to the next index of the string. Try messing around with it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <string>

std::string index_to_string(int n)
{
	// TODO
}

// assumes only lowercase letters...
// you'll need to adjust logic if you want more freedom
int string_to_index(const std::string& str)
{
	if (str.length() == 0)
	{
		return -1; // some error, maybe handle this...
	}
	
	int n = str[0] - 'a';
	for (size_t i = 1; i < str.length(); i++)
	{
		n = 26 * n + (str[i] - 'a');
	}
	
	return n;
}


int main()
{
	//  a <--> 0
	//  b <--> 1
	//  z <--> 25
	// ba <--> 26 * 1 + 0 = 26
	// bb <--> 26 * 1 + 1 = 27
	std::cout << string_to_index("a") << '\n';
	std::cout << string_to_index("b") << '\n';
	std::cout << string_to_index("z") << '\n';
	std::cout << string_to_index("ba") << '\n';
	std::cout << string_to_index("bb") << '\n';
}
Last edited on
Topic archived. No new replies allowed.