-
Notifications
You must be signed in to change notification settings - Fork 1
/
helper.rb
1901 lines (1387 loc) · 32.9 KB
/
helper.rb
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
require 'net/http'
require 'cgi'
class TrueClass
def to_i
1
end
end
class FalseClass
def to_i
0
end
end
class Integer
=begin
4.to_range
Returns:
Range(4..4)
=end
def to_range
(self..self)
end
=begin
4.to_vec
Returns:
Vector(4, 4)
=end
def to_vec
Vector.new(self, self)
end
=begin
4.to_vec
Returns:
Vector(4, 4, 4)
=end
def to_vec3
Vector3.new(self, self, self)
end
end
class BigDecimal
=begin
4.to_vec
Returns:
Vector(4, 4)
=end
def to_vec
Vector.new(self, self)
end
=begin
4.to_vec
Returns:
Vector(4, 4, 4)
=end
def to_vec3
Vector3.new(self, self, self)
end
end
class String
def to_vec
Vector.new(*self.split('_').map(&:to_i))
end
def to_vec3
Vector.new(*self.split('_').map(&:to_i))
end
=begin
Modified count function. If one char it counts the char, if string it counts the string.
"aaa".count('a')
"aaa".count('aaa')
Returns:
3
1
=end
alias_method :count_original, :count
def count(value)
return self.chars.each_cons(value.size).count{|row| row.join == value } if value.size > 1
return count_original(value)
end
=begin
"###\n#.#\n###".lines
Returns:
[
"###",
"#.#",
"###",
]
=end
alias_method :lines_original, :lines
def lines(*args, **kwargs, &block)
return split("\n") if args.first.nil?
lines_original
end
=begin
"###\n\n#.#\n\n###".blocks
Returns:
[
"###",
"#.#",
"###",
]
=end
def blocks
split("\n\n")
end
=begin
"###\n#.#\n###".to_2d
Returns:
[
"#", "#", "#",
"#", ".", "#",
"#", "#", "#",
]
=end
def to_2d
self.split("\n").map(&:chars)
end
=begin
"###\n#.#\n###".to_2d
Returns:
{
Vector(1,1) => '#',
Vector(1,1) => '#',
}
=end
def to_map
to_2d.to_map
end
=begin
"abcd".halve
Returns:
['ab', 'cd']
=end
def halve
[self[0, self.size/2], self[self.size/2..-1]]
end
=begin
"ABCD".is_upper?
Returns:
true
=end
def is_upper?
self == self.upcase
end
=begin
"abcd".is_lower?
Returns:
true
=end
def is_lower?
self == self.downcase
end
=begin
"5".is_number?
Returns:
true
=end
def is_number?
self.match?(/-?\d+/)
end
=begin
"a 5 b -5 c 10".numbers
Returns:
[5, -5, 10]
=end
def numbers
scan(/-?\d+/).map(&:to_i)
end
=begin
"aoc is cool".numbers
Returns:
['aoc', 'is', 'cool']
=end
def words
scan(/\w+/)
end
=begin
'abc123abc123'.sub(/.*\Kabc/, 'ABC')
Returns:
"abc123ABC123"
=end
def rsub(pattern, replace)
pattern = Regexp.quote(pattern) if pattern.is_a?(String)
sub(/.*\K#{pattern}/, replace)
end
end
class Array
=begin
Support for quick array to hash method
[1,2,3].to_h(true)
Returns:
{
1: true,
2: true,
3: true,
}
=end
alias_method :original_to_h, :to_h
def to_h(*args, **kwargs, &block)
return self.to_h { [_1, args.first] } if !args.first.nil?
original_to_h(*args, **kwargs, &block)
end
=begin
[
"#", "#", "#",
"#", ".", "#",
"#", "#", "#",
].to_2ds
Returns:
"###
#.#
###"
=end
def to_2ds
result = ""
self.each_with_index do |y, yi|
y.each_with_index do |x, xi|
result += x
end
result += "\n"
end
result
end
=begin
[
"#", "#", "#",
"#", ".", "#",
"#", "#", "#",
].pos(x: x, y: y)
Returns:
true
=end
def pos(x, y)
return if !pos?(x: x, y: y)
self[y][x]
end
=begin
[
"#", "#", "#",
"#", ".", "#",
"#", "#", "#",
].pos?(x: 1, y: 1)
Returns:
true
=end
def pos?(x: nil, y: nil)
result = true
if x && (x < 0 || x > self[0].length - 1)
result = false
end
if y && (y < 0 || y > self.length - 1)
result = false
end
result
end
def to_vec
Vector.new(self[0], self[1])
end
=begin
[
"#", "#", "#",
"#", ".", "#",
"#", "#", "#",
].to_map
Returns:
{
Vector(0,0) => '#'
Vector(0,1) => '#'
Vector(0,2) => '#'
# ...
}
=end
def to_map
result = {}
self.each_with_index do |y, yi|
y.each_with_index do |x, xi|
result[Vector.new(xi, yi)] = x
end
end
result
end
def dirs
path = self.first.is_a?(String) ? self.map(&:to_vec) : self
result = []
(0..path.size - 2).each do |ai|
va = path[ai]
vb = path[ai + 1]
result << vb - va
end
result
end
=begin
[
"#", "#", "#",
"#", ".", "#",
"#", "#", "#",
].select_vec('.')
Returns:
[ Vector(1,1) ]
=end
def select_vec(value = nil)
result = []
self.each_with_index do |y, yi|
y.each_with_index do |x, xi|
next if value && x != value
result << Vector.new(xi, yi)
end
end
result
end
=begin
[5, Range(5), 5].ensure_ranges
Returns:
[Range(5), Range(5), Range(5)]
=end
def ensure_ranges
self.map{|v| v.is_a?(Range) ? v : v.to_range }
end
=begin
[5].add_range([6,7,8])
Returns:
[Range(5..8)]
=end
def add_range(values)
self.map do |r|
r = r.to_range if r.respond_to?(:to_range)
Array.wrap(values).each do |value|
value = value.to_range if value.respond_to?(:to_range)
r += value
end
r
end.flatten.compact.rangify.ensure_ranges
end
=begin
[Range(5..8)].sub_range([6,7,8])
Returns:
[Range(5..5)]
=end
def sub_range(values)
self.map do |r|
r = r.to_range if r.respond_to?(:to_range)
Array.wrap(values).each do |value|
value = value.to_range if value.respond_to?(:to_range)
r -= value
end
r
end.flatten.compact.rangify.ensure_ranges
end
=begin
[Range(5..7), Range(9..11)].intersect_range([6,7,8])
Returns:
[Range(6..7)]
=end
def intersect_range(values)
self.map do |r|
r = r.to_range if r.respond_to?(:to_range)
Array.wrap(values).each do |value|
value = value.to_range if value.respond_to?(:to_range)
r = r & value
end
r
end.flatten.compact.rangify.ensure_ranges
end
=begin
[1, 2, 3].keys
Returns:
[0, 1, 2]
=end
def keys
each_keys.to_a
end
=begin
[1, 2, 3].each_keys {|i| puts i }
Returns:
0 1 2
=end
def each_keys
(0..self.count - 1)
end
def minx
0
end
def maxx
self[0].size - 1
end
def miny
0
end
def maxy
self.size - 1
end
=begin
Formula for Edge length (Umfang)
[Vector(0,1), ...].poligon_perimeter
Returns:
100
=end
# Umfang / Edge length
def poligon_perimeter
self.each_cons(2).sum {|a, b| a.poligon_distance(b) }
end
=begin
Formula for Shoelace
[Vector(0,1), ...].poligon_inner_area
Returns:
100
=end
# https://stackoverflow.com/a/4937281
# https://en.wikipedia.org/wiki/Shoelace_formula
def poligon_inner_area
self.each_cons(2).sum {|a, b| (a.x * b.y) - (b.x * a.y) }.abs / 2
end
=begin
Formula for Picks Theorem
current = DIR_DOWN
edges = [current.clone]
directions.each do |d, t|
current.x += d.x * t
current.y += d.y * t
edges << current.clone
end
edges.poligon_area.to_i
Returns:
100 (see 2023/spec/day_18_spec.rb)
=end
# https://en.wikipedia.org/wiki/Pick%27s_theorem
def poligon_area
(self.poligon_inner_area + (self.poligon_perimeter / 2) + 1)
end
end
class Hash
=begin
Hash.init_grid(2)
Returns:
{
Vector(0,0) => '.',
Vector(0,1) => '.',
Vector(0,2) => '.',
}
=end
def self.init_map(to_x, to_y = to_x, char = '.')
map = {}
(0..to_y).each do |yi|
(0..to_x).each do |xi|
map[[xi, yi].to_vec] = char
end
end
map
end
=begin
map.start
Returns:
Vector(0,0)
=end
def start
Vector.new(0, 0)
end
=begin
map.stop
Returns:
Vector(5,5)
=end
def stop
Vector.new(maxx, maxy)
end
=begin
{
Vector(0,0) => '#',
Vector(0,1) => '#',
Vector(0,2) => '#',
}
Returns:
"###
#.#
###"
=end
def to_2ds(highlight: [], xrange: nil, yrange: nil, fill_nil: false, same_color: false)
highlight = highlight.clone.map(&:to_vec) if highlight.present? && highlight.first.is_a?(String)
xrange = (self.minx..self.maxx) if xrange.nil?
yrange = (self.miny..self.maxy) if yrange.nil?
result = ""
yrange.each do |yi|
xrange.each do |xi|
pos = Vector.new(xi, yi)
if fill_nil && self[pos].nil?
self[pos] = '.'
end
if same_color && highlight.include?(pos)
result += Rainbow(self[pos].to_s).orange
elsif highlight.first == pos
result += Rainbow(self[pos].to_s).orange
elsif highlight.last == pos
result += Rainbow(self[pos].to_s).red
elsif highlight.include?(pos)
result += Rainbow(self[pos].to_s).green
else
result += self[pos].to_s
end
end
result += "\n"
end
result
end
=begin
This function will iterate the 2d grid with x, y
Full map:
file.to_map.each_2d do |x, y|
pp [x, y]
end
Fixed area:
file.to_map.each_2d(11, 7) do |x, y|
pp [x, y]
end
=end
def each_2d(mx = maxx + 1, my = maxy + 1)
(0..(my - 1)).each do |cy|
(0..(mx - 1)).each do |cx|
yield(cx, cy, Vector.new(cx,cy))
end
end
end
=begin
This function uses a list of area positions and finds the edge positions.
area = map.flood(Vector.new(0,0))
edges = map.area_edges(area)
Returns:
Set.new[Vector.new(1,0)]
=end
def area_edges(list, directions: DIRS_PLUS)
result = Set.new
list.each do |check|
directions.each do |dir|
pos = check + dir
next if list.include?(pos)
result << [pos, Vector.new(dir.x, dir.y)]
end
end
return result
end
=begin
This function uses a list of area edges and reduces it so that there is only one edge per side of the poligion.
area = map.flood(Vector.new(0,0))
edges = map.area_edges(area)
sides = map.area_sides(area)
Returns:
Set.new[Vector.new(1,0)]
=end
def area_sides(edges)
edges_uniq = Set.new
edges_search = edges.dup.to_a
opposite_dirs = {
DIR_UP => [DIR_LEFT, DIR_RIGHT],
DIR_DOWN => [DIR_LEFT, DIR_RIGHT],
DIR_RIGHT => [DIR_UP, DIR_DOWN],
DIR_LEFT => [DIR_UP, DIR_DOWN],
}
while edges_search.present? do
rowa = edges_search.shift
posa, dira = rowa
opposite_dirs[dira].each do |search_dir|
(1..1000000000000).each do |step|
rowl = [posa + (search_dir * step), dira]
if edges_search.include?(rowl)
edges_search = edges_search.select{ _1 != rowl }
else
break
end
end
end
edges_uniq << rowa
end
edges_uniq
end
=begin
This function floods a map by their value
areas = map.flood_areas
Returns:
[
Set.new[Vector.new(1,0)],
Set.new[Vector.new(2,0)],
Set.new[Vector.new(3,0)],
]
=end
def flood_areas
areas = []
seen = Set.new
self.each do |pos, value|
next if seen.include?(pos)
result = self.flood_pos(pos)
areas |= [result]
seen += result
end
areas
end
=begin
This function floods a specific position and everything with the same value.
map.flood_pos(Vector.new(0,0))
Returns:
Set.new[Vector.new(1,0)]
=end
def flood_pos(start, values: nil, directions: DIRS_PLUS, wrap: false, result: Set.new)
values = Array.wrap(self[start]).to_set if values.nil?
return Set.new if result.include?(start)
result << start
self.steps(start, directions, wrap: wrap).each do |pos|
next if values.exclude?(self[pos])
result += self.flood_pos(pos, values: values, directions: directions, wrap: wrap, result: result)
end
return result
end
def manhattan_paths(start, stop, block_char: '#')
result = []
path = []
cur_pos = start.clone
(cur_pos.x..stop.x).each do |xi|
check_pos = Vector.new(xi, cur_pos.y)
break if self[check_pos].blank? || self[check_pos] == block_char
path |= [check_pos]
cur_pos.x = xi
end
(cur_pos.y..stop.y).each do |yi|
check_pos = Vector.new(cur_pos.x, yi)
break if self[check_pos].blank? || self[check_pos] == block_char
path |= [check_pos]
cur_pos.y = yi
end
if cur_pos == stop
result |= [path]
end
path = []
cur_pos = start.clone
(cur_pos.y..stop.y).each do |yi|
check_pos = Vector.new(cur_pos.x, yi)
break if self[check_pos].blank? || self[check_pos] == block_char
path |= [check_pos]
cur_pos.y = yi
end
(cur_pos.x..stop.x).each do |xi|
check_pos = Vector.new(xi, cur_pos.y)
break if self[check_pos].blank? || self[check_pos] == block_char
path |= [check_pos]
cur_pos.x = xi
end
if cur_pos == stop
result |= [path]
end
result
end
=begin
This function provides a short path functionality.
If the moves are related to a cost factor this can be used.
If no cost is involved, it will sort by distance.
stop_on = -> (map:, pos:, path:, seen:, data:, cost_min:) do
print "."
return [ path.size, path, seen, data[:cost] ]
end
skip_on = -> (map:, pos:, dir:, path:, seen:, data:) do
next true if map[pos] == '#'
if data[:last_dir] == dir
data[:cost] += 1
else
data[:cost] += 1001
end
data[:last_dir] = dir
false
end
shortest, shortest_path, shortest_seen, cost_min = map.shortest_path(start, stop, stop_on: stop_on, skip_on: skip_on, data: { last_dir: DIR_RIGHT, cost: 0 })
Returns:
[
13,
[...],
Set[...],
5,
]
=end
def shortest_path(start, stop, directions: DIRS_PLUS, skip_on: nil, stop_on: nil, data: {})
shortest = nil
shortest_path = nil
shortest_seen = nil
cost_min = nil
cost_seen = {}
pos_dir_seen = {}
queue = Heap.new do |a, b|
if a[3][:cost]
a[3][:cost] < b[3][:cost]
elsif shortest.nil?
a[0].manhattan(stop) < b[0].manhattan(stop)
else
a[1].size < b[1].size
end
end