DEV Community

Discussion on: Daily Coding Puzzles - Nov 11th - Nov 16th

Collapse
 
kungtotte profile image
Thomas Landin • Edited

My Nim solution :)

Nim supports specifying ranges both in absolute terms and in relative terms. ^2 would be the second to last position of a range, etc :) As you can see at the end of the procedure you can also supply just one end of the range and Nim will infer the other end, so filtered[^1] would be just the final element of the sequence.

import sequtils # for filter

proc format_words(words: seq[string]): string =
  result = ""
  if words.len > 0:
    var filtered = filter(words, proc(w: string): bool = w.len > 0)
    for word in filtered[0..^2]:
      result.add(word & ", ")
    return result[0..^3] & (" and " & filtered[^1])

echo format_words(@["ninja","samurai","ronin","leonardo","michelangelo","donatello","raphael"])
echo format_words(@["ninja","samurai","ronin"])
echo format_words(@["ninja","", "ronin"])
echo format_words(@[])