Skip to content

Instantly share code, notes, and snippets.

@karataev
Created November 17, 2020 07:12
Show Gist options
  • Save karataev/902219003b4f4ddbbc6bdc8964cb546f to your computer and use it in GitHub Desktop.
Save karataev/902219003b4f4ddbbc6bdc8964cb546f to your computer and use it in GitHub Desktop.
A prototype to find possible valid IP addresses from a string
function getValidIpAddresses(str) {
let result = [];
for (let i = 1; i < str.length; i++) {
let first = str.slice(0, i);
if (first > 255) continue;
let withoutFirst = str.slice(i);
for (let j = 1; j < withoutFirst.length; j++) {
let second = withoutFirst.slice(0, j);
if (second > 255) continue;
let withoutFirstSecond = withoutFirst.slice(j);
for (let k = 1; k < withoutFirstSecond.length; k++) {
let third = withoutFirstSecond.slice(0, k);
if (third > 255) continue;
let last = withoutFirstSecond.slice(k);
if (last > 255) continue;
let item = `${first}.${second}.${third}.${last}`;
result.push(item);
}
}
}
return result;
}
console.clear();
console.log(getValidIpAddresses('19216811'));
// ["1.92.168.11", "19.2.168.11", "19.21.68.11", "19.216.8.11", "19.216.81.1", "192.1.68.11", "192.16.8.11", "192.16.81.1", "192.168.1.1"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment