algorithm.nim 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2015 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module implements some common generic algorithms on `openArray`s.
  10. ##
  11. ## Basic usage
  12. ## ===========
  13. ##
  14. runnableExamples:
  15. type People = tuple
  16. year: int
  17. name: string
  18. var a: seq[People]
  19. a.add((2000, "John"))
  20. a.add((2005, "Marie"))
  21. a.add((2010, "Jane"))
  22. # Sorting with default system.cmp
  23. a.sort()
  24. assert a == @[(year: 2000, name: "John"), (year: 2005, name: "Marie"),
  25. (year: 2010, name: "Jane")]
  26. proc myCmp(x, y: People): int =
  27. cmp(x.name, y.name)
  28. # Sorting with custom proc
  29. a.sort(myCmp)
  30. assert a == @[(year: 2010, name: "Jane"), (year: 2000, name: "John"),
  31. (year: 2005, name: "Marie")]
  32. ## See also
  33. ## ========
  34. ## * `sequtils module<sequtils.html>`_ for working with the built-in seq type
  35. ## * `tables module<tables.html>`_ for sorting tables
  36. import std/private/since
  37. when defined(nimPreviewSlimSystem):
  38. import std/assertions
  39. type
  40. SortOrder* = enum
  41. Descending, Ascending
  42. proc `*`*(x: int, order: SortOrder): int {.inline.} =
  43. ## Flips the sign of `x` if `order == Descending`.
  44. ## If `order == Ascending` then `x` is returned.
  45. ##
  46. ## `x` is supposed to be the result of a comparator, i.e.
  47. ## | `< 0` for *less than*,
  48. ## | `== 0` for *equal*,
  49. ## | `> 0` for *greater than*.
  50. runnableExamples:
  51. assert -123 * Descending == 123
  52. assert 123 * Descending == -123
  53. assert -123 * Ascending == -123
  54. assert 123 * Ascending == 123
  55. var y = order.ord - 1
  56. result = (x xor y) - y
  57. template fillImpl[T](a: var openArray[T], first, last: int, value: T) =
  58. var x = first
  59. while x <= last:
  60. a[x] = value
  61. inc(x)
  62. proc fill*[T](a: var openArray[T], first, last: Natural, value: T) =
  63. ## Assigns `value` to all elements of the slice `a[first..last]`.
  64. ##
  65. ## If an invalid range is passed, it raises `IndexDefect`.
  66. runnableExamples:
  67. var a: array[6, int]
  68. a.fill(1, 3, 9)
  69. assert a == [0, 9, 9, 9, 0, 0]
  70. a.fill(3, 5, 7)
  71. assert a == [0, 9, 9, 7, 7, 7]
  72. doAssertRaises(IndexDefect, a.fill(1, 7, 9))
  73. fillImpl(a, first, last, value)
  74. proc fill*[T](a: var openArray[T], value: T) =
  75. ## Assigns `value` to all elements of the container `a`.
  76. runnableExamples:
  77. var a: array[6, int]
  78. a.fill(9)
  79. assert a == [9, 9, 9, 9, 9, 9]
  80. a.fill(4)
  81. assert a == [4, 4, 4, 4, 4, 4]
  82. fillImpl(a, 0, a.high, value)
  83. proc reverse*[T](a: var openArray[T], first, last: Natural) =
  84. ## Reverses the slice `a[first..last]`.
  85. ##
  86. ## If an invalid range is passed, it raises `IndexDefect`.
  87. ##
  88. ## **See also:**
  89. ## * `reversed proc<#reversed,openArray[T],Natural,int>`_ reverse a slice and returns a `seq[T]`
  90. ## * `reversed proc<#reversed,openArray[T]>`_ reverse and returns a `seq[T]`
  91. runnableExamples:
  92. var a = [1, 2, 3, 4, 5, 6]
  93. a.reverse(1, 3)
  94. assert a == [1, 4, 3, 2, 5, 6]
  95. a.reverse(1, 3)
  96. assert a == [1, 2, 3, 4, 5, 6]
  97. doAssertRaises(IndexDefect, a.reverse(1, 7))
  98. var x = first
  99. var y = last
  100. while x < y:
  101. swap(a[x], a[y])
  102. dec(y)
  103. inc(x)
  104. proc reverse*[T](a: var openArray[T]) =
  105. ## Reverses the contents of the container `a`.
  106. ##
  107. ## **See also:**
  108. ## * `reversed proc<#reversed,openArray[T],Natural,int>`_ reverse a slice and returns a `seq[T]`
  109. ## * `reversed proc<#reversed,openArray[T]>`_ reverse and returns a `seq[T]`
  110. runnableExamples:
  111. var a = [1, 2, 3, 4, 5, 6]
  112. a.reverse()
  113. assert a == [6, 5, 4, 3, 2, 1]
  114. a.reverse()
  115. assert a == [1, 2, 3, 4, 5, 6]
  116. # the max is needed, since a.high is -1 if a is empty
  117. reverse(a, 0, max(0, a.high))
  118. proc reversed*[T](a: openArray[T]): seq[T] {.inline.} =
  119. ## Returns the elements of `a` in reverse order.
  120. ##
  121. ## **See also:**
  122. ## * `reverse proc<#reverse,openArray[T]>`_
  123. runnableExamples:
  124. assert [10, 11, 12].reversed == @[12, 11, 10]
  125. assert seq[string].default.reversed == @[]
  126. let n = a.len
  127. result.setLen(n)
  128. for i in 0..<n: result[i] = a[n - (i + 1)]
  129. proc reversed*[T](a: openArray[T], first: Natural, last: int): seq[T]
  130. {.inline, deprecated: "use: `reversed(toOpenArray(a, first, last))`".} =
  131. reversed(toOpenArray(a, first, last))
  132. when defined(nimHasEffectsOf):
  133. {.experimental: "strictEffects".}
  134. else:
  135. {.pragma: effectsOf.}
  136. proc binarySearch*[T, K](a: openArray[T], key: K,
  137. cmp: proc (x: T, y: K): int {.closure.}): int {.effectsOf: cmp.} =
  138. ## Binary search for `key` in `a`. Return the index of `key` or -1 if not found.
  139. ## Assumes that `a` is sorted according to `cmp`.
  140. ##
  141. ## `cmp` is the comparator function to use, the expected return values are
  142. ## the same as those of system.cmp.
  143. runnableExamples:
  144. assert binarySearch(["a", "b", "c", "d"], "d", system.cmp[string]) == 3
  145. assert binarySearch(["a", "b", "c", "d"], "c", system.cmp[string]) == 2
  146. let len = a.len
  147. if len == 0:
  148. return -1
  149. if len == 1:
  150. if cmp(a[0], key) == 0:
  151. return 0
  152. else:
  153. return -1
  154. result = 0
  155. if (len and (len - 1)) == 0:
  156. # when `len` is a power of 2, a faster shr can be used.
  157. var step = len shr 1
  158. var cmpRes: int
  159. while step > 0:
  160. let i = result or step
  161. cmpRes = cmp(a[i], key)
  162. if cmpRes == 0:
  163. return i
  164. if cmpRes < 0:
  165. result = i
  166. step = step shr 1
  167. if cmp(a[result], key) != 0: result = -1
  168. else:
  169. var b = len
  170. var cmpRes: int
  171. while result < b:
  172. var mid = (result + b) shr 1
  173. cmpRes = cmp(a[mid], key)
  174. if cmpRes == 0:
  175. return mid
  176. if cmpRes < 0:
  177. result = mid + 1
  178. else:
  179. b = mid
  180. if result >= len or cmp(a[result], key) != 0: result = -1
  181. proc binarySearch*[T](a: openArray[T], key: T): int =
  182. ## Binary search for `key` in `a`. Return the index of `key` or -1 if not found.
  183. ## Assumes that `a` is sorted.
  184. runnableExamples:
  185. assert binarySearch([0, 1, 2, 3, 4], 4) == 4
  186. assert binarySearch([0, 1, 2, 3, 4], 2) == 2
  187. binarySearch(a, key, cmp[T])
  188. const
  189. onlySafeCode = true
  190. proc lowerBound*[T, K](a: openArray[T], key: K,
  191. cmp: proc(x: T, k: K): int {.closure.}): int {.effectsOf: cmp.} =
  192. ## Returns the index of the first element in `a` that is not less than
  193. ## (i.e. greater or equal to) `key`, or last if no such element is found.
  194. ## In other words if you have a sorted sequence and you call
  195. ## `insert(thing, elm, lowerBound(thing, elm))`
  196. ## the sequence will still be sorted.
  197. ## Assumes that `a` is sorted according to `cmp`.
  198. ##
  199. ## If an invalid range is passed, it raises `IndexDefect`.
  200. ##
  201. ## This version uses `cmp` to compare the elements.
  202. ## The expected return values are the same as those of `system.cmp`.
  203. ##
  204. ## **See also:**
  205. ## * `upperBound proc<#upperBound,openArray[T],K,proc(T,K)>`_ sorted by `cmp` in the specified order
  206. ## * `upperBound proc<#upperBound,openArray[T],T>`_
  207. runnableExamples:
  208. var arr = @[1, 2, 3, 5, 6, 7, 8, 9]
  209. assert arr.lowerBound(3, system.cmp[int]) == 2
  210. assert arr.lowerBound(4, system.cmp[int]) == 3
  211. assert arr.lowerBound(5, system.cmp[int]) == 3
  212. arr.insert(4, arr.lowerBound(4, system.cmp[int]))
  213. assert arr == [1, 2, 3, 4, 5, 6, 7, 8, 9]
  214. result = a.low
  215. var count = a.high - a.low + 1
  216. var step, pos: int
  217. while count != 0:
  218. step = count shr 1
  219. pos = result + step
  220. if cmp(a[pos], key) < 0:
  221. result = pos + 1
  222. count -= step + 1
  223. else:
  224. count = step
  225. proc lowerBound*[T](a: openArray[T], key: T): int = lowerBound(a, key, cmp[T])
  226. ## Returns the index of the first element in `a` that is not less than
  227. ## (i.e. greater or equal to) `key`, or last if no such element is found.
  228. ## In other words if you have a sorted sequence and you call
  229. ## `insert(thing, elm, lowerBound(thing, elm))`
  230. ## the sequence will still be sorted.
  231. ## Assumes that `a` is sorted.
  232. ##
  233. ## This version uses the default comparison function `cmp`.
  234. ##
  235. ## **See also:**
  236. ## * `upperBound proc<#upperBound,openArray[T],K,proc(T,K)>`_ sorted by `cmp` in the specified order
  237. ## * `upperBound proc<#upperBound,openArray[T],T>`_
  238. proc upperBound*[T, K](a: openArray[T], key: K,
  239. cmp: proc(x: T, k: K): int {.closure.}): int {.effectsOf: cmp.} =
  240. ## Returns the index of the first element in `a` that is greater than
  241. ## `key`, or last if no such element is found.
  242. ## In other words if you have a sorted sequence and you call
  243. ## `insert(thing, elm, upperBound(thing, elm))`
  244. ## the sequence will still be sorted.
  245. ## Assumes that `a` is sorted according to `cmp`.
  246. ##
  247. ## If an invalid range is passed, it raises `IndexDefect`.
  248. ##
  249. ## This version uses `cmp` to compare the elements. The expected
  250. ## return values are the same as those of `system.cmp`.
  251. ##
  252. ## **See also:**
  253. ## * `lowerBound proc<#lowerBound,openArray[T],K,proc(T,K)>`_ sorted by `cmp` in the specified order
  254. ## * `lowerBound proc<#lowerBound,openArray[T],T>`_
  255. runnableExamples:
  256. var arr = @[1, 2, 3, 5, 6, 7, 8, 9]
  257. assert arr.upperBound(2, system.cmp[int]) == 2
  258. assert arr.upperBound(3, system.cmp[int]) == 3
  259. assert arr.upperBound(4, system.cmp[int]) == 3
  260. arr.insert(4, arr.upperBound(3, system.cmp[int]))
  261. assert arr == [1, 2, 3, 4, 5, 6, 7, 8, 9]
  262. result = a.low
  263. var count = a.high - a.low + 1
  264. var step, pos: int
  265. while count != 0:
  266. step = count shr 1
  267. pos = result + step
  268. if cmp(a[pos], key) <= 0:
  269. result = pos + 1
  270. count -= step + 1
  271. else:
  272. count = step
  273. proc upperBound*[T](a: openArray[T], key: T): int = upperBound(a, key, cmp[T])
  274. ## Returns the index of the first element in `a` that is greater than
  275. ## `key`, or last if no such element is found.
  276. ## In other words if you have a sorted sequence and you call
  277. ## `insert(thing, elm, upperBound(thing, elm))`
  278. ## the sequence will still be sorted.
  279. ## Assumes that `a` is sorted.
  280. ##
  281. ## This version uses the default comparison function `cmp`.
  282. ##
  283. ## **See also:**
  284. ## * `lowerBound proc<#lowerBound,openArray[T],K,proc(T,K)>`_ sorted by `cmp` in the specified order
  285. ## * `lowerBound proc<#lowerBound,openArray[T],T>`_
  286. template `<-`(a, b) =
  287. when defined(gcDestructors):
  288. a = move b
  289. elif onlySafeCode:
  290. shallowCopy(a, b)
  291. else:
  292. copyMem(addr(a), addr(b), sizeof(T))
  293. proc mergeAlt[T](a, b: var openArray[T], lo, m, hi: int,
  294. cmp: proc (x, y: T): int {.closure.}, order: SortOrder) {.effectsOf: cmp.} =
  295. # Optimization: If max(left) <= min(right) there is nothing to do!
  296. # 1 2 3 4 ## 5 6 7 8
  297. # -> O(n) for sorted arrays.
  298. # On random data this saves up to 40% of mergeAlt calls.
  299. if cmp(a[m], a[m+1]) * order <= 0: return
  300. var j = lo
  301. # copy a[j..m] into b:
  302. assert j <= m
  303. when onlySafeCode:
  304. var bb = 0
  305. while j <= m:
  306. b[bb] <- a[j]
  307. inc(bb)
  308. inc(j)
  309. else:
  310. copyMem(addr(b[0]), addr(a[j]), sizeof(T)*(m-j+1))
  311. j = m+1
  312. var i = 0
  313. var k = lo
  314. # copy proper element back:
  315. while k < j and j <= hi:
  316. if cmp(b[i], a[j]) * order <= 0:
  317. a[k] <- b[i]
  318. inc(i)
  319. else:
  320. a[k] <- a[j]
  321. inc(j)
  322. inc(k)
  323. # copy rest of b:
  324. when onlySafeCode:
  325. while k < j:
  326. a[k] <- b[i]
  327. inc(k)
  328. inc(i)
  329. else:
  330. if k < j: copyMem(addr(a[k]), addr(b[i]), sizeof(T)*(j-k))
  331. func sort*[T](a: var openArray[T],
  332. cmp: proc (x, y: T): int {.closure.},
  333. order = SortOrder.Ascending) {.effectsOf: cmp.} =
  334. ## Default Nim sort (an implementation of merge sort). The sorting
  335. ## is guaranteed to be stable (that is, equal elements stay in the same order)
  336. ## and the worst case is guaranteed to be O(n log n).
  337. ## Sorts by `cmp` in the specified `order`.
  338. ##
  339. ## The current implementation uses an iterative
  340. ## mergesort to achieve this. It uses a temporary sequence of
  341. ## length `a.len div 2`. If you do not wish to provide your own
  342. ## `cmp`, you may use `system.cmp` or instead call the overloaded
  343. ## version of `sort`, which uses `system.cmp`.
  344. ##
  345. ## ```nim
  346. ## sort(myIntArray, system.cmp[int])
  347. ## # do not use cmp[string] here as we want to use the specialized
  348. ## # overload:
  349. ## sort(myStrArray, system.cmp)
  350. ## ```
  351. ##
  352. ## You can inline adhoc comparison procs with the `do notation
  353. ## <manual_experimental.html#do-notation>`_. Example:
  354. ##
  355. ## ```nim
  356. ## people.sort do (x, y: Person) -> int:
  357. ## result = cmp(x.surname, y.surname)
  358. ## if result == 0:
  359. ## result = cmp(x.name, y.name)
  360. ## ```
  361. ##
  362. ## **See also:**
  363. ## * `sort proc<#sort,openArray[T]>`_
  364. ## * `sorted proc<#sorted,openArray[T],proc(T,T)>`_ sorted by `cmp` in the specified order
  365. ## * `sorted proc<#sorted,openArray[T]>`_
  366. ## * `sortedByIt template<#sortedByIt.t,untyped,untyped>`_
  367. runnableExamples:
  368. var d = ["boo", "fo", "barr", "qux"]
  369. proc myCmp(x, y: string): int =
  370. if x.len() > y.len() or x.len() == y.len(): 1
  371. else: -1
  372. sort(d, myCmp)
  373. assert d == ["fo", "qux", "boo", "barr"]
  374. var n = a.len
  375. var b = newSeq[T](n div 2)
  376. var s = 1
  377. while s < n:
  378. var m = n-1-s
  379. while m >= 0:
  380. mergeAlt(a, b, max(m-s+1, 0), m, m+s, cmp, order)
  381. dec(m, s*2)
  382. s = s*2
  383. proc sort*[T](a: var openArray[T], order = SortOrder.Ascending) = sort[T](a,
  384. system.cmp[T], order)
  385. ## Shortcut version of `sort` that uses `system.cmp[T]` as the comparison function.
  386. ##
  387. ## **See also:**
  388. ## * `sort func<#sort,openArray[T],proc(T,T)>`_
  389. ## * `sorted proc<#sorted,openArray[T],proc(T,T)>`_ sorted by `cmp` in the specified order
  390. ## * `sorted proc<#sorted,openArray[T]>`_
  391. ## * `sortedByIt template<#sortedByIt.t,untyped,untyped>`_
  392. proc sorted*[T](a: openArray[T], cmp: proc(x, y: T): int {.closure.},
  393. order = SortOrder.Ascending): seq[T] {.effectsOf: cmp.} =
  394. ## Returns `a` sorted by `cmp` in the specified `order`.
  395. ##
  396. ## **See also:**
  397. ## * `sort func<#sort,openArray[T],proc(T,T)>`_
  398. ## * `sort proc<#sort,openArray[T]>`_
  399. ## * `sortedByIt template<#sortedByIt.t,untyped,untyped>`_
  400. runnableExamples:
  401. let
  402. a = [2, 3, 1, 5, 4]
  403. b = sorted(a, system.cmp[int])
  404. c = sorted(a, system.cmp[int], Descending)
  405. d = sorted(["adam", "dande", "brian", "cat"], system.cmp[string])
  406. assert b == @[1, 2, 3, 4, 5]
  407. assert c == @[5, 4, 3, 2, 1]
  408. assert d == @["adam", "brian", "cat", "dande"]
  409. result = newSeq[T](a.len)
  410. for i in 0 .. a.high:
  411. result[i] = a[i]
  412. sort(result, cmp, order)
  413. proc sorted*[T](a: openArray[T], order = SortOrder.Ascending): seq[T] =
  414. ## Shortcut version of `sorted` that uses `system.cmp[T]` as the comparison function.
  415. ##
  416. ## **See also:**
  417. ## * `sort func<#sort,openArray[T],proc(T,T)>`_
  418. ## * `sort proc<#sort,openArray[T]>`_
  419. ## * `sortedByIt template<#sortedByIt.t,untyped,untyped>`_
  420. runnableExamples:
  421. let
  422. a = [2, 3, 1, 5, 4]
  423. b = sorted(a)
  424. c = sorted(a, Descending)
  425. d = sorted(["adam", "dande", "brian", "cat"])
  426. assert b == @[1, 2, 3, 4, 5]
  427. assert c == @[5, 4, 3, 2, 1]
  428. assert d == @["adam", "brian", "cat", "dande"]
  429. sorted[T](a, system.cmp[T], order)
  430. template sortedByIt*(seq1, op: untyped): untyped =
  431. ## Convenience template around the `sorted` proc to reduce typing.
  432. ##
  433. ## The template injects the `it` variable which you can use directly in an
  434. ## expression.
  435. ##
  436. ## Because the underlying `cmp()` is defined for tuples you can also do
  437. ## a nested sort.
  438. ##
  439. ## **See also:**
  440. ## * `sort func<#sort,openArray[T],proc(T,T)>`_
  441. ## * `sort proc<#sort,openArray[T]>`_
  442. ## * `sorted proc<#sorted,openArray[T],proc(T,T)>`_ sorted by `cmp` in the specified order
  443. ## * `sorted proc<#sorted,openArray[T]>`_
  444. runnableExamples:
  445. type Person = tuple[name: string, age: int]
  446. var
  447. p1: Person = (name: "p1", age: 60)
  448. p2: Person = (name: "p2", age: 20)
  449. p3: Person = (name: "p3", age: 30)
  450. p4: Person = (name: "p4", age: 30)
  451. people = @[p1, p2, p4, p3]
  452. assert people.sortedByIt(it.name) == @[(name: "p1", age: 60), (name: "p2",
  453. age: 20), (name: "p3", age: 30), (name: "p4", age: 30)]
  454. # Nested sort
  455. assert people.sortedByIt((it.age, it.name)) == @[(name: "p2", age: 20),
  456. (name: "p3", age: 30), (name: "p4", age: 30), (name: "p1", age: 60)]
  457. var result = sorted(seq1, proc(x, y: typeof(items(seq1), typeOfIter)): int =
  458. var it {.inject.} = x
  459. let a = op
  460. it = y
  461. let b = op
  462. result = cmp(a, b))
  463. result
  464. func isSorted*[T](a: openArray[T],
  465. cmp: proc(x, y: T): int {.closure.},
  466. order = SortOrder.Ascending): bool {.effectsOf: cmp.} =
  467. ## Checks to see whether `a` is already sorted in `order`
  468. ## using `cmp` for the comparison. The parameters are identical
  469. ## to `sort`. Requires O(n) time.
  470. ##
  471. ## **See also:**
  472. ## * `isSorted proc<#isSorted,openArray[T]>`_
  473. runnableExamples:
  474. let
  475. a = [2, 3, 1, 5, 4]
  476. b = [1, 2, 3, 4, 5]
  477. c = [5, 4, 3, 2, 1]
  478. d = ["adam", "brian", "cat", "dande"]
  479. e = ["adam", "dande", "brian", "cat"]
  480. assert isSorted(a) == false
  481. assert isSorted(b) == true
  482. assert isSorted(c) == false
  483. assert isSorted(c, Descending) == true
  484. assert isSorted(d) == true
  485. assert isSorted(e) == false
  486. result = true
  487. for i in 0..<len(a)-1:
  488. if cmp(a[i], a[i+1]) * order > 0:
  489. return false
  490. proc isSorted*[T](a: openArray[T], order = SortOrder.Ascending): bool =
  491. ## Shortcut version of `isSorted` that uses `system.cmp[T]` as the comparison function.
  492. ##
  493. ## **See also:**
  494. ## * `isSorted func<#isSorted,openArray[T],proc(T,T)>`_
  495. runnableExamples:
  496. let
  497. a = [2, 3, 1, 5, 4]
  498. b = [1, 2, 3, 4, 5]
  499. c = [5, 4, 3, 2, 1]
  500. d = ["adam", "brian", "cat", "dande"]
  501. e = ["adam", "dande", "brian", "cat"]
  502. assert isSorted(a) == false
  503. assert isSorted(b) == true
  504. assert isSorted(c) == false
  505. assert isSorted(c, Descending) == true
  506. assert isSorted(d) == true
  507. assert isSorted(e) == false
  508. isSorted(a, system.cmp[T], order)
  509. proc merge*[T](
  510. result: var seq[T],
  511. x, y: openArray[T], cmp: proc(x, y: T): int {.closure.}
  512. ) {.since: (1, 5, 1), effectsOf: cmp.} =
  513. ## Merges two sorted `openArray`. `x` and `y` are assumed to be sorted.
  514. ## If you do not wish to provide your own `cmp`,
  515. ## you may use `system.cmp` or instead call the overloaded
  516. ## version of `merge`, which uses `system.cmp`.
  517. ##
  518. ## .. note:: The original data of `result` is not cleared,
  519. ## new data is appended to `result`.
  520. ##
  521. ## **See also:**
  522. ## * `merge proc<#merge,seq[T],openArray[T],openArray[T]>`_
  523. runnableExamples:
  524. let x = @[1, 3, 6]
  525. let y = @[2, 3, 4]
  526. block:
  527. var merged = @[7] # new data is appended to merged sequence
  528. merged.merge(x, y, system.cmp[int])
  529. assert merged == @[7, 1, 2, 3, 3, 4, 6]
  530. block:
  531. var merged = @[7] # if you only want new data, clear merged sequence first
  532. merged.setLen(0)
  533. merged.merge(x, y, system.cmp[int])
  534. assert merged.isSorted
  535. assert merged == @[1, 2, 3, 3, 4, 6]
  536. import std/sugar
  537. var res: seq[(int, int)]
  538. res.merge([(1, 1)], [(1, 2)], (a, b) => a[0] - b[0])
  539. assert res == @[(1, 1), (1, 2)]
  540. assert seq[int].default.dup(merge([1, 3], [2, 4])) == @[1, 2, 3, 4]
  541. let
  542. sizeX = x.len
  543. sizeY = y.len
  544. oldLen = result.len
  545. result.setLen(oldLen + sizeX + sizeY)
  546. var
  547. ix = 0
  548. iy = 0
  549. i = oldLen
  550. while true:
  551. if ix == sizeX:
  552. while iy < sizeY:
  553. result[i] = y[iy]
  554. inc i
  555. inc iy
  556. return
  557. if iy == sizeY:
  558. while ix < sizeX:
  559. result[i] = x[ix]
  560. inc i
  561. inc ix
  562. return
  563. let itemX = x[ix]
  564. let itemY = y[iy]
  565. if cmp(itemX, itemY) > 0: # to have a stable sort
  566. result[i] = itemY
  567. inc iy
  568. else:
  569. result[i] = itemX
  570. inc ix
  571. inc i
  572. proc merge*[T](result: var seq[T], x, y: openArray[T]) {.inline, since: (1, 5, 1).} =
  573. ## Shortcut version of `merge` that uses `system.cmp[T]` as the comparison function.
  574. ##
  575. ## **See also:**
  576. ## * `merge proc<#merge,seq[T],openArray[T],openArray[T],proc(T,T)>`_
  577. runnableExamples:
  578. let x = [5, 10, 15, 20, 25]
  579. let y = [50, 40, 30, 20, 10].sorted
  580. var merged: seq[int]
  581. merged.merge(x, y)
  582. assert merged.isSorted
  583. assert merged == @[5, 10, 10, 15, 20, 20, 25, 30, 40, 50]
  584. merge(result, x, y, system.cmp)
  585. proc product*[T](x: openArray[seq[T]]): seq[seq[T]] =
  586. ## Produces the Cartesian product of the array.
  587. ## Every element of the result is a combination of one element from each seq in `x`,
  588. ## with the ith element coming from `x[i]`.
  589. ##
  590. ## .. warning:: complexity may explode.
  591. runnableExamples:
  592. assert product(@[@[1], @[2]]) == @[@[1, 2]]
  593. assert product(@[@["A", "K"], @["Q"]]) == @[@["K", "Q"], @["A", "Q"]]
  594. let xLen = x.len
  595. result = newSeq[seq[T]]()
  596. if xLen == 0:
  597. return
  598. if xLen == 1:
  599. result = @x
  600. return
  601. var
  602. indices = newSeq[int](xLen)
  603. initial = newSeq[int](xLen)
  604. index = 0
  605. var next = newSeq[T](xLen)
  606. for i in 0 ..< xLen:
  607. if len(x[i]) == 0: return
  608. initial[i] = len(x[i]) - 1
  609. indices = initial
  610. while true:
  611. while indices[index] == -1:
  612. indices[index] = initial[index]
  613. index += 1
  614. if index == xLen: return
  615. indices[index] -= 1
  616. for ni, i in indices:
  617. next[ni] = x[ni][i]
  618. result.add(next)
  619. index = 0
  620. indices[index] -= 1
  621. proc nextPermutation*[T](x: var openArray[T]): bool {.discardable.} =
  622. ## Calculates the next lexicographic permutation, directly modifying `x`.
  623. ## The result is whether a permutation happened, otherwise we have reached
  624. ## the last-ordered permutation.
  625. ##
  626. ## If you start with an unsorted array/seq, the repeated permutations
  627. ## will **not** give you all permutations but stop with the last.
  628. ##
  629. ## **See also:**
  630. ## * `prevPermutation proc<#prevPermutation,openArray[T]>`_
  631. runnableExamples:
  632. var v = @[0, 1, 2, 3]
  633. assert v.nextPermutation() == true
  634. assert v == @[0, 1, 3, 2]
  635. assert v.nextPermutation() == true
  636. assert v == @[0, 2, 1, 3]
  637. assert v.prevPermutation() == true
  638. assert v == @[0, 1, 3, 2]
  639. v = @[3, 2, 1, 0]
  640. assert v.nextPermutation() == false
  641. assert v == @[3, 2, 1, 0]
  642. if x.len < 2:
  643. return false
  644. var i = x.high
  645. while i > 0 and x[i-1] >= x[i]:
  646. dec i
  647. if i == 0:
  648. return false
  649. var j = x.high
  650. while j >= i and x[j] <= x[i-1]:
  651. dec j
  652. swap x[j], x[i-1]
  653. x.reverse(i, x.high)
  654. result = true
  655. proc prevPermutation*[T](x: var openArray[T]): bool {.discardable.} =
  656. ## Calculates the previous lexicographic permutation, directly modifying
  657. ## `x`. The result is whether a permutation happened, otherwise we have
  658. ## reached the first-ordered permutation.
  659. ##
  660. ## **See also:**
  661. ## * `nextPermutation proc<#nextPermutation,openArray[T]>`_
  662. runnableExamples:
  663. var v = @[0, 1, 2, 3]
  664. assert v.prevPermutation() == false
  665. assert v == @[0, 1, 2, 3]
  666. assert v.nextPermutation() == true
  667. assert v == @[0, 1, 3, 2]
  668. assert v.prevPermutation() == true
  669. assert v == @[0, 1, 2, 3]
  670. if x.len < 2:
  671. return false
  672. var i = x.high
  673. while i > 0 and x[i-1] <= x[i]:
  674. dec i
  675. if i == 0:
  676. return false
  677. x.reverse(i, x.high)
  678. var j = x.high
  679. while j >= i and x[j-1] < x[i-1]:
  680. dec j
  681. swap x[i-1], x[j]
  682. result = true
  683. proc rotateInternal[T](arg: var openArray[T]; first, middle, last: int): int =
  684. ## A port of std::rotate from C++.
  685. ## Ported from [this reference](http://www.cplusplus.com/reference/algorithm/rotate/).
  686. result = first + last - middle
  687. if first == middle or middle == last:
  688. return
  689. assert first < middle
  690. assert middle < last
  691. # m prefix for mutable
  692. var
  693. mFirst = first
  694. mMiddle = middle
  695. next = middle
  696. swap(arg[mFirst], arg[next])
  697. mFirst += 1
  698. next += 1
  699. if mFirst == mMiddle:
  700. mMiddle = next
  701. while next != last:
  702. swap(arg[mFirst], arg[next])
  703. mFirst += 1
  704. next += 1
  705. if mFirst == mMiddle:
  706. mMiddle = next
  707. next = mMiddle
  708. while next != last:
  709. swap(arg[mFirst], arg[next])
  710. mFirst += 1
  711. next += 1
  712. if mFirst == mMiddle:
  713. mMiddle = next
  714. elif next == last:
  715. next = mMiddle
  716. proc rotatedInternal[T](arg: openArray[T]; first, middle, last: int): seq[T] =
  717. let argLen = arg.len
  718. result = newSeq[T](argLen)
  719. for i in 0 ..< first:
  720. result[i] = arg[i]
  721. let n = last - middle
  722. let m = middle - first
  723. for i in 0 ..< n:
  724. result[first+i] = arg[middle+i]
  725. for i in 0 ..< m:
  726. result[first+n+i] = arg[first+i]
  727. for i in last ..< argLen:
  728. result[i] = arg[i]
  729. proc rotateLeft*[T](arg: var openArray[T]; slice: HSlice[int, int];
  730. dist: int): int {.discardable.} =
  731. ## Performs a left rotation on a range of elements. If you want to rotate
  732. ## right, use a negative `dist`. Specifically, `rotateLeft` rotates
  733. ## the elements at `slice` by `dist` positions.
  734. ##
  735. ## | The element at index `slice.a + dist` will be at index `slice.a`.
  736. ## | The element at index `slice.b` will be at `slice.a + dist - 1`.
  737. ## | The element at index `slice.a` will be at `slice.b + 1 - dist`.
  738. ## | The element at index `slice.a + dist - 1` will be at `slice.b`.
  739. ##
  740. ## Elements outside of `slice` will be left unchanged.
  741. ## The time complexity is linear to `slice.b - slice.a + 1`.
  742. ## If an invalid range (`HSlice`) is passed, it raises `IndexDefect`.
  743. ##
  744. ## `slice`
  745. ## : The indices of the element range that should be rotated.
  746. ##
  747. ## `dist`
  748. ## : The distance in amount of elements that the data should be rotated.
  749. ## Can be negative, can be any number.
  750. ##
  751. ## **See also:**
  752. ## * `rotateLeft proc<#rotateLeft,openArray[T],int>`_ for a version which rotates the whole container
  753. ## * `rotatedLeft proc<#rotatedLeft,openArray[T],HSlice[int,int],int>`_ for a version which returns a `seq[T]`
  754. runnableExamples:
  755. var a = [0, 1, 2, 3, 4, 5]
  756. a.rotateLeft(1 .. 4, 3)
  757. assert a == [0, 4, 1, 2, 3, 5]
  758. a.rotateLeft(1 .. 4, 3)
  759. assert a == [0, 3, 4, 1, 2, 5]
  760. a.rotateLeft(1 .. 4, -3)
  761. assert a == [0, 4, 1, 2, 3, 5]
  762. doAssertRaises(IndexDefect, a.rotateLeft(1 .. 7, 2))
  763. let sliceLen = slice.b + 1 - slice.a
  764. let distLeft = ((dist mod sliceLen) + sliceLen) mod sliceLen
  765. arg.rotateInternal(slice.a, slice.a + distLeft, slice.b + 1)
  766. proc rotateLeft*[T](arg: var openArray[T]; dist: int): int {.discardable.} =
  767. ## Same as `rotateLeft`, but with default arguments for slice,
  768. ## so that this procedure operates on the entire
  769. ## `arg`, and not just on a part of it.
  770. ##
  771. ## **See also:**
  772. ## * `rotateLeft proc<#rotateLeft,openArray[T],HSlice[int,int],int>`_ for a version which rotates a range
  773. ## * `rotatedLeft proc<#rotatedLeft,openArray[T],int>`_ for a version which returns a `seq[T]`
  774. runnableExamples:
  775. var a = [1, 2, 3, 4, 5]
  776. a.rotateLeft(2)
  777. assert a == [3, 4, 5, 1, 2]
  778. a.rotateLeft(4)
  779. assert a == [2, 3, 4, 5, 1]
  780. a.rotateLeft(-6)
  781. assert a == [1, 2, 3, 4, 5]
  782. let argLen = arg.len
  783. let distLeft = ((dist mod argLen) + argLen) mod argLen
  784. arg.rotateInternal(0, distLeft, argLen)
  785. proc rotatedLeft*[T](arg: openArray[T]; slice: HSlice[int, int],
  786. dist: int): seq[T] =
  787. ## Same as `rotateLeft`, just with the difference that it does
  788. ## not modify the argument. It creates a new `seq` instead.
  789. ##
  790. ## Elements outside of `slice` will be left unchanged.
  791. ## If an invalid range (`HSlice`) is passed, it raises `IndexDefect`.
  792. ##
  793. ## `slice`
  794. ## : The indices of the element range that should be rotated.
  795. ##
  796. ## `dist`
  797. ## : The distance in amount of elements that the data should be rotated.
  798. ## Can be negative, can be any number.
  799. ##
  800. ## **See also:**
  801. ## * `rotateLeft proc<#rotateLeft,openArray[T],HSlice[int,int],int>`_ for the in-place version of this proc
  802. ## * `rotatedLeft proc<#rotatedLeft,openArray[T],int>`_ for a version which rotates the whole container
  803. runnableExamples:
  804. var a = @[1, 2, 3, 4, 5]
  805. a = rotatedLeft(a, 1 .. 4, 3)
  806. assert a == @[1, 5, 2, 3, 4]
  807. a = rotatedLeft(a, 1 .. 3, 2)
  808. assert a == @[1, 3, 5, 2, 4]
  809. a = rotatedLeft(a, 1 .. 3, -2)
  810. assert a == @[1, 5, 2, 3, 4]
  811. let sliceLen = slice.b + 1 - slice.a
  812. let distLeft = ((dist mod sliceLen) + sliceLen) mod sliceLen
  813. arg.rotatedInternal(slice.a, slice.a + distLeft, slice.b + 1)
  814. proc rotatedLeft*[T](arg: openArray[T]; dist: int): seq[T] =
  815. ## Same as `rotateLeft`, just with the difference that it does
  816. ## not modify the argument. It creates a new `seq` instead.
  817. ##
  818. ## **See also:**
  819. ## * `rotateLeft proc<#rotateLeft,openArray[T],int>`_ for the in-place version of this proc
  820. ## * `rotatedLeft proc<#rotatedLeft,openArray[T],HSlice[int,int],int>`_ for a version which rotates a range
  821. runnableExamples:
  822. var a = @[1, 2, 3, 4, 5]
  823. a = rotatedLeft(a, 2)
  824. assert a == @[3, 4, 5, 1, 2]
  825. a = rotatedLeft(a, 4)
  826. assert a == @[2, 3, 4, 5, 1]
  827. a = rotatedLeft(a, -6)
  828. assert a == @[1, 2, 3, 4, 5]
  829. let argLen = arg.len
  830. let distLeft = ((dist mod argLen) + argLen) mod argLen
  831. arg.rotatedInternal(0, distLeft, argLen)