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

81 lines
1.1 KiB
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 ){ # new rule for part 2
split(str, arr, ",")
sing = 0
for(i in arr){
if( tolower(arr[i]) == arr[i]){ # if lowercase
count = 0
for( j in arr ){
if (i!=j && arr[i] == arr[j]) count++
}
if( arr[i]=="start" ){
if(count>0) return 1
} else{
if(count>0) sing++
if(count>1 || sing>2) 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()
split(s, arr, ",")
nd = arr[length(arr)]
dests(a, nd)
for(i in a){
enq( s "," a[i] )
}
}
}while(!qempty())
# for(i in stack) print stack[i]
print sp
}