Sha256: 77e034a8350dbb5c58fe75ee303c1a702c70e9ef5c748c22a4e9970048cbb715

Contents?: true

Size: 738 Bytes

Versions: 47

Compression:

Stored size: 738 Bytes

Contents

import
  algorithm, sequtils, strutils

type TAnagram = tuple
  word: string
  chars: seq[char]  # the lowercased and sorted chars of the word

proc isAnagramTo(a, b: TAnagram): bool {.noSideEffect, procVar.} =
  a.chars == b.chars and cmpIgnoreCase(a.word, b.word) != 0

proc anagram(word: string): TAnagram =
  var chars = toSeq(word.toLowerAscii().items)
  sort(chars, cmp[char])
  (word, chars)

proc detectAnagrams*(word: string, candidates: seq[string]): seq[string] =
  ## Returns a sequence of those `candidates` that are anagrams of `word`.
  ##
  ## .. code-block:: nimrod
  ##   assert detectAnagrams("Ant", @["tan", "ant"]) == @["tan"]
  let reference = anagram(word)
  candidates.filterIt(anagram(it).isAnagramTo(reference))

Version data entries

47 entries across 47 versions & 1 rubygems

Version Path
trackler-2.2.1.139 tracks/nim/exercises/anagram/example.nim
trackler-2.2.1.138 tracks/nim/exercises/anagram/example.nim
trackler-2.2.1.137 tracks/nim/exercises/anagram/example.nim
trackler-2.2.1.136 tracks/nim/exercises/anagram/example.nim
trackler-2.2.1.135 tracks/nim/exercises/anagram/example.nim
trackler-2.2.1.134 tracks/nim/exercises/anagram/example.nim
trackler-2.2.1.133 tracks/nim/exercises/anagram/example.nim