Advertisement
Guest User

Untitled

a guest
Sep 4th, 2015
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.59 KB | None | 0 0
  1. # https://www.hackerrank.com/challenges/maximise-sum
  2.  
  3. # Accept input
  4. ##
  5.  
  6. def respond_bad_input
  7. puts "Bad input."
  8. end
  9.  
  10. def check_for_new_max(mod, array, old_max)
  11. (get_mod_sum(mod,array)) > old_max
  12. end
  13.  
  14. def get_mod_sum(mod, array)
  15. (array.inject{ |sum,x| sum + x }) % mod
  16. end
  17.  
  18. index_size = 0
  19. index_modulo = 1
  20. index_array = 2
  21.  
  22. test_cases_count = 0
  23. test_cases = []
  24.  
  25. input_array = ARGF.to_a
  26.  
  27. if input_array.count > 0
  28. test_cases_count = input_array[0]
  29. else
  30. respond_bad_input
  31. end
  32.  
  33. (1..(input_array.count-1)).step(2).each do |index|
  34. if input_array.count-1 > index+1
  35. respond_bad_input
  36. else
  37. size = input_array[index].split(" ")[0].to_i
  38. modulo = input_array[index].split(" ")[1].to_i
  39. test_array = input_array[index+1].split(" ")
  40. test_array.map!{ |value| value.to_i }
  41.  
  42. test_cases.push([size, modulo, test_array ])
  43. end
  44. end
  45.  
  46. # Run each test case
  47. ##
  48. test_cases.each do |current_case|
  49. max_value = 0
  50.  
  51. current_case[index_array].each_with_index do |value, index|
  52.  
  53. sub_array = [value]
  54.  
  55. if check_for_new_max(current_case[index_modulo], sub_array, max_value)
  56. max_value = get_mod_sum(current_case[index_modulo], sub_array)
  57. end
  58.  
  59. (index..(current_case[index_array].count-1)).each do |sub_index|
  60. sub_array = sub_array.push sub_index
  61.  
  62. if check_for_new_max(current_case[index_modulo], sub_array, max_value)
  63. max_value = get_mod_sum(current_case[index_modulo], sub_array)
  64. max_array = sub_array
  65. end
  66. end
  67. end
  68.  
  69. puts max_value
  70. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement