显示给定输入数字的数据集中字母表的所有可能组合
Displaying all possible combinations of alphabets from a dataset for a given input number
我试图实现的是从给定的输入数字中获得字母组合。例如,如果我给出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>
我很困惑如何继续前进,哪种方法是正确的,提前感谢!
该方案使用一个对象进行查找,并使用一个recision进行字符串上的迭代。
调用
c()
的getCombination('1111')
示例如果可能的话,首先对单个字符进行迭代,然后对两个字符进行迭代。
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中通过rtl字母表对列表进行排序和分组
- 对于循环-在循环内部循环,用于获取带有ascii值的字母表
- 只允许数字出现在字母表后面
- 在JavaScript中增加字母表
- JQuery文本区域字母表
- 如何使正则表达式接受ONLY字母表和空格
- 字母表中的选择
- 仅当后面跟着字母表时才允许使用空格字符的验证
- 如何使用regex从字母表字符串中删除特定的字母
- 显示给定输入数字的数据集中字母表的所有可能组合
- 存储字母表中每个字母在所需位置的字符串中出现的次数
- 基于字母表的选择元素的动态选项组
- 将字母表中的所有字母实例替换为另一个
- “map.getBounds()”结果在传单.js集中输入表单后更改
- 在 Jquery 中创建词汇表字母表
- 在CSS和/或Javascript中给定文本中俄语字母表的每个字符都有不同的颜色
- 我正在尝试遍历所有字母表的数组并将所有其他字母大写.任何解决方案
- 为字母表中的所有字母创建链接
- JavaScript 循环字母表与搜索词
- 选择单选按钮时更改字母表