410

Look ma' I know my algorithms!

RubyConf Argentina 2014

October 24, 2014

Transcript

14. Ordered array How many pairs (a,b) where a ≠ b

-100 <= a + b <= 100

17. Array: [-100, 1, 100] (-100, 1), (-100, 100), (1, 100)

-100 + 1 = 99 YES
18. Array: [-100, 1, 100] (-100, 1), (-100, 100), (1, 100)

-100 + 100 = 0 YES
19. Array: [-100, 1, 100] (-100, 1), (-100, 100), (1, 100)

1 + 100 = 101 NO

Result: 2

a + b <= 100
22. def count! combinations = @numbers.combination(2).to_a! ! combinations! .map{ |a,b| a

+ b }! .select do |sum|! sum.abs <= THRESHOLD! end.size! end

25. Big O notation How WELL an algorithm SCALES as the

DATA involved INCREASES

27. Calc Array size (length=N) Count elements one by one: O(N)

Length stored in variable: O(1)

29. Remember: f < g => O(f + g) = O(g)

O(K . f) = O(f) O(1) < O(ln N) < O(N) < O(N2) < O(eN)
30. Ex: Binary Search Find 7 in [1, 2, 3, 4,

5, 6, 7, 8] 1. element in the middle is 5 2. 5 == 7 ? NO 3. 5 < 7 ? YES => Find 7 in [6, 7, 8] Step 1
31. ! Find 7 in [0, 1, 2, 3, 4, 5,

6, 7, 8] 1. element in the middle is 7 2. 7 == 7 ? YES! FOUND IT!! Step 2
32. Ex: Binary Search Worst case: ceil ( Log2 N )

23 = 8 ONLY 3 steps

N) Sequential search O(N) Traverse a matrix NxN O(N2)

38. None
39. None
40. None
41. None
42. None
43. None

47. None
48. What do we REALLY get? O(N2 / cores) = O(N

2 ) jRubyGo Scala

53. Given [1,2,3,4,5] Take 1, then print [5,4,3,2] Take 2, then

print [5,4,3] and so on…
54. What’s the ORDER of this code? @nums.each_with_index do |a,i|! !

puts @nums.slice(i+1,N).reverse! .inspect! end
55. What’s the ORDER of this code? @nums.each_with_index do |a,i|! !

puts @nums.slice(i+1,N).reverse! .inspect! end Looks like O(N)
56. What’s the ORDER of this code? @nums.each_with_index do |a,i|! !

puts @nums.slice(i+1,N).reverse! .inspect! end Behaves like O(N2)

59. What’s the ORDER of this code? @nums.each_with_index do |a,i|! !

puts @nums.slice(i+1,N).reverse! .inspect! end O(N2)!