/
itertools.nim
897 lines (777 loc) · 24.5 KB
/
itertools.nim
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
##[
This package is a Nim rewrite of a
[very popular Python module](https://docs.python.org/3/library/itertools.html)
of the same name.
It also includes some of the iterators from
[iterutils](https://boltons.readthedocs.io/en/latest/iterutils.html).
Installation
------------
```
nimble install itertools
```
Required Nim version is at least 0.18.0.
Supported iterators
-------------------
* infinite iterators:
* count
* cycle
* repeat
* terminating iterators:
* accumulate
* chain
* compress
* dropWhile
* filterFalse
* groupBy
* groupConsecutive
* islice
* takeWhile
* combinatoric iterators:
* product
* distinctPermutations
* permutations
* combinations
* iterutils iterators:
* chunked
* windowed
* pairwise
* unique
]##
when defined(nimHasEffectsOf):
{.experimental: "strictEffects".}
else:
{.pragma: effectsOf.}
import algorithm, sets, tables
iterator count*[T: SomeNumber](start: T, step: SomeNumber = 1): T =
## Infinite iterator, counts from a ``start`` to infinity with a ``step`` step-size.
##
## The default value of ``step`` is one.
runnableExamples:
var
s1: seq[int] = @[]
s2: seq[float] = @[]
s3: seq[int] = @[]
s4: seq[float] = @[]
s5: seq[float] = @[]
for i in count(7): # int, default
if i > 10: break
s1.add(i)
for i in count(9.4): # float, default
if i > 12: break
s2.add(i)
for i in count(5, 2): # int, int
if i > 12:
break
s3.add(i)
for i in count(9.6, 2.7): # float, float
if i > 17:
break
s4.add(i)
for i in count(11.6, 3): # float, int
if i > 20: break
s5.add(i)
doAssert s1 == @[7, 8, 9, 10]
doAssert s2 == @[9.4, 10.4, 11.4]
doAssert s3 == @[5, 7, 9, 11]
doAssert s4 == @[9.6, 12.3, 15.0]
doAssert s5 == @[11.6, 14.6, 17.6]
var
n = start
step = T(step)
while true:
yield n
n += step
iterator cycle*[T](s: openArray[T]): T =
## Infinite iterator, cycles through the members of a sequence -- when it
## gets to the end of it, it starts again from the beginning.
runnableExamples:
let
a = @[1, 3, 9, 5]
b = @[2.0, 7.5, 11.3]
c = "axm"
d = @["me", "myself", "I"]
var
s1: seq[int] = @[]
s2: seq[float] = @[]
s3: seq[char] = @[]
s4: seq[string] = @[]
for i in a.cycle:
if s1.len > 5: break
s1.add(i)
for i in b.cycle:
if s2.len > 4: break
s2.add(i)
for i in c.cycle:
if s3.len > 4: break
s3.add(i)
for i in d.cycle:
if s4.len > 5: break
s4.add(i)
doAssert s1 == @[1, 3, 9, 5, 1, 3]
doAssert s2 == @[2.0, 7.5, 11.3, 2.0, 7.5]
doAssert s3 == @['a', 'x', 'm', 'a', 'x']
doAssert s4 == @["me", "myself", "I", "me", "myself", "I"]
let s = @s
var i = 0
while true:
yield s[i]
inc i
if i == s.len:
i = 0
iterator repeat*[T](x: T, times = -1): T =
## Infinite iterator which yields an object ``x`` infinite number of times if
## ``times`` is not specified.
##
## If ``times`` is specified, it runs that number of times.
runnableExamples:
let
a = 3
b = 2.7
c = "Nim"
d = @[1, 2]
var
s1: seq[int] = @[]
s2: seq[float] = @[]
s3: seq[string] = @[]
s4: seq[seq[int]] = @[]
for i in a.repeat:
if s1.len > 5: break
s1.add(i)
for i in b.repeat(5):
s2.add(i)
for i in c.repeat:
if s3.len > 4: break
s3.add(i)
for i in d.repeat(3):
s4.add(i)
doAssert s1 == @[3, 3, 3, 3, 3, 3]
doAssert s2 == @[2.7, 2.7, 2.7, 2.7, 2.7]
doAssert s3 == @["Nim", "Nim", "Nim", "Nim", "Nim"]
doAssert s4 == @[@[1, 2], @[1, 2], @[1, 2]]
if times <= 0:
while true:
yield x
else:
for _ in 1 .. times:
yield x
iterator accumulate*[T](s: openArray[T], f: proc(a, b: T): T): T {.effectsOf: f.} =
## Iterator which yields accumulated results of binary function ``f``.
##
## The result of ``f`` must be of the same type as members of ``s``.
## The first yielded value is the first member of ``s``.
runnableExamples:
let
a = @[1, 3, 7, 5, 4]
b = [1.0, 2.5, 6, 4, 5]
var
s1: seq[int] = @[]
s2: seq[float] = @[]
proc myadd(x, y: int): int = x + y
proc mymult(x, y: float): float = x * y
for x in accumulate(a, myadd):
s1.add(x)
for x in accumulate(b, mymult):
s2.add(x)
doAssert s1 == @[1, 4, 11, 16, 20]
doAssert s2 == @[1.0, 2.5, 15.0, 60.0, 300.0]
var total = s[0]
yield total
for i in 1 ..< s.len:
total = f(total, s[i])
yield total
iterator chain*[T](xs: varargs[seq[T]]): T =
## Iterator which yields elements of each passed sequence.
runnableExamples:
let
a = @[1, 5, 4]
b = @[9, 8, 7]
c = @[22, 33, 44]
var
s1: seq[int] = @[]
s2: seq[int] = @[]
s3: seq[int] = @[]
for x in chain(a):
s1.add(x)
for x in chain(b, c):
s2.add(x)
for x in chain(c, a, b):
s3.add(x)
doAssert s1 == @[1, 5, 4]
doAssert s2 == @[9, 8, 7, 22, 33, 44]
doAssert s3 == @[22, 33, 44, 1, 5, 4, 9, 8, 7]
for arg in xs:
for x in arg:
yield x
iterator chain*(xs: varargs[string]): char =
## Iterator which yields characters of each passed string.
runnableExamples:
let
a = "abc"
b = "xyz"
var s1: string = ""
for x in chain(a, b):
s1.add x
doAssert s1 == "abcxyz"
for arg in xs:
for x in arg:
yield x
iterator compress*[T](s: openArray[T], b: openArray[bool]): T =
## Iterator which yields only those elements of a sequence ``s`` for which
## the element of a selector ``b`` is ``true``.
##
## Stops as soon as either ``s`` or ``b`` are exhausted.
runnableExamples:
let
a = @[1, 2, 3, 4, 5, 6, 7, 8, 9]
b = [9.5, 8.1, 7.3]
c = @['a', 'b', 'c', 'd', 'e']
d = [true, false, true, true, false, true]
var
s1: seq[int] = @[]
s2: seq[float] = @[]
s3: seq[char] = @[]
for x in compress(a, d):
s1.add(x)
for x in compress(b, d):
s2.add(x)
for x in compress(c, d):
s3.add(x)
doAssert s1 == @[1, 3, 4, 6]
doAssert s2 == @[9.5, 7.3]
doAssert s3 == @['a', 'c', 'd']
let l = min(s.len, b.len)
for i in 0 ..< l:
if b[i]:
yield s[i]
iterator dropWhile*[T](s: openArray[T], f: proc(a: T): bool): T {.effectsOf: f.} =
## Iterator which drops the elements from a sequence ``s`` as long as the
## predicate is ``true``. Afterwards, it returns every element.
runnableExamples:
let
a = @[1, 3, 7, 2, 1, 4]
b = ['a', 'd', 'h', 'd']
var
s1: seq[int] = @[]
s2: seq[int] = @[]
s3: seq[char] = @[]
proc myodd(a: int): bool = a mod 2 == 1
proc mysmall(a: int): bool = a < 7
proc mysmall(a: char): bool = a < 'h'
for x in dropWhile(a, myodd):
s1.add(x)
for x in dropWhile(a, mysmall):
s2.add(x)
for x in dropWhile(b, mysmall):
s3.add(x)
doAssert s1 == @[2, 1, 4]
doAssert s2 == @[7, 2, 1, 4]
doAssert s3 == @['h', 'd']
var i = 0
while i < s.len and f(s[i]):
inc i
while i < s.len:
yield s[i]
inc i
iterator filterFalse*[T](s: openArray[T], f: proc(a: T): bool): T {.effectsOf: f.} =
## Iterator which filters the container ``s`` and yields only the elements
## for which ``f`` is false.
runnableExamples:
let
a = @[1, 3, 7, 2, 1, 4]
b = ['a', 'd', 'h', 'd']
var
s1: seq[int] = @[]
s2: seq[int] = @[]
s3: seq[char] = @[]
proc myodd(a: int): bool = a mod 2 == 1
proc mysmall(a: int): bool = a < 7
proc mysmall(a: char): bool = a < 'h'
for x in filterFalse(a, myodd):
s1.add(x)
for x in filterFalse(a, mysmall):
s2.add(x)
for x in filterFalse(b, mysmall):
s3.add(x)
doAssert s1 == @[2, 4]
doAssert s2 == @[7]
doAssert s3 == @['h']
for x in s:
if not f(x):
yield x
iterator groupBy*[T](s: openArray[T]): tuple[k: T, v: seq[T]] =
## Iterator which groups the same elements together, yielding a tuple
## ``(key, group)``.
runnableExamples:
let
a = @[1, 2, 5, 2, 7, 5, 1, 2]
b = ['a', 'b', 'b', 'a', 'b', 'a', 'n', 'd']
var s1: seq[tuple[k: int, v: seq[int]]] = @[]
var s2: seq[tuple[k: char, v: seq[char]]] = @[]
for x in groupBy(a):
s1.add(x)
for x in groupBy(b):
s2.add(x)
import algorithm
doAssert s1.sortedByIt(it.k) == @[(k: 1, v: @[1, 1]), (k: 2, v: @[2, 2, 2]),
(k: 5, v: @[5, 5]), (k: 7, v: @[7])]
doAssert s2.sortedByIt(it.k) == @[
(k: 'a', v: @['a', 'a', 'a']), (k: 'b', v: @['b', 'b', 'b']),
(k: 'd', v: @['d']), (k: 'n', v: @['n'])]
var t = initTable[T, seq[T]]()
for x in s:
t.mGetOrPut(x, @[]).add(x)
for x in t.pairs:
yield x
iterator groupBy*[T, U](s: openArray[T], f: proc(a: T): U): tuple[k: U, v: seq[T]] {.effectsOf: f.} =
## Iterator which groups the elements based on applying a procedure ``f``
## on each element, yielding a tuple ``(key, group)``.
runnableExamples:
let
a = @[1, 2, 5, 2, 7, 5, 1, 2]
b = ['a', 'b', 'b', 'a', 'b', 'a', 'n', 'd']
c = ["ac", "dc", "who", "cream", "clash"]
proc isOdd(x: int): bool = x mod 2 == 1
proc isA(x: char): bool = x == 'a'
proc length(x: string): int = x.len
var s1: seq[tuple[k: bool, v: seq[int]]] = @[]
var s2: seq[tuple[k: bool, v: seq[char]]] = @[]
var s3: seq[tuple[k: int, v: seq[string]]] = @[]
for x in groupBy(a, isOdd):
s1.add(x)
for x in groupBy(b, isA):
s2.add(x)
for x in groupBy(c, length):
s3.add(x)
import algorithm
doAssert s1.sortedByIt(it.k) == @[(k: false, v: @[2, 2, 2]),
(k: true, v: @[1, 5, 7, 5, 1])]
doAssert s2.sortedByIt(it.k) == @[(k: false, v: @['b', 'b', 'b', 'n', 'd']),
(k: true, v: @['a', 'a', 'a'])]
doAssert s3.sortedByIt(it.k) == @[(k: 2, v: @["ac", "dc"]), (k: 3, v: @["who"]),
(k: 5, v: @["cream", "clash"])]
var t = initTable[U, seq[T]]()
for x in s:
let fx = f(x)
t.mGetOrPut(fx, @[]).add(x)
for x in t.pairs:
yield x
iterator groupConsecutive*[T](s: openArray[T]): tuple[k: T, v: seq[T]] =
## Iterator which groups the same *consecutive* elements together,
## yielding a tuple ``(key, group)``.
runnableExamples:
let
a = [1, 1, 1, 2, 3, 3, 1, 2, 2, 2]
b = "abcaabccc"
var
s1: seq[tuple[k: int, v: seq[int]]] = @[]
s2: seq[tuple[k: char, v: seq[char]]] = @[]
for x in groupConsecutive(a):
s1.add(x)
for x in groupConsecutive(b):
s2.add(x)
doAssert s1 == @[(1, @[1, 1, 1]), (2, @[2]), (3, @[3, 3]), (1, @[1]), (2, @[2, 2, 2])]
doAssert s2 == @[('a', @['a']), ('b', @['b']), ('c', @['c']),
('a', @['a', 'a']), ('b', @['b']), ('c', @['c', 'c', 'c'])]
var k = s[0]
var v = @[k]
var i = 1
while i < s.len:
if s[i] != k:
yield (k, v)
k = s[i]
v = @[k]
else:
v.add k
inc i
yield (k, v)
iterator groupConsecutive*[T, U](s: openArray[T], f: proc(a: T): U): tuple[k: U, v: seq[T]] {.effectsOf: f.} =
## Iterator which groups the *consecutive* elements based on applying a procedure ``f``
## on each element, yielding a tuple ``(key, group)``.
runnableExamples:
let
a = @[1, 3, 5, 2, 1, 3, 5, 2, 4, 6, 1]
b = ['a', 'b', 'c', 'a', 'b', 'a', 'a', 'd']
c = ["ac", "dc", "dylan", "who", "cream", "clash"]
proc isOdd(x: int): bool = x mod 2 == 1
proc isA(x: char): bool = x == 'a'
proc length(x: string): int = x.len
var s1: seq[tuple[k: bool, v: seq[int]]] = @[]
var s2: seq[tuple[k: bool, v: seq[char]]] = @[]
var s3: seq[tuple[k: int, v: seq[string]]] = @[]
for x in groupConsecutive(a, isOdd):
s1.add(x)
for x in groupConsecutive(b, isA):
s2.add(x)
for x in groupConsecutive(c, length):
s3.add(x)
doAssert s1 == @[(true, @[1, 3, 5]), (false, @[2]), (true, @[1, 3, 5]),
(false, @[2, 4, 6]), (true, @[1])]
doAssert s2 == @[(true, @['a']), (false, @['b', 'c']), (true, @['a']),
(false, @['b']), (true, @['a', 'a']), (false, @['d'])]
doAssert s3 == @[(2, @["ac", "dc"]), (5, @["dylan"]), (3, @["who"]),
(5, @["cream", "clash"])]
var k = f(s[0])
var v = @[s[0]]
var i = 1
while i < s.len:
let fx = f(s[i])
if fx != k:
yield (k, v)
k = fx
v = @[s[i]]
else:
v.add s[i]
inc i
yield (k, v)
iterator islice*[T](s: openArray[T], start = 0, stop = -1, step = 1): T =
## Iterator which yields elements of ``s``, starting from ``start`` (default = 0),
## until ``stop`` (default = -1, go to the end), with step-size ``step``
## (default = 1).
runnableExamples:
let
a = @[1, 4, 3, 2, 5, 8, 6, 7, 9]
b = [3.3, 4.4, 9.9, 6.6, 2.2]
var
s1: seq[int] = @[]
s2: seq[int] = @[]
s3: seq[float] = @[]
s4: seq[float] = @[]
for x in islice(a, 3):
s1.add(x)
for x in islice(a, 3, 5):
s2.add(x)
for x in islice(b, step = 2):
s3.add(x)
for x in islice(b, 1, 99, 2):
s4.add(x)
doAssert s1 == @[2, 5, 8, 6, 7, 9]
doAssert s2 == @[2, 5, 8]
doAssert s3 == @[3.3, 9.9, 2.2]
doAssert s4 == @[4.4, 6.6]
var
i = start
stop = stop
if stop == -1 or stop >= s.len:
stop = s.len - 1
while i <= stop:
yield s[i]
i += step
iterator takeWhile*[T](s: openArray[T], f: proc(a: T): bool): T {.effectsOf: f.} =
## Iterator which yields elements of ``s`` as long as predicate is true.
runnableExamples:
let
a = @[1, 3, 5, 2, 7, 9]
b = ['a', 'c', 'd', 'c']
var
s1: seq[int] = @[]
s2: seq[int] = @[]
s3: seq[char] = @[]
proc myodd(a: int): bool = a mod 2 == 1
proc mysmall(a: int): bool = a < 5
proc mysmall(a: char): bool = a < 'd'
for x in takeWhile(a, myodd):
s1.add(x)
for x in takeWhile(a, mysmall):
s2.add(x)
for x in takeWhile(b, mysmall):
s3.add(x)
doAssert s1 == @[1, 3, 5]
doAssert s2 == @[1, 3]
doAssert s3 == @['a', 'c']
for x in s:
if f(x):
yield x
else:
break
iterator product*[T](s: openArray[T], repeat: Positive): seq[T] =
## Iterator yielding Cartesian products of ``s`` with itself, ``repeat``
## number of times.
runnableExamples:
let
a = [0, 1]
b = "abc"
var
s1: seq[seq[int]] = @[]
s2: seq[seq[char]] = @[]
for x in product(a, 3):
s1.add(x)
for x in product(b, 2):
s2.add(x)
doAssert s1 == @[@[0, 0, 0], @[0, 0, 1], @[0, 1, 0], @[0, 1, 1],
@[1, 0, 0], @[1, 0, 1], @[1, 1, 0], @[1, 1, 1]]
doAssert s2 == @[@['a', 'a'], @['a', 'b'], @['a', 'c'], @['b', 'a'],
@['b', 'b'], @['b', 'c'], @['c', 'a'], @['c', 'b'],
@['c', 'c']]
var counters = newSeq[int](repeat)
block outer:
while true:
var result = newSeq[T](repeat)
for i, cnt in counters:
result[i] = s[cnt]
yield result
var i = repeat - 1
while true:
inc counters[i]
if counters[i] == s.len:
counters[i] = 0
dec i
else: break
if i < 0:
break outer
iterator product*[T, U](s1: openArray[T], s2: openArray[U]): tuple[a: T, b: U] =
## Iterator producing tuples with Cartesian product of the arguments.
## Equivalent to nested for-loops.
runnableExamples:
let
a = @[1, 2, 3]
b = "ab"
var s: seq[tuple[a: int, b: char]] = @[]
for x in product(a, b):
s.add(x)
doAssert s == @[(a: 1, b: 'a'), (a: 1, b: 'b'), (a: 2, b: 'a'),
(a: 2, b: 'b'), (a: 3, b: 'a'), (a: 3, b: 'b')]
for a in s1:
for b in s2:
yield (a, b)
iterator product*[T, U, V](s1: openArray[T], s2: openArray[U], s3: openArray[V]):
tuple[a: T, b: U, c: V] =
## Iterator producing tuples with Cartesian product of the arguments.
## Equivalent to nested for-loops.
runnableExamples:
let
a = @[1, 2]
b = "ab"
c = [9.9, 7.2]
var s: seq[tuple[a: int, b: char, c: float]] = @[]
for x in product(a, b, c):
s.add(x)
doAssert s == @[(a: 1, b: 'a', c: 9.9), (a: 1, b: 'a', c: 7.2),
(a: 1, b: 'b', c: 9.9), (a: 1, b: 'b', c: 7.2),
(a: 2, b: 'a', c: 9.9), (a: 2, b: 'a', c: 7.2),
(a: 2, b: 'b', c: 9.9), (a: 2, b: 'b', c: 7.2)]
for a in s1:
for b in s2:
for c in s3:
yield (a, b, c)
iterator product*[T, U, V, W](s1: openArray[T], s2: openArray[U], s3: openArray[V],
s4: openArray[W]): tuple[a: T, b: U, c: V, d: W] =
## Iterator producing tuples with Cartesian product of the arguments.
## Equivalent to nested for-loops.
runnableExamples:
let
a = @[1, 2]
b = "a"
c = [9.9]
d = "xyz"
var s: seq[tuple[a: int, b: char, c: float, d: char]] = @[]
for x in product(a, b, c, d):
s.add(x)
doAssert s == @[(a: 1, b: 'a', c: 9.9, d: 'x'), (a: 1, b: 'a', c: 9.9, d: 'y'),
(a: 1, b: 'a', c: 9.9, d: 'z'), (a: 2, b: 'a', c: 9.9, d: 'x'),
(a: 2, b: 'a', c: 9.9, d: 'y'), (a: 2, b: 'a', c: 9.9, d: 'z')]
for a in s1:
for b in s2:
for c in s3:
for d in s4:
yield (a, b, c, d)
iterator distinctPermutations*[T](s: openArray[T]): seq[T] =
## Iterator which yields distinct permutations of ``s``.
##
## Permutations are yielded in lexicographical order, without duplicates.
## If you want to include duplicates, use ``permutations``.
runnableExamples:
let
a = "bab"
b = "zzz"
var
s1: seq[seq[char]] = @[]
s2: seq[seq[char]] = @[]
for x in distinctPermutations(a):
s1.add(x)
for x in distinctPermutations(b):
s2.add(x)
doAssert s1 == @[@['a', 'b', 'b'], @['b', 'a', 'b'], @['b', 'b', 'a']]
doAssert s2 == @[@['z', 'z', 'z']]
var x = @s
x.sort(cmp)
yield x
while x.nextPermutation():
yield x
iterator permutations*[T](s: openArray[T]): seq[T] =
## Iterator which yields all (number of permutations = ``(s.len)!``)
## permutations of ``s``.
##
## If ``s`` contains duplicate elements, some permutations will be the same.
## If you want permutations without duplicates, use ``distinctPermutations``.
runnableExamples:
let
a = "bab"
b = "zzz"
var
s1: seq[seq[char]] = @[]
s2: seq[seq[char]] = @[]
for x in permutations(a):
s1.add(x)
for x in permutations(b):
s2.add(x)
doAssert s1 == @[@['b', 'a', 'b'], @['b', 'b', 'a'], @['a', 'b', 'b'],
@['a', 'b', 'b'], @['b', 'b', 'a'], @['b', 'a', 'b']]
doAssert s2 == @[@['z', 'z', 'z'], @['z', 'z', 'z'], @['z', 'z', 'z'],
@['z', 'z', 'z'], @['z', 'z', 'z'], @['z', 'z', 'z']]
var indices = newSeq[int](s.len)
for i in 0 ..< s.len:
indices[i] = i
var x = @s
for indPerm in distinctPermutations(indices):
for i in 0 ..< s.len:
x[i] = s[indPerm[i]]
yield x
iterator combinations*(n, r: Positive): seq[int] =
## Iterator which yields combinations of size ``r`` of a range ``0 ..< n``.
##
## Both arguments must be positive numbers.
runnableExamples:
let
a = 5
b = 4
c = 2
var
s1: seq[seq[int]] = @[]
s2: seq[seq[int]] = @[]
for x in combinations(a, b):
s1.add(x)
for x in combinations(a, c):
s2.add(x)
doAssert s1 == @[@[0, 1, 2, 3], @[0, 1, 2, 4], @[0, 1, 3, 4],
@[0, 2, 3, 4], @[1, 2, 3, 4]]
doAssert s2 == @[@[0, 1], @[0, 2], @[0, 3], @[0, 4],
@[1, 2], @[1, 3], @[1, 4], @[2, 3], @[2, 4], @[3, 4]]
var
x = newSeq[int](r)
stack = @[0]
while stack.len > 0:
var
i = stack.high
v = stack.pop()
while v < n:
x[i] = v
inc v
inc i
stack.add(v)
if i == r:
yield x
break
iterator combinations*[T](s: openArray[T], r: Positive): seq[T] =
## Iterator which yields combinations of ``s`` of length ``r``.
##
## Length ``r`` must be a positive number.
runnableExamples:
let
a = "98765"
b = 4
c = 2
var
s1: seq[seq[char]] = @[]
s2: seq[seq[char]] = @[]
for x in combinations(a, b):
s1.add(x)
for x in combinations(a, c):
s2.add(x)
doAssert s1 == @[@['9', '8', '7', '6'], @['9', '8', '7', '5'],
@['9', '8', '6', '5'], @['9', '7', '6', '5'],
@['8', '7', '6', '5']]
doAssert s2 == @[@['9', '8'], @['9', '7'], @['9', '6'], @['9', '5'],
@['8', '7'], @['8', '6'], @['8', '5'], @['7', '6'],
@['7', '5'], @['6', '5']]
var x = newSeq[T](r)
for indComb in combinations(s.len, r):
for i in 0 ..< r:
x[i] = s[indComb[i]]
yield x
iterator chunked*[T](s: openArray[T], size: Positive): seq[T] =
## Iterator which yields ``size``-sized chunks from ``s``.
runnableExamples:
let
a = "abcde"
b = [11, 12, 13, 14, 15, 16, 17, 18]
var
s1: seq[seq[char]] = @[]
s2: seq[seq[int]] = @[]
for x in chunked(a, 2):
s1.add(x)
for x in chunked(b, 3):
s2.add(x)
doAssert s1 == @[@['a', 'b'], @['c', 'd'], @['e']]
doAssert s2 == @[@[11, 12, 13], @[14, 15, 16], @[17, 18]]
var i: int
while i + size < len(s):
yield s[i ..< i+size]
i += size
yield s[i .. ^1]
iterator windowed*[T](s: openArray[T], size: Positive): seq[T] =
## Iterator which yields ``size``-sized moving window from ``s``.
runnableExamples:
let
a = "abcde"
b = [11, 12, 13, 14, 15, 16]
var
s1: seq[seq[char]] = @[]
s2: seq[seq[int]] = @[]
for x in windowed(a, 2):
s1.add(x)
for x in windowed(b, 3):
s2.add(x)
doAssert s1 == @[@['a', 'b'], @['b', 'c'], @['c', 'd'], @['d', 'e']]
doAssert s2 == @[@[11, 12, 13], @[12, 13, 14], @[13, 14, 15], @[14, 15, 16]]
var i: int
while i + size <= len(s):
yield s[i ..< i+size]
inc i
iterator pairwise*[T](s: openArray[T]): seq[T] =
## Convenience wrapper. The same as ``windowed(s, 2)``.
for x in windowed(s, 2):
yield x
iterator unique*[T](s: openArray[T]): T =
## Iterator which yields unique members of ``s``, keeping the original order.
runnableExamples:
let
a = "baobab"
b = [3, 4, 3, 3, 3, 4, 3, 3]
var
s1: seq[char] = @[]
s2: seq[int] = @[]
for x in unique(a):
s1.add(x)
for x in unique(b):
s2.add(x)
doAssert s1 == @['b', 'a', 'o']
doAssert s2 == @[3, 4]
var seen = initHashSet[T]()
for x in s:
if not seen.containsOrIncl(x):
yield x
when isMainModule:
# needed to run the tests in ``runnableExamples``
for _ in count(3): break
for _ in count(3.0, 2.5): break
for _ in cycle(@[3, 4]): break
for _ in repeat(1): break
for _ in accumulate(@[3, 5], proc(a, b: int): int = a + b): break
for _ in chain(@[1], @[3]): break
for _ in compress(@[1, 2], @[false, true]): break
for _ in dropWhile(@[1, 2], proc(a: int): bool = a < 0): break
for _ in filterFalse(@[1, 2], proc(a: int): bool = a < 0): break
for _ in groupBy(@[1, 2], proc(x: int): bool = x mod 2 == 0): break
for _ in islice(@[1, 2, 3], 2): break
for _ in takeWhile(@[1, 2], proc(a: int): bool = a < 2): break
for _ in product([9, 8], 3): break
for _ in product(@[1, 2], @[3, 4]): break
for _ in product(@[1, 2], @[3, 4], @[5, 6]): break
for _ in product(@[1, 2], @[3, 4], @[5, 6], @[7, 8]): break
for _ in distinctPermutations(@[1, 2, 3]): break
for _ in permutations(@[1, 2, 3]): break
for _ in combinations(5, 2): break
for _ in combinations(@[1, 2, 3], 2): break
for _ in chunked(@[1, 2, 3], 2): break
for _ in windowed(@[1, 2, 3], 2): break
for _ in unique(@[1, 2, 3]): break