Created
May 10, 2013 07:17
-
-
Save ArtBears/5552893 to your computer and use it in GitHub Desktop.
I recreated my other card trick which was in c++ to a ruby application. I'm trying to see if I can simplify the code even more.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
=begin | |
This is a number analogy to a famous card trick. | |
Ask the user to enter a three-digit number. Think | |
of the number as ABC (where A, B, C are the three | |
digits of the number). Now, find the remainders of | |
the numbers formed by ABC, BCA, and CAB when divided | |
by 11. We will call these remainders X, Y, Z. Add | |
them up as X+Y, Y+Z, Z+X. If any of the sums are odd, | |
increase or decrease it by 11 (whichever operation | |
results in a positive number less than 20; note if | |
the sum is 9, just report this and stop the process). | |
Finally, divide each of the sums in half. The | |
resulting digits are A, B, C. Write a program that | |
implements this algorithm. | |
=end | |
def first_number(x) | |
p = x.to_i % 100 | |
q = ((x.to_i - p.to_i) / 100) | |
return q | |
end | |
def second_number(x) | |
p = ((x.to_i % 100) * 10) / 100 | |
return p | |
end | |
def third_number(x) | |
p = x.to_i % 10 | |
return p | |
end | |
def find_remainder(hundreds, tens, ones) | |
hundreds = hundreds.to_i * 100 | |
tens = tens.to_i * 10 | |
new_number = (hundreds + tens + ones) % 11 | |
return new_number | |
end | |
def is_odd(x) | |
if (x % 2) == 0 | |
return false | |
else return true | |
end | |
end | |
def less_than_20(x) | |
if x < 9 | |
x = (x + 11) / 2 | |
elsif x > 9 | |
x = (x-11) / 2 | |
else | |
return x | |
end | |
return x | |
end | |
def equation(x, y, z) | |
u = x + y | |
p = y + z | |
s = z + x | |
if is_odd(u) == true | |
u = less_than_20(u) | |
else | |
u = u / 2 | |
end | |
if(is_odd(p) == true) | |
p = less_than_20(p) | |
else | |
p = p / 2 | |
end | |
if(is_odd(s) == true) | |
s = less_than_20(s) | |
else | |
s = s / 2 | |
end | |
puts "A: " << u.to_s | |
puts "B: " << p.to_s | |
puts "C: " << s.to_s | |
end | |
puts "Enter a 3 digit number: " | |
abc = gets.chomp | |
if (abc.to_i > 99 && abc.to_i < 1000) | |
a = first_number(abc) | |
b = second_number(abc) | |
c = third_number(abc) | |
x = find_remainder(a,b,c) | |
y = find_remainder(b,c,a) | |
z = find_remainder(c,a,b) | |
equation(x,y,z) | |
else | |
puts "The integer must be 3 digits!" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment