From 89c13d8f3864dd939d4f78d34fade4fd8e9bdebc Mon Sep 17 00:00:00 2001 From: Seth Date: Mon, 28 Apr 2025 10:30:37 +0000 Subject: [PATCH] complete but wrong answer --- 4/index.js | 74 ++++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 58 insertions(+), 16 deletions(-) diff --git a/4/index.js b/4/index.js index e9b96f8..be7b968 100644 --- a/4/index.js +++ b/4/index.js @@ -1,27 +1,69 @@ -const fs = require("fs") -const forwardRegex = /XMAS/g -const backwardRegex = /SAMX/g -const input = fs.readFileSync("input.txt","utf-8") -const inputArr = input.split("\n") -let totalMatches= 0; +const fs = require("fs"); +const forwardRegex = /XMAS/g; +const backwardRegex = /SAMX/g; +const input = fs.readFileSync("input.txt", "utf-8"); +const inputArr = input.split("\n"); +let totalMatches = 0; // console.log(inputArr) // const forwardMatchs = input.match(forwardRegex) // console.log(input) // console.log(forwardMatchs.length) //create a sliding window to match the words +// for (row of inputArr) { +// // console.log(row) +// const forwardMatches = row.match(forwardRegex); +// const backwordsMatches = row.match(backwardRegex); -for (row of inputArr){ - // console.log(row) - const forwardMatches = row.match(forwardRegex) - const backwordsMatches= row.match(backwardRegex) +// if (forwardMatches) { +// totalMatches += forwardMatches.length; +// } +// if (backwordsMatches) { +// totalMatches += backwordsMatches.length; +// } +// } - if(forwardMatches){ - totalMatches += forwardMatches.length - } - if(backwordsMatches){ - totalMatches += backwordsMatches.length +// console.log(inputArr) +const maxRows = inputArr.length; +const maxLetters = inputArr[0].length; + +//horizontal words +for (let x = 0; x < maxRows; x++) { + for (let y = 0; y + 3 <= maxLetters; y++) { + const word = inputArr[x][y] + inputArr[x][y + 1] + inputArr[x][y + 2] + inputArr[x][y + 3]; + if (forwardRegex.test(word) || backwardRegex.test(word)) { + totalMatches++; } + } } -console.log("totalMatches: ",totalMatches) \ No newline at end of file +//vertical words +for (let x = 0; x + 3 < maxRows; x++) { + for (let y = 0; y <= maxLetters; y++) { + const word = inputArr[x][y] + inputArr[x + 1][y] + inputArr[x + 2][y] + inputArr[x + 3][y]; + if (forwardRegex.test(word) || backwardRegex.test(word)) { + totalMatches++; + } + } +} +//angled words 1 +for (let x = 0; x + 4 < maxRows; x++) { + for (let y = 0; y +3< maxLetters; y++) { + const word = inputArr[x][y] + inputArr[x + 1][y + 1] + inputArr[x + 2][y + 2] + inputArr[x + 3][y + 3]; + if (forwardRegex.test(word) || backwardRegex.test(word)) { + totalMatches++; + } + } +} +//angled words 2 +for (let x = 0; x + 4 < maxRows; x++) { + for (let y = 0; y +3< maxLetters; y++) { + const word = inputArr[x][y+3] + inputArr[x+1][y + 2] + inputArr[x + 2][y + 1] + inputArr[x+3][y]; + if (forwardRegex.test(word) || backwardRegex.test(word)) { + totalMatches++; + } + console.log(word); + } +} + +console.log("totalMatches: ", totalMatches);