Skip to content

Instantly share code, notes, and snippets.

@kawakami-o3
Created August 21, 2011 20:21
Show Gist options
  • Save kawakami-o3/1161104 to your computer and use it in GitHub Desktop.
Save kawakami-o3/1161104 to your computer and use it in GitHub Desktop.
Why is this short code incorrect, "Runtime Error"?
#!/usr/bin/ruby
# http://www.codechef.com/COOK13/problems/DRAGNXOR/
n = gets.to_i
n.times do
arr = gets.split.map {|i| i.to_i}
bit = 0
[1,2].each do |i|
while arr[i] > 0
bit += arr[i] % 2
arr[i] /= 2
end
end
## Runtime Error
if bit <= arr[0]
puts (0..bit-1).inject(0) {|s,i| s+=2**(arr[0]-1-i)}
else
puts (0..arr[0]-(bit-arr[0])-1).inject(0) {|s,i| s+=2**(arr[0]-1-i)}
end
## correct code
#t = [bit, arr[0]-(bit-arr[0])].min -1
#puts (0..t).inject(0) {|s,i| s+=2**(arr[0]-1-i)}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment