【问题标题】:replacing letters in text (pseudo-code)替换文本中的字母(伪代码)
【发布时间】:2012-01-08 15:57:24
【问题描述】:

我正在编写一个脚本来创建用户名。它应该是四个字母长;传统上,我们使用姓氏的 3 个字母 + 名字的 1 个字母。
如果它已被使用,我们会手动考虑替代方案。

所以,如果我的名字是 Fred Flinstones,我们应该试试 FLIF。如果这不起作用;我们遍历名称:FLIA, FLIB, FLIC ... FLIZ, FLAA, FLAB, FLAC, ... FLZZ, FAAA, FAAB, ...

最简单的方法是遍历最后一个字母;然后通过倒数第二个字母进行另一组循环并遍历最后一个字母;然后通过倒数第三、倒数第二、倒数的一组循环;第四+第三+第二+最后。 这使得很多 do while 循环嵌套在彼此中 + 其他人无法阅读 + 大量输入。
我可以为每个字母使用一个计数器,但这似乎也不优雅 我可以尝试使用一个计数器,然后使用mod 26 查看需要替换多少个字母(但这似乎很复杂)。

有没有一些优雅/有效的方法来做到这一点?


第一次尝试尽可能保持字符串“逻辑正确”的奖励积分(例如,为 Fred 保留最后一个字母 F 或跳过字母 FLIF;FLNF、FLSF、FLTF、...)。

【问题讨论】:

    标签: pseudocode auto-generate


    【解决方案1】:

    不确定这是否是您的意思,但如果您按照以下方式构建用户名脚本(我使用 PHP 作为语言),您可以通过添加具有更高模糊因子的选项来扩展它,同时保持代码可读性:

    echo findName('FLINTSTONE', 'FRED');
    
    function findName($last, $first) {
        for ($fuzzFactor = 0; ; $fuzzFactor++) {
            $candidates = fuzzNames($last, $first, $fuzzFactor);
    
            if (empty($candidates)) {
                // exhausted
                return "sorry, I'm out of options!";
            }
    
            foreach ($candidates as $candidate) {
                if (isUnique($candidate)) {
                    return $candidate;
                }
            }
        }
    }
    
    function fuzzNames($last, $first, $fuzzFactor) {
        switch ($fuzzFactor) {
            case 0:
                // no fuzz, return first choice
                return array(substr($last, 0, 3) . $first[0]);
            case 1:
                // replace the third letter of the last name
                // by the fourth/fifth/.../last letter (FLNF, FLTF, ... , FLEF)
                $candidates = array();
                for ($i = 3; $i < strlen($last); $i++) {
                    $candidates[] = substr($last, 0, 2) . $last[$i] . $first[0];
                }
                return $candidates;
            case 2:
                // replace the second and third letter of the last name
                // by their follow-ups (FINF, FITF, ... , FNEF)
                $candidates = array();
                for ($i = 2; $i < strlen($last) - 1; $i++) {
                    for ($j = $i + 1; $j < strlen($last); $j++) {
                        $candidates[] = $last[0] . $last[$i] . $last[$j] . $first[0];
                    }
                }
                return $candidates;
            default:
                return array();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-05
      • 2022-09-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多