Skip to content

Instantly share code, notes, and snippets.

@mvasilkov
Last active February 11, 2020 08:50
Show Gist options
  • Save mvasilkov/a03f2c3f8a491531de9b9a54904710ab to your computer and use it in GitHub Desktop.
Save mvasilkov/a03f2c3f8a491531de9b9a54904710ab to your computer and use it in GitHub Desktop.
Programming interview question
'use strict'
// Take a valid octet from a string. Octet can be 1-3 characters
function takeOctet(octets, string) {
// If we have 4 octets, and nothing is left on the string, we're done
if (octets.length === 4) {
if (string.length === 0) {
console.log(`${octets[0]}.${octets[1]}.${octets[2]}.${octets[3]}`)
}
// Return anyway
return
}
// Check for no possible solutions: the longest octet is 3 chars
// String too long:
if (string.length > (4 - octets.length) * 3) return
// String too short:
if (string.length < 4 - octets.length) return
// Take an octet, 1-3 characters
for (let n = 1; n < 4; ++n) {
// Not enough characters, continue
if (n > string.length) continue
const octet = string.substring(0, n)
// Recursively call takeOctet() if this octet is valid
if (+octet < 256) {
takeOctet(octets.concat(octet), string.substring(n))
}
}
}
function printIPs(string) {
takeOctet([], string)
}
// Test case
console.log('\n\n999666\n------')
printIPs('999666')

Write a function that receives a string, which is an IP address without dots. Like this: "127001"

The function should print all valid IPs that you can get from that string by adding dots. For example, for "123123" there are many valid IPs:

  • 123.1.2.3
  • 1.23.12.3
  • 1.2.31.23

...and so on. We need to print them all, in any order. For simplicity, let's say IP always has 3 dots.

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