-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathindex.ts
More file actions
3681 lines (3121 loc) · 92.5 KB
/
Copy pathindex.ts
File metadata and controls
3681 lines (3121 loc) · 92.5 KB
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
// #region TYPES
// =============
/** Entries is an array of index-value pairs, with unique indices. */
export type Entries<T> = [number, T][];
/** IEntries is a list of index-value pairs, with unique indices. */
export type IEntries<T> = Iterable<[number, T]>;
/** Lists is a pair of index array and value array, with unique indices. */
export type Lists<T> = [number[], T[]];
/** ILists is a pair of index iterable list and value iterable list, with unique indices. */
export type ILists<T> = [Iterable<number>, Iterable<T>];
/**
* Handle reading of a single value.
* @returns value
*/
export type ReadFunction<T> = () => T;
/**
* Handle combining of two values.
* @param a a value
* @param b another value
* @returns combined value
*/
export type CombineFunction<T> = (a: T, b: T) => T;
/**
* Handle comparison of two values.
* @param a a value
* @param b another value
* @returns a<b: -ve, a=b: 0, a>b: +ve
*/
export type CompareFunction<T> = (a: T, b: T) => number;
/**
* Handle processing of values in an array.
* @param v value in array
* @param i index of value in array
* @param x array containing the value
*/
export type ProcessFunction<T> = (v: T, i: number, x: T[] | null) => void;
/**
* Handle selection of values in an array.
* @param v value in array
* @param i index of value in array
* @param x array containing the value
* @returns selected?
*/
export type TestFunction<T> = (v: T, i: number, x: T[] | null) => boolean;
/**
* Handle transformation of a value to another.
* @param v value in array
* @param i index of value in array
* @param x array containing the value
* @returns transformed value
*/
export type MapFunction<T, U> = (v: T, i: number, x: T[] | null) => U;
/**
* Handle reduction of multiple values into a single value.
* @param acc accumulator (temporary result)
* @param v value in array
* @param i index of value in array
* @param x array containing the value
* @returns reduced value
*/
export type ReduceFunction<T, U> = (acc: U, v: T, i: number, x: T[] | null) => U;
/**
* Handle ending of a combined array.
* @param dones iᵗʰ array done?
* @returns combined array done?
*/
export type EndFunction = (dones: boolean[]) => boolean;
/**
* Handle swapping of two values in an array.
* @param x an array (updated!)
* @param i an index
* @param j another index
* @returns x | x[i] ⇔ x[j]
*/
export type SwapFunction<T> = (x: T[], i: number, j: number) => T[];
// #endregion
// #region METHODS
// ===============
// #region HELPERS
// ---------------
/** Return the same (first) value. */
function IDENTITY<T>(v: T): T {
return v;
}
/** Compare two values. */
function COMPARE<T>(a: T, b: T): number {
return a<b? -1 : (a>b? 1 : 0);
}
/** Find the remainder of x/y with sign of y (floored division). */
function mod(x: number, y: number): number {
return x - y * Math.floor(x/y);
}
/** Convert an iterable to set. */
function toSet<T, U=T>(x: T[], fm: MapFunction<T, U> | null=null): Set<T|U> {
if (!fm) return new Set(x);
const a = new Set<U>(); let i = -1;
for (const v of x)
a.add(fm(v, ++i, x));
return a;
}
// #endregion
// #region GENERATE
// ----------------
/**
* Generate array from given number range.
* @param v start number
* @param V end number, excluding
* @param dv step size [1]
* @returns [v, v+dv, v+2dv, ...]
*/
export function fromRange(v: number, V: number, dv: number=1): number[] {
const n = (V - v)/dv, a = [];
for (let i=0; i<n; ++i, v+=dv)
a.push(v);
return a;
}
/**
* Generate array from repeated function invocation.
* @param fn function
* @param n number of values
* @returns [fn(), fn(), ...]
*/
export function fromInvocation<T>(fn: () => T, n: number): T[] {
const a = [];
for (let i=0; i<n; ++i)
a.push(fn());
return a;
}
export {fromInvocation as fromCall};
/**
* Generate array from repeated function application.
* @param fm map function (v, i)
* @param v start value
* @param n number of values
* @returns [v, fm(v), fm(fm(v)), ...]
*/
export function fromApplication<T>(fm: MapFunction<T, T>, v: T, n: number): T[] {
const a = [];
if (n!==0) a.push(v);
for (let i=1; i!==n; ++i)
a.push(v = fm(v, i, null));
return a;
}
export {fromApplication as fromApply};
/**
* Convert an iterable to array.
* @param x an iterable
* @returns x as array
*/
export function fromIterable<T>(x: Iterable<T>): T[] {
return [...x];
}
export {fromIterable as from};
/**
* Convert an iterable to array!
* @param x an iterable (updatable if array!)
* @returns x as array
*/
export function fromIterable$<T>(x: Iterable<T>): T[] {
return Array.isArray(x)? x : [...x];
}
export {fromIterable$ as from$};
// #endregion
// #region CLONE
// -------------
/**
* Shallow clone an array.
* @param x an array
* @returns shallow clone of x
*/
export function shallowClone<T>(x: T[]): T[] {
return x.slice();
}
export {shallowClone as clone};
/**
* Deep clone an array.
* @param x an array
* @returns deep clone of x
*/
export function deepClone<T>(x: T[]): T[] {
return structuredClone(x);
}
// #endregion
// #region ABOUT
// -------------
/**
* Check if value is an array.
* @param v a value
* @returns v is an array?
*/
export function is(v: unknown): v is unknown[] {
return Array.isArray(v);
}
/**
* Obtain all indices.
* @param x an array
* @returns [0, 1, ..., |x|-1]
*/
export function keys<T>(x: T[]): number[] {
return [...x.keys()];
}
/**
* List all indices.
* @param x an array
* @returns 0, 1, ..., |x|-1
*/
export function ikeys<T>(x: T[]): IterableIterator<number> {
return x.keys();
}
/**
* Get all values.
* @param x an array
* @returns [v₀, v₁, ...] | vᵢ = x[i]
*/
export function values<T>(x: T[]): T[] {
return x.slice();
}
/**
* List all values.
* @param x an array
* @returns v₀, v₁, ... | vᵢ = x[i]
*/
export function ivalues<T>(x: T[]): IterableIterator<T> {
return x.values();
}
/**
* Obtain all index-value pairs.
* @param x an array
* @returns [[0, v₀], [1, v₁], ...] | vᵢ = x[i]
*/
export function entries<T>(x: T[]): Entries<T> {
return [...x.entries()];
}
/**
* List all index-value pairs.
* @param x an array
* @returns [0, v₀], [1, v₁], ... | vᵢ = x[i]
*/
export function ientries<T>(x: T[]): IEntries<T> {
return x.entries();
}
// #endregion
// #region INDEX
// -------------
/**
* Get zero-based index for an element in array.
* @param x an array
* @param i ±index
* @returns i' | x[i'] = x[i]; i' ∈ [0, |x|]
*/
export function index<T>(x: T[], i: number): number {
const X = x.length;
return i>=0? Math.min(i, X) : Math.max(X+i, 0);
}
/**
* Get zero-based index range for part of array.
* @param x an array
* @param i begin ±index [0]
* @param I end ±index (exclusive) [|x|]
* @returns [i', I'] | i' ≤ I'; i', I' ∈ [0, |x|]
*/
export function indexRange<T>(x: T[], i: number=0, I: number=x.length): [number, number] {
const X = x.length;
i = i>=0? Math.min(i, X) : Math.max(X+i, 0);
I = I>=0? Math.min(I, X) : Math.max(X+I, 0);
return [i, Math.max(i, I)];
}
// #endregion
// #region LENGTH
// --------------
/**
* Check if an array is empty.
* @param x an array
* @returns |x| = 0?
*/
export function isEmpty<T>(x: T[]): boolean {
return x.length===0;
}
/**
* Find the length of an array.
* @param x an array
* @param i begin ±index [0]
* @param I end ±index (exclusive) [X]
* @returns |x[i..I]|
*/
export function length<T>(x: T[], i: number=0, I: number=x.length): number {
[i, I] = indexRange(x, i, I);
return I-i;
}
export {length as size};
/**
* Resize an array to given length!
* @param x an array
* @param n new length
* @param vd default value
* @returns resized x
*/
export function resize$<T>(x: T[], n: number, vd: T): T[] {
const X = x.length; x.length = n;
if (n>X) x.fill(vd, X);
return x;
}
/**
* Remove all elements from an array!
* @param x an array (updated!)
* @returns cleared x
*/
export function clear$<T>(x: T[]): T[] {
x.length = 0;
return x;
}
// #endregion
// #region GET/SET
// ---------------
/**
* Get value at index.
* @param x an array
* @param i index
* @returns x[i]
*/
export function get<T>(x: T[], i: number): T {
return x[index(x, i)];
}
export {get as at};
// Get values at index range.
// export {slice as getRange};
/**
* Get values at indices.
* @param x an array
* @param is indices
* @returns [x[i₀], x[i₁], ...] | [i₀, i₁, ...] = is
*/
export function getAll<T>(x: T[], is: number[]): T[] {
return is.map(i => get(x, i));
}
/**
* Get value at path in a nested array.
* @param x a nested array
* @param p path
* @returns x[i₀][i₁][...] | [i₀, i₁, ...] = p
*/
export function getPath(x: unknown[], p: number[]): unknown {
let a: unknown | undefined = x;
for (const i of p)
a = is(a)? get(a, i) : undefined;
return a;
}
/**
* Check if nested array has a path.
* @param x a nested array
* @param p path
* @returns x[i₀][i₁][...] exists? | [i₀, i₁, ...] = p
*/
export function hasPath(x: unknown[], p: number[]): boolean {
let a: unknown | undefined = x;
for (const i of p) {
if (!is(a)) return false;
a = get(a, i);
}
return true;
}
/**
* Set value at index.
* @param x an array
* @param i index
* @param v value
* @returns x' | x' = x; x'[i] = v
*/
export function set<T>(x: T[], i: number, v: T): T[] {
return set$(x.slice(), i, v);
}
export {set as with};
/**
* Set value at index!
* @param x an array (updated!)
* @param i index
* @param v value
* @returns x | x[i] = v
*/
export function set$<T>(x: T[], i: number, v: T): T[] {
x[index(x, i)] = v;
return x;
}
// TODO: setRange$()
// TODO: setAll$()
/**
* Set value at path in a nested array!
* @param x a nested array (updated!)
* @param p path
* @param v value
* @returns x | x[i₀][i₁][...] = v; [i₀, i₁, ...] = p
*/
export function setPath$(x: unknown[], p: number[], v: unknown): unknown[] {
const y = getPath(x, p.slice(0, -1));
if (is(y)) set$(y, last(p) as number, v);
return x;
}
/**
* Exchange two values.
* @param x an array
* @param i an index
* @param j another index
* @returns x' | x' = x; x'[i] = x[j]; x'[j] = x[i]
*/
export function swap<T>(x: T[], i: number, j: number): T[] {
return swap$(x.slice(), i, j);
}
/**
* Exchange two values!
* @param x an array (updated!)
* @param i an index
* @param j another index
* @returns x | x[i] ⇔ x[j]
*/
export function swap$<T>(x: T[], i: number, j: number): T[] {
i = index(x, i); j = index(x, j);
const t = x[i]; x[i] = x[j]; x[j] = t;
return x;
}
/**
* Exchange two values!
* @param x an array (updated!)
* @param i an +ve index
* @param j another +ve index
* @returns x | x[i] ⇔ x[j]
*/
function swapRaw$<T>(x: T[], i: number, j: number): T[] {
const t = x[i]; x[i] = x[j]; x[j] = t;
return x;
}
// NOTE: May also be called swapUnchecked$().
/**
* Exchange two ranges of values.
* @param x an array
* @param i begin index of first range
* @param I end index of first range (exclusive)
* @param j begin index of second range
* @param J end index of second range (exclusive)
* @returns x' | x' = x; x'[i..I] = x[j..J]; x'[j..J] = x[i..I]
*/
export function swapRanges<T>(x: T[], i: number, I: number, j: number, J: number): T[] {
[i, I] = indexRange(x, i, I);
[j, J] = indexRange(x, j, J);
if (j<i) [i, I, j, J] = [j, J, i, I];
if (j<I) return x.slice(); // Skip if ranges overlap!
return x.slice(0, i).concat(x.slice(j, J), x.slice(i, j), x.slice(I));
}
/**
* Exchange two ranges of values!
* @param x an array (updated!)
* @param i begin index of first range
* @param I end index of first range (exclusive)
* @param j begin index of second range
* @param J end index of second range (exclusive)
* @returns x | x[i..I] ⇔ x[j..J]
*/
export function swapRanges$<T>(x: T[], i: number, I: number, j: number, J: number): T[] {
[i, I] = indexRange(x, i, I);
[j, J] = indexRange(x, j, J);
if (j<i) [i, I, j, J] = [j, J, i, I];
if (j<I) return x; // Skip if ranges overlap!
const t = x.slice(i, I);
x.splice(i, I-i, ...x.slice(j, J));
x.splice(j, J-j, ...t);
return x;
}
// TODO: swapAll$()
/**
* Remove value at index.
* @param x an array
* @param i index
* @returns x[0..i] ⧺ x[i+1..]
*/
export function remove<T>(x: T[], i: number): T[] {
i = index(x, i);
return x.slice(0, i).concat(x.slice(i+1));
}
/**
* Remove value at index!
* @param x an array (updated!)
* @param i index
* @returns x \\: [i]
*/
export function remove$<T>(x: T[], i: number): T[] {
x.splice(i, 1);
return x;
}
/**
* Remove value at path in a nested array!
* @param x a nested array (updated!)
* @param p path
* @returns x \\: [i₀][i₁][...] | [i₀, i₁, ...] = p
*/
export function removePath$(x: unknown[], p: number[]): unknown[] {
const y = getPath(x, p.slice(0, -1));
if (is(y)) y.splice(last(p) as number, 1);
return x;
}
// #endregion
// #region SORT
// ------------
/**
* Examine if array is sorted.
* @param x an array
* @param fc compare function (a, b)
* @param fm map function (v, i, x)
* @returns x is sorted?
*/
export function isSorted<T, U=T>(x: T[], fc: CompareFunction<T|U> | null=null, fm: MapFunction<T, T|U> | null=null): boolean {
return searchUnsortedValue(x, fc, fm) === -1;
}
/**
* Examine if array has an unsorted value.
* @param x an array
* @param fc compare function (a, b)
* @param fm map function (v, i, x)
* @returns x is not sorted?
*/
export function hasUnsortedValue<T, U=T>(x: T[], fc: CompareFunction<T|U> | null=null, fm: MapFunction<T, T|U> | null=null): boolean {
return searchUnsortedValue(x, fc, fm) >= 0;
}
/**
* Find first index of an unsorted value.
* @param x an array
* @param fc compare function (a, b)
* @param fm map function (v, i, x)
* @returns index of first unsorted value, -1 if sorted
*/
export function searchUnsortedValue<T, U=T>(x: T[], fc: CompareFunction<T|U> | null=null, fm: MapFunction<T, T|U> | null=null): number {
fc = fc || COMPARE;
fm = fm || IDENTITY;
const X = x.length;
if (X<=1) return -1;
let w0 = fm(x[0], 0, x);
for (let i=1; i<X; ++i) {
const w = fm(x[i], i, x);
if (fc(w0, w)>0) return i;
w0 = w;
}
return -1;
}
/**
* Arrange values in order.
* @param x an array
* @param fc compare function (a, b)
* @param fm map function (v, i, x)
* @param fs swap function (x, i, j)
* @returns x' | x' = x; x'[i] ≤ x'[j] ∀ i ≤ j
*/
export function sort<T, U=T>(x: T[], fc: CompareFunction<T|U> | null=null, fm: MapFunction<T, T|U> | null=null, fs: SwapFunction<T> | null=null): T[] {
return sort$(x.slice(), fc, fm, fs);
}
export {sort as toSorted};
/**
* Arrange values in order!
* @param x an array (updated!)
* @param fc compare function (a, b)
* @param fm map function (v, i, x)
* @param fs swap function (x, i, j)
* @returns x | x[i] ≤ x[j] ∀ i ≤ j
*/
export function sort$<T, U=T>(x: T[], fc: CompareFunction<T|U> | null=null, fm: MapFunction<T, T|U> | null=null, fs: SwapFunction<T> | null=null): T[] {
fc = fc || COMPARE;
if (!fm && !fs) return x.sort(fc);
const X = x.length;
fm = fm || IDENTITY;
fs = fs || swapRaw$;
return rangedPartialIntroSort$(x, 0, X, X, fc, fm, fs);
}
/**
* Arrange a range of values in order.
* @param x an array
* @param i begin index
* @param I end index (exclusive)
* @param fc compare function (a, b)
* @param fm map function (v, i, x)
* @param fs swap function (x, i, j)
* @returns x' | x' = x; x'[i] ≤ x'[j] ∀ i ≤ j
*/
export function rangedSort<T, U=T>(x: T[], i: number, I: number, fc: CompareFunction<T|U> | null=null, fm: MapFunction<T, T|U> | null=null, fs: SwapFunction<T> | null=null): T[] {
return rangedSort$(x.slice(), i, I, fc, fm, fs);
}
/**
* Arrange a range of values in order!
* @param x an array (updated!)
* @param i begin index
* @param I end index (exclusive)
* @param fc compare function (a, b)
* @param fm map function (v, i, x)
* @param fs swap function (x, i, j)
* @returns x | x[i] ≤ x[j] ∀ i ≤ j
*/
export function rangedSort$<T, U=T>(x: T[], i: number, I: number, fc: CompareFunction<T|U> | null=null, fm: MapFunction<T, T|U> | null=null, fs: SwapFunction<T> | null=null): T[] {
fc = fc || COMPARE;
fm = fm || IDENTITY;
fs = fs || swapRaw$;
[i, I] = indexRange(x, i, I);
return rangedPartialIntroSort$(x, i, I, I-i, fc, fm, fs);
}
/**
* Partially arrange values in order.
* @param x an array
* @param n minimum number of values to sort
* @param fc compare function (a, b)
* @param fm map function (v, i, x)
* @param fs swap function (x, i, j)
* @returns x' | x' = x; x'[i] ≤ x'[j] ∀ i ≤ j
*/
export function partialSort<T, U=T>(x: T[], n: number, fc: CompareFunction<T|U> | null=null, fm: MapFunction<T, T|U> | null=null, fs: SwapFunction<T> | null=null): T[] {
return partialSort$(x.slice(), n, fc, fm, fs);
}
/**
* Partially arrange values in order!
* @param x an array (updated!)
* @param n minimum number of values to sort
* @param fc compare function (a, b)
* @param fm map function (v, i, x)
* @param fs swap function (x, i, j)
* @returns x | x[i] ≤ x[j] ∀ i ≤ j
*/
export function partialSort$<T, U=T>(x: T[], n: number, fc: CompareFunction<T|U> | null=null, fm: MapFunction<T, T|U> | null=null, fs: SwapFunction<T> | null=null): T[] {
return rangedPartialSort$(x, 0, x.length, n, fc, fm, fs);
}
/**
* Partially arrange a range of values in order.
* @param x an array
* @param i begin index
* @param I end index (exclusive)
* @param n minimum number of values to sort
* @param fc compare function (a, b)
* @param fm map function (v, i, x)
* @param fs swap function (x, i, j)
* @returns x' | x' = x; x'[i] ≤ x'[j] ∀ i ≤ j
*/
export function rangedPartialSort<T, U=T>(x: T[], i: number, I: number, n: number, fc: CompareFunction<T|U> | null=null, fm: MapFunction<T, T|U> | null=null, fs: SwapFunction<T> | null=null): T[] {
return rangedPartialSort$(x.slice(), i, I, n, fc, fm, fs);
}
/**
* Partially arrange a range of values in order!
* @param x an array (updated!)
* @param i begin index
* @param I end index (exclusive)
* @param n minimum number of values to sort
* @param fc compare function (a, b)
* @param fm map function (v, i, x)
* @param fs swap function (x, i, j)
* @returns x | x[i] ≤ x[j] ∀ i ≤ j
*/
export function rangedPartialSort$<T, U=T>(x: T[], i: number, I: number, n: number, fc: CompareFunction<T|U> | null=null, fm: MapFunction<T, T|U> | null=null, fs: SwapFunction<T> | null=null): T[] {
fc = fc || COMPARE;
fm = fm || IDENTITY;
fs = fs || swapRaw$;
[i, I] = indexRange(x, i, I);
return rangedPartialIntroSort$(x, i, I, n, fc, fm, fs);
}
/**
* Partially arrange values in order!
* @param x an array (updated!)
* @param i begin index
* @param I end index (exclusive)
* @param n minimum number of values to sort
* @param fc compare function (a, b)
* @param fm map function (v, i, x)
* @param fs swap function (x, i, j)
* @returns x | x[i] ≤ x[j] ∀ i ≤ j
*/
function rangedPartialIntroSort$<T, U=T>(x: T[], i: number, I: number, n: number, fc: CompareFunction<T|U>, fm: MapFunction<T, T|U>, fs: SwapFunction<T>): T[] {
const d = Math.floor(Math.log2(I-i)*2); // Maximum depth of recursion
const s = 16; // When to switch to insertion sort
return rangedPartialIntroSortDo$(x, i, I, d, s, n, fc, fm, fs);
}
// Partially arrange a range of values in order with hybrid quick sort, heap sort, and insertion sort.
function rangedPartialIntroSortDo$<T, U=T>(x: T[], i: number, I: number, d: number, s: number, n: number, fc: CompareFunction<T|U>, fm: MapFunction<T, T|U>, fs: SwapFunction<T>): T[] {
if (n<=0 || I-i<=1) return x; // Nothing to sort
if (I-i<=s) return rangedPartialInsertionSort$(x, i, I, n, fc, fm, fs); // Insertion sort
if (d<=0) return rangedPartialHeapSort$(x, i, I, n, fc, fm, fs); // Heap sort
let p = i + Math.floor((I-i)*Math.random()); // Choose pivot
p = rangedQuickSortPartition$(x, i, I, p, fc, fm, fs); // Partition array
rangedPartialIntroSortDo$(x, i, p, d, s, Math.min(p-i, n), fc, fm, fs); // Sort left part
rangedPartialIntroSortDo$(x, p+1, I, d, s, Math.min(I-p-1, n), fc, fm, fs); // Sort right part
return x;
}
/**
* Partially arrange a range of values in order!
* @param x an array (updated!)
* @param i begin index
* @param I end index (exclusive)
* @param n minimum number of values to sort
* @param fc compare function (a, b)
* @param fm map function (v, i, x)
* @param fs swap function (x, i, j)
* @returns x | x[i] ≤ x[j] ∀ i ≤ j
*/
function _rangedPartialQuickSort$<T, U=T>(x: T[], i: number, I: number, n: number, fc: CompareFunction<T|U>, fm: MapFunction<T, T|U>, fs: SwapFunction<T>): T[] {
if (n<=0 || I-i<=1) return x; // Nothing to sort
let p = i + Math.floor((I-i)*Math.random()); // Choose pivot
p = rangedQuickSortPartition$(x, i, I, p, fc, fm, fs); // Partition array
_rangedPartialQuickSort$(x, i, p, Math.min(p-i, n), fc, fm, fs); // Sort left part
_rangedPartialQuickSort$(x, p+1, I, Math.min(I-p-1, n), fc, fm, fs); // Sort right part
return x;
}
// TODO: Make this a generic function.
// Partition the array into two parts, such that values in the first part are less than values in the second part.
function rangedQuickSortPartition$<T, U=T>(x: T[], i: number, I: number, p: number, fc: CompareFunction<T|U>, fm: MapFunction<T, T|U>, fs: SwapFunction<T>): number {
const wp = fm(x[p], p, x); // Pivot value
let j = i-1; // Last index of values ≤ pivot
fs(x, p, I-1); // Move pivot to end
for (let k=i; k<I-1; ++k) {
const wk = fm(x[k], k, x);
if (fc(wk, wp) > 0) continue;
fs(x, ++j, k); // Move value ≤ pivot to left
}
fs(x, ++j, I-1); // Move pivot to middle
return j; // Return pivot index
}
/**
* Partially arrange a range of values in order!
* @param x an array (updated!)
* @param i begin index
* @param I end index (exclusive)
* @param n minimum number of values to sort
* @param fc compare function (a, b)
* @param fm map function (v, i, x)
* @param fs swap function (x, i, j)
* @returns x | x[i] ≤ x[j] ∀ i ≤ j
*/
function rangedPartialHeapSort$<T, U=T>(x: T[], i: number, I: number, n: number, fc: CompareFunction<T|U>, fm: MapFunction<T, T|U>, fs: SwapFunction<T>): T[] {
rangedBuildReverseMinHeap$(x, i, I, fc, fm, fs);
for (const r=I-1; n>0 && i<I; ++i, --n) {
fs(x, i, r); // Move root to the beginning
rangedReverseMinHeapify$(x, i+1, I, r, fc, fm, fs); // Rebuild heap
}
return x;
}
// Build a reverse min-heap from a range of values, where root node is the smallest and placed at the end.
function rangedBuildReverseMinHeap$<T, U=T>(x: T[], i: number, I: number, fc: CompareFunction<T|U>, fm: MapFunction<T, T|U>, fs: SwapFunction<T>): void {
for (let r=I-Math.floor((I-i)/2); r<I; ++r) // Reverse of r = X/2-1 .. 0
rangedReverseMinHeapify$(x, i, I, r, fc, fm, fs);
}
/**
* Reverse min-heapify a range of values, such that root node is the smallest and placed at the end.
* @param x an array (updated!)
* @param i begin index
* @param I end index (exclusive)
* @param r root index
* @param fc compare function (a, b)
* @param fm map function (v, i, x)
* @param fs swap function (x, i, j)
*/
function rangedReverseMinHeapify$<T, U=T>(x: T[], i: number, I: number, r: number, fc: CompareFunction<T|U>, fm: MapFunction<T, T|U>, fs: SwapFunction<T>): void {
let s = r; // Index of smallest value
const lt = 2*r - I; // Left child, reverse of lt = 2*r+1
const rt = lt - 1; // Right child, reverse of rt = 2*r+2
if (lt>=i && fc(fm(x[lt], lt, x), fm(x[s], s, x)) < 0) s = lt; // Left child is smaller?
if (rt>=i && fc(fm(x[rt], rt, x), fm(x[s], s, x)) < 0) s = rt; // Right child is smaller?
if (s !== r) { // Smallest is not root?
fs(x, s, r); // Swap root with smallest
rangedReverseMinHeapify$(x, i, I, s, fc, fm, fs); // Rebuild heap
}
}
// Build a max-heap from a range of values, where root node is the smallest and placed at the beginning.
function rangedBuildMaxHeap$<T, U=T>(x: T[], i: number, I: number, fc: CompareFunction<T|U>, fm: MapFunction<T, T|U>, fs: SwapFunction<T>): void {
for (let r=i+Math.floor((I-i)/2)-1; r>=i; --r)
rangedMaxHeapify$(x, i, I, r, fc, fm, fs);
}
/**
* Max-heapify a range of values, such that root node is the largest and placed at the beginning.
* @param x an array (updated!)
* @param i begin index
* @param I end index (exclusive)
* @param r root index
* @param fc compare function (a, b)
* @param fm map function (v, i, x)
* @param fs swap function (x, i, j)
*/
function rangedMaxHeapify$<T, U=T>(x: T[], i: number, I: number, r: number, fc: CompareFunction<T|U>, fm: MapFunction<T, T|U>, fs: SwapFunction<T>): void {
let s = r; // Index of largest value
const lt = 2*r - i + 1; // Left child, like lt = 2*r+1
const rt = lt + 1; // Right child, like rt = 2*r+2
if (lt<I && fc(fm(x[lt], lt, x), fm(x[s], s, x)) > 0) s = lt; // Left child is larger?
if (rt<I && fc(fm(x[rt], rt, x), fm(x[s], s, x)) > 0) s = rt; // Right child is larger?
if (s !== r) { // Largest is not root?
fs(x, s, r); // Swap root with largest
rangedMaxHeapify$(x, i, I, s, fc, fm, fs); // Rebuild heap
}
}
/**
* Partially arrange a range of values in order!
* @param x an array (updated!)
* @param i begin index
* @param I end index (exclusive)
* @param n minimum number of values to sort (ignored)
* @param fc compare function (a, b)
* @param fm map function (v, i, x)
* @param fs swap function (x, i, j)
* @returns x | x[i] ≤ x[j] ∀ i ≤ j
*/
function rangedPartialInsertionSort$<T, U=T>(x: T[], i: number, I: number, n: number, fc: CompareFunction<T|U>, fm: MapFunction<T, T|U>, fs: SwapFunction<T>): T[] {
// NOTE: Insertion sort does not support partial sorting, so we ignore n.
if (fs===swapRaw$) return rangedPartialInsertionSortSwapless$(x, i, I, n, fc, fm, fs);
else return rangedPartialInsertionSortSwap$ (x, i, I, n, fc, fm, fs);
}
// Sort a range of values in order with swap-enabled version of insertion sort.
function rangedPartialInsertionSortSwap$<T, U=T>(x: T[], i: number, I: number, _n: number, fc: CompareFunction<T|U>, fm: MapFunction<T, T|U>, fs: SwapFunction<T>): T[] {
for (let j=i+1; j<I; ++j) {
const key = x[j];
const wkey = fm(key, j, x);
for (let k=j-1; k>=i && fc(fm(x[k], k, x), wkey)>0; --k)
fs(x, k, k+1);
}
return x;
}
// Sort a range of values in order with swapless version of insertion sort.
function rangedPartialInsertionSortSwapless$<T, U=T>(x: T[], i: number, I: number, _n: number, fc: CompareFunction<T|U>, fm: MapFunction<T, T|U>, _fs: SwapFunction<T>): T[] {
for (let j=i+1; j<I; ++j) {
const key = x[j];
const wkey = fm(key, j, x);
let k = j-1;
for (; k>=i && fc(fm(x[k], k, x), wkey)>0; --k)
x[k+1] = x[k];
x[k+1] = key;
}
return x;
}