编写一个程序或函数,该程序或函数以Morse代码中的数学表达式作为输入,并以Morse代码返回解决方案。
有效操作加:+和减号:_ (下划线)。您可以假设您只接收到非负整数输入,并且结果将是非负的。
表达式将至少包含两个术语,最多包含10个术语。不会有两个相邻的运算符,即.----+_-....,也不会有括号。
数字由单个空格分隔。您可以选择将运算符与数字分隔开来,在每一侧都有一个空格(参见示例)。
数字0-9的Morse等效值是:
0 -----
1 .----
2 ..---
3 ...--
4 ....-
5 .....
6 -....
7 --...
8 ---..
9 ----.Input
Output
.----+.---- (1+1=2) Optional input: .---- + .----
..---
-...._...-- (6-3=3) Optional input: -.... _ ...--
...--
..---_...--+..--- (2-3+2=1)
1
..---+...--_....-+---.._..... (2+3-4+8-5=4)
....-
.---- ..---_-....+...-- ...-- (12-6+33=39)
...-- ----.
----. -----+----.+..--- ----._..... .....+---..+-...._.----+----.+----._..--- ----- (90+9+29-55+8+6-1+9+9-20=84)
---.. ....-适用有关I/O格式等的标准规则。只接受几个尾随空格和一个换行符。你不能把这个数字分成几行。您不能使用eval或等效的。
这是代码高尔夫,所以以字节为单位的最短代码获胜。
发布于 2016-03-07 18:24:27
有很大的改进空间
q=>(q.replace(/[.-]{5}/g,q=>(a=q.split`.`.length)&&q[4]=='-'?a-1:11-a).replace(/ /g,'').split(/([_+])/).reduce((l,o)=>l+(+o?(n=='_'?-(+o):+o):(n=o)&&0),0,n='')+[]).split``.map(u=>(((a='.....')+'-----').slice(5-u)+a).substr(0,5)).join` `碎裂
q=>
(
//grab each set of 5 dits/dahs
q.replace(/[.-]{5}/g,
//count dits
//if last digit is '-' return dits-1
//else return 11-dits
q=>(a=q.split`.`.length)&&q[4]=='-'?a-1:11-a)
//remove spaces and split on operators + and _
.replace(/ /g,'').split(/([_+])/)
//reduce the array into one element
//start with 0;
//when we come across a number add it to the total
//when we come across an operator change current op to it
.reduce((l,o)=>l+(+o?(n=='_'?-(+o):+o):(n=o)&&0),0,n='')
//cast to string
+[])
//turn to array
.split``
//turn each digit back to morse
.map(u=>(".....-----".slice(5-u)+'.....').substr(0,5)).join` ` 用法
f=q=>(q.replace(/[.-]{5}/g,q=>(a=q.split`.`.length)&&q[4]=='-'?a-1:11-a).replace(/ /g,'').split(/([_+])/).reduce((l,o)=>l+(+o?(n=='_'?-(+o):+o):(n=o)&&0),0,n='')+[]).split``.map(u=>(((a='.....')+'-----').slice(5-u)+a).substr(0,5)).join` `
f("----. -----+----.+..--- ----._..... .....+---..+-...._.----+----.+----._..--- -----")https://codegolf.stackexchange.com/questions/74942
复制相似问题