Last active
February 23, 2017 00:02
-
-
Save ClemRz/344a173e70b775139c73 to your computer and use it in GitHub Desktop.
My solutions to Advent Of Code 2015 puzzles
This file contains 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
/** PART I **/ | |
var str = $('pre').innerHTML, | |
count = 0; | |
for (var i = 0; i < str.length; i++) { | |
count += str[i] === '(' ? 1 : -1; | |
} | |
console.log(count); | |
/** PART II **/ | |
var str = $('pre').innerHTML, | |
count = 0; | |
for (var i = 0; i < str.length; i++) { | |
count += str[i] === '(' ? 1 : -1; | |
if (count < 0) { | |
console.log(i+1); | |
break; | |
} | |
} |
This file contains 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
/** PART I **/ | |
$('pre').innerHTML | |
.match(/[^\n]+/g) | |
.map(function(str) { | |
var a = str.split('x'), | |
l = a[0] * 1, | |
h = a[1] * 1, | |
w = a[2] * 1, | |
s = [l * w, w * h, h * l]; | |
return s.reduce((p, c) => p + 2 * c, 0) + Math.min(...s); | |
}) | |
.reduce((p, c) => p + c); | |
/** PART II **/ | |
$('pre').innerHTML | |
.match(/[^\n]+/g) | |
.map(function(str) { | |
var a = str.split('x'), | |
l = a[0] * 1, | |
h = a[1] * 1, | |
w = a[2] * 1, | |
s = [l + w, w + h, h + l]; | |
return 2 * Math.min(...s) + l * h * w; | |
}) | |
.reduce((p, c) => p + c); |
This file contains 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
/** PART I **/ | |
Object.size = function(obj) { | |
var size = 0, key; | |
for (key in obj) { | |
if (obj.hasOwnProperty(key)) size += typeof obj[key] === "object" ? Object.size(obj[key]) : 1; | |
} | |
return size; | |
}; | |
var m = {0: {0: 1}}, | |
x = 0, | |
y = 0; | |
$('pre').innerHTML | |
.match(/(>|<|\^|v)/g) | |
.forEach(function (d) { | |
switch (d) { | |
case '>': | |
x++; | |
break; | |
case '<': | |
x--; | |
break; | |
case '^': | |
y++; | |
break; | |
case 'v': | |
y--; | |
break; | |
} | |
if (m[x] === undefined) m[x] = {}; | |
if (m[x][y] === undefined) m[x][y] = 0 | |
m[x][y]++; | |
}); | |
Object.size(m); | |
/** PART II **/ | |
Object.size = function(obj) { | |
var size = 0, key; | |
for (key in obj) { | |
if (obj.hasOwnProperty(key)) size += typeof obj[key] === "object" ? Object.size(obj[key]) : 1; | |
} | |
return size; | |
}; | |
function move(person, direction) { | |
switch (direction) { | |
case '>': | |
person.x++; | |
break; | |
case '<': | |
person.x--; | |
break; | |
case '^': | |
person.y++; | |
break; | |
case 'v': | |
person.y--; | |
break; | |
} | |
} | |
function drop(person) { | |
if (m[person.x] === undefined) m[person.x] = {}; | |
if (m[person.x][person.y] === undefined) m[person.x][person.y] = 0 | |
m[person.x][person.y]++; | |
} | |
var m = {0: {0: 2}}, | |
gps = {santa: {x: 0, y:0}, robot: {x: 0, y:0}}, | |
map = $('pre').innerHTML.match(/(>|<|\^|v)/g); | |
for(var i=0;i<map.length;i+=2) { | |
move(gps.santa, map[i]); | |
drop(gps.santa); | |
move(gps.robot, map[i+1]); | |
drop(gps.robot); | |
} | |
Object.size(m); |
This file contains 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
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Day 4</title> | |
<script> | |
/* | |
* A JavaScript implementation of the RSA Data Security, Inc. MD5 Message | |
* Digest Algorithm, as defined in RFC 1321. | |
* Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 | |
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet | |
* Distributed under the BSD License | |
* See http://pajhome.org.uk/crypt/md5 for more info. | |
*/ | |
/* | |
* Configurable variables. You may need to tweak these to be compatible with | |
* the server-side, but the defaults work in most cases. | |
*/ | |
var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */ | |
var b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance */ | |
/* | |
* These are the functions you'll usually want to call | |
* They take string arguments and return either hex or base-64 encoded strings | |
*/ | |
function hex_md5(s) { return rstr2hex(rstr_md5(str2rstr_utf8(s))); } | |
function b64_md5(s) { return rstr2b64(rstr_md5(str2rstr_utf8(s))); } | |
function any_md5(s, e) { return rstr2any(rstr_md5(str2rstr_utf8(s)), e); } | |
function hex_hmac_md5(k, d) | |
{ return rstr2hex(rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d))); } | |
function b64_hmac_md5(k, d) | |
{ return rstr2b64(rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d))); } | |
function any_hmac_md5(k, d, e) | |
{ return rstr2any(rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d)), e); } | |
/* | |
* Perform a simple self-test to see if the VM is working | |
*/ | |
function md5_vm_test() | |
{ | |
return hex_md5("abc").toLowerCase() == "900150983cd24fb0d6963f7d28e17f72"; | |
} | |
/* | |
* Calculate the MD5 of a raw string | |
*/ | |
function rstr_md5(s) | |
{ | |
return binl2rstr(binl_md5(rstr2binl(s), s.length * 8)); | |
} | |
/* | |
* Calculate the HMAC-MD5, of a key and some data (raw strings) | |
*/ | |
function rstr_hmac_md5(key, data) | |
{ | |
var bkey = rstr2binl(key); | |
if(bkey.length > 16) bkey = binl_md5(bkey, key.length * 8); | |
var ipad = Array(16), opad = Array(16); | |
for(var i = 0; i < 16; i++) | |
{ | |
ipad[i] = bkey[i] ^ 0x36363636; | |
opad[i] = bkey[i] ^ 0x5C5C5C5C; | |
} | |
var hash = binl_md5(ipad.concat(rstr2binl(data)), 512 + data.length * 8); | |
return binl2rstr(binl_md5(opad.concat(hash), 512 + 128)); | |
} | |
/* | |
* Convert a raw string to a hex string | |
*/ | |
function rstr2hex(input) | |
{ | |
try { hexcase } catch(e) { hexcase=0; } | |
var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef"; | |
var output = ""; | |
var x; | |
for(var i = 0; i < input.length; i++) | |
{ | |
x = input.charCodeAt(i); | |
output += hex_tab.charAt((x >>> 4) & 0x0F) | |
+ hex_tab.charAt( x & 0x0F); | |
} | |
return output; | |
} | |
/* | |
* Convert a raw string to a base-64 string | |
*/ | |
function rstr2b64(input) | |
{ | |
try { b64pad } catch(e) { b64pad=''; } | |
var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; | |
var output = ""; | |
var len = input.length; | |
for(var i = 0; i < len; i += 3) | |
{ | |
var triplet = (input.charCodeAt(i) << 16) | |
| (i + 1 < len ? input.charCodeAt(i+1) << 8 : 0) | |
| (i + 2 < len ? input.charCodeAt(i+2) : 0); | |
for(var j = 0; j < 4; j++) | |
{ | |
if(i * 8 + j * 6 > input.length * 8) output += b64pad; | |
else output += tab.charAt((triplet >>> 6*(3-j)) & 0x3F); | |
} | |
} | |
return output; | |
} | |
/* | |
* Convert a raw string to an arbitrary string encoding | |
*/ | |
function rstr2any(input, encoding) | |
{ | |
var divisor = encoding.length; | |
var i, j, q, x, quotient; | |
/* Convert to an array of 16-bit big-endian values, forming the dividend */ | |
var dividend = Array(Math.ceil(input.length / 2)); | |
for(i = 0; i < dividend.length; i++) | |
{ | |
dividend[i] = (input.charCodeAt(i * 2) << 8) | input.charCodeAt(i * 2 + 1); | |
} | |
/* | |
* Repeatedly perform a long division. The binary array forms the dividend, | |
* the length of the encoding is the divisor. Once computed, the quotient | |
* forms the dividend for the next step. All remainders are stored for later | |
* use. | |
*/ | |
var full_length = Math.ceil(input.length * 8 / | |
(Math.log(encoding.length) / Math.log(2))); | |
var remainders = Array(full_length); | |
for(j = 0; j < full_length; j++) | |
{ | |
quotient = Array(); | |
x = 0; | |
for(i = 0; i < dividend.length; i++) | |
{ | |
x = (x << 16) + dividend[i]; | |
q = Math.floor(x / divisor); | |
x -= q * divisor; | |
if(quotient.length > 0 || q > 0) | |
quotient[quotient.length] = q; | |
} | |
remainders[j] = x; | |
dividend = quotient; | |
} | |
/* Convert the remainders to the output string */ | |
var output = ""; | |
for(i = remainders.length - 1; i >= 0; i--) | |
output += encoding.charAt(remainders[i]); | |
return output; | |
} | |
/* | |
* Encode a string as utf-8. | |
* For efficiency, this assumes the input is valid utf-16. | |
*/ | |
function str2rstr_utf8(input) | |
{ | |
var output = ""; | |
var i = -1; | |
var x, y; | |
while(++i < input.length) | |
{ | |
/* Decode utf-16 surrogate pairs */ | |
x = input.charCodeAt(i); | |
y = i + 1 < input.length ? input.charCodeAt(i + 1) : 0; | |
if(0xD800 <= x && x <= 0xDBFF && 0xDC00 <= y && y <= 0xDFFF) | |
{ | |
x = 0x10000 + ((x & 0x03FF) << 10) + (y & 0x03FF); | |
i++; | |
} | |
/* Encode output as utf-8 */ | |
if(x <= 0x7F) | |
output += String.fromCharCode(x); | |
else if(x <= 0x7FF) | |
output += String.fromCharCode(0xC0 | ((x >>> 6 ) & 0x1F), | |
0x80 | ( x & 0x3F)); | |
else if(x <= 0xFFFF) | |
output += String.fromCharCode(0xE0 | ((x >>> 12) & 0x0F), | |
0x80 | ((x >>> 6 ) & 0x3F), | |
0x80 | ( x & 0x3F)); | |
else if(x <= 0x1FFFFF) | |
output += String.fromCharCode(0xF0 | ((x >>> 18) & 0x07), | |
0x80 | ((x >>> 12) & 0x3F), | |
0x80 | ((x >>> 6 ) & 0x3F), | |
0x80 | ( x & 0x3F)); | |
} | |
return output; | |
} | |
/* | |
* Encode a string as utf-16 | |
*/ | |
function str2rstr_utf16le(input) | |
{ | |
var output = ""; | |
for(var i = 0; i < input.length; i++) | |
output += String.fromCharCode( input.charCodeAt(i) & 0xFF, | |
(input.charCodeAt(i) >>> 8) & 0xFF); | |
return output; | |
} | |
function str2rstr_utf16be(input) | |
{ | |
var output = ""; | |
for(var i = 0; i < input.length; i++) | |
output += String.fromCharCode((input.charCodeAt(i) >>> 8) & 0xFF, | |
input.charCodeAt(i) & 0xFF); | |
return output; | |
} | |
/* | |
* Convert a raw string to an array of little-endian words | |
* Characters >255 have their high-byte silently ignored. | |
*/ | |
function rstr2binl(input) | |
{ | |
var output = Array(input.length >> 2); | |
for(var i = 0; i < output.length; i++) | |
output[i] = 0; | |
for(var i = 0; i < input.length * 8; i += 8) | |
output[i>>5] |= (input.charCodeAt(i / 8) & 0xFF) << (i%32); | |
return output; | |
} | |
/* | |
* Convert an array of little-endian words to a string | |
*/ | |
function binl2rstr(input) | |
{ | |
var output = ""; | |
for(var i = 0; i < input.length * 32; i += 8) | |
output += String.fromCharCode((input[i>>5] >>> (i % 32)) & 0xFF); | |
return output; | |
} | |
/* | |
* Calculate the MD5 of an array of little-endian words, and a bit length. | |
*/ | |
function binl_md5(x, len) | |
{ | |
/* append padding */ | |
x[len >> 5] |= 0x80 << ((len) % 32); | |
x[(((len + 64) >>> 9) << 4) + 14] = len; | |
var a = 1732584193; | |
var b = -271733879; | |
var c = -1732584194; | |
var d = 271733878; | |
for(var i = 0; i < x.length; i += 16) | |
{ | |
var olda = a; | |
var oldb = b; | |
var oldc = c; | |
var oldd = d; | |
a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936); | |
d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586); | |
c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819); | |
b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330); | |
a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897); | |
d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426); | |
c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341); | |
b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983); | |
a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416); | |
d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417); | |
c = md5_ff(c, d, a, b, x[i+10], 17, -42063); | |
b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162); | |
a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682); | |
d = md5_ff(d, a, b, c, x[i+13], 12, -40341101); | |
c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290); | |
b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329); | |
a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510); | |
d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632); | |
c = md5_gg(c, d, a, b, x[i+11], 14, 643717713); | |
b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302); | |
a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691); | |
d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083); | |
c = md5_gg(c, d, a, b, x[i+15], 14, -660478335); | |
b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848); | |
a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438); | |
d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690); | |
c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961); | |
b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501); | |
a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467); | |
d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784); | |
c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473); | |
b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734); | |
a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558); | |
d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463); | |
c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562); | |
b = md5_hh(b, c, d, a, x[i+14], 23, -35309556); | |
a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060); | |
d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353); | |
c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632); | |
b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640); | |
a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174); | |
d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222); | |
c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979); | |
b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189); | |
a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487); | |
d = md5_hh(d, a, b, c, x[i+12], 11, -421815835); | |
c = md5_hh(c, d, a, b, x[i+15], 16, 530742520); | |
b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651); | |
a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844); | |
d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415); | |
c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905); | |
b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055); | |
a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571); | |
d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606); | |
c = md5_ii(c, d, a, b, x[i+10], 15, -1051523); | |
b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799); | |
a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359); | |
d = md5_ii(d, a, b, c, x[i+15], 10, -30611744); | |
c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380); | |
b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649); | |
a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070); | |
d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379); | |
c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259); | |
b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551); | |
a = safe_add(a, olda); | |
b = safe_add(b, oldb); | |
c = safe_add(c, oldc); | |
d = safe_add(d, oldd); | |
} | |
return Array(a, b, c, d); | |
} | |
/* | |
* These functions implement the four basic operations the algorithm uses. | |
*/ | |
function md5_cmn(q, a, b, x, s, t) | |
{ | |
return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b); | |
} | |
function md5_ff(a, b, c, d, x, s, t) | |
{ | |
return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); | |
} | |
function md5_gg(a, b, c, d, x, s, t) | |
{ | |
return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); | |
} | |
function md5_hh(a, b, c, d, x, s, t) | |
{ | |
return md5_cmn(b ^ c ^ d, a, b, x, s, t); | |
} | |
function md5_ii(a, b, c, d, x, s, t) | |
{ | |
return md5_cmn(c ^ (b | (~d)), a, b, x, s, t); | |
} | |
/* | |
* Add integers, wrapping at 2^32. This uses 16-bit operations internally | |
* to work around bugs in some JS interpreters. | |
*/ | |
function safe_add(x, y) | |
{ | |
var lsw = (x & 0xFFFF) + (y & 0xFFFF); | |
var msw = (x >> 16) + (y >> 16) + (lsw >> 16); | |
return (msw << 16) | (lsw & 0xFFFF); | |
} | |
/* | |
* Bitwise rotate a 32-bit number to the left. | |
*/ | |
function bit_rol(num, cnt) | |
{ | |
return (num << cnt) | (num >>> (32 - cnt)); | |
} | |
/** PART I **/ | |
var key = 'iwrupvqb', n = 0, m; | |
while(hex_md5(key+n).slice(0, 5) !== '00000') n++; | |
console.log(n); | |
console.log(hex_md5(key+n)); | |
/** PART II **/ | |
m = n + 1; | |
while(hex_md5(key+m).slice(0, 6) !== '000000') m++; | |
console.log(m); | |
console.log(hex_md5(key+m)); | |
</script> | |
</head> | |
<body></body> | |
</html> |
This file contains 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
/** PART I **/ | |
function has3Vowels(str) { | |
return /(?:[^aeiou\W]*[aeiuo]){3,}[^aeiou\W]*/g.test(str); | |
} | |
function hasTwiceALetter(str) { | |
return /(\w)(\1+)/g.test(str); | |
} | |
function containsOneBadStr(str) { | |
return /(ab|cd|pq|xy)/g.test(str); | |
} | |
$('pre').innerHTML | |
.match(/[^\n]+/g) | |
.map(function (str) { | |
return has3Vowels(str) && hasTwiceALetter(str) && !containsOneBadStr(str) ? 1 : 0; | |
}) | |
.reduce((p, c) => p + c, 0); | |
/** PART II **/ | |
function hasTwiceAPairOfLetters(str) { | |
return /([\w]{2}).*\1+/g.test(str); | |
} | |
function hasASandwichRepetition(str) { | |
return /([\w]).\1/g.test(str); | |
} | |
$('pre').innerHTML | |
.match(/[^\n]+/g) | |
.map(function (str) { | |
return hasTwiceAPairOfLetters(str) && hasASandwichRepetition(str) ? 1 : 0; | |
}) | |
.reduce((p, c) => p + c, 0); | |
This file contains 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
/** PART I **/ | |
function transform(str, light) { | |
if (str.indexOf('turn') > -1) { | |
return str.indexOf('on') > -1; | |
} | |
return !light; | |
} | |
var grid = {}, lightsOn = 0; | |
for(var i=0;i<1000;i++) { | |
grid[i] = {}; | |
for(var j=0;j<1000;j++) { | |
grid[i][j] = false; | |
} | |
} | |
$('pre').innerHTML | |
.match(/[^\n]+/g) | |
.map(function (str) { | |
var m = str.match(/(\d+)/g), | |
w = m[0]*1, | |
s = m[1]*1, | |
e = m[2]*1, | |
n = m[3]*1; | |
for(var i=w;i<e+1;i++) { | |
for(var j=s;j<n+1;j++) grid[i][j] = transform(str, grid[i][j]); | |
} | |
}); | |
for(var i=0;i<1000;i++) { | |
for(var j=0;j<1000;j++) { | |
lightsOn += grid[i][j]; | |
} | |
} | |
lightsOn; | |
/** PART II **/ | |
function transform(str, light) { | |
if (str.indexOf('turn') > -1) { | |
return str.indexOf('on') > -1 ? 1 : -1; | |
} | |
return 2; | |
} | |
var grid = {}, lightsOn = 0; | |
for(var i=0;i<1000;i++) { | |
grid[i] = {}; | |
for(var j=0;j<1000;j++) { | |
grid[i][j] = 0; | |
} | |
} | |
$('pre').innerHTML | |
.match(/[^\n]+/g) | |
.map(function (str) { | |
var m = str.match(/(\d+)/g), | |
w = m[0]*1, | |
s = m[1]*1, | |
e = m[2]*1, | |
n = m[3]*1; | |
for(var i=w;i<e+1;i++) { | |
for(var j=s;j<n+1;j++) grid[i][j] = Math.max(grid[i][j] + transform(str, grid[i][j]), 0); | |
} | |
}); | |
for(var i=0;i<1000;i++) { | |
for(var j=0;j<1000;j++) { | |
lightsOn += grid[i][j]; | |
} | |
} | |
lightsOn; | |
This file contains 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
/** PART I **/ | |
function check(str) { | |
return !isNaN(str) || wires[str] !== undefined; | |
} | |
function getValue(str) { | |
return isNaN(str) ? wires[str] : str *= 1; | |
} | |
function proceed(str) { | |
var flag = false; | |
for(var p in wires) { | |
if (wires.hasOwnProperty(p)) { | |
var re = new RegExp('.*\\b'+p+'\\b.*-> [a-z]+', 'g'), | |
m = str.match(re); | |
if (m === null) continue; | |
m.map(function (s) { | |
var arr = s.split(' '), | |
res = arr.pop(); | |
if (wires[res] === undefined) { | |
switch(arr.length - 1) { | |
case 3: | |
if (check(arr[0]) && check(arr[2])) { | |
var a = getValue(arr[0]), | |
b = getValue(arr[2]); | |
switch(arr[1]) { | |
case "AND": | |
wires[res] = a & b; | |
break; | |
case "OR": | |
wires[res] = a | b; | |
break; | |
case "LSHIFT": | |
wires[res] = a << b; | |
break; | |
case "RSHIFT": | |
wires[res] = a >> b; | |
break; | |
default: | |
console.error(arr[1]); | |
break; | |
} | |
flag = true; | |
} | |
break; | |
case 2: | |
if (arr[0] !== "NOT") console.error(arr[0]); | |
if (check(arr[1])) { | |
wires[res] = ~ getValue(arr[1]); | |
flag = true; | |
} | |
break; | |
case 1: | |
if (check(arr[0])) { | |
wires[res] = getValue(arr[0]); | |
flag = true; | |
} | |
break; | |
default: | |
console.error(arr[1]); | |
break; | |
} | |
} | |
}); | |
} | |
} | |
if (!flag) { | |
console.error('endless'); | |
wires.a = null; | |
} | |
} | |
function getInitializers(str) { | |
return str.match(/(\n|^)[\d]+ -> [a-z]+/g); | |
} | |
function initialize(str) { | |
getInitializers(str).map(function (str) { | |
var a = /([\d]+) -> ([a-z]+)/g.exec(str); | |
wires[a[2]] = a[1]*1; | |
}); | |
} | |
var str = $('pre').innerHTML, | |
wires = {}; | |
initialize(str); | |
while(wires.a === undefined) proceed(str); | |
console.log(wires.a); | |
/** PART II **/ | |
wires = {b: wires.a, c: 0}; | |
while(wires.a === undefined) proceed(str); | |
console.log(wires.a); |
This file contains 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
/** PART I **/ | |
$('pre').innerHTML | |
.match(/[^\n]+/g) | |
.map(function (str) { | |
return(str.length - eval(str).length); | |
}) | |
.reduce((p, c) => p + c, 0); | |
/** PART II **/ | |
$('pre').innerHTML | |
.match(/[^\n]+/g) | |
.map(function (str) { | |
return(str.match(new RegExp('[\\\\"]{1}','g')).length + 2); | |
}) | |
.reduce((p, c) => p + c, 0); |
This file contains 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 getPath(visited, cities) { | |
var arr = []; | |
visited.forEach(function (i) { | |
arr.push(cities[i]); | |
}); | |
return arr.join(' -> '); | |
} | |
function getSum(visited, graph) { | |
var sum = 0; | |
for (var i=1; i<visited.length; i++) { | |
sum += graph[visited[i-1]][visited[i]]; | |
} | |
return sum; | |
} | |
function getGraph(str, cities) { | |
var graph = []; | |
str.match(/[^\n]+/g) | |
.map(function (s) { | |
var arr = s.split(' '), | |
from = arr[0], | |
to = arr[2], | |
dst = arr[4]*1; | |
if (cities.indexOf(from) < 0) cities.push(from); | |
if (cities.indexOf(to) < 0) cities.push(to); | |
if (graph[cities.indexOf(from)] === undefined) graph[cities.indexOf(from)] = []; | |
if (graph[cities.indexOf(to)] === undefined) graph[cities.indexOf(to)] = []; | |
graph[cities.indexOf(from)][cities.indexOf(from)] = 0; | |
graph[cities.indexOf(from)][cities.indexOf(to)] = dst; | |
graph[cities.indexOf(to)][cities.indexOf(from)] = dst; | |
}); | |
return graph; | |
} | |
function run(L, t, n, k, graph, cities) { | |
if(k==0) { | |
var path = getPath(L, cities), | |
sum = getSum(L, graph); | |
if (!result || (rule == options.min && result > sum || rule == options.max && result < sum)) { | |
result = sum; | |
resultPath = path; | |
} | |
counter++; | |
} else { | |
for(var i=0;i < n; i++) { | |
var L2 = L.concat([t[i]]), | |
t2 = [], | |
j = 0; | |
for(var r = 0 ; r < n ; r++) { | |
if(r != i) { | |
t2[j] = t[r] | |
j++; | |
} | |
} | |
run(L2, t2, n-1, k-1, graph, cities); | |
} | |
} | |
} | |
function init(graph, cities) { | |
var graph = graph || [ | |
// London, Dublin, Belfast | |
/* London */ [0, 464, 518], | |
/* Dublin */ [464, 0, 141], | |
/* Belfast */ [518, 141, 0] | |
], | |
cities = cities || ["London", "Dublin", "Belfast"], | |
n = graph.length, | |
k = graph[0].length, | |
t = []; | |
cities.forEach(function(v, i) { | |
t.push(i); | |
}); | |
counter = 0; | |
result = 0; | |
run([], t, n, k, graph, cities); | |
console.log(rule + ': ' + result + ' (' + resultPath + '). Runs: ' + counter); | |
} | |
var counter, result, resultPath, | |
options = {min: 'Min', max: 'Max'}, | |
rule = options.min, | |
cities = [], | |
graph = getGraph($('pre').innerHTML, cities); | |
/** PART I **/ | |
// 8! = 40320 possibilities | |
init(graph, cities); | |
/** PART II **/ | |
rule = options.max; | |
init(graph, cities); |
This file contains 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 getSequence(a) { | |
return a.match(/(\w)\1*/g) //<-- Here is the magic | |
.map(function (s) { | |
return s.length+s[0]; | |
}) | |
.join(''); | |
} | |
function getSequences(n, a) { | |
for(var i=0;i<n;i++) { | |
a = getSequence(a); | |
} | |
return a.length; | |
} | |
/** PART I **/ | |
console.log(getSequences(40, "3113322113")); | |
/** PART II **/ | |
console.log(getSequences(50, "3113322113")); |
This file contains 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
"use strict"; | |
(function () { | |
function getIncreasedStr(str) { | |
var rtsArr = str.split("").reverse(); | |
if (rtsArr[0] === "z") { | |
return str.length === 1 ? "a" : getIncreasedStr(rtsArr.reverse().slice(0, -1).join("")) + "a"; | |
} else { | |
rtsArr[0] = String.fromCharCode(rtsArr[0].charCodeAt(0) + 1); | |
} | |
return rtsArr.reverse().join(""); | |
} | |
function hasOneIncreasingStraight(str) { | |
for (var i=2; i<str.length; i++) { | |
if (str[i] === getIncreasedStr(str[i-1]) && str[i-1] === getIncreasedStr(str[i-2])) { | |
return true; | |
} | |
} | |
return false; | |
} | |
function hasOneForbiddenLetter(str) { | |
return /[iol]+/g.test(str); | |
} | |
function containsTwoPairsOfLetters(str) { | |
return /(\w)\1.*(\w)\2/g.test(str); | |
} | |
function isAGoodPassword(str) { | |
return hasOneIncreasingStraight(str) && !hasOneForbiddenLetter(str) && containsTwoPairsOfLetters(str); | |
} | |
function getNextPassword(str, n) { | |
n = n || 1; | |
while(!isAGoodPassword(str)) str = getIncreasedStr(str); | |
return n > 1 ? getNextPassword(getIncreasedStr(str), n - 1) : str; | |
} | |
function test() { | |
//TODO implement tests here | |
} | |
var puzzle = "vzbxkghb"; | |
/** PART I **/ | |
console.log(getNextPassword(puzzle)); | |
/** PART II **/ | |
console.log(getNextPassword(puzzle, 2)); | |
})(); |
This file contains 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
"use strict"; | |
(function () { | |
function loadScript(url, callback){ | |
var script = document.createElement("script") | |
script.type = "text/javascript"; | |
if (script.readyState){ //IE | |
script.onreadystatechange = function(){ | |
if (script.readyState == "loaded" || script.readyState == "complete"){ | |
script.onreadystatechange = null; | |
callback(); | |
} | |
}; | |
} else { //Others | |
script.onload = function(){ | |
callback(); | |
}; | |
} | |
script.src = url; | |
document.getElementsByTagName("head")[0].appendChild(script); | |
} | |
function loadJQuery(callback) { | |
loadScript("https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js", callback); | |
} | |
function getPuzzle(url, asJson) { | |
var json; | |
$.ajax({ | |
url: url, | |
dataType: asJson ? 'json' : 'text', | |
async: false | |
}).done(function (str) { | |
json = str; | |
}); | |
return json; | |
} | |
function sumNumbers(a) { | |
if (typeof a === 'string') { | |
return sumNumbersAsString(a); | |
} | |
return sumNumbersAsObject(a, 0); | |
} | |
function sumNumbersAsString(str) { | |
return str | |
.match(/(-?\d+)/g) | |
.map(function(s) { | |
return s*1; | |
}) | |
.reduce((p, c) => p + c); | |
} | |
function sumNumbersAsObject(obj) { | |
switch ($.type(obj)) { | |
case 'object': | |
for(var prop in obj) { | |
if (obj.hasOwnProperty(prop) && obj[prop] === 'red') { | |
return 0; | |
} | |
} | |
case 'array': | |
var sum = 0; | |
for(var prop in obj) { | |
if(obj.hasOwnProperty(prop)) { | |
sum += sumNumbersAsObject(obj[prop]); | |
} | |
} | |
return sum; | |
case 'string': | |
return isNaN(obj) ? 0 : obj*1; | |
case 'number': | |
return obj; | |
} | |
} | |
function init() { | |
$ = window.$; | |
/** PART I **/ | |
console.log(sumNumbers(getPuzzle(puzzleUrl))); | |
/** PART II **/ | |
console.log(sumNumbers(getPuzzle(puzzleUrl, true))); | |
} | |
var puzzleUrl = "http://adventofcode.com/day/12/input"; | |
loadJQuery(init); | |
})(); |
This file contains 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
"use strict"; | |
(function () { | |
function getPath(visited, attendees) { | |
var arr = []; | |
visited.forEach(function (i) { | |
arr.push(attendees[i]); | |
}); | |
return arr.join(' -> '); | |
} | |
function getSum(visited, graph) { | |
var sum = 0; | |
for (var i=1; i<visited.length; i++) { | |
sum += graph[visited[i-1]][visited[i]]; | |
sum += graph[visited[i]][visited[i-1]]; | |
} | |
i --; | |
sum += graph[visited[i]][visited[0]]; | |
sum += graph[visited[0]][visited[i]]; | |
return sum; | |
} | |
function getGraph(str, attendees) { | |
var graph = []; | |
str.match(/[^\n]+/g) | |
.map(function (s) { | |
var from = s.match(/[A-Z]{1}[a-z]+/g)[0], | |
to = s.match(/[A-Z]{1}[a-z]+/g)[1], | |
sign = s.match(/(lose|gain)/g)[0] === "lose" ? -1 : 1, | |
hap = sign * s.match(/\d+/g)[0]; | |
if (attendees.indexOf(from) < 0) attendees.push(from); | |
if (attendees.indexOf(to) < 0) attendees.push(to); | |
if (graph[attendees.indexOf(from)] === undefined) graph[attendees.indexOf(from)] = []; | |
graph[attendees.indexOf(from)][attendees.indexOf(from)] = 0; | |
graph[attendees.indexOf(from)][attendees.indexOf(to)] = hap; | |
}); | |
return graph; | |
} | |
function run(L, t, n, k, graph, attendees) { | |
if(k==0) { | |
var path = getPath(L, attendees), | |
sum = getSum(L, graph); | |
if (!result || (rule == options.min && result > sum || rule == options.max && result < sum)) { | |
result = sum; | |
resultPath = path; | |
} | |
counter++; | |
} else { | |
for(var i=0;i < n; i++) { | |
var L2 = L.concat([t[i]]), | |
t2 = [], | |
j = 0; | |
for(var r = 0 ; r < n ; r++) { | |
if(r != i) { | |
t2[j] = t[r] | |
j++; | |
} | |
} | |
run(L2, t2, n-1, k-1, graph, attendees); | |
} | |
} | |
} | |
function addMe(graph, attendees) { | |
for (var i=0; i<graph.length; i++) { | |
graph[i][graph[i].length] = 0; | |
} | |
graph[i] = []; | |
for (var j=0; j<graph[0].length; j++) { | |
graph[i][j] = 0; | |
} | |
attendees.push("me"); | |
} | |
function init(graph, attendees) { | |
var graph = graph || [ | |
// Alice, Bob, Carol, David | |
/* Alice */ [0, 54, -79, -2], | |
/* Bob */ [83, 0, -7, -63], | |
/* Carol */ [-62, 60, 0, 55], | |
/* David */ [46, -7, 41, 0], | |
], | |
attendees = attendees || ["Alice", "Bob", "Carol", "David"], | |
n = graph.length, | |
k = graph[0].length, | |
t = []; | |
attendees.forEach(function(v, i) { | |
t.push(i); | |
}); | |
counter = 0; | |
result = 0; | |
run([], t, n, k, graph, attendees); | |
console.log(rule + ': ' + result + ' (' + resultPath + '). Runs: ' + counter); | |
} | |
var counter, result, resultPath, | |
options = {min: 'Min', max: 'Max'}, | |
rule = options.max, | |
attendees = [], | |
graph = getGraph($('pre').innerHTML, attendees); | |
/** PART I **/ | |
// 8! = 40320 possibilities | |
init(graph, attendees); | |
/** PART II **/ | |
// 9! = 362880 possibilities | |
addMe(graph, attendees); | |
init(graph, attendees); | |
})(); |
This file contains 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
"use strict"; | |
(function () { | |
function getFleet(str) { | |
var fleet = {}; | |
str.match(/[^\n]+/g) | |
.map(function (s) { | |
var name = s.match(/[A-Z]{1}[a-z]+/g)[0], | |
numbers = s.match(/\d+/g).map((s) => s * 1), | |
speed = numbers[0], | |
timeSpeeding = numbers[1], | |
timeResting = numbers[2]; | |
fleet[name] = { | |
s: speed, | |
t1: timeSpeeding, | |
T: timeSpeeding + timeResting, | |
p: 0 | |
}; | |
}); | |
return fleet; | |
} | |
function getFastestReindeer(fleet, raceTime) { | |
var max = 0, fastestReindeer; | |
for (var reindeer in fleet) { | |
if (fleet.hasOwnProperty(reindeer)) { | |
var r = fleet[reindeer]; | |
r.D = (Math.floor(raceTime/r.T)*r.t1+Math.min(raceTime%r.T, r.t1))*r.s; | |
if (r.D > max) { | |
max = r.D; | |
fastestReindeer = reindeer; | |
} | |
} | |
} | |
return fastestReindeer; | |
} | |
function getMaxDistance(fleet, raceTime) { | |
return fleet[getFastestReindeer(fleet, raceTime)].D; | |
} | |
function getMaxPoints(fleet, raceTime) { | |
for (var i=1; i<raceTime+1; i++) { | |
fleet[getFastestReindeer(fleet, i)].p ++; | |
} | |
var max = 0; | |
for (var reindeer in fleet) { | |
if (fleet.hasOwnProperty(reindeer)) { | |
max = fleet[reindeer].p > max ? fleet[reindeer].p : max; | |
} | |
} | |
return max; | |
} | |
function init() { | |
var raceTime = 2503, | |
fleet = getFleet($('pre').innerHTML); | |
/** PART I **/ | |
console.log(getMaxDistance(fleet, raceTime)); | |
/** PART II **/ | |
console.log(getMaxPoints(fleet, raceTime)) | |
} | |
init(); | |
})(); |
This file contains 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
"use strict"; | |
(function () { | |
function getMax(func, dim, inf, sup, step, params, restrFunc) { | |
var s = sup - params.reduce((p, c) => p + c, 0), | |
max = 0, | |
ret = {y: 0, params: params}; | |
if (dim > 0) { | |
for (var x=inf; x<=s; x+=step) { | |
var obj = getMax(func, dim - 1, inf, sup, step, params.concat([x]), restrFunc); | |
if (obj.y > max) { | |
max = obj.y; | |
ret = obj; | |
} | |
} | |
} else { | |
if (typeof restrFunc !== "function" || restrFunc.apply(this, params)) { | |
ret.y = func.apply(this, params); | |
} | |
} | |
return ret; | |
} | |
function getIngredients(str) { | |
var ingredients = []; | |
str.match(/[^\n]+/g).map(function (s) { | |
var numbers = s.match(/-?\d+/g).map((s) => s * 1); | |
ingredients.push(numbers.slice(0, -1)); | |
}); | |
return ingredients; | |
} | |
function getCalories(str) { | |
var calories = []; | |
str.match(/[^\n]+/g).map(function (s) { | |
var numbers = s.match(/-?\d+/g).map((s) => s * 1); | |
calories.push(numbers.slice(-1)[0]); | |
}); | |
return calories; | |
} | |
function transpose(A) { | |
var B = []; | |
for (var i=0; i<A.length; i++) { | |
for (var j=0; j<A[i].length; j++) { | |
if (B[j] === undefined) B[j] = []; | |
B[j][i] = A[i][j]; | |
} | |
} | |
return B; | |
} | |
function min0(f) { | |
return Math.max(0, f); | |
} | |
function getSum(p, vars) { | |
var ret = 0; | |
for (var i=0; i<p.length; i++) { | |
ret += p[i]*vars[i]; | |
} | |
return ret; | |
} | |
function getF(properties) { | |
return function () { | |
var args = arguments, | |
sums = properties.map(function (p) { | |
return min0(getSum(p, args)); | |
}); | |
return sums.reduce((p, c) => p*c); | |
}; | |
} | |
function init() { | |
var str = $('pre').innerHTML, | |
ingredients = getIngredients(str), | |
properties = transpose(ingredients), | |
calories = getCalories(str), | |
f = getF(properties), | |
d = ingredients.length, | |
i = 0, | |
s = 100, | |
st = 1, | |
p = []; | |
/** PART I **/ | |
var res = getMax(f, d, i, s, st, p); | |
console.log("f("+res.params.join(", ")+") = "+res.y); | |
/** PART II **/ | |
var r = function() { return getSum.apply(this, [calories, arguments]) === 500; }, | |
res = getMax(f, d, i, s, st, p, r); | |
console.log("f("+res.params.join(", ")+") = "+res.y); | |
} | |
init(); | |
})(); |
This file contains 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
"use strict"; | |
(function () { | |
function getSues(str) { | |
var sues = []; | |
str.match(/[^\n]+/g).map(function (s) { | |
var detected = s.match(/\b[a-z]+\b/g), | |
n = s.match(/\d+/g).map((s) => s*1), | |
sue = n[0]; | |
sues[sue] = {}; | |
for(var i=0; i<detected.length; i++) { | |
sues[sue][detected[i]] = n[i + 1]; | |
} | |
}); | |
return sues; | |
} | |
function propertyMatch(value, name, ref, matchFunc) { | |
if (!ref.hasOwnProperty(name)) return; | |
matchFunc = matchFunc || function(value, name, ref) { return ref[name] === value; }; | |
return matchFunc(value, name, ref); | |
} | |
function propertiesMatch(obj, ref, matchFunc) { | |
var match = true; | |
for (var name in obj) { | |
if (obj.hasOwnProperty(name)) { | |
var value = obj[name]; | |
match = match && propertyMatch(value, name, ref, matchFunc); | |
} | |
} | |
return match; | |
} | |
function findMatch(arr, ref, matchFunc) { | |
for (var n=1; n<arr.length; n++) { | |
var obj = arr[n]; | |
if (propertiesMatch(obj, ref, matchFunc)) return n; | |
} | |
} | |
function init() { | |
var sues = getSues($('pre').innerHTML), | |
ticket = { | |
children: 3, | |
cats: 7, | |
samoyeds: 2, | |
pomeranians: 3, | |
akitas: 0, | |
vizslas: 0, | |
goldfish: 5, | |
trees: 3, | |
cars: 2, | |
perfumes: 1 | |
}; | |
/** PART I **/ | |
console.log(findMatch(sues, ticket)); | |
/** PART II **/ | |
var matchFunction = function(value, name, ref) { | |
var lt = ['pomeranians', 'goldfish'], | |
gt = ['cats', 'trees']; | |
if (lt.indexOf(name) > -1) { | |
return value < ref[name]; | |
} | |
if (gt.indexOf(name) > -1) { | |
return value > ref[name]; | |
} | |
return value === ref[name]; | |
}; | |
console.log(findMatch(sues, ticket, matchFunction)); | |
} | |
init(); | |
})(); |
This file contains 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
"use strict"; | |
(function () { | |
function getCombinations(A, k) { | |
var c = []; | |
if (k > 1) { | |
for (var i=0; i<A.length; i++) { | |
c = c.concat(getCombinations(A.slice(i + 1), k-1).map((e) => e.concat(A[i]))); | |
} | |
return c; | |
} else { | |
return A.map((e) => [e]); | |
} | |
} | |
function getAllCombinations(A, filter) { | |
var P = []; | |
for (var k=1; k<=A.length; k++) { | |
P = P.concat(getCombinations(A, k).filter(filter)); | |
} | |
return P; | |
} | |
function getDistribution(P) { | |
var D = []; | |
for (var i=0; i<P.length; i++) { | |
var n = P[i].length; | |
D[n] = D[n] ? D[n] + 1 : 1; | |
} | |
return D; | |
} | |
function init() { | |
var puzzle = [11, 30, 47, 31, 32, 36, 3, 1, 5, 3, 32, 36, 15, 11, 46, 26, 28, 1, 19, 3], | |
restriction = function(e) { return e.reduce((p, c) => p + c) === 150; }, | |
P = getAllCombinations(puzzle, restriction); | |
// 1,048,575 raw combinations | |
/** PART I **/ | |
console.log(P.length); | |
/** PART II **/ | |
console.log(getDistribution(P)); | |
} | |
init(); | |
})(); |
This file contains 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
"use strict"; | |
(function () { | |
function getInitialState(str) { | |
var arr = [], | |
i = 0; | |
str.match(/[^\n]+/g).map(function (s) { | |
arr[i] = []; | |
for(var j=0; j<s.length; j++) { | |
arr[i][j] = getState(s[j]); | |
} | |
i++; | |
}); | |
return arr; | |
} | |
function getNextArrayState(arr, modifier) { | |
var newArr = []; | |
for(var i=0; i<arr.length; i++) { | |
newArr[i] = []; | |
for(var j=0; j<arr[i].length; j++) { | |
newArr[i][j] = getNexElementState(arr, i, j); | |
} | |
} | |
return typeof modifier === "function" ? modifier(newArr) : newArr; | |
} | |
function getNthArrayState(arr, n, modifier) { | |
for(var i=0; i<n; i++) { | |
arr = getNextArrayState(arr, modifier); | |
} | |
return arr; | |
} | |
function getNexElementState(arr, i, j) { | |
var neighbors = getNeighbors(arr, i, j), | |
sum = neighbors.sum(); | |
if (sum === 3) return 1; | |
return (arr[i][j] && sum === 2)*1; | |
} | |
function getNeighbors(arr, i, j) { | |
var neighbors = []; | |
for(var y=i-1; y<=i+1; y++) { | |
for(var x=j-1; x<=j+1; x++) { | |
if (x !== j || y !== i) neighbors.push(getNeighbor(arr, y, x)); | |
} | |
} | |
return neighbors; | |
} | |
function getNeighbor(arr, i, j) { | |
if (i < 0 || j < 0 || i >= arr.length || j >= arr[0].length) return 0; | |
return arr[i][j]; | |
} | |
function getState(str) { | |
return str === '#' ? 1 : 0; | |
} | |
function countLightsOn(arr) { | |
return arr.map((e) => e.sum()).sum() | |
} | |
function display(arr) { | |
var str = arr.map((e) => e.map((c) => c ? '#' : '.').join('')).join('\n') | |
console.log(str); | |
} | |
function init() { | |
Array.prototype.sum = function() { | |
return this.reduce((p, c) => p + c); | |
} | |
var n = 100, | |
initial = getInitialState($('pre').innerHTML), | |
initialTest = [ | |
[0, 1, 0, 1, 0, 1], | |
[0, 0, 0, 1, 1, 0], | |
[1, 0, 0, 0, 0, 1], | |
[0, 0, 1, 0, 0, 0], | |
[1, 0, 1, 0, 0, 1], | |
[1, 1, 1, 1, 0, 0] | |
]; | |
/** PART I **/ | |
var last = getNthArrayState(initial, n) | |
console.log(countLightsOn(last)); | |
/** PART II **/ | |
var cornersAlwaysOn = function(arr) { | |
var m = arr.length - 1, | |
n = arr[0].length - 1; | |
arr[0][0] = 1; | |
arr[0][m] = 1; | |
arr[n][0] = 1; | |
arr[n][m] = 1; | |
return arr; | |
} | |
last = getNthArrayState(cornersAlwaysOn(initial), n, cornersAlwaysOn); | |
console.log(countLightsOn(last)); | |
} | |
init(); | |
})(); |
This file contains 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
"use strict"; | |
(function () { | |
var _elves = [], | |
_firstElf = 1; | |
function getPresents(houseNr, factor, maxHouses) { | |
var presents = 0, | |
i = _firstElf; | |
while (maxHouses && _elves[i] >= maxHouses) i++; | |
_firstElf = i; | |
for (var elfNr=_firstElf; elfNr<=houseNr; elfNr++) { | |
if (maxHouses) _elves[elfNr] = _elves[elfNr] || 0; | |
if (!maxHouses || _elves[elfNr] < maxHouses) { | |
if (!(houseNr%elfNr)) { | |
presents += elfNr*factor; | |
if (maxHouses) _elves[elfNr] ++; | |
} | |
} else { | |
_firstElf = elfNr; | |
} | |
} | |
return presents | |
} | |
function getLowestHouseNr(target, factor, maxHouses) { | |
var houseNr = 1; | |
while (getPresents(houseNr, factor, maxHouses) < target) houseNr++; | |
return houseNr; | |
} | |
function init() { | |
var puzzle = 33100000; | |
/** PART I **/ | |
console.log(getLowestHouseNr(puzzle, 10)); | |
/** PART II **/ | |
console.log(getLowestHouseNr(puzzle, 11, 50)); | |
} | |
init(); | |
})(); |
This file contains 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
"use strict"; | |
(function () { | |
var _cost; | |
function pickCombinations(A, B) { | |
var c = [[], []]; | |
for (var i=0; i<A.length; i++) { | |
for (var j=0; j<B.length; j++) { | |
c[0].push(A[i]); | |
c[1].push(B[j]); | |
} | |
} | |
return c; | |
} | |
function getCombinations(A, k) { | |
if (k === 1) return A.map((e) => [e]); | |
var c = []; | |
for (var i=0; i<A.length; i++) { | |
c = c.concat(getCombinations(A.slice(i + 1), k-1).map((e) => e.concat(A[i]))); | |
} | |
return c; | |
} | |
function playerWins(player, boss) { | |
var playerDamage = Math.max(player.damage - boss.armor, 1), | |
bossDamage = Math.max(boss.damage - player.armor, 1); | |
return playerDamage >= bossDamage; | |
} | |
function buy(person, object) { | |
person.damage += object.damage; | |
person.armor += object.armor; | |
} | |
function buyItems(person, aisle, items) { | |
for (var i=0; i<items.length; i++) { | |
buy(person, aisle[items[i]]); | |
} | |
} | |
function getCost(aisle, items) { | |
var cost = 0; | |
for (var i=0; i<items.length; i++) { | |
cost += aisle[items[i]].cost; | |
} | |
return cost; | |
} | |
function orderByCost(A, shop) { | |
var B = {}; | |
for (var i=0; i<A[0].length; i++) { | |
var a = A[0][i], | |
b = A[1][i], | |
cA = getCost(shop.armors, a), | |
cB = getCost(shop.rings, b), | |
c = cA + cB; | |
B[c] = B[c] || []; | |
B[c].push([a, b]); | |
} | |
return B; | |
} | |
function clonePerson(person) { | |
var newPerson = { | |
points: person.points, | |
damage: person.damage, | |
armor: person.armor | |
}; | |
return newPerson; | |
} | |
function fight(shop, player, boss, rule, transform) { | |
rule = rule || function (a, b) { | |
return !b || a < b; | |
}; | |
transform = transform || function (bool) { | |
return bool; | |
} | |
var weapons = shop.weapons, | |
armors = shop.armors, | |
rings = shop.rings, | |
configurations = [ | |
{armors: 0, rings: 0}, | |
{armors: 0, rings: 1}, | |
{armors: 1, rings: 0}, | |
{armors: 0, rings: 2}, | |
{armors: 1, rings: 1}, | |
{armors: 1, rings: 2} | |
], | |
armorsRingsConfigurations = []; | |
for (var i=0; i<configurations.length; i++) { | |
var configuration = configurations[i], | |
A = configuration.armors ? getCombinations(armors.getKeys(), configuration.armors) : [[]], | |
B = configuration.rings ? getCombinations(rings.getKeys(), configuration.rings) : [[]], | |
C = pickCombinations(A, B), | |
P = orderByCost(C, shop); | |
for (var weapon in weapons) { | |
if (!weapons.hasOwnProperty(weapon)) continue; | |
for (var key in P) { | |
if (key === 'getKeys' || !P.hasOwnProperty(key)) continue; | |
var cost = key*1 + weapons[weapon].cost; | |
if (!rule(cost, _cost)) continue; | |
for (var j=0; j<P[key].length; j++) { | |
var _player = clonePerson(player), | |
_boss = clonePerson(boss), | |
selection = P[key][j], | |
selectedArmors = selection[0], | |
selectedRings = selection[1]; | |
buy(_player, weapons[weapon]); | |
if (selectedArmors) buyItems(_player, armors, selectedArmors); | |
if (selectedRings) buyItems(_player, rings, selectedRings); | |
var wins = playerWins(_player, _boss); | |
if (transform(wins) && rule(cost, _cost)) { | |
_cost = cost; | |
} | |
} | |
} | |
} | |
} | |
return _cost; | |
} | |
function init() { | |
Object.prototype.getKeys = function() { | |
var keys = []; | |
for(var k in this) if (this.hasOwnProperty(k)) keys.push(k); | |
return keys; | |
}; | |
var shop = { | |
weapons: { | |
'Dagger': {cost: 8, damage: 4, armor: 0}, | |
'Shortsword': {cost: 10, damage: 5, armor: 0}, | |
'Warhammer': {cost: 25, damage: 6, armor: 0}, | |
'Longsword': {cost: 40, damage: 7, armor: 0}, | |
'Greataxe': {cost: 74, damage: 8, armor: 0} | |
}, | |
armors: { | |
'Leather': {cost: 13, damage: 0, armor: 1}, | |
'Chainmail': {cost: 31, damage: 0, armor: 2}, | |
'Splintmail': {cost: 53, damage: 0, armor: 3}, | |
'Bandedmail': {cost: 75, damage: 0, armor: 4}, | |
'Platemail': {cost: 102, damage: 0, armor: 5} | |
}, | |
rings: { | |
'Damage +1': {cost: 25, damage: 1, armor: 0}, | |
'Damage +2': {cost: 50, damage: 2, armor: 0}, | |
'Damage +3': {cost: 100, damage: 3, armor: 0}, | |
'Defense +1': {cost: 20, damage: 0, armor: 1}, | |
'Defense +2': {cost: 40, damage: 0, armor: 2}, | |
'Defense +3': {cost: 80, damage: 0, armor: 3} | |
} | |
}, | |
boss = { | |
points: 100, | |
damage: 8, | |
armor: 2 | |
}, | |
player = { | |
points: 100, | |
damage: 0, | |
armor: 0 | |
}; | |
/** PART I **/ | |
console.log(fight(shop, player, boss)); | |
/** PART II **/ | |
_cost = 0; | |
var mostExpensive = function (a, b) { | |
return a > b; | |
}, | |
lose = function (bool) { | |
return !bool; | |
}; | |
console.log(fight(shop, player, boss, mostExpensive, lose)); | |
} | |
init(); | |
})(); |
This file contains 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
"use strict"; | |
(function () { | |
var _instructions, _i, _registers; | |
function displayRegisters() { | |
console.log('\na = ' + _registers.a + '\nb = ' + _registers.b); | |
} | |
function runProgram() { | |
while(_instructions[_i]) interpretCurrentInstruction(); | |
} | |
function interpretCurrentInstruction() { | |
var arr = _instructions[_i].replace(',', '').split(' '), | |
offset = 0; | |
switch (arr[0]) { | |
case 'hlf': | |
_registers[arr[1]] *= 0.5; | |
_i ++; | |
break; | |
case 'tpl': | |
_registers[arr[1]] *= 3; | |
_i ++; | |
break; | |
case 'inc': | |
_registers[arr[1]] ++; | |
_i ++; | |
break; | |
case 'jmp': | |
offset = arr[1]*1; | |
_i += offset; | |
break | |
case 'jie': | |
offset = _registers[arr[1]] % 2 ? 1 : arr[2]*1; | |
_i += offset; | |
break | |
case 'jio': | |
offset = _registers[arr[1]] === 1 ? arr[2]*1 : 1; | |
_i += offset; | |
break | |
} | |
} | |
function reset() { | |
_instructions = ['jio a, +19', 'inc a', 'tpl a', 'inc a', 'tpl a', 'inc a', 'tpl a', 'tpl a', 'inc a', 'inc a', 'tpl a', 'tpl a', 'inc a', 'inc a', 'tpl a', 'inc a', 'inc a', 'tpl a', 'jmp +23', 'tpl a', 'tpl a', 'inc a', 'inc a', 'tpl a', 'inc a', 'inc a', 'tpl a', 'inc a', 'tpl a', 'inc a', 'tpl a', 'inc a', 'tpl a', 'inc a', 'inc a', 'tpl a', 'inc a', 'inc a', 'tpl a', 'tpl a', 'inc a', 'jio a, +8', 'inc b', 'jie a, +4', 'tpl a', 'inc a', 'jmp +2', 'hlf a', 'jmp -7']; | |
_registers = {a: 0, b: 0}; | |
_i = 0; | |
} | |
function test() { | |
var setContext = function() { | |
_instructions = ['inc a', 'jio a, +2', 'tpl a', 'inc a']; | |
}; | |
reset(); | |
setContext(); | |
runProgram(); | |
console.log('Test ' + (_registers.a === 2 && _registers.b === 0 ? 'passed.' : 'failed.')); | |
} | |
function initPartI(player, boss) { | |
reset(); | |
runProgram(); | |
displayRegisters(); | |
} | |
function initPartII(player, boss) { | |
reset(); | |
_registers.a = 1; | |
runProgram(); | |
displayRegisters(); | |
} | |
function init() { | |
test(); | |
/** PART I **/ | |
initPartI(); | |
/** PART II **/ | |
initPartII(); | |
} | |
init(); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment