I forgot to mention it, but do read the instructions this time too.
We need to analyze the rows and tell if they are safe or not.
Similarly to last time, let's read the file using the fetch function using an async function as
the wrapper, and split the lines into an array.
async function main(){
let file_response = await fetch("./input2.txt");
let file_string = await file_response.text();
let file_lines = file_string.split("\n");
}
main();
Next, we need to create a variable to track the unsafe lines, iterate through the lines with
another for of loop and split the datapoints by whitespaces.
let unsafe_num = 0;
for (let i of file_lines) {
let data_list = i.split(" ");
}
Now still inside this for loop, we need to convert the array of strings into an array of numbers.
data_list = data_list.map(text => Number(text));
The ".map()"
function takes one argument for our purposes, a function...
This is called a "lambda" function for... well... reasons. The syntax is "(arguments) => { return some_value; }. This, however, can be simplified to "argument => some_value".
...which it calls for every element in the array, and returns an array built from the values that function returns.
Now we need to do the checking:
let ascending = (data_list[0] - data_list[1]) < 0;
let last;
for (let j of data_list) {
if (last === undefined){
last = j;
continue;
}
if (Math.abs(last - j) > 3 || Math.abs(last - j) === 0 || (((last - j) < 0)) !== ascending) { // last-j is negative if j is larger, so it's ascending
unsafe_num++;
break;
}
last = j;
}
We create two variables here, one checking for the direction of the change and one to store the last number in the array.
The first if statement is there to handle the start of the loop and initialize the "last" variable.
The second if statement marks the line unsafe if one of the three things occurs.
The difference is larger than 3
The difference is zero
The direction of change doesn't match the initially determined one.
If the difference is unsafe, we add one to the counter and break out of the loop.
The next and final step is printing out the number of safe lines. This is done outside the two for loops, at the end of the main() function.