|
Oktatás * Programozás 1 * Szkriptnyelvek Teaching • Programming 1 (BI) Félévek Linkek * kalendárium |
Nim2 /
remove duplicatesLet's solve this exercise: "Consider the following list: Solution 1 (arbitrary order)If we need to remove the duplicates, then we can immediately think of using a set. import std/sequtils # toSeq(iter), map, filter import std/algorithm # sorted(seq), reversed(seq) import std/sets let li = @[5, 2, 3, 5, 1, 4, -200, 5, 1, 3, 2, 2, 5] result = sorted(li.toHashSet.toSeq) echo result # @[-200, 1, 2, 3, 4, 5] Solution 2 (keep order)If we have a seq and we want to remove the duplicates, then there's a seq method for this (link): func deduplicate[T](s: openArray[T]; isSorted: bool = false): seq[T] It removes the duplicates AND keeps the original order of the elements. In this case, it's not necessary to convert the seq to a set and then back to a seq. import std/sequtils # toSeq(iter), map, filter import std/algorithm # sorted(seq), reversed(seq) let li = @[5, 2, 3, 5, 1, 4, -200, 5, 1, 3, 2, 2, 5] echo li.deduplicate() # @[5, 2, 3, 1, 4, -200] ; the order is kept echo sorted(li.deduplicate) # @[-200, 1, 2, 3, 4, 5] |
![]() Blogjaim, hobbi projektjeim * The Ubuntu Incident [ edit ] |