Advertisement
rockdrilla

wtf, rev.1

Mar 31st, 2017
596
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 2.14 KB | None | 0 0
  1. #!/usr/bin/env ruby
  2. n = STDIN.readline().strip().to_i()
  3. numbers = STDIN.readline().split(/\s/).compact().map(&:to_i)
  4. answer = STDIN.readline().strip().to_i()
  5.  
  6. if (numbers.length != n) then
  7.   printf("array size mismatch\n")
  8.   exit
  9. end
  10.  
  11. def exit_no_solution()
  12.   printf("no solution\n")
  13.   exit
  14. end
  15.  
  16. min = numbers[0]
  17. i = 1; while (i < n) do
  18.   min -= numbers[i]
  19.   i += 1 ## it's better to use "i++", but Ruby doesn't have increment
  20. end
  21. if (answer < min) then
  22.   exit_no_solution()
  23. end
  24.  
  25. max = 0
  26. i = 0; while i < n do
  27.   max += numbers[i]
  28.   i += 1 ## it's better to use "i++", but Ruby doesn't have increment
  29. end
  30.  
  31. if (answer > max) then
  32.   exit_no_solution()
  33. end
  34.  
  35. ## array with signs: "false" means "-", "true" means "+" %)
  36. signs = Array.new(n, false) ### [false, false, false, ...]
  37. signs[0] = true ### [true, false, false, ...]
  38.  
  39. while true do
  40.   result = 0
  41.   i = 0; while i < n do
  42.     if signs[i] then
  43.       result += numbers[i]
  44.     else
  45.       result -= numbers[i]
  46.     end
  47.     i += 1 ## it's better to use "i++", but Ruby doesn't have increment
  48.   end
  49.  
  50.   if result == answer then
  51.     printf("%d = ", answer)
  52.     i = 0; while i < n do
  53.       if (i != 0) then
  54.         if signs[i] then
  55.           printf(" + ")
  56.         else
  57.           printf(" - ")
  58.         end
  59.       end
  60.       printf("%d", numbers[i])
  61.       i += 1 ## it's better to use "i++", but Ruby doesn't have increment
  62.     end
  63.     printf("\n")
  64.     exit
  65.   end
  66.  
  67.   ## treat signs as little-endian binary value and implement increment logic on top of it
  68.   ## k - index of last "false" element
  69.   k = n; while k != 0 do
  70.     k -= 1 ## it's better to use "k--", but Ruby doesn't have decrement
  71.     if ! signs[k] then
  72.       break
  73.     end
  74.   end
  75.  
  76.   ## if k points to first element then our "little-endian value" has reached maximum value
  77.   ## nothing to do here, sorry
  78.   if k == 0 then
  79.     break
  80.   end
  81.  
  82.   ## increment element
  83.   signs[k] = true
  84.  
  85.   ## decrement elements after current
  86.   i = k + 1; while i < n do
  87.     signs[i] = false
  88.     i += 1 ## it's better to use "i++", but Ruby doesn't have increment
  89.   end
  90.  
  91.   ## proceed to next iteration
  92. end
  93.  
  94. exit_no_solution()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement