该算法题来自于 codewars【语言: javascript】,翻译如有误差,敬请谅解~
- 任务
- 给出一系列术语组成的数组,如果其中任何一个术语与
Alan Partridge
有关,就返回Mine's a Pint!
-
Mine's a Pint
之后!的数量,由所提供的数组(x)与的Alan Partridge
相关的术语个数确定。相关术语为:
Partridge
PearTree
Chat
Dan
Toblerone
Lynn
AlphaPapa
Nomad - 如果没有任何一个术语与
Alan Partridge
相关,请返回Lynn, I've pierced my foot on a spike!!
- 例如:
part(['Grouse', 'Partridge', 'Pheasant']) // 'Mine's a Pint!'
part(['Pheasant', 'Goose', 'Starling', 'Robin']) // 'Lynn, I've pierced my foot on a spike!!'
part(['Grouse', 'Partridge', 'Pheasant', 'Goose', 'Starling', 'Robin', 'Thrush', 'Emu', 'PearTree', 'Chat', 'Dan', 'Square', 'Toblerone', 'Lynn', 'AlphaPapa', 'BMW', 'Graham', 'Tool', 'Nomad', 'Finger', 'Hamster']) // 'Mine's a Pint!!!!!!!!'
- 解答
- 其一
function part(x){
let len = x.join('').replace(/Partridge|PearTree|Chat|Dan|Toblerone|Lynn|AlphaPapa|Nomad/g,'#').split('#').length - 1;
let str = "Lynn, I've pierced my foot on a spike!!";
if (len) str = "Mine\'s a Pint" + '!'.repeat(len);
return str;
}
- 其二
function part(x){
var count = x.filter(e => ['Partridge','PearTree','Chat','Dan','Toblerone','Lynn','AlphaPapa','Nomad'].indexOf(e) != -1).length;
return count > 0 ? 'Mine\'s a Pint' + '!'.repeat(count) : 'Lynn, I\'ve pierced my foot on a spike!!';
}