Skip to content

Instantly share code, notes, and snippets.

@nilbus
Last active December 11, 2015 13:26
Show Gist options
  • Select an option

  • Save nilbus/37332d4fc5cd84cd54cc to your computer and use it in GitHub Desktop.

Select an option

Save nilbus/37332d4fc5cd84cd54cc to your computer and use it in GitHub Desktop.
def seed
1 # standing in for a non-numeric object that also responds to #next
end
# missing: Return enough items fill an array of existing items so that it has 10
# (multiple implementations)
# Test: assert_equal([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], missing([]))
# Test: assert_equal([9, 10], missing([1, 2, 3, 4, 5, 6, 7, 8]))
# @param queue: an Array with up to 10 items
# Imperative style
def missing(existing)
result = []
while result.size < 10 - existing.size
result << (result.last.try(:next) || existing.last.try(:next) || seed)
end
result
end
# each_with_object over a number range
def missing(existing)
(existing.size...10).each_with_object([]) do |_, result|
result << (result.last.try(:next) || existing.last.try(:next) || seed)
end
end
# recursive
def missing(existing, result = [])
return result if existing.size + result.size >= 10
incoming = result.last.try(:next) || existing.last.try(:next) || seed
missing(existing, result + [incoming])
end
def seed
1 # standing in for a non-numeric object that also responds to #next
end
# replenish: Add items to the queue until it has 10
# (multiple implementations)
# Test: assert_equal([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], replenish([]))
# @param queue: an Array with up to 10 items
# Imperative style
def replenish(queue)
result = queue.dup.presence || [seed]
while result.size < 10
result << result.last.next
end
result
end
# each_with_object over a number range
def replenish(queue)
queue = queue.presence || [seed]
(queue.size...10).each_with_object(queue.dup.presence) do |_, result|
result << result.last.next
end
end
# recursive
def replenish(queue)
return queue if queue.size >= 10
incoming = queue.last.try(:next) || seed
replenish(queue + [incoming])
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment