Browse Source

Day 3

master
William Davis 8 months ago
parent
commit
70d00df1a2
  1. 1000
      03/data
  2. 97
      03/main.awk

1000
03/data

File diff suppressed because it is too large Load Diff

97
03/main.awk

@ -0,0 +1,97 @@
function decimal(b) {
dec = 0 # LOL
split(b, digits, "")
for ( place = 1; place <= length(digits); place++ ) {
dec += digits[place] * 2 ** ( length(b) - place )
}
return dec
}
function rating(seq_array) {
digit = 1
while ( length(seq_array) > 1 ) {
tally = 0
# finding most common digit at index
for ( item in seq_array ) {
tally += substr(seq_array[item],digit,1)
}
if ( tally >= length(seq_array) / 2 ) { choice = 1 }
if ( tally < length(seq_array) / 2 ) { choice = 0 }
# print "choice was: " choice
# delete non matching items from array
for ( item in seq_array ) {
# print substr(seq_array[item],digit,1) "---? " digit
if ( substr(seq_array[item],digit,1) != choice ) { delete seq_array[item] }
}
digit += 1
# print "index: " digit
}
for ( item in seq_array ) { return seq_array[item] }
}
function unrating(seq_array) {
digit = 1
while ( length(seq_array) > 1 ) {
tally = 0
for ( item in seq_array ) {
tally += substr(seq_array[item],digit,1)
}
if ( tally >= length(seq_array) / 2 ) { choice = 0 } # trivially reversed
if ( tally < length(seq_array) / 2 ) { choice = 1 }
for ( item in seq_array ) {
if ( substr(seq_array[item],digit,1) != choice ) { delete seq_array[item] }
}
digit += 1
}
for ( item in seq_array ) { return seq_array[item] }
}
# ----------------------
function reductor(num) {
if ( num == 500 ) { print "WARNING" }
if ( num < NR / 2 )
return 0
return 1
}
function deductor(num) {
if ( num == 500 ) { print "WARNING" }
if ( num < NR / 2 )
return 1
return 0
}
BEGIN {
FS="";
my_index = 1
}
{
for ( i = 1; i <= length($0); i++ ) array[i] += $i
bin[NR] = $0
oxygen[NR] = $0
dioxide[NR] = $0
}
END {
for ( i = 1; i <= length($0); i++ ) {
gamma = gamma reductor(array[i]) # string append
epsilon = epsilon deductor(array[i]) # good place for ` * 0 ` additive identity?
}
print decimal(gamma) " * " decimal(epsilon) " = " decimal(gamma) * decimal(epsilon)
print " ---- problem 2 ---- "
print decimal(rating(oxygen)) * decimal(unrating(dioxide)) # 5941884
}
Loading…
Cancel
Save