Created
November 28, 2013 03:16
-
-
Save kfitfk/7686787 to your computer and use it in GitHub Desktop.
group pinyin array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** 把中文转换成拼音数组后,如果有多音字,枚举所有可能的组合 | |
* 示例: | |
* [ [ 'a' ], | |
* [ 'b', 'c', 'd' ], | |
* [ 'e', 'f' ], | |
* [ 'g' ] ] | |
* 使用getResult方法将会返回: | |
* ["abeg", "abfg", "aceg", "acfg", "adeg", "adfg"] | |
*/ | |
function getCount (arr) { | |
var count = 1; | |
arr.forEach(function(item) { | |
count *= item.length; | |
}); | |
return count; | |
} | |
function getResult(arr) { | |
var results = []; | |
var cCount = getCount(arr) | |
var gCount = cCount; | |
var gLen = 0; | |
var index = 0; | |
for(var i = 0; i < arr.length; i++) { | |
gLen = arr[i].length; | |
if(gLen > 1) { | |
gCount /= gLen; | |
for(var j = 0; j < cCount;) { | |
if(!results[j]) results[j] = ''; | |
results[j] += arr[i][index]; | |
if(++j % gCount === 0) { | |
index = ++index >= gLen ? 0 : index; | |
} | |
} | |
index = 0; | |
} | |
else { | |
for(var j = 0; j < cCount; j++) { | |
if(!results[j]) results[j] = ''; | |
results[j] += arr[i][0]; | |
} | |
} | |
} | |
return results; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment