Skip to content

Instantly share code, notes, and snippets.

@narskidan
Last active May 11, 2024 20:56
Show Gist options
  • Save narskidan/97f073221109330ef7fbcddb02541d37 to your computer and use it in GitHub Desktop.
Save narskidan/97f073221109330ef7fbcddb02541d37 to your computer and use it in GitHub Desktop.
Restore IP coding challenge (fun with Pancho)
function* restore(raw: string, ip = ''): Generator {
if (raw.length === 0)
yield ip.slice(1);
for (const i of [0, 1, 2]) {
const octet = raw.slice(0, i+1);
if (i >= raw.length
|| Number(octet) > 255
|| ip.split('.').length > 4
|| octet.length > 1 && octet[0] === '0'
) continue;
yield* restore(raw.slice(i+1), `${ip}.${octet}`);
}
}
console.log([...restore('12345678')]);
|= raw=tape
^- ~
=/ ip ""
|-
?~ `*`raw
~& `tape`(slag 1 ip) ~
=< ~
%+ turn
%+ gulf 0
(min 2 (dec (lent raw)))
|= i=@ud
=/ octet (swag [0 +(i)] raw)
?:
?|
(gth `@ud`(slav %ud (crip octet)) 255)
(gth (lent (fand ~['.'] ip)) 3)
==
~
%= ^$
raw (slag +(i) raw)
ip "{ip}.{octet}"
==
const isValidIp = (ip: string) => {
const octets = ip.slice(1).split('.')
if (octets.length !== 4) {
return false;
}
return octets.every(octet => {
const noLeadingZero = (octet.length > 1 && octet[0] !== '0') || octet.length === 1;
const isEightBits = Number(octet) < 256;
return isEightBits && noLeadingZero;
})
}
const restoreIp = (corruptedIp: string, newIp = ''): string[] => {
let [firstDigit, secondDigit, thirdDigit] = corruptedIp.split('');
switch (corruptedIp.length) {
case 0:
return [newIp];
case 1:
return [`${newIp}.${corruptedIp}`];
case 2:
return [
`${newIp}.${corruptedIp}`,
`${newIp}.${firstDigit}.${secondDigit}`
]
default:
const smallOctet = restoreIp(
corruptedIp.slice(1),
`${newIp}.${firstDigit}`
);
const mediumOctet = restoreIp(
corruptedIp.slice(2),
`${newIp}.${firstDigit+secondDigit}`
);
const bigOctet = restoreIp(
corruptedIp.slice(3),
`${newIp}.${firstDigit+secondDigit+thirdDigit}`
);
return smallOctet
.concat(mediumOctet)
.concat(bigOctet)
.filter(isValidIp);
}
return ['anything below this line is dead code!']
}
console.log(restoreIp('12345678'))
@narskidan
Copy link
Author

Based on this challenge intended for Hoon: https://docs.urbit.org/language/hoon/examples/restore-ip

@narskidan
Copy link
Author

Finally added Hoon version! I think my solution is way simpler than the official solutions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment