DEV Community

Cover image for Daily Challenge #272 - Printer Errors
dev.to staff
dev.to staff

Posted on

Daily Challenge #272 - Printer Errors

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!

Top comments (14)

Collapse
 
_bkeren profile image
''

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}`
}
Collapse
 
jjjimenez100 profile image
Joshua Jimenez

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}`;
};
Collapse
 
rafaacioly profile image
Rafael Acioly

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)}"
Collapse
 
aminnairi profile image
Amin

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

Collapse
 
pavi2410 profile image
Pavitra Golchha • Edited

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
Collapse
 
boris profile image
Boris Quiroz

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")
Collapse
 
peter279k profile image
peter279k

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);
}
Collapse
 
cesclass profile image
Cyril ESCLASSAN

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)
Collapse
 
qm3ster profile image
Mihail Malo

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
Collapse
 
savagepixie profile image
SavagePixie

JavaScript

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

Image of Quadratic

Free AI chart generator

Upload data, describe your vision, and get Python-powered, AI-generated charts instantly.

Try Quadratic free

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay