Last active
December 4, 2021 04:13
-
-
Save asonge/f50017d1b2a936f4d6a737c935243702 to your computer and use it in GitHub Desktop.
AoC 3.2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
L=require('fs').readFileSync(0,{encoding:'utf8'}).split("\n");B=L[0].length;a=[0,1].map(v=>{n=L.map(l=>parseInt(l,2));for(b=B-1;b>=0&&n.length>1;b--){c=[0,0];n.map(n=>c[n>>b&1]++);n=n.filter(n=>(n>>b&1)==v^(c[0]>c[1]))}return n[0];});console.log(a[0]*a[1]) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function ex2(lines) { | |
let o2lines = lines | |
let co2lines = lines | |
for(let i=0;i<lines[0].length;i++) { | |
let counts = [0,0] | |
o2lines.forEach(line => { | |
counts[+line[i]] += 1 | |
}) | |
if(counts[0] > counts[1]) { | |
o2lines = o2lines.length > 1 ? o2lines.filter(line => line[i]=='0') : o2lines | |
} else { | |
o2lines = o2lines.length > 1 ? o2lines.filter(line => line[i]=='1') : o2lines | |
} | |
} | |
for(let i=0;i<lines[0].length;i++) { | |
let counts = [0,0] | |
co2lines.forEach(line => { | |
counts[+line[i]] += 1 | |
}) | |
if(counts[0] > counts[1]) { | |
co2lines = co2lines.length > 1 ? co2lines.filter(line => line[i]=='1') : co2lines | |
} else { | |
co2lines = co2lines.length > 1 ? co2lines.filter(line => line[i]=='0') : co2lines | |
} | |
} | |
console.log(parseInt(o2lines[0],2)*parseInt(co2lines[0],2)) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function ex2_2(lines) { | |
let bits = lines[0].length; | |
let a = [0,0]; | |
for(let val=0;val<2;val++) { | |
let numbers = lines.map(line => parseInt(line, 2)); | |
let bit = bits; | |
for(bit=bits-1;bit>= 0&&numbers.length>1;bit--) { | |
let c = [0,0]; | |
numbers.map(n => c[n >> bit & 1]++) | |
// console.log(numbers, c); | |
numbers = numbers.filter(n=>(n>>bit&1)==val^(c[0]>c[1])) | |
if(numbers.length===1) break; | |
} | |
a[val] = numbers[0] | |
} | |
console.log(answers) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment