Algorithms (Data Transformations)

Edit this Page

Algorithms are how we transform data from one form to another. When programming, algorithms are sets of instructions stored as functions.

The following algorithm takes a list of names as input and returns the longest name as output:

(in Ruby)

def find_longest_name(people)
  people.reduce("") do |longest_so_far, person|
    longest_so_far.length > person.length ? longest_so_far : person
  end
end

find_longest_name(["Annabelle", "Jamal", "Rhonda"])
# "Annabelle"
find_longest_name(["Jarvis", "Kaitlin", "Adrian"])
# "Kaitlin"

(in JavaScript)

function findLongestName(people) {
  return people.reduce(function(longestSoFar, person) {
    return longestSoFar.length > person.length ? longestSoFar : person;
  }, "")
}

findLongestName(["Annabelle", "Jamal", "Rhonda"]);
// "Annabelle"
findLongestName(["Jarvis", "Kaitlin", "Adrian"]);
// "Kaitlin"

This algorithm could be translated into english by saying:

Reduce the list of people to a single person by iterating over each person, comparing this persons length to the longest person so far, and capturing the longer of the two as the new longest element so far.