Skip to content

Instantly share code, notes, and snippets.

Validation

Example 6

Inputs:

  • Target number: 20
  • Factors: [19]

Output

  • 19
function sumOfMultiples(targetNumber, factors) {
var multiples = [];
if (factors.length === 0) {
factors = [3, 5];
}
factors.forEach(function(factor) {
var currentMultiple;
for (currentMultiple = factor; currentMultiple < targetNumber; currentMultiple += factor) {
if (multiples.indexOf(currentMultiple) === -1) {
def sum_of_multiples(target, factors)
multiples = []
factors = [3, 5] if factors.length == 0
factors.each do |factor|
current_multiple = factor
while current_multiple < target
multiples << current_multiple
current_multiple += factor

Example 1

Inputs:

  • Target number: 20
  • Number to get multiples: [3, 5]

Output

  • 78

Algorithm

First Mental Model

Determine a list of all multiples of a set of factors up to a target value, then filter the list of multiples to the unique values. Finally, compute and return the sum of the unique multiples.

  1. Create an empty array called multiples that will contain the multiples.
  2. Check whether the list of factors is empty. If there are no factors, set the list to [3, 5]
  3. For every factor in the factors list:
    1. Set the current_multiple to factor to keep track of the multiples of factor.
    2. While current_multiple < target
      1. Append the current_multiple to multiples.
      2. Add factor to current_multiple.
  4. Filter duplicate numbers from multiples.

Where to Start?

In this step, if you have a mental model, you can start there. Otherwise, start with the "Data Structure" step and think of how you'd build and manipulate it to get the output. For instance, if it's an array, you'd probably focus on constructing or iterating over a collection.

Validation

Example 1

Inputs:

  • Target number: 20
  • Factors: [3, 5]

Output

  • 78

Example 2

Mental Model

A mental model is an explanation of someone's thought process about how something works in the real world (source: wikipedia)

Problem Domain

A problem domain is the area of expertise or application that needs to be examined to solve a problem (source: problem domain wiki). It limits the scope of the problem.

Pitfall Description
Missed requirements Missed requirements can lead to unnecessary refactoring, especially if the initial implementation cannot accommodate the missed requirements.
Unforeseen edge cases Unforeseen edge cases can also lead to unnecessary refactoring or the insertion of new code that obscures the intent of the code.
Hard to understand code When you refactor code to accommodate a new and better understanding of the problem, the resulting code is often harder to understand since your revised logic may be more complex than otherwise.
Difficult to maintain code The refactors can sometimes lead to unintended dependencies that make it difficult to change the code.
Difficult to scale code Not planning for scaling can lead to inefficiencies and complexity.