#function help

7 messages · Page 1 of 1 (latest)

unborn peak
#

Can anyone help me create a c++ function that does the following:

Takes a parameter(s) and the next largest number that starts with the same letter as the inputted number will be the same as the inputted variable.

For example:

If the input is 2, then the output is 3 (because the two start with a T, so the next largest number will be three because it also starts with a T).

If the input is 8, the output will be 11 (because the eight starts with an E, so the next largest number will be 11 because it also starts with an E).

If the input is 18, the output will be 80 (because eighteen starts with an E so the next largest number that starts with an E will be 80).

fast lotus
#

What have you tried?

unborn peak
# fast lotus What have you tried?

I've tried a lot of things like algorithms that would first find the starting letter for said number then increment until it find the next largest number that will share that same starting letter. But that didn't work.

fast lotus
#

Why don't you show us what you've done so people can point out where it's not quite correct or direct you towards making it work

#

That way, at least there's a starting point

unborn peak
#

Can you come up with a more elegant solution?

#include <iostream>
#include <vector>
#include <map>

char firstLetter(int num) {
    if (num >= 1 && num <= 9) return "OTTFFSSEN"[num - 1];
    if (num == 19) return 'N'; 
    if (num == 18) return 'E'; 
    if (num >= 10 && num <= 17) return "TETFFSSEN"[num - 10];
    if (num >= 20 && num <= 99) return "OTTFFSSEN"[(num / 10) - 1];
    if (num >= 100) return firstLetter(num / 10);
    return ' ';
}

int getNextNumber(int input) {
    char letter = firstLetter(input);
    static std::map<char, std::vector<int>> mapping = {
        {'O', {1, 100, 1000, 10000, 100000, 1000000}},
        {'T', {2, 3, 10, 20, 200, 2000, 20000, 200000}},
        {'F', {4, 5, 14, 15, 40, 400, 4000, 40000, 400000}},
        {'S', {6, 7, 16, 17, 60, 600, 6000, 60000, 600000}},
        {'E', {8, 11, 18, 80, 800, 8000, 80000, 800000}}, 
        {'N', {9, 19, 90, 900, 9000, 90000, 900000}}
    };

    auto& nums = mapping[letter];
    for (int i = 0; i < nums.size(); ++i) {
        if (nums[i] == input) {
            return nums[i + 1];
        }
    }

    return -1;
}
limber tiger
#
    if (num == 19) return 'N'; 
    if (num == 18) return 'E'; 
    if (num >= 10 && num <= 17) return "TETFFSSEN"[num - 10];
``` did you add 18 and 19 and change the range cause there was an error with those numbers? if so maybe the string should be "TETTFFSSEN"