algorithm.nim 30 KB

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