小编典典

算法问题:字母组合

algorithm

我正在尝试编写一段代码来执行以下操作:

取数字0到9,并给该数字分配一个或多个字母。例如:

0 = N,
1 = L,
2 = T,
3 = D,
4 = R,
5 = V or F,
6 = B or P,
7 = Z,
8 = H or CH or J,
9 = G

当我有0123这样的代码时,对它进行编码很容易。显然,它将组成代码NLTD。当引入数字5,6或8时,情况会有所不同。051之类的数字可能会导致多种可能性:

NVL和NFL

显而易见,较长的数字甚至包括5、6或8这样的数字,甚至会变得“更糟”。

由于对数学非常不好,我还无法提出一个像样的解决方案,该解决方案无法让我为程序提供大量数字,并吐出所有可能的字母组合。因此,我希望获得一些帮助,因为我似乎无法弄清楚。挖掘一些有关排列和组合的信息,但是没有运气。

感谢您的任何建议/提示。我需要编写代码的语言是PHP,但是任何常规提示将不胜感激。

更新:

更多背景信息:(非常感谢您的快速回复!)

我的问题背后的想法是建立一个脚本,该脚本将帮助人们轻松地将他们想记住的数字转换为更容易记住的单词。有时将其称为“伪命理学”。

我希望脚本给我所有可能的组合,然后将其组合到剥离单词数据库中。这些被剥离的单词仅来自词典,而我在问题中提到的所有字母都被剥离了。这样,要编码的数字通常可以轻松地与一个或多个数据库记录相关。发生这种情况时,您最终会得到一个单词列表,可以用来记住要记住的数字。


阅读 481

收藏
2020-07-28

共1个答案

小编典典

您要保留数字->字母分配的一般结构是一个或多个数组,类似于:

// 0 = N, 1 = L, 2 = T, 3 = D, 4 = R, 5 = V or F, 6 = B or P, 7 = Z, 
// 8 = H or CH or J, 9 = G
$numberMap = new Array (
    0 => new Array("N"),
    1 => new Array("L"),
    2 => new Array("T"),
    3 => new Array("D"),
    4 => new Array("R"),
    5 => new Array("V", "F"),
    6 => new Array("B", "P"),
    7 => new Array("Z"),
    8 => new Array("H", "CH", "J"),
    9 => new Array("G"),
);

然后,一些递归逻辑为我们提供了类似于以下功能:

function GetEncoding($number) {
    $ret = new Array();
    for ($i = 0; $i < strlen($number); $i++) {
        // We're just translating here, nothing special.
        // $var + 0 is a cheap way of forcing a variable to be numeric
        $ret[] = $numberMap[$number[$i]+0];
    }
}

function PrintEncoding($enc, $string = "") {
    // If we're at the end of the line, then print!
    if (count($enc) === 0) {
        print $string."\n";
        return;
    }

    // Otherwise, soldier on through the possible values.
    // Grab the next 'letter' and cycle through the possibilities for it.
    foreach ($enc[0] as $letter) {
        // And call this function again with it!
        PrintEncoding(array_slice($enc, 1), $string.$letter);
    }
}

递归三声欢呼!这将通过以下方式使用:

PrintEncoding(GetEncoding("052384"));

并且,如果您真的希望将其作为数组,请使用输出缓冲并使用“ \ n”作为拆分字符串进行爆炸。

2020-07-28