advent-of-code/12021/12/12.awk

73 lines
1018 B
Awk

# queue
function enq( d ){
q[tail++] = d
}
function deq(){
return q[head++]
}
function peek(){
return q[head]
}
function qempty(){
return head>=tail
}
# paths
function linkedto(path, d ){
t = path
gsub(d,"",t)
gsub("-","",t)
return t
}
function dests(arr,node){
delete arr
p=0
for( i in path ){
if(path[i]~node){
arr[p++] = linkedto(path[i],node)
}
}
}
function hasduplicate( str ){ # true if lowercase duplicates
split(str, arr, ",")
for(i in arr){
if( tolower(arr[i]) == arr[i]){
for( j in arr ){
if (i!=j && arr[i] == arr[j])
return 1
}
}
}
return 0
}
{
path[NR] = $0
}
END{
s = "start"
enq(s)
do{
if(peek()~"end"){
stack[sp++] = deq() # done
}
else if(hasduplicate(peek())){
deq()
}
else if(!qempty()){
s=deq(); #print "deq:", s, head, tail
split(s, arr, ",")
nd = arr[length(arr)]
dests(a, nd)
for(i in a){
enq( s "," a[i] )
# print "enq:", s "," a[i]
}
}
}while(!qempty())
# for(i in stack) print stack[i]
print sp
}