Summarize and say sequence: Difference between revisions
Content added Content deleted
(Changed the key of cache to a seq[char] which eliminates a "join" and improve performance by almost 50%.) |
|||
Line 2,902: | Line 2,902: | ||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
A version which uses a cache to store the number of iterations and thus avoids to compute the sequence for each permutation. The version without cache |
A version which uses a cache to store the number of iterations and thus avoids to compute the sequence for each permutation. The version without cache runs in more than 9 seconds. This version runs in less than 300 ms. |
||
<lang Nim>import algorithm, sequtils, sets, strutils, tables |
<lang Nim>import algorithm, sequtils, sets, strutils, tables |
||
var cache: Table[ |
var cache: Table[seq[char], int] # Maps key -> number of iterations. |
||
Line 2,930: | Line 2,930: | ||
proc seqLength(seed: string): int = |
proc seqLength(seed: string): int = |
||
## Return the number of iterations for the given seed. |
## Return the number of iterations for the given seed. |
||
let |
let key = sorted(seed, Descending) |
||
if |
if key in cache: return cache[key] |
||
result = toSeq(sequence( |
result = toSeq(sequence(seed)).len |
||
cache[ |
cache[key] = result |
||