-
Notifications
You must be signed in to change notification settings - Fork 0
/
advcode2022.rs
4527 lines (4003 loc) · 146 KB
/
advcode2022.rs
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
use std::collections::{HashSet, HashMap};
use std::iter::FromIterator;
pub fn p01() {
let contents = r#"1000
2000
3000
4000
5000
6000
7000
8000
9000
10000"#;
let contents = std::fs::read_to_string("./assets/adv2022/adv01.txt").unwrap();
let calories: Vec<Vec<usize>> = contents.trim().split("\n\n").map(
|lines| lines.split("\n").map(|cc| cc.parse().unwrap()).collect()
).collect();
let mut calories_max: Vec<usize> = calories.into_iter().map(|cc| cc.into_iter().sum::<usize>()).collect();
eprintln!("max calories: {:?}", calories_max.iter().max());
calories_max.sort();
eprintln!("top 3 calories: {:?}", calories_max.iter().rev().take(3).sum::<usize>());
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum P02Shape {
Rock,
Paper,
Scissor,
}
impl P02Shape {
pub fn from_u8(idx: u8) -> Self {
match idx {
0 => Self::Rock,
1 => Self::Paper,
2 => Self::Scissor,
_ => unreachable!("primitive integer must between 0-2"),
}
}
pub fn from_u8_rev(slf: u8, score: u8) -> Self {
match score {
0 => P02Shape::from_u8(slf).win(),
1 => P02Shape::from_u8(slf),
2 => P02Shape::from_u8(slf).lose(),
_ => unreachable!("primitive integer must between 0-2"),
}
}
pub fn lose(self) -> Self {
use P02Shape::*;
match self {
Rock => Paper,
Scissor => Rock,
Paper => Scissor,
}
}
pub fn win(self) -> Self {
use P02Shape::*;
match self {
Rock => Scissor,
Scissor => Paper,
Paper => Rock,
}
}
pub fn round(self, right: Self) -> usize {
use P02Shape::*;
let base = ((self as u8) + 1) as usize;
let score = match (self, right) {
(l, r) if l == r => 3,
(Rock, Scissor) => 6,
(Scissor, Paper) => 6,
(Paper, Rock) => 6,
_ => 0,
};
base + score
}
}
pub fn p02() {
let contents = r#"A Y
B X
C Z"#;
let contents = std::fs::read_to_string("./assets/adv2022/adv02.txt").unwrap();
let shapes: Vec<(P02Shape, P02Shape)> = contents.trim().split("\n").map(|line| {
let (abc, xyz) = line.split_once(" ").unwrap();
let abc = abc.chars().next().unwrap() as u8 - 'A' as u8;
let xyz = xyz.chars().next().unwrap() as u8 - 'X' as u8;
(P02Shape::from_u8(abc), P02Shape::from_u8(xyz))
}).collect();
let score: usize = shapes.iter().map(|(other, slf)| {
slf.round(*other)
}).sum();
// eprintln!("{:?}", shapes);
eprintln!("score: {:?}", score);
let shapes: Vec<(P02Shape, P02Shape)> = contents.trim().split("\n").map(|line| {
let (abc, xyz) = line.split_once(" ").unwrap();
let abc = abc.chars().next().unwrap() as u8 - 'A' as u8;
let xyz = xyz.chars().next().unwrap() as u8 - 'X' as u8;
(P02Shape::from_u8(abc), P02Shape::from_u8_rev(abc, xyz))
}).collect();
let score: usize = shapes.iter().map(|(other, slf)| {
slf.round(*other)
}).sum();
// eprintln!("{:?}", shapes);
eprintln!("score: {:?}", score);
}
pub fn p03() {
let contents = r#"vJrwpWtwJgWrhcsFMMfFFhFp
jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
PmmdzqPrVvPwwTWBwg
wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn
ttgJtRGJQctTZtZT
CrZsJsPPZsGzwwsLwLmpwMDw"#;
let contents = std::fs::read_to_string("./assets/adv2022/adv03.txt").unwrap();
let priorities: usize = contents.trim().split("\n").map(|line| {
let mut items: Vec<usize> = line.trim().chars().map(|c| {
let idx = if c.is_lowercase() {
c as u8 - 'a' as u8
} else {
(c as u8 - 'A' as u8) + 26
};
idx as usize + 1
}).collect();
let len = items.len();
assert!(len % 2 == 0);
let cap = len / 2;
let (left, right) = items.split_at_mut(cap);
left.sort();
right.sort();
let common = left.iter().find(|idx| {
right.binary_search(idx).is_ok()
});
*common.unwrap()
}).sum();
eprintln!("priorities: {}", priorities);
let priorities: Vec<Vec<usize>> = contents.trim().split("\n").map(|line| {
let items: Vec<usize> = line.trim().chars().map(|c| {
let idx = if c.is_lowercase() {
c as u8 - 'a' as u8
} else {
(c as u8 - 'A' as u8) + 26
};
idx as usize + 1
}).collect();
items
}).collect();
assert!(priorities.len() % 3 == 0);
let mut tot = 0;
for idx in 0..(priorities.len() / 3) {
let chunk0: HashSet<usize> = priorities[0+3*idx].iter().map(|p| *p).collect();
let chunk1: HashSet<usize> = priorities[1+3*idx].iter().map(|p| *p).collect();
let chunk2: HashSet<usize> = priorities[2+3*idx].iter().map(|p| *p).collect();
let inter: HashSet<usize> = chunk0.intersection(&chunk1).map(Clone::clone).collect();
let inter: HashSet<usize> = inter.intersection(&chunk2).map(Clone::clone).collect();
assert_eq!(inter.len(), 1);
let common = inter.into_iter().next().unwrap();
eprintln!("{:?}", common);
tot += common;
}
eprintln!("priorities: {}", tot);
}
fn p04_pair(input: &str) -> nom::IResult<&str, (usize, usize)> {
let (input, x) = nom::character::complete::u64(input)?;
let (input, _) = nom::character::complete::char('-')(input)?;
let (input, y) = nom::character::complete::u64(input)?;
Ok((input, (x as usize, y as usize)))
}
pub fn p04() {
let contents = r#"2-4,6-8
2-3,4-5
5-7,7-9
2-8,3-7
6-6,4-6
2-6,4-8"#;
let contents = std::fs::read_to_string("./assets/adv2022/adv04.txt").unwrap();
let pairs: usize = contents.trim().split("\n").map(|line| {
let (_, ((x0, y0), _, (x1, y1))) = nom::sequence::tuple((
p04_pair,
// nom::character::complete::char(','),
nom::bytes::complete::tag(","),
p04_pair,
))(line).unwrap();
(x0, y0, x1, y1)
}).filter(|(x0, y0, x1, y1)| {
(x0 <= x1 && y0 >= y1) ||
(x0 >= x1 && y0 <= y1)
}).count();
eprintln!("pairs: {}", pairs);
let pairs: usize = contents.trim().split("\n").map(|line| {
let (_, ((x0, y0), _, (x1, y1))) = nom::sequence::tuple((
p04_pair,
// nom::character::complete::char(','),
nom::bytes::complete::tag(","),
p04_pair,
))(line).unwrap();
(x0, y0, x1, y1)
}).filter(|(x0, y0, x1, y1)| {
!(x0 > y1 || y0 < x1)
}).count();
eprintln!("overlap pairs: {}", pairs);
}
fn p05_stack(input: &str) -> nom::IResult<&str, Vec<Vec<Option<char>>>> {
let bucket = nom::sequence::delimited(
nom::character::complete::char('['),
nom::character::complete::anychar,
nom::character::complete::char(']'),
);
let empty = nom::multi::count(
nom::character::complete::char(' '),
3
);
let cell1 = nom::combinator::map(bucket, |c| Some(c));
let cell2 = nom::combinator::map(empty, |c| None);
let cell = nom::branch::alt((cell1, cell2));
let cells = nom::multi::separated_list1(nom::character::complete::char(' '), cell);
let (input, cells) = nom::multi::separated_list0(nom::character::complete::newline, cells)(input)?;
let idx = nom::sequence::delimited(
nom::character::complete::char(' '),
nom::character::complete::u8,
nom::character::complete::char(' '),
);
let (input, _) = nom::character::complete::newline(input)?;
let (input, index) = nom::multi::separated_list0(nom::character::complete::char(' '), idx)(input)?;
let width = index.len();
assert!(index == (0..width).map(|w| w as u8 +1).collect::<Vec<u8>>());
assert!(cells.iter().all(|row| row.len() == width));
let height = cells.len();
let mut stacks = Vec::with_capacity(width);
for column in 0..width {
let mut stack: Vec<_> = (0..height).into_iter().map(|row| cells[row][column]).collect();
stack.reverse();
stacks.push(stack);
}
Ok((input, stacks))
}
#[derive(Debug, Clone)]
struct P05Cmd {
from: usize,
to: usize,
count: usize,
}
fn p05_cmd(input: &str) -> nom::IResult<&str, Vec<P05Cmd>> {
let line = |input| -> nom::IResult<&str, P05Cmd> {
let (input, _) = nom::bytes::complete::tag("move ")(input)?;
let (input, count) = nom::character::complete::u8(input)?;
let (input, _) = nom::bytes::complete::tag(" from ")(input)?;
let (input, from) = nom::character::complete::u8(input)?;
let (input, _) = nom::bytes::complete::tag(" to ")(input)?;
let (input, to) = nom::character::complete::u8(input)?;
Ok((input, P05Cmd { from: from as usize - 1, to: to as usize - 1, count: count as usize }))
};
nom::multi::separated_list0(nom::character::complete::newline, line)(input)
}
fn p05_process_step(stack: &mut Vec<Vec<Option<char>>>, from: usize, to: usize, width: &mut usize, height: &mut usize) {
let from_index = stack[from].iter().take_while(|c| c.is_some()).count();
let to_index = stack[to].iter().take_while(|c| c.is_some()).count();
if to_index >= *height {
stack.iter_mut().map(|column| column.push(None)).for_each(drop);
*height += 1;
}
assert!(from_index >= 1);
let c = stack[from][from_index-1].take();
stack[to][to_index] = c;
// 除了自己受影响,其他列也需要调整
if stack.iter().all(|column| column[*height-1].is_none()) {
stack.iter_mut().map(|column| {
let c = column.pop().unwrap();
debug_assert!(c.is_none());
}).for_each(drop);
*height -= 1;
}
}
fn p05_process(stack: &mut Vec<Vec<Option<char>>>, cmd: &P05Cmd, width: &mut usize, height: &mut usize, v2: bool) {
let P05Cmd { from, to, count } = cmd.clone();
if v2 {
for _ in 0..count {
p05_process_step(stack, from, to, width, height);
}
// 只需要把序号重新整理下就可以
let to_index = stack[to].iter().take_while(|c| c.is_some()).count();
assert!(to_index >= count);
stack[to][(to_index-count)..to_index].reverse();
} else {
for _ in 0..count {
p05_process_step(stack, from, to, width, height);
}
}
}
fn p05_display(stack: &mut Vec<Vec<Option<char>>>, width: usize, height: usize) {
for idx in 0..height {
for jdx in 0..width {
eprint!("{}", stack[jdx][idx].unwrap_or(' '));
}
eprintln!();
}
}
pub fn p05() {
let contents = r#" [D]
[N] [C]
[Z] [M] [P]
1 2 3
move 1 from 2 to 1
move 3 from 1 to 3
move 2 from 2 to 1
move 1 from 1 to 2"#;
let contents = &std::fs::read_to_string("./assets/adv2022/adv05.txt").unwrap();
let (_, (stack_orig, _, cmds)) = nom::sequence::tuple((
p05_stack,
nom::multi::many1(nom::character::complete::newline),
p05_cmd,
))(contents).unwrap();
let mut stack = stack_orig.clone();
let mut width = stack.len();
assert!(width > 0);
let mut height = stack[0].len();
assert!(height > 0);
for cmd in cmds.iter() {
// eprintln!("{:?}", stack);
p05_process(&mut stack, cmd, &mut width, &mut height, false);
}
// eprintln!("{:?}", stack);
// eprintln!("{:?}", cmds);
p05_display(&mut stack, width, height);
let mut stack = stack_orig.clone();
let mut width = stack.len();
assert!(width > 0);
let mut height = stack[0].len();
assert!(height > 0);
for cmd in cmds.iter() {
// eprintln!("{:?}", stack);
p05_process(&mut stack, cmd, &mut width, &mut height, true);
}
// eprintln!("{:?}", stack);
// eprintln!("{:?}", cmds);
p05_display(&mut stack, width, height);
}
pub fn p06() {
let contents = &std::fs::read_to_string("./assets/adv2022/adv06.txt").unwrap();
for contents in [
r#"mjqjpqmgbljsphdztnvjfqwrcgsmlb"#, // has some bugs.
r#"bvwbjplbgvbhsrlpgdmjqwftvncz"#,
r#"nppdvjthqldpwncqszvftbrmjlhg"#,
r#"nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg"#,
r#"zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw"#,
&std::fs::read_to_string("./assets/adv2022/adv06.txt").unwrap().trim(),
] {
// let mut buf: [char; 4] = [0 as char; 4];
// let mut is_marker;
// for (idx, marker) in contents.chars().enumerate() {
// buf.rotate_left(1);
// *buf.last_mut().unwrap() = marker;
//
// if idx < 4 { continue; }
// is_marker = true;
// 'is_dup: for idx in 0..buf.len() {
// for jdx in idx+1..buf.len() {
// if buf[idx] == buf[jdx] {
// is_marker = false;
// break 'is_dup;
// }
// }
// }
//
// if is_marker {
// eprintln!("found marker@{}: {:?}", idx+1, contents);
// break;
// }
// }
let characters: Vec<char> = contents.chars().collect();
let width: usize = 14;
let mut counts = [0; 26];
for (idx, character) in characters.iter().enumerate() {
let first = *character as u8 - 'a' as u8;
counts[first as usize] += 1;
if idx < width { continue; }
if !counts.iter().any(|c| *c > 1) {
eprintln!("found marker@{}: {:?}", idx, contents);
break;
}
let last = characters[idx - width] as u8 - 'a' as u8;
counts[last as usize] -= 1;
}
}
}
// P07 的难点在于,如果不单纯为了解决问题,我们需要构建一个简易的文件树系统,
// dir 相互移动,需要同时持有子节点和父节点,这显然就到了rust的不擅长领域。有GC
// 的语言,可以疯狂用 gc 做,有shared_ptr 可以用unsafe做,但rust不允许unsafe,
// 这就导致 Arc/Cell 等的大量嵌套。最后太过复杂,转而 Arean 方案。
#[derive(Debug)]
pub enum P07EntryType {
Dir,
File,
Root
}
#[derive(Debug, Default)]
pub struct P07System {
nodes_child: Vec<Vec<usize>>,
nodes_paren: Vec<usize>,
nodes_count: usize,
nodes_alive: usize,
nodes_infos: Vec<P07Info>,
}
#[derive(Debug, Default)]
pub struct P07Info {
name: String,
is_dir: bool,
is_file: bool,
is_root: bool,
size_file: Option<usize>,
size_dir: usize,
}
impl P07System {
fn root() -> Self {
let mut slf = Self::default();
let node_root = slf.new();
slf.nodes_child[node_root].push(node_root);
slf.nodes_paren[node_root] = node_root;
slf.nodes_infos[node_root] = P07Info::new_root();
slf.nodes_alive = 1;
slf.nodes_count = 1;
slf
}
pub fn new(&mut self) -> usize {
assert!(self.nodes_alive == self.nodes_count);
let node = self.nodes_count;
self.nodes_count += 1;
self.nodes_alive += 1;
self.nodes_child.push(vec![]);
self.nodes_paren.push(node);
self.nodes_infos.push(P07Info::default());
node
}
pub fn parse_new_item(&mut self, node: usize, item: P07Info) {
let mut node_found = None;
for &child in self.nodes_child[node].iter() {
if self.nodes_infos[child].name == item.name {
node_found = Some(child);
break;
}
}
if node_found.is_none() {
let node_new = self.new();
node_found.replace(node_new);
}
let node_found = node_found.unwrap();
self.nodes_infos[node_found] = item;
self.nodes_paren[node_found] = node;
self.nodes_child[node].push(node_found);
}
pub fn parse_cd(&mut self, paren: usize, name: String) -> usize {
if name == "/" { return 0; }
if name == ".." { return self.nodes_paren[paren]; }
for &node in self.nodes_child[paren].iter() {
let info = &self.nodes_infos[node];
if info.name == name { return node; }
}
let node = self.new();
self.nodes_paren[node] = paren;
self.nodes_infos[node] = P07Info::new_dir(name);
return node;
}
}
impl P07Info {
fn new_dir(name: impl Into<String>) -> Self {
let mut slf = Self::default();
slf.name = name.into();
slf.is_dir = true;
slf
}
fn new_root() -> Self {
let mut slf = Self::new_dir("/");
slf.is_root = true;
slf
}
fn new_file(name: impl Into<String>, size: usize) -> Self {
let mut slf = Self::default();
slf.name = name.into();
slf.is_file = true;
slf.size_file = Some(size);
slf
}
}
pub enum P07Cmd {
Cd(String),
Ls,
}
fn p07_parse_cmd(input: &str) -> nom::IResult<&str, P07Cmd> {
let (input, _) = nom::bytes::complete::tag("$ ")(input)?;
let cd = nom::sequence::preceded(
nom::bytes::complete::tag("cd "),
nom::multi::many1(nom::character::complete::satisfy(|c| c.is_alphanumeric() || c == '/' || c == '.')),
);
let ls = nom::bytes::complete::tag("ls");
let (input, cmd) = nom::branch::alt((
nom::combinator::map(cd, |ss: Vec<char>| P07Cmd::Cd(ss.into_iter().collect())),
nom::combinator::map(ls, |_| P07Cmd::Ls),
))(input)?;
let (input, _) = nom::character::complete::newline(input)?;
Ok((input, cmd))
}
fn p07_parse_ls(input: &str) -> nom::IResult<&str, Vec<P07Info>> {
let dir = nom::sequence::preceded(
nom::bytes::complete::tag("dir "),
nom::multi::many1(nom::character::complete::satisfy(|c| c.is_alphanumeric() || c == '/')),
);
let file = nom::sequence::tuple((
nom::character::complete::u64::<&str, _>,
nom::character::complete::space1,
nom::multi::many1(nom::character::complete::satisfy(|c| c.is_alphanumeric() || c == '.')),
));
let dir = nom::combinator::map(dir, |name| {
let mut info = P07Info::default();
let name: String = name.into_iter().collect();
info.is_dir = true;
info.is_root = name == "/";
info.name = name;
info
});
let file = nom::combinator::map(file, |(fsize, _, fname)| {
let mut info = P07Info::default();
info.name = fname.into_iter().collect();
info.is_file = true;
info.size_file = Some(fsize as usize);
info
});
let dir_or_file = nom::branch::alt((dir, file));
let (input, out) = nom::multi::separated_list0(nom::character::complete::newline, dir_or_file)(input)?;
let (input, _) = nom::character::complete::newline(input)?;
Ok((input, out))
}
fn p07_with_cmd(dir: &mut P07System, node: usize, stdout: &str) {
if stdout.is_empty() { return; }
let (stdout, cmd) = p07_parse_cmd(stdout).unwrap();
match cmd {
P07Cmd::Cd(folder) => {
let node = dir.parse_cd(node, folder);
p07_with_cmd(dir, node, stdout);
},
P07Cmd::Ls => {
let (stdout, items) = p07_parse_ls(stdout).unwrap();
for item in items {
dir.parse_new_item(node, item)
}
p07_with_cmd(dir, node, stdout);
}
}
}
fn p07_walk_display(dir: &P07System, node: usize, tab: usize) {
let print_space = || { for _ in 0..tab { eprint!(" "); } };
if dir.nodes_infos[node].is_dir {
print_space(); eprintln!("- {} (dir, {})", dir.nodes_infos[node].name, dir.nodes_infos[node].size_dir);
for &child in dir.nodes_child[node].iter() {
if child == node { continue; }
p07_walk_display(dir, child, tab+1);
}
} else if dir.nodes_infos[node].is_file {
print_space(); eprintln!("- {} (file, size={})", dir.nodes_infos[node].name, dir.nodes_infos[node].size_file.unwrap());
}
}
fn p07_walk_fill_size(dir: &mut P07System, node: usize) -> usize {
if dir.nodes_infos[node].is_dir {
let mut size_tot = 0;
for &child in dir.nodes_child[node].clone().iter() {
if child == node { continue; }
size_tot += p07_walk_fill_size(dir, child);
}
dir.nodes_infos[node].size_dir = size_tot;
return size_tot;
} else if dir.nodes_infos[node].is_file {
dir.nodes_infos[node].size_file.unwrap()
} else {
0
}
}
fn p07_walk_find_small_folder(dir: &P07System, node: usize, sum: &mut usize) {
if dir.nodes_infos[node].is_dir {
if dir.nodes_infos[node].size_dir < 100000 { *sum += dir.nodes_infos[node].size_dir; }
for &child in dir.nodes_child[node].iter() {
if child == node { continue; }
p07_walk_find_small_folder(dir, child, sum);
}
}
}
fn p07_walk_find_smallest_big_folder(dir: &P07System, node: usize, threshold: usize, big_folders: &mut Vec<(usize, usize)>) {
if dir.nodes_infos[node].is_dir {
if dir.nodes_infos[node].size_dir >= threshold { big_folders.push((dir.nodes_infos[node].size_dir, node)); }
for &child in dir.nodes_child[node].iter() {
if child == node { continue; }
p07_walk_find_smallest_big_folder(dir, child, threshold, big_folders);
}
}
}
pub fn p07() {
let contents = r#"$ cd /
$ ls
dir a
14848514 b.txt
8504156 c.dat
dir d
$ cd a
$ ls
dir e
29116 f
2557 g
62596 h.lst
$ cd e
$ ls
584 i
$ cd ..
$ cd ..
$ cd d
$ ls
4060174 j
8033020 d.log
5626152 d.ext
7214296 k
"#;
// note the last newline must be used.
let contents = &std::fs::read_to_string("./assets/adv2022/adv07.txt").unwrap();
let mut root = P07System::root();
p07_with_cmd(&mut root, 0, contents);
p07_walk_fill_size(&mut root, 0);
p07_walk_display(&root, 0, 0);
let mut sum = 0;
p07_walk_find_small_folder(&root, 0, &mut sum);
eprintln!("All small folder: {}", sum);
let mut big_folders = vec![];
let threshold = 30000000 - (70000000 - root.nodes_infos[0].size_dir);
p07_walk_find_smallest_big_folder(&root, 0, threshold, &mut big_folders);
big_folders.sort();
eprintln!("{} => {:?}", threshold, big_folders);
}
fn p08_parse_height(input: &str) -> nom::IResult<&str, Vec<Vec<usize>>> {
nom::multi::separated_list1(
nom::character::complete::newline,
nom::multi::many1(nom::combinator::map(nom::character::complete::satisfy(|c: char| c.is_digit(10)), |v| (v as u8 - '0' as u8) as usize))
)(input)
}
fn p08_walk_visable(tree: &Vec<Vec<usize>>, visable: &mut Vec<Vec<bool>>, height: usize, width: usize, idx: usize, jdx: usize) -> bool {
true
}
pub fn p08() {
let contents = r#"30373
25512
65332
33549
35390"#;
let contents = &std::fs::read_to_string("./assets/adv2022/adv08.txt").unwrap();
let (_, trees) = p08_parse_height(&contents).unwrap();
let height = trees.len();
assert!(height > 0);
let width = trees[0].len();
assert!(width > 0);
let mut visable = vec![vec![false; width]; height];
let mut max_left_to_right = vec![vec![-1isize; width]; height];
let mut max_top_to_bottom = vec![vec![-1isize; width]; height];
let mut max_right_to_left = vec![vec![-1isize; width]; height];
let mut max_bottom_to_top = vec![vec![-1isize; width]; height];
for idx in 0..height {
max_left_to_right[idx][1] = trees[idx][0] as isize;
for jdx in 2..width {
max_left_to_right[idx][jdx] = max_left_to_right[idx][jdx-1].max( trees[idx][jdx-1] as isize );
}
}
for jdx in 0..width {
max_top_to_bottom[1][jdx] = trees[0][jdx] as isize;
for idx in 2..height {
max_top_to_bottom[idx][jdx] = max_top_to_bottom[idx-1][jdx].max( trees[idx-1][jdx] as isize );
}
}
for idx in 0..height {
max_right_to_left[idx][width-2] = trees[idx][width-1] as isize;
for jdx in (0..(width-2)).rev() {
max_right_to_left[idx][jdx] = max_right_to_left[idx][jdx+1].max( trees[idx][jdx+1] as isize);
}
}
for jdx in 0..width {
max_bottom_to_top[height-2][jdx] = trees[height-1][jdx] as isize;
for idx in (0..(height-2)).rev() {
max_bottom_to_top[idx][jdx] = max_bottom_to_top[idx+1][jdx].max(trees[idx+1][jdx] as isize);
}
}
for idx in 0..height {
for jdx in 0..width {
if idx == 0 || jdx == 0 || idx == height - 1 || jdx == width - 1 {
visable[idx][jdx] = true;
} else {
let height = trees[idx][jdx];
#[allow(unused_parens)]
if (
height as isize > max_left_to_right[idx][jdx] ||
height as isize > max_right_to_left[idx][jdx] ||
height as isize > max_top_to_bottom[idx][jdx] ||
height as isize > max_bottom_to_top[idx][jdx]
) {
visable[idx][jdx] = true;
}
}
}
}
// eprintln!("{:?}", trees);
// eprintln!("{:?}", visable);
let mut count = 0;
for idx in 0..height {
for jdx in 0..width {
if visable[idx][jdx] { count += 1; }
}
}
eprintln!("Tot: {}", count);
let mut max_left_to_right = vec![vec![1usize; width]; height];
let mut max_top_to_bottom = vec![vec![1usize; width]; height];
let mut max_right_to_left = vec![vec![1usize; width]; height];
let mut max_bottom_to_top = vec![vec![1usize; width]; height];
for idx in 0..height {
for jdx in 1..width {
let mut next = max_left_to_right[idx][jdx];
while jdx > next && trees[idx][jdx-next] < trees[idx][jdx] {
max_left_to_right[idx][jdx] += max_left_to_right[idx][jdx-next];
next = max_left_to_right[idx][jdx];
}
}
}
for jdx in 0..width {
for idx in 1..height {
let mut next = max_top_to_bottom[idx][jdx];
while idx > next && trees[idx-next][jdx] < trees[idx][jdx] {
max_top_to_bottom[idx][jdx] += max_top_to_bottom[idx-next][jdx];
next = max_top_to_bottom[idx][jdx];
}
}
}
for idx in 0..height {
for jdx in (0..(width-1)).rev() {
let mut next = max_right_to_left[idx][jdx];
while jdx + next < width - 1 && trees[idx][jdx+next] < trees[idx][jdx] {
max_right_to_left[idx][jdx] += max_right_to_left[idx][jdx+next];
next = max_right_to_left[idx][jdx];
}
}
}
for jdx in 0..width {
for idx in (1..(height-1)).rev() {
let mut next = max_bottom_to_top[idx][jdx];
while idx + next < height - 1 && trees[idx+next][jdx] < trees[idx][jdx] {
max_bottom_to_top[idx][jdx] += max_bottom_to_top[idx+next][jdx];
next = max_bottom_to_top[idx][jdx];
}
}
}
let mut score = 1;
for idx in 0..height {
for jdx in 0..width {
let lr = max_left_to_right[idx][jdx];
let tb = max_top_to_bottom[idx][jdx];
let rl = max_right_to_left[idx][jdx];
let bt = max_bottom_to_top[idx][jdx];
if idx == 0 || jdx == 0 || idx == height - 1 || jdx == width - 1 {
} else {
score = score.max(lr * tb *rl * bt);
}
// print!("({} {} {} {}) ", tb, lr, bt, rl);
}
// println!();
}
eprintln!("Ideal: {}", score);
}
#[derive(Debug, Copy, Clone)]
enum P09Motion { R, U,L,D }
fn p09_parse_motions(input: &str) -> nom::IResult<&str, Vec<(P09Motion, usize)>> {
use P09Motion::*;
let motion = nom::branch::alt((
nom::combinator::value(U, nom::character::complete::char::<&str, _>('U')),
nom::combinator::value(D, nom::character::complete::char::<&str, _>('D')),
nom::combinator::value(L, nom::character::complete::char::<&str, _>('L')),
nom::combinator::value(R, nom::character::complete::char::<&str, _>('R')),
));
nom::multi::separated_list0(
nom::character::complete::newline,
nom::sequence::tuple((
nom::sequence::terminated(motion, nom::character::complete::space1),
nom::combinator::map(nom::character::complete::u64, |s| s as usize),
)),
)(input)
}
#[derive(Debug, Default)]
struct P07Position {
hx: isize,
hy: isize,
tx: isize,
ty: isize,
}
impl P07Position {
pub fn walk(&mut self, motion: P09Motion) {
use P09Motion::*;
match motion {
L => { self.hx -= 1; },
R => { self.hx += 1; },
U => { self.hy += 1; },
D => { self.hy -= 1; },
}
if self.ty + 1 < self.hy {
self.ty = self.ty + 1;
self.tx = self.hx;
}
if self.ty > self.hy + 1 {
self.ty = self.ty - 1;
self.tx = self.hx;
}
if self.tx > self.hx + 1 {
self.tx = self.tx - 1;
self.ty = self.hy;
}
if self.tx + 1 < self.hx {
self.tx = self.tx + 1;
self.ty = self.hy;
}
}
}
fn p09_motion(motion: P09Motion, (hx, hy): &mut (isize, isize)) {
use P09Motion::*;
match motion {
L => { *hx -= 1; },
R => { *hx += 1; },
U => { *hy += 1; },
D => { *hy -= 1; },
}
}
fn p09_walk((hx, hy): &mut (isize, isize), (tx, ty): &mut (isize, isize)) {
let hsize = *hx - *tx; let vsize = *hy - *ty;
// 先排除相邻点位,剩下的规则就简单多了
if hsize.abs() + vsize.abs() <= 1 { return; }
if hsize.abs() == 1 && vsize.abs() == 1 { return; }
if hsize > 0 { *tx += 1; }
if hsize < 0 { *tx -= 1; }
if vsize > 0 { *ty += 1; }
if vsize < 0 { *ty -= 1; }
}
fn p09_display_knots(knots: &[(isize, isize)]) {
let mut x0 = 0; let mut x1 = 0;
let mut y0 = 0; let mut y1 = 0;
for &(px, py) in knots.iter() {
x0 = x0.min(px); x1 = x1.max(px);
y0 = y0.min(py); y1 = y1.max(py);
}
let mut bars = vec![vec![9999; (x1-x0) as usize + 1]; (y1-y0) as usize + 1];
bars[(0-y0) as usize][(0-x0) as usize] = 9998;
for (idx, (px, py)) in knots.iter().enumerate() {
bars[(py-y0) as usize][(px-x0) as usize] = idx.min(bars[(py-y0) as usize][(px-x0) as usize]);
}
bars.reverse();
// eprintln!("{:?}", (x0, y0, x1, y1));
for bar in bars.into_iter() {
for b in bar.into_iter() {
if b <= 9 {
print!("{}", b);
} else if b == 9998 {
print!("s");
} else {
print!(".");
}
}
println!();
}
}
fn p09_display<'a>(points_iter: impl Iterator<Item=&'a (isize, isize)>) {
let mut points: Vec<(isize, isize)> = vec![];
let mut x0 = 0; let mut x1 = 0;
let mut y0 = 0; let mut y1 = 0;
for &(px, py) in points_iter {
x0 = x0.min(px); x1 = x1.max(px);
y0 = y0.min(py); y1 = y1.max(py);
points.push((px, py));
}
let mut bars = vec![vec![false; (x1-x0) as usize + 1]; (y1-y0) as usize + 1];
for (px, py) in points.into_iter() {
bars[(py-y0) as usize][(px-x0) as usize] = true;
}
bars.reverse();
// eprintln!("{:?}", (x0, y0, x1, y1));
for bar in bars.into_iter() {