DEV Community

Discussion on: Let's Solve: Code Challenge - Picking Numbers

Collapse
 
tobias_salzmann profile image
Tobias Salzmann • Edited

I like the approach! Maybe a bit of feedback:

The necessity of using comments to structure code is often an indication for a function being too long. Your code is already well structured, so you can directly extract the parts of your code as functions:

function main() {
    var numbers = readInput();
    var numberCounts = constructAndPopulateMap(numbers);
    var maxSum = findMaxSumOfAdjacentNumbers(numberCounts);

    console.log(maxSum);
}

function readInput() {
  var n = parseInt(readLine());
  a = readLine().split(' ');
  a = a.map(Number);
  return a;
}

function constructAndPopulateMap(numbers){
  var map = new Array(100);
    map.fill(0);

  for(var i = 0; i < a.length; i++){
        map[a[i]]++;
  }

  return map;
}

function findMaxSumOfAdjacentNumbers(map) {
  var max = 0;
  for(var i = 1; i < map.length; i++){
    if(map[i] + map[i - 1] > max){
      max = map[i] + map[i - 1];
    }
  }
  return max;
}
Enter fullscreen mode Exit fullscreen mode

This has several benefits:

  • no comments needed
  • Variables are scoped appropriately.
  • You can easily test the parts of your program.
  • Improved readability

Here's a solution (minus the parsing) using exclusively functions from the utility library ramda. Each number is assigned to 2 potential clusters and all that's left is to find the most common cluster.
There is quite some functional lingo in there, but it doesn't require much javascript knowledge.

const largestCluster = (numbers) => {
  const countByValue = reduceBy(inc, 0)(identity)
  const maxOccurences = pipe(countByValue, values, reduce(max, 0))

  const clusters = chain(n => [[n-1, n], [n, n + 1]])(numbers)
  return maxOccurences(clusters)
}
Enter fullscreen mode Exit fullscreen mode

repl:
ramdajs.com/repl/?v=0.25.0#?const%...