Skip to content

Commit 36284ef

Browse files
committed
Advent day 3 2 star finished
1 parent f7bebd4 commit 36284ef

File tree

2 files changed

+33
-2
lines changed

2 files changed

+33
-2
lines changed

src/day03.spec.ts

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,24 @@
11
import { expect, it, describe } from 'vitest'
22

3-
import { sumOfMultiplications} from '@/day03'
3+
import { sumOfMultiplications, sumOfMultiplicationsWithLimitations} from '@/day03'
44

55

66
describe('it should solve day 3 correctly', () => {
7-
it('should only consider the correct sentences adding its multiplications', () => {
7+
it('should consider the correct sentences adding its multiplications', () => {
88
// Arrange
99
const stringToMatch = 'xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5))'
1010
// Act
1111
const result = sumOfMultiplications(stringToMatch)
1212
// Assert
1313
expect(result).toEqual(161)
1414
})
15+
16+
it('should consider the correct sentences taking the do and dont instrucions into account', () =>{
17+
// Arrange
18+
const stringToMatch = "xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5))"
19+
// Act
20+
const result = sumOfMultiplicationsWithLimitations(stringToMatch)
21+
// Assert
22+
expect(result).toEqual(48)
23+
})
1524
})

src/day03.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,4 +23,26 @@ export function sumOfMultiplications(text: string): number {
2323
return sumOfProducts
2424
}
2525

26+
export function sumOfMultiplicationsWithLimitations(text: string): number{
27+
const regex = /mul\((\d+),(\d+)\)|(don't\(\))|(do\(\))/g
28+
let sumOfProducts = 0
29+
let skipOrders = false
30+
const matches = text.matchAll(regex)
31+
for(const match of matches){
32+
let firstIsNumber= !isNaN(Number(match[1]))
33+
let secondtIsNumber= !isNaN(Number(match[2]))
34+
35+
if(match[3] === "don't()"){
36+
skipOrders = true
37+
}
38+
if(match[4] === 'do()') {
39+
skipOrders = false;
40+
}
41+
if(skipOrders === false && firstIsNumber && secondtIsNumber){
42+
sumOfProducts += Number(match[1]) * Number(match[2])
43+
}
44+
}
45+
return sumOfProducts
46+
}
47+
2648

0 commit comments

Comments
 (0)