给定一个字典文件(在每一行中包含一个单词或短语的文本文件,其中可能有标点符号,但没有数字;行是按字母顺序排列的),您必须输出每个单词的组合,其中一个字母可以从一个单词中删除以生成另一个单词;删除的字母应该用括号括起来。
例如,输入
cat
cart
code
golf
ode
verify
versify给出的输出
ca(r)t
(c)ode
ver(s)ify获取同一对的多种方法只能显示一次。您可以输出scra(p)ped或scrap(p)ed,但两者都不能输出。
输出应按较长的条目按字母顺序排列;
mart
mar
mat
ma应该有一个输出
ma(r)
ma(t)
ma(r)t
mar(t)后两者都可能是按顺序排列的。
字典文件可能包括大写、空格、连字符或撇号;这些应该被忽略。例如,
inlay
in-play应该产生in(p)lay。您的输出应该都在相同的情况下。允许额外的空白。
输入可以是STDIN,也可以是文件;它由换行符分隔。输出可以是函数或STDOUT的返回值(如果需要,也可以写入文件)。
这是密码-高尔夫,所以以字节为单位的最短代码获胜。
(这是我对PPCG的第一次挑战--如果我做错了什么,请告诉我,我会解决的。)
发布于 2015-09-28 09:29:22
一个带有字符串参数的函数,没有来自文件的输入。我问OP这是否有效。
测试在符合EcmaScript 6的浏览器中运行代码片段(实现箭头函数、模板字符串、扩展操作符- Firefox,可能是Safari或MS,而不是Chrome)
f=t=>t.split`
`.map(w=>(d[k=w.replace(/\W/g,'').toLowerCase()]={},k),d={},r=[]).map(w=>[...w].map((c,i,v)=>(d[v[i]='',x=v.join``]&&!d[x][w]&&r.push(d[x][w]=(v[i]=`(${c})`,v.join``)),v[i]=c)))&&r.sort((a,b)=>a.length-b.length)
// LESS GOLFED
Q=t=>{
// convert to canonical form and put in a dictionary
// each value in the dictionary is an hashtable tha will store the list
// of words that can generate the current word, removing a letter
d={},
t=t.split`\n`.map(w=>(k=w.replace(/\W/g,'').toLowerCase(),d[k]={},k))
r=[], // result array
t.forEach(w =>
[...w].forEach((c,i,v)=>( // for each letter in word, try to remove
v[i]='', x=v.join``, // build string with missing letter
v[i]='('+c+')', y=v.join``, // and build string with brackets
v[i]=c, // restore the current letter
d[x] && // if the word with removed letter is present in the dictionary
!d[x][w] && // and not already from the same generating word
r.push(d[x][w]=y) // update dictionary and add word to result array
))
)
return r.sort((a,b)=>a.length-b.length) // sort result by length
}
// TEST
function test() { R.innerHTML=f(I.value) }textarea { height: 20em }Test <button onclick="test()">-></button>
<span id=R></span>
<br><textarea id=I>cat
cart
code
golf
node
scraped
scrapped
verify
versify
mart
mar
mat
ma</textarea>发布于 2015-09-28 08:31:30
->d{o=[]
c={}
d=d.sort_by{|w|[w.size,w]}.map{|w|w=w.upcase.gsub /[^A-Z]/,''
c[w]=l=1
w.size.times{|i|p,x,s=w[0...i],w[i],w[i+1..-1]
c[p+s]&&l!=x&&o<<p+"(#{w[i]})"+s
l=x}}
o}在这里测试它:http://ideone.com/86avbe
这里的可读版本:http://ideone.com/ynFItB
发布于 2015-09-28 14:51:31
我决定采用不同的方法来解决这个问题,使用regex。
->d{o=[]
d.map{|x|x.upcase!.gsub! /[-' ]/,''}
d.map{|x|(x.size+1).times{|i|o+=d.map{|w|w.b.sub! /(#{x[0...i]})(.)(#{x[i..-1]})/,'\1(\2)\3'if w[i]!=w[i+1]}}}
o.compact.sort_by{|w|[w.size,w.gsub(/[()]/,'')]}.uniq}https://codegolf.stackexchange.com/questions/58859
复制相似问题