gpt4 book ai didi

javascript - 显示给定输入数字的数据集中所有可能的字母组合

转载 作者:搜寻专家 更新时间:2023-11-01 04:23:21 24 4
gpt4 key购买 nike

我想要实现的是从给定的输入数字中获取字母组合。例如。如果我输入 111,输出应该是 ['AAA','KA','AK']。如果输入为 1111,则输出应为 ['AAAA','KAA','AKA','AAK','KK']。部分工作代码如下,其中我得到了输入 111 的 ['K','K']:

    <html>
<head>
<h1>Javascript</h1>
</head>
<body>
<script>
var dataset =
{A:'1',B:'2',C:'3',D:'4',E:'5',F:'6',G:'7',H:'8',I:'9',
J:'10',K:'11',L:'12',M:'13',N:'14',O:'15',P:'16',Q:'17',R:'18',
S:'19',T:'20',U:'21',V:'22',W:'23',X:'24',Y:'25',Z:'26'};

var arr = [];
var z;
var result = [];

var find = function(input){
for(var key in dataset) {
if(dataset[key] === input) {
return key;
}
}
}

var foo = function(x){
z = x.toString();

for(var i=0;i<z.length;i++){
arr.push(z.charAt(i));
}


for(var i=0;i<arr.length;i++){
if(arr[i]+arr[i+1] <= 26){
var returnedkey = find(arr[i]+arr[i+1]);
result.push(returnedkey);
}
}

}

foo(111);
console.log(arr);
console.log(result);

</script>
</body>

我很困惑如何进一步进行,哪个是正确的方法,提前致谢!

最佳答案

该提议使用一个对象进行查找,并使用一个对象对字符串进行迭代。

Example of getCombination('1111') with the call of c()

First iterate over a single character and then iterate over two characters, if possible.

left right  letter result
---- ----- ------ -----
1111 one
111 A one
11 AA one
1 AAA one
AAAA one AAAA
11 AA one
AAK two AAK
111 A one
1 AK two
AKA one AKA
11 K two
1 KA one
KAA one KAA
11 K two
KK two KK

function getCombination(s) {
function c(left, right) {
if (!left) {
result.push(right);
return;
}
// checks if the first character of left is in the letter object
// then call c without the first letter of left
// and right with the letter from the letter object of the first character
letters[left[0]] && c(left.substring(1), right + letters[left[0]]);

// it is basically the same as above, but with two characters
left.length > 1 && letters[left.substring(0, 2)] && c(left.substring(2), right + letters[left.substring(0, 2)]);
}

var letters = { 1: 'A', 2: 'B', 3: 'C', 4: 'D', 5: 'E', 6: 'F', 7: 'G', 8: 'H', 9: 'I', 10: 'J', 11: 'K', 12: 'L', 13: 'M', 14: 'N', 15: 'O', 16: 'P', 17: 'q', 18: 'R', 19: 'S', 20: 'T', 21: 'U', 22: 'V', 23: 'W', 24: 'X', 25: 'Y', 26: 'Z' },
result = [];

c(s, '');
return result;
}

document.write('<pre>' + JSON.stringify(getCombination('1111'), 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(getCombination('1011121314'), 0, 4) + '</pre>');

关于javascript - 显示给定输入数字的数据集中所有可能的字母组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36331707/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com