给定两个字符串时,查找两个字符串之间的转换表(替换密码),如果不可能进行翻译,则输出false。答案必须最小化,并从左到右创建。要在单词之间翻译的第一个字符必须是翻译表中的第一个字符。此外,任何未翻译的信件(与原址相同)都不应出现在翻译表中。
也许最容易通过例子来定义:
"bat", "sap" => ["bt","sp"]注意排序,["tb","ps"]的输出对此挑战无效。
"sense", "12n12" => ["se","12"]注意如何没有翻译n,因为它是1到1的关系。
"rabid", "snail" => ["rabd","snal"]注意如何没有翻译i,因为它是1到1的关系。
"ass", "all" => ["s","l"]不包括a,它保持不变,由于模式匹配,s可以映射到l。
"3121212", "ABLBLBL" => ["312","ABL"]完全匹配模式。
"banana", "angular" => false(长度不同,不可能)。
"animal", "snails" => false(每个字符只能在翻译的每一面使用一次)。
"can","cnn" => false(在翻译中隐式使用n,因此,用n->a定义翻译表无效)
因此,[aimal,sails]是一个无效的答案,使这个错误。
"a1", "22" => false见“警告”,这是虚假的。在这种情况下,这是因为a和1都不能映射到2。(每个字符只能在翻译的每一面使用一次)。
这个答案似乎是一个很好的基准:https://codegolf.stackexchange.com/a/116807/59376
如果您对两个未列出的字对的功能有疑问,请遵从此实现。
a不会等于b,并且a和b都不会是空的。a和b是可打印的ASCII字母序列.a和b。snails到animals的翻译是不可能的。"a1","22"->[a1,12],其中a首先被a替换,然后得到的1's被替换为2's,这是不正确的,假设所有的翻译都是相互独立的,这意味着这是错误的。意思:"a1“和A 1,12的翻译表计算为12 (而不是22)发布于 2017-04-17 18:34:00
f=
(s,t)=>!t[s.length]&&[...s].every((c,i)=>n[d=t[i]]==c||d&&!m[c]&&!n[d]&&(n[m[c]=d]=c,c==d||(a+=c,b+=d)),m={},n={},a=b='')&&[a,b]<div oninput=o.textContent=f(s.value,t.value)><input id=s><input id=t><pre id=o>发布于 2017-04-17 17:43:54
->a,b{a.size!=b.size||(m=a.chars.zip b.chars).any?{|i,j|m.any?{|k,l|(i==k)^(j==l)}}?0:m.select{|x,y|x!=y}.uniq.transpose.map(&:join)}更可读的是:
->a, b{
# Pair the letters in each string - [AB, AB, AB,...]
pairs = a.chars.zip(b.chars)
# If there's any combination of two pairs that share one character but not both,
# or if the strings have different lengths, then the input's invalid.
if a.size != b.size || pairs.any?{|i,j| pairs.any? {|k, l| (i==k)!=(j==l) }}
return 0 # 0 isn't actually falsy in Ruby, but this challenge allows it anyway
end
return pairs.select{|x,y| x != y} # Remove unchanged letters
.uniq # Remove duplicates
.transpose # Change [AB, AB, AB] form to [AAA, BBB] form.
.map(&:join) # Convert the arrays back into strings
}这里是Goruby的84字节版本,它是Ruby,但是在编译解释器时设置了高尔夫球标志。除其他外,它允许您将方法调用缩写为它们的最短唯一标识符。
->a,b{a.sz!=b.sz||(m=a.ch.z b).ay?{|i,j|m.y?{|k,l|(i==k)^(j==l)}}?0:m.rj{|x,y|x==y}.u.tr.m(&:j)}发布于 2017-04-17 19:45:02
BEGIN{RS="(.)"}RT~/\W/{S=1}RT~/\w/&&S{if(RT!=x=A[++b]){if(B[z=RT]==""){B[z]=x
c=c x
d=d z}a=B[z]!=x?0:a}}!S{A[++a]=RT}END{if(a==b)print c,d}用法:将代码放在FILE中:
awk -f FILE <<< "string1 string2"输入字符串需要分隔空格。
如果输出失败,则输出为空,或由空格分隔的两个字符串。
https://codegolf.stackexchange.com/questions/116786
复制相似问题