loading...
Cover image for Daily Challenge #272 - Printer Errors

Daily Challenge #272 - Printer Errors

thepracticaldev profile image dev.to staff ・1 min read

In a factory, a printer prints labels for boxes. For one kind of box, 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.

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 a to z.

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

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

Tests:
s = "aaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbmmmmmmmmmmmmmmmmmmmxyz"
s = "aaabbbbbbccccccddddddeee"
s = "verylargepiggoesoink"

Good luck!


This challenge comes from g964 on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!

Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!

Posted on by:

thepracticaldev profile

dev.to staff

@thepracticaldev

The hardworking team behind dev.to ❤️

Discussion

pic
Editor guide
 

JS


const error_printer = word => {
    const regex = /[a-m]/g
    const proper_num_of_matches = ((word || '').match(regex) || []).length
    return `${word.length - proper_num_of_matches}/${word.length}`
}
 

JS - Functional, no regex.

const error_printer = word => {
    const invalidCharacters = [...word]
          .map(word => word.charCodeAt(0))
          .filter(
              charCode => charCode < 97 || charCode > 109
           );
    return `${invalidCharacters.length}/${word.length}`;
};
 

Python solution 🐍

from collections import Counter

def print_errors(colors: str) -> str:
  color_tracker = Counter(colors)
  allowed_colors = range(ord('a'), ord('n'))  # same as "ord('m') + 1"
  color_errors = 0
  for color, amount in color_tracker.items():
    if ord(color) not in allowed_colors:
      color_errors += amount

  return f"{color_errors}/{len(colors)}"
 

Haskell

module Main where


getPrinterErrorRate :: String -> String
getPrinterErrorRate x =
    show (length $ filter (not . flip elem ['a'..'m']) x)
        ++ "/"
        ++ show (length x)


main :: IO ()
main = do
    print $ getPrinterErrorRate "aaabbbbhaijjjm" -- "0/14"
    print $ getPrinterErrorRate "aaaxbbbbyyhwawiwjjjwwm" -- "8/22"
    print $ getPrinterErrorRate "aaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbmmmmmmmmmmmmmmmmmmmxyz" -- 3/56
    print $ getPrinterErrorRate "aaabbbbbbccccccddddddeee" -- "0/24"
    print $ getPrinterErrorRate "verylargepiggoesoink" -- "9/20"

Test

 

Kotlin

fun printer_error(input: String): String
    = "${input.filter { it !in 'a'..'m'}.length}/${input.length}"

Output

  • printer_error("aaabbbbhaijjjm") -> 0/14
  • printer_error("aaaxbbbbyyhwawiwjjjwwm") -> 8/22
  • printer_error("aaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbmmmmmmmmmmmmmmmmmmmxyz") -> 3/56
  • printer_error("aaabbbbbbccccccddddddeee") -> 0/24
  • printer_error("verylargepiggoesoink") -> 9/20
 

Python

import string

def print_error(s):
    chars = string.ascii_lowercase
    good = list(chars)[chars.find('a'):chars.find('m')+1]
    count = 0

    for c in s:
        if c not in good:
            count += 1

    print("{}/{}".format(count, len(s)))


print_error("aaabbbbhaijjjm")
print_error("aaaxbbbbyyhwawiwjjjwwm")
print_error("aaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbmmmmmmmmmmmmmmmmmmmxyz")
print_error("aaabbbbbbccccccddddddeee")
print_error("verylargepiggoesoink")
 

Here is the simple solution with PHP and ASCII code function:

function printerError($s) {
  $startChar = ord('a');
  $lastChar = ord('m');

  $index = 0;
  $missedCount = 0;
  for (; $index<strlen($s); $index++) {
    if (ord($s[$index]) > $lastChar && $startChar < ord($s[$index])) {
      $missedCount += 1;
    }
  }

  return $missedCount . '/' . strlen($s);
}
 

JS w/ regexp

function error_printer(s) {
    const init_len = s.length;
    const err_len = s.replace(/[a-m]/g, "").length;
    return `${err_len}/${init_len}`;
}

Python w/o regexp

def error_printer(s) :
    init_len = len(s)
    err_len = len([e for e in s if ord(e) < ord('a') or ord(e) > ord('m')])
    return str(err_len) + "/" + str(init_len)
 

nodejs

const perro = wurd => {
  let i = 0
  for x of Buffer.from(wurd, "ascii") if (x > 109 || x < 97) i++
  return `${i}/${wurd.length}`
}

And a silly one:

const perro = wurd => Buffer.from(wurd, "ascii")
  .reduce((a, x) => a + (x > 109 || x < 97), 0)
  + "/" + wurd.length
 

JavaScript

const errorPrinter = str => `${str.replace(/[a-m]/g, '').length} / ${str.length}`
 

how to count with javascript regex

const perro = wurd => {
  const re = /[^a-m]/g
  let i = 0
  while (re.test(wurd)) i++
  return `${i}/${wurd.length}`
}
 

Ruby

def printer_error(colors)
  "#{colors.scan(/[n-z]/i).length}/#{colors.length}"
end
 

Javascript

(str) => `${(str.match(/[n-z]+/g) || []).length}/${str.length}`
 

Javascript

const error_printer = (s) => `${s.split('').filter(c => c.charCodeAt() > 109).length}/${s.length}`