1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-25 15:47:44 +00:00

AK: Fix DeprecatedString::bijective_base_from for large numbers

The output of the DeprecatedString::bijective_base_from() is now
correct for numbers larger than base^2.

This makes column names display correctly in Spreadsheet.
This commit is contained in:
Tim Ledbetter 2023-02-24 20:29:14 +00:00 committed by Ali Mohammad Pur
parent fa34832297
commit 6b2f3ad6c8
2 changed files with 14 additions and 9 deletions

View file

@ -246,6 +246,7 @@ DeprecatedString DeprecatedString::repeated(StringView string, size_t count)
DeprecatedString DeprecatedString::bijective_base_from(size_t value, unsigned base, StringView map) DeprecatedString DeprecatedString::bijective_base_from(size_t value, unsigned base, StringView map)
{ {
value++;
if (map.is_null()) if (map.is_null())
map = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"sv; map = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"sv;
@ -255,15 +256,16 @@ DeprecatedString DeprecatedString::bijective_base_from(size_t value, unsigned ba
Array<char, round_up_to_power_of_two(sizeof(size_t) * 8 + 1, 2)> buffer; Array<char, round_up_to_power_of_two(sizeof(size_t) * 8 + 1, 2)> buffer;
size_t i = 0; size_t i = 0;
do { do {
buffer[i++] = map[value % base]; auto remainder = value % base;
value /= base; auto new_value = value / base;
} while (value > 0); if (remainder == 0) {
new_value--;
remainder = map.length();
}
// NOTE: Weird as this may seem, the thing that comes after 'Z' is 'AA', which as a number would be '00' buffer[i++] = map[remainder - 1];
// to make this work, only the most significant digit has to be in a range of (1..25) as opposed to (0..25), value = new_value;
// but only if it's not the only digit in the string. } while (value > 0);
if (i > 1)
--buffer[i - 1];
for (size_t j = 0; j < i / 2; ++j) for (size_t j = 0; j < i / 2; ++j)
swap(buffer[j], buffer[i - j - 1]); swap(buffer[j], buffer[i - j - 1]);

View file

@ -290,7 +290,10 @@ TEST_CASE(bijective_base)
EXPECT_EQ(DeprecatedString::bijective_base_from(25), "Z"); EXPECT_EQ(DeprecatedString::bijective_base_from(25), "Z");
EXPECT_EQ(DeprecatedString::bijective_base_from(26), "AA"); EXPECT_EQ(DeprecatedString::bijective_base_from(26), "AA");
EXPECT_EQ(DeprecatedString::bijective_base_from(52), "BA"); EXPECT_EQ(DeprecatedString::bijective_base_from(52), "BA");
EXPECT_EQ(DeprecatedString::bijective_base_from(704), "ABC"); EXPECT_EQ(DeprecatedString::bijective_base_from(701), "ZZ");
EXPECT_EQ(DeprecatedString::bijective_base_from(702), "AAA");
EXPECT_EQ(DeprecatedString::bijective_base_from(730), "ABC");
EXPECT_EQ(DeprecatedString::bijective_base_from(18277), "ZZZ");
} }
TEST_CASE(roman_numerals) TEST_CASE(roman_numerals)