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}`;
}