Doing the next challenge but this time, I’ve done them both in Node and in Perl, and I’ll blog the Node versions.

### TASK #1 › Smallest Positive Number

You are given unsorted list of integers @N.

Write a script to find out the smallest positive number missing.

``````// I don't do anything that really NEEDS to be forced to be
// strict, I don't think, but that's kinda the same with my
// Perl
"use strict";

// with perl, we can explicitly control whether we're dealing
// with \$a, \$b, \$c or @n, but with JS, you need to create the
// array more or less explicitly
// Array(12).fill().,map((n, i) => 1 + i) ) is JS's way of doing
// the range operator, which would be 1..12 in Perl.

console.log(spnm([5, 2, -2, 0]));
console.log(spnm([1, 8, -1]));
console.log(spnm([2, 0, -1]));
console.log(
spnm(
Array(12)
.fill()
.map((n, i) => 1 + i)
)
);

function spnm(array) {
let list = array.filter((i) => i > 0); // filter out non-positives
let max = 1 + Math.max(...list); // find one plus the highest number
let range = Array(max)
.fill()
.map((n, i) => 1 + i); // range 1..max

// hash for easy lookup. There might be a shorter way, but
// this works
let hash = {};
for (let i in list) {
let n = list[i];
hash[n] = 1;
}

// we're looking for a number that doesn't exist in the array
// so that's a check on the "hash" we created. In JS, that's a
// an object.
for (let i in range) {
let n = range[i];
if (!hash[n]) {
return n;
}
}

// Sir, the impossible scenario we never planned for?
// Well, we better come up with a plan.
return -1;
}
``````

### TASK #2 › Count Candies

You are given rankings of @N candidates.

Write a script to find out the total candies needed for all candidates. You are asked to follow the rules below:

a) You must given at least one candy to each candidate. b) Candidate with higher ranking get more candies than their mmediate neighbors on either side.

``````"use strict";

console.log(candy_count([1, 2, 2]));
console.log(candy_count([1, 4, 3, 2]));

function candy_count(candidates) {
let total = 0;
console.log(candidates);
for (let i in candidates) {
i = parseInt(i); // string by default
let v = candidates[i];
let prev = candidates[i - 1] || 0;
let next = candidates[i + 1] || 0;

// I didn't fully get the rules at first, thinking that
// a candidate must be higher than left and right to get
// the point, but instead, it's
//   + higher than left gets a point
//   + higher than right gets a point
// so in the case of [1,2,1], the values you get are
//                   [1,3,1], and the total is 5.

total++;
if (v > prev && prev != 0) {
total++;
}
if (v > next && next != 0) {
total++;
}
}