的JavaScript(ECMAScript的6) - 148个 139 135特性
版本2:
更新为使用数组理解:
[a[i][0]for(i in a=[].concat(...s.split('\n').map(x=>x.split(/ */).sort().map((x,i,a)=>x+(a[i-1]==x?++j:j=0)))).sort())if(a[i-1]<a[i])]
版本1:
[].concat(...s.split('\n').map(x=>x.split(/ */).sort().map((x,i,a)=>x+(a[i-1]==x?++j:j=0)))).sort().filter((x,i,a)=>a[i-1]!=x).map(x=>x[0])
假设:
- 输入字符串在变量中
s
;
- 我们可以忽略输入的大小写(由问题指定-即全部为大写或小写);
- 输出是一个字符数组(大约与JavaScript可以达到OP对字符列表的要求一样);和
- 输出将显示在控制台上。
有评论:
var l = s.split('\n') // split the input up into sentences
.map(x=>x.split(/ */) // split each sentence up into letters ignoring any
// whitespace
.sort() // sort the letters in each sentence alphabetically
.map((x,i,a)=>x+(a[i-1]==x?++j:j=0)))
// append the frequency of previously occurring identical
// letters in the same sentence to each letter.
// I.e. "HELLO WORLD" =>
// ["D0","E0","H0","L0","L1","L2","O0","O1","R0","W0"]
[].concat(...l) // Flatten the array of arrays of letters+frequencies
// into a single array.
.sort() // Sort all the letters and appended frequencies
// alphabetically.
.filter((x,i,a)=>a[i-1]!=x) // Remove duplicates and return the sorted
.map(x=>x[0]) // Get the first letter of each entry (removing the
// frequencies) and return the array.
如果你想:
- 以字符串形式返回,然后
.join('')
在末尾添加;
- 接受用户输入,然后将
s
变量替换为prompt()
; 要么
- 将其编写为函数,
f
然后添加f=s=>
到开头。
正在运行:
s="HELLO\nI LOVE CAT\nI LOVE DOG\nI LOVE MOMMY\nMOMMY LOVE DADDY";
[].concat(...s.split('\n').map(x=>x.split(/ */).sort().map((x,i,a)=>x+(a[i-1]==x?++j:j=0)))).sort().filter((x,i,a)=>a[i-1]!=x).map(x=>x[0])
给出输出:
["A","C","D","D","D","E","G","H","I","L","L","M","M","M","O","O","T","V","Y","Y"]
v
输出中应该有一个字母;)