Skip to content

Commit

Permalink
refactor: 2015 Day 4
Browse files Browse the repository at this point in the history
Refactor day 4 of 2015
  • Loading branch information
marcobiedermann committed Apr 5, 2024
1 parent c4dd82c commit 993a7ee
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 16 deletions.
24 changes: 12 additions & 12 deletions 2015/day/4/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
});
});
});
14 changes: 10 additions & 4 deletions 2015/day/4/index.ts
Original file line number Diff line number Diff line change
@@ -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;
}

Expand Down

0 comments on commit 993a7ee

Please sign in to comment.