| Date | 2011/4/10 |
|---|---|
| Name | BullsAndCows |
| Description | A number guessing game written in Ruby |
| Filename | BullsAndCowsRuby.rb |
| Content |
|
| Sample Input: | |
| Sample Output: | |
| Expected Test Command: | ruby BullsAndCowsRuby.rb |
puts("Bulls and Cows")
puts("==============")
puts("This is an ancient game with guessing numbers.")
begin
secretDigit=4.times.map{Random.new.rand(0..9)}
secret=secretDigit.join("")
puts("A secret number of 4-digit has been draw!")
bull=0
begin
ans=""
playNextGame=""
begin
$stdout.print("Please enter a 4-digit number (or type 'quit' to exit):")
ans=gets.chomp
end while (ans =~ /^\d{4}$|^quit$/)==nil
if ans=="quit"
puts("The secret number is: "+secret)
else
bull=0
cow=0
arr=ans.split("").map{|num| num.to_i}
for i in 0..3
if arr[i]==secretDigit[i]
bull+=1
end
end
for i in 0..3
for j in 0..3
if arr[j]==secretDigit[i]
cow+=1
arr[j]= -1
break
end
end
end
cow=cow-bull
if cow==0 and bull==0
msg="Neither a bull nor a cow!"
else
if bull==4
msg="4 bulls! You are a genius!"
else
if cow==0
if bull==1
msg="1 bull only."
else
msg=bull.to_s+" bulls only."
end
else
if bull==0
if cow==1
msg="1 cow only."
else
msg=cow.to_s+" cows only."
end
else
if bull==1
msg="1 bull and "
else
msg=bull.to_s+" bulls and "
end
if cow==1
msg+=" 1 cow."
else
msg+=cow.to_s+" cows."
end
end
end
end
end
puts(msg)
end
end until bull==4 or ans=="quit"
if ans!="quit"
begin
$stdout.print("Do you want to play a new game (Y/N)?")
playNextGame=gets.chomp
end until playNextGame.upcase=="Y" or playNextGame.upcase=="N"
end
end until playNextGame.upcase!="Y" or ans=="quit"
puts("Thank you for playing Bulls and Cows!")| Date | 2011/4/9 |
|---|---|
| Name | Add Two Numbers |
| Description | Add Two Numbers using Ruby |
| Filename | AddTwoNumRuby.rb |
| Content |
|
| Sample Input: | 123 3.5 dsfasd 4 fdsafds 6 |
| Sample Output: | 126 0 |
| Expected Test Command: | ruby AddTwoNumRuby.rb < testdata.txt |
begin nCount=0 total=0 while true temp=gets.chomp.split(/\s+/) temp.each do|n| begin if nCount%2==0 total=Integer(n) nCount+=1 else number2=Integer(n) total+=number2 nCount+=1 $stdout.print(total.to_s+" ") end rescue end end end rescue end
| Date | 2011/4/8 |
|---|---|
| Name | Hello Friend |
| Description | Ask user's name and echo greeting message to user using Ruby |
| Filename | HelloFriendRuby.rb |
| Content |
|
| Sample Input: | Peter Pan |
| Sample Output: | Hello, Peter Pan! |
| Expected Test Command: | ruby HelloFriendRuby.rb < testdata.txt |
begin
while true
print("Your name?")
name=gets.chomp
puts("Hello, "+name+"!")
end
rescue
end
| Date | 2011/4/7 |
|---|---|
| Name | Hello World |
| Description | Display greeting message to user using Ruby |
| Filename | HelloWorldRuby.rb |
| Content |
|
| Sample Input: | |
| Sample Output: | Hello, World! |
| Expected Test Command: | scalac HelloWorldScala.scala scala HelloWorldScala |
puts("Hello, World!")