Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Problem 1
- # Write three functions that compute the sum of the numbers in a given list using a for-loop, a while-loop, and recursion.
- array = [1, 2, 3, 4, 5]
- result = 0
- # array.sum
- array.each do |num|
- result += num
- end
- puts result
- while array.empty? == true
- result = result +=array[0]
- end
- puts result
- def sum_rec(array)
- return 0 if array.length == 0
- array[0] + sum_rec(array[1..-1])
- end
- # Problem 2
- # Write a function that combines two lists by alternatingly taking elements.
- #For example: given the two lists [a, b, c] and [1, 2, 3], the function should return [a, 1, b, 2, c, 3].
- letters = ['a', 'b', 'c']
- numbers = [1, 2, 3]
- print letters.zip(numbers).flatten
- # Problem 3
- # Write a function that computes the list of the first 100 Fibonacci numbers.
- # By definition, the first two numbers in the Fibonacci sequence are 0 and 1,
- # and each subsequent number is the sum of the previous two. As an example,
- # here are the first 10 Fibonnaci numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, and 34.
- a = 0
- b = 1
- 10.times do
- temp = a
- a = b
- b = temp + b
- end
- puts a
- # Problem 4
- # Write a function that given a list of non negative integers, arranges them such
- # that they form the largest possible number. For example, given [50, 2, 1, 9],
- # the largest formed number is 95021.
- #check [0] index in array for largest number and compare to the rest of the array
- #check [-1..1] index in array for largest num
- # Problem 5
- # Write a program that outputs all possibilities to put + or - or nothing between
- # the numbers 1, 2, ..., 9 (in this order) such that the result is always 100.
- # For example: 1 + 2 + 34 – 5 + 67 – 8 + 9 = 100.
Add Comment
Please, Sign In to add comment