Guest User

Untitled

a guest
Aug 17th, 2018
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. # Problem 1
  2. # Write three functions that compute the sum of the numbers in a given list using a for-loop, a while-loop, and recursion.
  3.  
  4. array = [1, 2, 3, 4, 5]
  5. result = 0
  6. # array.sum
  7.  
  8. array.each do |num|
  9. result += num
  10. end
  11. puts result
  12.  
  13. while array.empty? == true
  14. result = result +=array[0]
  15. end
  16. puts result
  17.  
  18. def sum_rec(array)
  19. return 0 if array.length == 0
  20. array[0] + sum_rec(array[1..-1])
  21. end
  22.  
  23. # Problem 2
  24. # Write a function that combines two lists by alternatingly taking elements.
  25. #For example: given the two lists [a, b, c] and [1, 2, 3], the function should return [a, 1, b, 2, c, 3].
  26.  
  27. letters = ['a', 'b', 'c']
  28. numbers = [1, 2, 3]
  29.  
  30. print letters.zip(numbers).flatten
  31.  
  32. # Problem 3
  33. # Write a function that computes the list of the first 100 Fibonacci numbers.
  34. # By definition, the first two numbers in the Fibonacci sequence are 0 and 1,
  35. # and each subsequent number is the sum of the previous two. As an example,
  36. # here are the first 10 Fibonnaci numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, and 34.
  37. a = 0
  38. b = 1
  39. 10.times do
  40. temp = a
  41. a = b
  42. b = temp + b
  43. end
  44. puts a
  45.  
  46. # Problem 4
  47. # Write a function that given a list of non negative integers, arranges them such
  48. # that they form the largest possible number. For example, given [50, 2, 1, 9],
  49. # the largest formed number is 95021.
  50.  
  51. #check [0] index in array for largest number and compare to the rest of the array
  52. #check [-1..1] index in array for largest num
  53.  
  54. # Problem 5
  55. # Write a program that outputs all possibilities to put + or - or nothing between
  56. # the numbers 1, 2, ..., 9 (in this order) such that the result is always 100.
  57. # For example: 1 + 2 + 34 – 5 + 67 – 8 + 9 = 100.
Add Comment
Please, Sign In to add comment