/
algorithm.d
5932 lines (5413 loc) · 166 KB
/
algorithm.d
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
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Written in the D programming language.
/**
Implements algorithms oriented mainly towards processing of
sequences. Some functions are semantic equivalents or supersets of
those found in the $(D $(LESS)_algorithm$(GREATER)) header in $(WEB
sgi.com/tech/stl/, Alexander Stepanov's Standard Template Library) for
C++.
Note:
Many functions in this module are parameterized with a function or a
$(GLOSSARY predicate). The predicate may be passed either as a
function name, a delegate name, a $(GLOSSARY functor) name, or a
compile-time string. The string may consist of $(B any) legal D
expression that uses the symbol $(D a) (for unary functions) or the
symbols $(D a) and $(D b) (for binary functions). These names will NOT
interfere with other homonym symbols in user code because they are
evaluated in a different context. The default for all binary
comparison predicates is $(D "a == b") for unordered operations and
$(D "a < b") for ordered operations.
Example:
----
int[] a = ...;
static bool greater(int a, int b)
{
return a > b;
}
sort!(greater)(a); // predicate as alias
sort!("a > b")(a); // predicate as string
// (no ambiguity with array name)
sort(a); // no predicate, "a < b" is implicit
----
Macros:
WIKI = Phobos/StdAlgorithm
Copyright: Copyright Andrei Alexandrescu 2008 - 2009.
License: <a href="http://www.boost.org/LICENSE_1_0.txt">Boost License 1.0</a>.
Authors: $(WEB erdani.org, Andrei Alexandrescu)
Copyright Andrei Alexandrescu 2008 - 2009.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
module std.algorithm;
import std.c.string;
import std.array;
import std.contracts;
import std.conv;
import std.date;
import std.functional;
import std.math;
import std.metastrings;
import std.range;
import std.string;
import std.traits;
import std.typecons;
import std.typetuple;
version(unittest)
{
import std.random, std.stdio, std.string;
}
/**
Implements the homonym function (also known as $(D transform)) present
in many languages of functional flavor. The call $(D map!(fun)(range))
returns a range of which elements are obtained by applying $(D fun(x))
left to right for all $(D x) in $(D range). The original ranges are
not changed. Evaluation is done lazily. The range returned by $(D map)
caches the last value such that evaluating $(D front) multiple times
does not result in multiple calls to $(D fun).
Example:
----
int[] arr1 = [ 1, 2, 3, 4 ];
int[] arr2 = [ 5, 6 ];
auto squares = map!("a * a")(chain(arr1, arr2));
assert(equal(squares, [ 1, 4, 9, 16, 25, 36 ]));
----
Multiple functions can be passed to $(D map). In that case, the
element type of $(D map) is a tuple containing one element for each
function.
Example:
----
auto arr1 = [ 1, 2, 3, 4 ];
foreach (e; map!("a + a", "a * a")(arr1))
{
writeln(e.field[0], " ", e.field[1]);
}
----
*/
template map(fun...)
{
static if (fun.length > 1)
{
// alias Map!(Adjoin!(staticMap!(unaryFun, fun))
// .For!(staticMap!(ElementType, Range)).fun,
// Chain!(Range)).doIt
// map;
Map!(adjoin!(staticMap!(unaryFun, fun)), Range)
map(Range)(Range r)
{
return typeof(return)(r);
}
}
else
{
//alias Map!(unaryFun!(fun), Chain!(Range)).doIt map;
Map!(unaryFun!(fun), Range) map(Range)(Range r)
{
return typeof(return)(r);
}
}
}
struct Map(alias fun, Range) if (isInputRange!(Range))
{
alias typeof(fun(.ElementType!(Range).init)) ElementType;
Range _input;
ElementType _cache;
private void fillCache() { if (!_input.empty) _cache = fun(_input.front); }
this(Range input) { _input = input; fillCache; }
bool empty() { return _input.empty; }
void popFront() { _input.popFront; fillCache; }
ElementType front() { return _cache; }
}
unittest
{
scope(failure) writeln("Unittest failed at line ", __LINE__);
int[] arr1 = [ 1, 2, 3, 4 ];
int[] arr2 = [ 5, 6 ];
auto squares = map!("a * a")(arr1);
assert(equal(squares, [ 1, 4, 9, 16 ][]));
assert(equal(map!("a * a")(chain(arr1, arr2)), [ 1, 4, 9, 16, 25, 36 ][]));
uint i;
foreach (e; map!("a", "a * a")(arr1))
{
assert(e.field[0] == ++i);
assert(e.field[1] == i * i);
}
}
// reduce
/**
Implements the homonym function (also known as $(D accumulate), $(D
compress), $(D inject), or $(D foldl)) present in various programming
languages of functional flavor. The call $(D reduce!(fun)(seed,
range)) first assigns $(D seed) to an internal variable $(D result),
also called the accumulator. Then, for each element $(D x) in $(D
range), $(D result = fun(result, x)) gets evaluated. Finally, $(D
result) is returned. The one-argument version $(D reduce!(fun)(range))
works similarly, but it uses the first element of the range as the
seed (the range must be non-empty).
Many aggregate range operations turn out to be solved with $(D reduce)
quickly and easily. The example below illustrates $(D reduce)'s
remarkable power and flexibility.
Example:
----
int[] arr = [ 1, 2, 3, 4, 5 ];
// Sum all elements
auto sum = reduce!("a + b")(0, arr);
assert(sum == 15);
// Compute the maximum of all elements
auto largest = reduce!(max)(arr);
assert(largest == 5);
// Compute the number of odd elements
auto odds = reduce!("a + (b & 1)")(0, arr);
assert(odds == 3);
// Compute the sum of squares
auto ssquares = reduce!("a + b * b")(0, arr);
assert(ssquares == 55);
// Chain multiple ranges into seed
int[] a = [ 3, 4 ];
int[] b = [ 100 ];
auto r = reduce!("a + b")(chain(a, b));
assert(r == 107);
// Mixing convertible types is fair game, too
double[] c = [ 2.5, 3.0 ];
auto r1 = reduce!("a + b")(chain(a, b, c));
assert(r1 == 112.5);
----
$(DDOC_SECTION_H Multiple functions:) Sometimes it is very useful to
compute multiple aggregates in one pass. One advantage is that the
computation is faster because the looping overhead is shared. That's
why $(D reduce) accepts multiple functions. If two or more functions
are passed, $(D reduce) returns a $(XREF typecons, Tuple) object with
one member per passed-in function. The number of seeds must be
correspondingly increased.
Example:
----
double[] a = [ 3.0, 4, 7, 11, 3, 2, 5 ];
// Compute minimum and maximum in one pass
auto r = reduce!(min, max)(a);
// The type of r is Tuple!(double, double)
assert(r.field[0] == 2); // minimum
assert(r.field[1] == 11); // maximum
// Compute sum and sum of squares in one pass
r = reduce!("a + b", "a + b * b")(tuple(0.0, 0.0), a);
assert(r.field[0] == 35); // sum
assert(r.field[1] == 233); // sum of squares
// Compute average and standard deviation from the above
auto avg = r.field[0] / a.length;
auto stdev = sqrt(r.field[1] / a.length - avg * avg);
----
*/
template reduce(fun...)
{
alias Reduce!(fun).reduce reduce;
}
template Reduce(fun...)
{
private:
static if (fun.length > 1)
{
template TypeTupleN(E, int n)
{
static if (n == 1) alias E TypeTupleN;
else alias TypeTuple!(E, TypeTupleN!(E, n - 1)) TypeTupleN;
}
enum L = fun.length;
template ReturnType(E)
{
alias Tuple!(TypeTupleN!(E, L)) ReturnType;
}
}
else
{
template ReturnType(E)
{
alias E ReturnType;
}
}
public:
Unqual!E reduce(E, R)(E seed, R r)
{
Unqual!E result = seed;
foreach (e; r)
{
static if (fun.length == 1)
{
result = binaryFun!(fun[0])(result, e);
}
else
{
foreach (i, Unused; typeof(E.field))
{
result.field[i] = binaryFun!(fun[i])(result.field[i], e);
}
}
}
return result;
}
ReturnType!(ElementType!(Range))
reduce(Range)(Range r) if (isInputRange!Range)
{
enforce(!r.empty);
static if (fun.length == 1)
{
auto e = r.front;
}
else
{
typeof(return) e;
foreach (i, Unused; typeof(typeof(return).field))
{
e.field[i] = r.front;
}
}
r.popFront;
return reduce(e, r);
}
}
unittest
{
int[] a = [ 3, 4 ];
auto r = reduce!("a + b")(0, a);
assert(r == 7);
r = reduce!("a + b")(a);
assert(r == 7);
r = reduce!(min)(a);
assert(r == 3);
double[] b = [ 100 ];
auto r1 = reduce!("a + b")(chain(a, b));
assert(r1 == 107);
// two funs
auto r2 = reduce!("a + b", "a - b")(tuple(0, 0), a);
assert(r2.field[0] == 7 && r2.field[1] == -7);
auto r3 = reduce!("a + b", "a - b")(a);
assert(r3.field[0] == 7 && r3.field[1] == -1);
a = [ 1, 2, 3, 4, 5 ];
// Stringize with commas
string rep = reduce!("a ~ `, ` ~ to!(string)(b)")("", a);
assert(rep[2 .. $] == "1, 2, 3, 4, 5", "["~rep[2 .. $]~"]");
}
unittest
{
const float a = 0.0;
const float[] b = [ 1.2, 3, 3.3 ];
float[] c = [ 1.2, 3, 3.3 ];
auto r = reduce!"a + b"(a, b);
r = reduce!"a + b"(a, c);
}
/**
Fills a range with a value.
Example:
----
int[] a = [ 1, 2, 3, 4 ];
fill(a, 5);
assert(a == [ 5, 5, 5, 5 ]);
----
*/
void fill(Range, Value)(Range range, Value filler)
if (isForwardRange!Range && is(typeof(Range.init.front = Value.init)))
{
for (; !range.empty; range.popFront)
{
range.front = filler;
}
}
unittest
{
int[] a = [ 1, 2, 3 ];
fill(a, 6);
assert(a == [ 6, 6, 6 ]);
void fun0()
{
foreach (i; 0 .. 1000)
{
foreach (ref e; a) e = 6;
}
}
void fun1() { foreach (i; 0 .. 1000) fill(a, 6); }
//void fun2() { foreach (i; 0 .. 1000) fill2(a, 6); }
//writeln(benchmark!(fun0, fun1, fun2)(10000));
}
/**
Fills $(D range) with a pattern copied from $(D filler). The length of
$(D range) does not have to be a multiple of the length of $(D
filler). If $(D filler) is empty, an exception is thrown.
Example:
----
int[] a = [ 1, 2, 3, 4, 5 ];
int[] b = [ 8, 9 ];
fill(a, b);
assert(a == [ 8, 9, 8, 9, 8 ]);
----
*/
void fill(Range1, Range2)(Range1 range, Range2 filler)
if (isForwardRange!Range1 && isForwardRange!Range2
&& is(typeof(Range1.init.front = Range2.init.front)))
{
enforce(!filler.empty);
auto t = filler;
for (; !range.empty; range.popFront, t.popFront)
{
if (t.empty) t = filler;
range.front = t.front;
}
}
unittest
{
int[] a = [ 1, 2, 3, 4, 5 ];
int[] b = [1, 2];
fill(a, b);
assert(a == [ 1, 2, 1, 2, 1 ]);
}
// filter
/**
Implements the homonym function present in various programming
languages of functional flavor. The call $(D filter!(fun)(range))
returns a new range only containing elements $(D x) in $(D r) for
which $(D pred(x)) is $(D true).
Example:
----
int[] arr = [ 1, 2, 3, 4, 5 ];
// Sum all elements
auto small = filter!("a < 3")(arr);
assert(small == [ 1, 2 ]);
// In combination with chain() to span multiple ranges
int[] a = [ 3, -2, 400 ];
int[] b = [ 100, -101, 102 ];
auto r = filter!("a > 0")(chain(a, b));
assert(equals(r, [ 3, 400, 100, 102 ]));
// Mixing convertible types is fair game, too
double[] c = [ 2.5, 3.0 ];
auto r1 = filter!("cast(int) a != a")(chain(c, a, b));
assert(r1 == [ 2.5 ]);
----
*/
Filter!(unaryFun!(pred), Range)
filter(alias pred, Range)(Range rs)
{
return typeof(return)(rs);
}
struct Filter(alias pred, Range) if (isInputRange!(Range))
{
Range _input;
this(Range r)
{
_input = r;
while (!_input.empty && !pred(_input.front)) _input.popFront;
}
ref Filter opSlice()
{
return this;
}
bool empty() { return _input.empty; }
void popFront()
{
do
{
_input.popFront;
} while (!_input.empty && !pred(_input.front));
}
ElementType!(Range) front()
{
return _input.front;
}
}
unittest
{
int[] a = [ 3, 4 ];
auto r = filter!("a > 3")(a);
assert(equal(r, [ 4 ][]));
a = [ 1, 22, 3, 42, 5 ];
auto under10 = filter!("a < 10")(a);
assert(equal(under10, [1, 3, 5][]));
}
// move
/**
Moves $(D source) into $(D target) via a destructive
copy. Specifically: $(UL $(LI If $(D hasAliasing!T) is true (see
$(XREF traits, hasAliasing)), then the representation of $(D source)
is bitwise copied into $(D target) and then $(D source = T.init) is
evaluated.) $(LI Otherwise, $(D target = source) is evaluated.)) See
also $(XREF contracts, pointsTo).
Preconditions:
$(D !pointsTo(source, source))
*/
void move(T)(ref T source, ref T target)
{
if (&source == &target) return;
assert(!pointsTo(source, source));
static if (hasAliasing!(T))
{
static if (is(T == class))
{
target = source;
}
else
{
memcpy(&target, &source, target.sizeof);
}
source = T.init;
}
else
{
target = source;
}
}
unittest
{
Object obj1 = new Object;
Object obj2 = obj1;
Object obj3;
move(obj2, obj3);
assert(obj2 is null && obj3 is obj1);
struct S1 { int a = 1, b = 2; }
S1 s11 = { 10, 11 };
S1 s12;
move(s11, s12);
assert(s11.a == 10 && s11.b == 11 && s12.a == 10 && s12.b == 11);
struct S2 { int a = 1; int * b; }
S2 s21 = { 10, new int };
S2 s22;
move(s21, s22);
assert(s21.a == 1 && s21.b == null && s22.a == 10 && s22.b != null);
}
/// Ditto
T move(T)(ref T src)
{
T result;
move(src, result);
return result;
}
// moveAll
/**
For each element $(D a) in $(D src) and each element $(D b) in $(D
tgt) in lockstep in increasing order, calls $(D move(a, b)). Returns
the leftover portion of $(D tgt). Throws an exeption if there is not
enough room in $(D tgt) to acommodate all of $(D src).
Preconditions:
$(D walkLength(src) >= walkLength(tgt))
*/
Range2 moveAll(Range1, Range2)(Range1 src, Range2 tgt)
{
for (; !src.empty; src.popFront, tgt.popFront)
{
enforce(!tgt.empty);
move(src.front, tgt.front);
}
return tgt;
}
unittest
{
int[] a = [ 1, 2, 3 ];
int[] b = new int[5];
assert(moveAll(a, b) is b[3 .. $]);
assert(a == b[0 .. 3]);
assert(a == [ 1, 2, 3 ]);
}
// moveSome
/**
For each element $(D a) in $(D src) and each element $(D b) in $(D
tgt) in lockstep in increasing order, calls $(D move(a, b)). Stops
when either $(D src) or $(D tgt) have been exhausted. Returns the
leftover portion of the two ranges.
*/
Tuple!(Range1, Range2) moveSome(Range1, Range2)(Range1 src, Range2 tgt)
{
for (; !src.empty && !tgt.empty; src.popFront, tgt.popFront)
{
enforce(!tgt.empty);
move(src.front, tgt.front);
}
return tuple(src, tgt);
}
unittest
{
int[] a = [ 1, 2, 3, 4, 5 ];
int[] b = new int[3];
assert(moveSome(a, b).field[0] is a[3 .. $]);
assert(a[0 .. 3] == b);
assert(a == [ 1, 2, 3, 4, 5 ]);
}
// swap
/**
Swaps $(D lhs) and $(D rhs). See also $(XREF contracts, pointsTo).
Preconditions:
$(D !pointsTo(lhs, lhs) && !pointsTo(lhs, rhs) && !pointsTo(rhs, lhs)
&& !pointsTo(rhs, rhs))
*/
// void swap(T)(ref T lhs, ref T rhs)
// {
// assert(!pointsTo(lhs, lhs) && !pointsTo(lhs, rhs)
// && !pointsTo(rhs, lhs) && !pointsTo(rhs, rhs));
// auto t = lhs;
// lhs = rhs;
// rhs = t;
// }
void swap(T)(ref T a, ref T b) if (!is(typeof(T.init.proxySwap(T.init))))
{
static if (is(T == struct))
{
// For structs, move memory directly
// First check for undue aliasing
assert(!pointsTo(a, b) && !pointsTo(b, a)
&& !pointsTo(a, a) && !pointsTo(b, b));
// Swap bits
ubyte[T.sizeof] t = void;
memcpy(&t, &a, T.sizeof);
memcpy(&a, &b, T.sizeof);
memcpy(&b, &t, T.sizeof);
}
else
{
// For non-struct types, suffice to do the classic swap
auto t = a;
a = b;
b = t;
}
}
// Not yet documented
void swap(T)(T lhs, T rhs) if (is(typeof(T.init.proxySwap(T.init))))
{
lhs.proxySwap(rhs);
}
unittest
{
int a = 42, b = 34;
swap(a, b);
assert(a == 34 && b == 42);
struct S { int x; char c; int[] y; }
S s1 = { 0, 'z', [ 1, 2 ] };
S s2 = { 42, 'a', [ 4, 6 ] };
//writeln(s2.tupleof.stringof);
swap(s1, s2);
assert(s1.x == 42);
assert(s1.c == 'a');
assert(s1.y == [ 4, 6 ]);
assert(s2.x == 0);
assert(s2.c == 'z');
assert(s2.y == [ 1, 2 ]);
}
// split
/**
Splits a range using another range or an element as a separator. This
can be used with any range type, but is most popular with string
types.
Example:
---
int[] a = [ 1, 2, 0, 3, 0, 4, 5, 0 ];
int[][] w = [ [1, 2], [3], [4, 5] ];
uint i;
foreach (e; splitter(a)) assert(e == w[i++]);
assert(i == 3);
----
*/
struct Splitter(Range, Separator)
if (!is(typeof(ElementType!Range.init == Separator.init)))
{
private:
Range _input;
Separator _separator;
// _frontLength == size_t.max means empty
size_t _frontLength = size_t.max;
static if (isBidirectionalRange!Range)
size_t _backLength = size_t.max;
size_t separatorLength() { return _separator.length; }
void ensureFrontLength()
{
if (_frontLength != _frontLength.max) return;
assert(!_input.empty);
// compute front length
_frontLength = _input.length - find(_input, _separator).length;
static if (isBidirectionalRange!Range)
if (_frontLength == _input.length) _backLength = _frontLength;
}
void ensureBackLength()
{
static if (isBidirectionalRange!Range)
if (_backLength != _backLength.max) return;
assert(!_input.empty);
// compute back length
static if (isBidirectionalRange!Range)
{
_backLength = _input.length -
find(retro(_input), retro(_separator)).length;
}
}
public:
this(Range input, Separator separator)
{
_input = input;
_separator = separator;
}
Range front()
{
assert(!empty);
ensureFrontLength;
return _input[0 .. _frontLength];
}
bool empty()
{
return _frontLength == size_t.max && _input.empty;
}
void popFront()
{
assert(!empty);
ensureFrontLength;
if (_frontLength == _input.length)
{
// done, there's no separator in sight
_input = _input[_frontLength .. _frontLength];
_frontLength = _frontLength.max;
static if (isBidirectionalRange!Range)
_backLength = _backLength.max;
return;
}
if (_frontLength + separatorLength == _input.length)
{
// Special case: popping the first-to-last item; there is
// an empty item right after this.
_input = _input[_input.length .. _input.length];
_frontLength = 0;
static if (isBidirectionalRange!Range)
_backLength = 0;
return;
}
// Normal case, pop one item and the separator, get ready for
// reading the next item
_input = _input[_frontLength + separatorLength .. _input.length];
// mark _frontLength as uninitialized
_frontLength = _frontLength.max;
}
// Bidirectional functionality as suggested by Brad Roberts.
static if (isBidirectionalRange!Range)
{
Range back()
{
ensureBackLength;
return _input[_input.length - _backLength .. _input.length];
}
void popBack()
{
ensureBackLength;
if (_backLength == _input.length)
{
// done
_input = _input[0 .. 0];
_frontLength = _frontLength.max;
_backLength = _backLength.max;
return;
}
if (_backLength + separatorLength == _input.length)
{
// Special case: popping the first-to-first item; there is
// an empty item right before this. Leave the separator in.
_input = _input[0 .. 0];
_frontLength = 0;
_backLength = 0;
return;
}
// Normal case
_input = _input[0 .. _input.length - _backLength - separatorLength];
_backLength = _backLength.max;
}
}
}
struct Splitter(Range, Separator)
if (is(typeof(ElementType!Range.init == Separator.init)))
{
Range _input;
Separator _separator;
size_t _frontLength = size_t.max;
size_t _backLength = size_t.max;
this(Range input, Separator separator)
{
_input = input;
_separator = separator;
computeFront();
computeBack();
}
bool empty()
{
return _input.empty;
}
Range front()
{
if (_frontLength == _frontLength.max)
{
// This is not the first iteration, clean up separators
while (!_input.empty && _input.front == _separator)
_input.popFront();
computeFront();
}
return _input[0 .. _frontLength];
}
void popFront()
{
computeFront();
_input = _input[_frontLength .. $];
_frontLength = _frontLength.max;
}
Range back()
{
if (_backLength == _backLength.max)
{
while (!_input.empty && _input.back == _separator) _input.popBack();
computeBack();
}
assert(_backLength <= _input.length, text(_backLength));
return _input[$ - _backLength .. $];
}
void popBack()
{
computeBack();
enforce(_backLength <= _input.length);
_input = _input[0 .. $ - _backLength];
_backLength = _backLength.max;
}
private:
void computeFront()
{
if (_frontLength == _frontLength.max)
{
_frontLength = _input.length - _input.find(_separator).length;
}
}
void computeBack()
{
if (_backLength == _backLength.max)
{
//_backLength = find(retro(_input), _separator).length;
_backLength = 0;
auto i = _input;
while (!i.empty)
{
if (i.back == _separator) break;
++_backLength;
i.popBack();
}
}
assert(_backLength <= _input.length);
}
}
/// Ditto
Splitter!(Range, Separator)
splitter(Range, Separator)(Range r, Separator s)
if (is(typeof(ElementType!(Range).init == ElementType!(Separator).init)) ||
is(typeof(ElementType!(Range).init == Separator.init)))
{
return typeof(return)(r, s);
}
unittest
{
auto s = ",abc, de, fg,hi,";
auto sp0 = splitter(s, ',');
//foreach (e; sp0) writeln("[", e, "]");
assert(equal(sp0, ["", "abc", " de", " fg", "hi", ""][]));
auto s1 = ", abc, de, fg, hi, ";
auto sp1 = splitter(s1, ", ");
//foreach (e; sp1) writeln("[", e, "]");
assert(equal(sp1, ["", "abc", "de", " fg", "hi", ""][]));
int[] a = [ 1, 2, 0, 3, 0, 4, 5, 0 ];
int[][] w = [ [1, 2], [3], [4, 5], [] ];
uint i;
foreach (e; splitter(a, 0))
{
assert(i < w.length);
assert(e == w[i++]);
}
assert(i == w.length);
// Now go back
auto s2 = splitter(a, 0);
foreach_reverse (e; s2)
{
assert(i > 0);
assert(equal(e, w[--i]), text(e));
}
assert(i == 0);
}
unittest
{
auto s6 = ",";
auto sp6 = splitter(s6, ',');
foreach (e; sp6)
{
//writeln("{", e, "}");
}
assert(equal(sp6, ["", ""][]));
}
// uniq
/**
Iterates unique consecutive elements of the given range (functionality
akin to the $(WEB wikipedia.org/wiki/_Uniq, _uniq) system
utility). Equivalence of elements is assessed by using the predicate
$(D pred), by default $(D "a == b"). If the given range is
bidirectional, $(D uniq) also yields a bidirectional range.
Example:
----
int[] arr = [ 1, 2, 2, 2, 2, 3, 4, 4, 4, 5 ];
assert(equal(uniq(arr), [ 1, 2, 3, 4, 5 ][]));
----
*/
struct Uniq(alias pred, R)
{
R _input;
this(R input)
{
_input = input;
}
ref Uniq opSlice()
{
return this;
}
void popFront()
{
auto last = _input.front;
do
{
_input.popFront;
}
while (!_input.empty && binaryFun!(pred)(last, _input.front));
}
void popBack()
{
auto last = _input.back;
do
{
_input.popBack;
}
while (!_input.empty && binaryFun!(pred)(last, _input.back));
}
bool empty() { return _input.empty; }
ElementType!(R) front() { return _input.front; }
ElementType!(R) back() { return _input.back; }
}
/// Ditto
Uniq!(pred, Range) uniq(alias pred = "a == b", Range)(Range r)
{
return typeof(return)(r);
}
unittest
{
int[] arr = [ 1, 2, 2, 2, 2, 3, 4, 4, 4, 5 ];
auto r = uniq(arr);
assert(equal(r, [ 1, 2, 3, 4, 5 ][]));
}