From 993a7ee42210f4aa1c12b2d4b343bb3aa0bcb2f0 Mon Sep 17 00:00:00 2001 From: Marco Biedermann <5244986+marcobiedermann@users.noreply.github.com.> Date: Fri, 5 Apr 2024 12:47:37 +0200 Subject: [PATCH] refactor: 2015 Day 4 Refactor day 4 of 2015 --- 2015/day/4/index.test.ts | 24 ++++++++++++------------ 2015/day/4/index.ts | 14 ++++++++++---- 2 files changed, 22 insertions(+), 16 deletions(-) diff --git a/2015/day/4/index.test.ts b/2015/day/4/index.test.ts index 1588e3f..d64d73e 100644 --- a/2015/day/4/index.test.ts +++ b/2015/day/4/index.test.ts @@ -3,20 +3,20 @@ import { part1, part2 } from '.'; const input = 'ckczppom'; -describe('Day 4', () => { - describe('Part 1', () => { - it('should find a hash which starts with five zeros', () => { - expect.assertions(1); - - expect(part1(input)).toStrictEqual(117946); +describe('2015', () => { + describe('Day 4', () => { + describe('Part 1', () => { + it('should find a hash which starts with five zeros', () => { + expect(part1('abcdef')).toBe(609043); + expect(part1('pqrstuv')).toBe(1048970); + expect(part1(input)).toBe(117946); + }); }); - }); - - describe('Part 2', () => { - it('should find a hash which starts with six zeros', () => { - expect.assertions(1); - expect(part2(input)).toStrictEqual(3938038); + describe('Part 2', () => { + it('should find a hash which starts with six zeros', () => { + expect(part2(input)).toBe(3938038); + }); }); }); }); diff --git a/2015/day/4/index.ts b/2015/day/4/index.ts index 1bcfee3..c9baf09 100644 --- a/2015/day/4/index.ts +++ b/2015/day/4/index.ts @@ -1,13 +1,19 @@ -import crypto from 'crypto'; +import crypto from 'node:crypto'; + +const ZERO = '0' as const; + +function getMd5Hash(input: string): string { + return crypto.createHash('md5').update(input).digest('hex'); +} function part1(key: string, digits = 5): number { + const str = ZERO.repeat(digits); let index = 1; while (true) { - const input = `${key}${index}`; - const hash = crypto.createHash('md5').update(input).digest('hex'); + const hash = getMd5Hash(`${key}${index}`); - if (hash.slice(0, digits) === '0'.repeat(digits)) { + if (hash.startsWith(str)) { return index; }