使用javascript数组中的单词组合 [英] word combination in an array using javascript
问题描述
让我们说我有一个数组['Alex','Sam','Robert']
Let's says I've an array['Alex', 'Sam', 'Robert']
我想将它们结合起来:
采用第一个array [0]并附加array [2],这将是AlexRobert
Take first array[0] and append with array[2] which will be AlexRobert
array [0]的第一个字母是A,并附加有array [2]的是Robert,它将是ARobert
first letter of array[0] which is A and append with array[2] that is Robert which will be ARobert
以array [0]为Alex,并附加array [2]的第一个字母R为AlexR
Take array[0] which is Alex and append with first letter of array[2] that is R which will be AlexR
将第一个array [0]附加到array [1]的第一个字母以及要成为AlexSRobert的array [2]上.
Take first array[0] append with first letter of array[1] along with array[2] which will become AlexSRobert.
基本上,整个想法是当有人输入名字,中间名&姓我应该能够组合并猜测电子邮件ID.例如,Juan F. Nathaniel的数组形式将类似于['Juan','F','Nathaniel']
Basically the whole idea is when someone enter first name, middle name & last name I should be able to make combination and guess email ids. For example- Juan F. Nathaniel the array form will be like ['Juan', 'F', 'Nathaniel']
我想要名字,中间名和姓氏的组合,例如jaunn,jnathaniel,jaunfnathaniel
I want the combination of first, middle and last name like jaunn, jnathaniel, jaunfnathaniel
我是初学者,这是我写的东西:
I'm beginner and here is what I've written:
var nameCombination = function(name){
var counting = name.split(" ");
for (var i=0; i<counting.length; i++){
console.log(counting[i] + counting[i+1]);
console.log(counting[i].split("",1) + counting[i+1]);
}
}
nameCombination('Alex Sam Robert');
推荐答案
可以使用递归方法解决此问题.
This problem can be solved using recursive approach.
var combinations = function(names, i, n){
if(i == n){
return [];
}
last_names = combinations(names, i + 1, n);
name_combinations = last_names.map(function(last_name){
return [
last_name,
names[i] + last_name,
names[i] + last_name[0],
names[i][0] + last_name,
names[i][0] + last_name[0]
]
});
name_combinations = [].concat.apply([], name_combinations);
name_combinations.push(names[i]);
return name_combinations;
};
var nameCombinations = function(name){
var name_array = name.split(' ');
return Array.from(new Set(combinations(name_array, 0, name_array.length)));
};
nameCombinations('first last');
上述功能可以为给定名称生成所有所需的组合.
above function can generate all the desired combinations for a given name.
例如:nameCombinations('first last')将返回["last","firstlast","firstl","flast","fl","first"]].
for example: nameCombinations('first last') will return ["last", "firstlast", "firstl", "flast", "fl", "first"].
这篇关于使用javascript数组中的单词组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!