From 2dab36b36edd1864db82a266ab2044c22cca0330 Mon Sep 17 00:00:00 2001 From: Loosetooth Date: Sat, 1 Feb 2025 23:50:01 +0100 Subject: [PATCH] add kata --- 5kyu/count-ip-addresses/description.md | 8 ++++++++ 5kyu/count-ip-addresses/solution.ts | 17 +++++++++++++++++ 5kyu/count-ip-addresses/tests.ts | 11 +++++++++++ 3 files changed, 36 insertions(+) create mode 100644 5kyu/count-ip-addresses/description.md create mode 100644 5kyu/count-ip-addresses/solution.ts create mode 100644 5kyu/count-ip-addresses/tests.ts diff --git a/5kyu/count-ip-addresses/description.md b/5kyu/count-ip-addresses/description.md new file mode 100644 index 0000000..9eef242 --- /dev/null +++ b/5kyu/count-ip-addresses/description.md @@ -0,0 +1,8 @@ +Implement a function that receives two IPv4 addresses, and returns the number of addresses between them (including the first one, excluding the last one). + +All inputs will be valid IPv4 addresses in the form of strings. The last address will always be greater than the first one. + +Examples +* With input "10.0.0.0", "10.0.0.50" => return 50 +* With input "10.0.0.0", "10.0.1.0" => return 256 +* With input "20.0.0.10", "20.0.1.0" => return 246 diff --git a/5kyu/count-ip-addresses/solution.ts b/5kyu/count-ip-addresses/solution.ts new file mode 100644 index 0000000..52d79a4 --- /dev/null +++ b/5kyu/count-ip-addresses/solution.ts @@ -0,0 +1,17 @@ +/** + * Regards an IP address as a number with 4 digits. + * Each digit can be between 0 and 255. + * The result of this function is the total number of possible IPs 'lower' than the given IP. + */ +const ipToNum = (ip: string): number => { + const digits = ip.split('.').map(Number) as [number, number, number, number]; + console.log(digits); + if(digits.length !== 4) { + throw new Error('Invalid IP address'); + } + return digits.reduce((sum, digit) => sum * 256 + digit, 0); +} + +export function ipsBetween(start: string, end: string): number { + return ipToNum(end) - ipToNum(start); +} \ No newline at end of file diff --git a/5kyu/count-ip-addresses/tests.ts b/5kyu/count-ip-addresses/tests.ts new file mode 100644 index 0000000..e4d0580 --- /dev/null +++ b/5kyu/count-ip-addresses/tests.ts @@ -0,0 +1,11 @@ +// See https://www.chaijs.com for how to use Chai. +import { assert } from "chai"; +import { ipsBetween } from "./solution"; + +// TODO Add your tests here +describe("example", function() { + it("test", function() { + assert.equal(ipsBetween("10.0.0.0", "10.0.0.50"), 50, 'ipsBetween("10.0.0.0", "10.0.0.50")'); + assert.equal(ipsBetween("20.0.0.10", "20.0.1.0"), 246, 'ipsBetween("20.0.0.10", "20.0.1.0")'); + }); +}); \ No newline at end of file