我正在尝试编写一个函数来执行其中的注释中清楚描述的内容:
function single_ops(w)
{
/* Given a word w, return an array of all strings that are w with:
(1) 1 letter inserted, that letter being one which is distance
1 away on the keyboard
(2) 1 letter replaced, that letter being one which is distance
1 away on the keyboard
(3) 1 letter removed
(4) 2 adjacent letters swapped
*/
}
我写了一个有效的程序,但它非常混乱!
var A = new Array(); // Associative array to store words, so we can add them w/out addding repeats
for (var i = 0, j = w.length; i < j; ++i)
{
var closeChars = kdmap[w[i]];
var s1a = w.slice(0,i); // equals w[0], ..., w[i-1]
var s2a = w.slice(i,j); // equals w[i], ..., w[j-1]
var s1b = w.slice(0,i+1); // equals w[0], ..., w[i]
var s2b = w.slice(i+1,j) // equals w[i+1], ..., w[j-1]
for (var k = 0, n = closeChars.length; k < n; ++k)
{
var cc = closeChars[k];
// (1) ----------------------------------------------
A[s1a + cc + s2a] = 1; // equals w[0],..., w[i-1], cc, w[i],..., w[j-1]
A[s1b + cc + s2b] = 1; // equals w[0], ..., w[i], cc, w[i+1], ..., w[j-1]
// (2) ----------------------------------------------
A[s1a + cc + s2b] = 1; // equals w[0], ..., w[i-1], cc, w[i+1], ..., w[j-1]
}
// (3) --------------------------------------------------
if (j > 1)
A[s1a + s2b] = 1; // equals w[0], ..., w[i-1], w[i+1], ..., w[j-1]
// (4) --------------------------------------------------
A[s1a + s2b.slice(0,1) + s2a.slice(0,1) + s2b.slice(1,s2b.length)] = 1;
}
return A;
我只是向你展示我的工作代码,所以大家不认为我是想让你为我写的。 ;)
我有几个问题:
if (j > 1)
,因为我不希望数组中有任何空字符串。显然,如果条件总是以相同的方式进行评估,那么在循环中设置条件并不理想,但是我的替代方案是什么?哦,这是kdmap
,我做的“关键距离图”:
/* Map from each character on the keyboard to the characters that
are of distance 1 from it:
*/
var kdmap = {'a': ['q','w','s','z'],
'b': ['v','g','h','n'],
'c': ['x','d','f','v'],
'd': ['s','e','r','f','c','x'],
'e': ['w','s','d','r'],
'f': ['d','r','t','g','v','c'],
'g': ['f','t','y','h','b','v'],
'h': ['g','y','u','j','n','b'],
'i': ['u','h','j','i'],
'j': ['h','n','m','k','i','u','y'],
'k': ['j','i','o','l','m'],
'l': ['k','o','p'],
'm': ['n','j','k'],
'n': ['b','h','j','m'],
'o': ['i','k','l','p'],
'p': ['o','l'],
'q': ['a','w'],
'r': ['e','d','f','t'],
's': ['a','w','e','d','x','z'],
't': ['r','f','g','y'],
'u': ['y','h','j','i'],
'v': ['c','f','g','b'],
'w': ['q','a','s','e'],
'x': ['z','s','d','c'],
'y': ['t','g','h','u'],
'z': ['a','s','x']
};