CodeWar(JavaScript)---Printer Errors

9 篇文章 0 订阅

Printer Errors

问题:

In a factory a printer prints labels for boxes. For one kind of boxes the printer has to use colors which, for the sake of simplicity, are named with letters from a to m.

The colors used by the printer are recorded in a control string. For example a “good” control string would be aaabbbbhaijjjm meaning that the printer used three times color a, four times color b, one time color h then one time color a…

Sometimes there are problems: lack of colors, technical malfunction and a “bad” control string is produced e.g. aaaxbbbbyyhwawiwjjjwwm with letters not from a to m.

You have to write a function printer_error which given a string will output the error rate of the printer as a string representing a rational whose numerator is the number of errors and the denominator the length of the control string. Don’t reduce this fraction to a simpler expression.

The string has a length greater or equal to one and contains only letters from ato z.

#Examples:

s="aaabbbbhaijjjm"
error_printer(s) => "0/14"

s="aaaxbbbbyyhwawiwjjjwwm"
error_printer(s) => "8/22"

翻译(来自有道翻译):

在工厂里,打印机为盒子打印标签。对于一种盒子,打印机必须使用从a到m的字母命名的颜色,为了简单起见。

打印机使用的颜色记录在控制字符串中。例如,一个“好的”控制字符串是aaabbbbhaijjjm,意思是打印机使用三次颜色a,四次颜色b,一次颜色h,然后一次颜色a…

有时会有一些问题:缺少颜色,技术故障和一个“坏”的控制字符串产生,例如aaaxbbbbyyhwawiwjjjwwm与字母不是从a到m。

您必须编写一个函数printer_error,它给出一个字符串,将打印机的错误率输出为一个字符串,该字符串表示一个rational,其分子是错误的数量,分母是控制字符串的长度。不要把这个分数简化成一个更简单的表达式。

字符串的长度大于或等于1,并且只包含来自a to z的字母。

#例子:

s="aaabbbbhaijjjm"
error_printer(s) => "0/14"

s="aaaxbbbbyyhwawiwjjjwwm"
error_printer(s) => "8/22"

个人解题代码:

//思路:创建一个数组tmp, 用split()方法切割字符串并放入tmp中
//定义一个记录字母总数的sum、一个记录错误字母总数的errSum
//定义一个n-z的正则表达式reg
//遍历tmp中元素,使用reg判断类型,sum、errSum自增并输出
function printerError(s) {
  var tmp = s.split('');
  var sum = 0;
  var errNum = 0;
  var reg = /^[n-z]+$/
  for(var i = 0 ; i < tmp.length ; i++){
    sum++
    if(reg.test(tmp[i])){
      errNum++  
    }
  }
  return (errNum+"/"+sum)
}

高亮答案:

function printerError(s) {
  return `${s.replace(/[a-m]/ig, '').length}/${s.length}`;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值