From 449e5fd844745697d5c8f91b094050caf3fd7f87 Mon Sep 17 00:00:00 2001 From: Archargelod Date: Wed, 7 Feb 2024 23:34:17 +0800 Subject: Week 255 in Nim --- challenge-255/archargelod/nim/ch_1.nim | 25 ++++++++++++++++++++++++ challenge-255/archargelod/nim/ch_2.nim | 35 ++++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100755 challenge-255/archargelod/nim/ch_1.nim create mode 100755 challenge-255/archargelod/nim/ch_2.nim diff --git a/challenge-255/archargelod/nim/ch_1.nim b/challenge-255/archargelod/nim/ch_1.nim new file mode 100755 index 0000000000..8ae9b010f6 --- /dev/null +++ b/challenge-255/archargelod/nim/ch_1.nim @@ -0,0 +1,25 @@ +#!/usr/bin/env -S nim r -d:release --verbosity:0 --hints:off +import tables + +func findOddChar*(base, mixed: string): char = + if mixed.len - base.len != 1: + raiseAssert("Mixed string should be exactly 1 character longer than base.") + + var mixedLetters = mixed.toCountTable + for c in base: + mixedLetters.inc(c, -1) + + for key, val in mixedLetters: + if val != 0: + return key + +when isMainModule: + import std/unittest + + suite "required tests": + test "Perl vs Preel": + check findOddChar("Perl", "Preel") == 'e' + test "Weekly vs Weeakly": + check findOddChar("Weekly", "Weeakly") == 'a' + test "Box vs Boxy": + check findOddChar("Box", "Boxy") == 'y' diff --git a/challenge-255/archargelod/nim/ch_2.nim b/challenge-255/archargelod/nim/ch_2.nim new file mode 100755 index 0000000000..1f967e80ac --- /dev/null +++ b/challenge-255/archargelod/nim/ch_2.nim @@ -0,0 +1,35 @@ +#!/usr/bin/env -S nim r -d:release --verbosity:0 --hints:off +import std/[strutils, parseutils, tables] + +proc mostFrequentWord(paragraph: string, banned: string): string = + var counts: CountTable[string] + + var index = 0 + while true: + index += paragraph.skipUntil(Letters, index) + let length = paragraph.skipWhile(Letters, index) + index += length + + if index >= paragraph.len: + break + + let word = paragraph[index - length ..< index] + if word != banned: + counts.inc(word) + + counts.largest.key + +when isMainModule: + import std/unittest + + suite "required tests": + test "Example 1": + check mostFrequentWord( + "Joe hit a ball, the hit ball flew far after it was hit.", + "hit" + ) == "ball" + test "Example 2": + check mostFrequentWord( + "Perl and Raku belong to the same family. Perl is the most popular language in the weekly challenge.", + "the" + ) == "Perl" -- cgit