fork download
  1. # Problem-1 : Trimorphic.
  2.  
  3. def trimorphic?(n)
  4. def check(n, c)
  5. n == 0 || (n%10 == c%10 && check(n/10, c/10))
  6. end
  7. n = n.abs
  8. check(n, n**3)
  9. end
  10.  
  11. 100.times do |i|
  12. if trimorphic?(i)
  13. printf("%-6d : %d\n", i**3, i)
  14. end
  15. end
  16.  
  17. # Problem-2 : Pendulum.
  18.  
  19. def pendulum_1(s)
  20. r = []
  21. s.chars.sort!.each_with_index do |x, i|
  22. r.public_send(i.even? ? :unshift : :push, x)
  23. end
  24. r.join
  25. end
  26.  
  27. def pendulum_2(s)
  28. n = s.size
  29. m = (n+1) / 2
  30. r = []
  31. s.chars.sort!.each_with_index do |x, i|
  32. j = i / 2
  33. r[i.even? ? m-j-1 : m+j] = x
  34. end
  35. r.join
  36. end
  37.  
  38. def pendulum_3(s)
  39. t = s.chars.sort!
  40. l, r = t.drop(1).partition.each_with_index {|_, i| i.odd?}
  41. (l.reverse + t.take(1) + r).join
  42. end
  43.  
  44. def pendulum_4(s)
  45. l, r = (1...s.size).partition{|x| x.even?}
  46. s.chars.sort!.values_at(*l.reverse, 0, *r).join
  47. end
  48.  
  49. # ..
  50.  
  51. def test(f)
  52. ss = ["", "a", "ba", "bca", "computer", "science"]
  53. rs = ["", "a", "ab", "cab", "tpmceoru", "sieccen"]
  54.  
  55. ss.zip(rs) do |s, r|
  56. s = f.call(s)
  57. if s != r
  58. puts " Failed: expected `#{r}' got `#{s}'"
  59. return
  60. end
  61. end
  62. puts " Passed"
  63. end
  64.  
  65. def time(f)
  66. def choices(pool, n)
  67. n.times.map{pool[rand(pool.size)]}
  68. end
  69.  
  70. symbols = (32..126).map(&:chr) # printable
  71. elapsed = 0
  72.  
  73. 16.times do |i|
  74. s = choices(symbols, 2**i).join
  75. t = Time.now
  76. f.call(s)
  77. elapsed += Time.now - t
  78. end
  79. printf(" Elapsed: %.6f\n", elapsed)
  80. end
  81.  
  82. fs = [
  83. method(:pendulum_1),
  84. method(:pendulum_2),
  85. method(:pendulum_3),
  86. method(:pendulum_4)
  87. ]
  88.  
  89. fs.each do |f|
  90. puts f.name
  91. test(f)
  92. time(f)
  93. end
Success #stdin #stdout 0.36s 17252KB
stdin
Standard input is empty
stdout
0      : 0
1      : 1
64     : 4
125    : 5
216    : 6
729    : 9
13824  : 24
15625  : 25
117649 : 49
132651 : 51
421875 : 75
438976 : 76
970299 : 99
pendulum_1
 Passed
 Elapsed: 0.076422
pendulum_2
 Passed
 Elapsed: 0.042979
pendulum_3
 Passed
 Elapsed: 0.060657
pendulum_4
 Passed
 Elapsed: 0.046573