-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtask_7_2.pl
139 lines (109 loc) · 2.74 KB
/
task_7_2.pl
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
#!/usr/bin/perl
#===============================================================================
#
# FILE: t7.pl
#
# USAGE: ./t7.pl
#
# DESCRIPTION: Solution for https://adventofcode.com/2018/day/7 part 2
#
# OPTIONS: ---
# REQUIREMENTS: ---
# BUGS: ---
# NOTES: ---
# AUTHOR: Lubos Kolouch
# ORGANIZATION:
# VERSION: 1.0
# CREATED: 12/07/2018 08:43:41 AM
# REVISION: ---
#===============================================================================
#
# worker_task - {id}->{task}
# ->{end}
#
#
# task_depend - {next}->{task_before}
# ->{task_before2}
#
# all_tasks
use strict;
use warnings;
use autodie;
use 5.026;
my %task_depend;
my %all_tasks;
my %task_in_progress;
my %worker_task;
my @finished_tasks;
my $actors = shift // 5;
my $task_duration = shift // 60;
my $step = -1;
open( my $file, '<', 'input7.txt' );
sub load_tasks {
while (<$file>) {
my ( $first, $second ) = $_ =~ /Step\h+(.).*?step\h+(.)/msx;
$task_depend{$second}{$first} = 1;
$all_tasks{$first} = 1;
$all_tasks{$second} = 1;
}
close $file;
return 1;
}
sub is_free_worker {
my $id = shift;
return 1 unless $worker_task{$id};
return 0;
}
sub next_available_task {
my $what;
for ( sort keys %all_tasks ) {
next if $task_in_progress{$_};
unless ( defined $task_depend{$_} ) {
$task_in_progress{$_} = 1;
return $_;
}
}
return 0;
}
sub cleanup_task {
my $what = shift;
for ( keys %all_tasks ) {
delete $task_depend{$_}{$what} if defined $task_depend{$_}{$what};
delete $task_depend{$_} if scalar keys %{ $task_depend{$_} } == 0;
}
push @finished_tasks, $what;
return 1;
}
sub cleanup_worker_task {
for ( keys %worker_task ) {
if ( $worker_task{$_}->{end} == $step ) {
cleanup_task( $worker_task{$_}{task} );
delete $worker_task{$_};
}
}
return 1;
}
sub print_worker_tasks {
print $step. ' ';
defined $worker_task{$_} ? print $worker_task{$_}{task} . ' ' : print '. ' for ( 1 .. $actors );
say join '', @finished_tasks;
return 1;
}
sub main {
load_tasks;
say "S " . join ' ', 1 .. $actors;
while ( scalar %all_tasks > scalar @finished_tasks ) {
$step++;
cleanup_worker_task;
for ( 1 .. $actors ) {
next unless is_free_worker($_);
my $what = next_available_task;
last unless $what;
$worker_task{$_}->{task} = $what;
$worker_task{$_}->{end} = $step + ord($what) - 64 + $task_duration;
}
print_worker_tasks;
}
return 1;
}
main;