0

I was playing around with some challenges at codeeval.com and I get stuck when it comes to submitting my code. There is this weird bunch of code and I just don't understand, where to put my code :) Here is what I see:

 =begin
 Sample code to read in test cases:
 File.open(ARGV[0]).each_line do |line|
 #Do something with line, ignore empty lines
 #...
 end
 =end

The task is: Given numbers x and n, where n is a power of 2, print out the smallest multiple of n which is greater than or equal to x. Do not use division or modulo operator.

INPUT SAMPLE:

The first argument will be a path to a filename containing a comma separated list of two integers, one list per line. E.g.

13,8

17,16

OUTPUT SAMPLE:

Print to stdout, the smallest multiple of n which is greater than or equal to x, one per line. E.g.

16
32

My code works, when I run it through the terminal. It looks like this:

def multiples(x, n)
while n < x
n *= 2
end
puts n
end 

Thank you for your attention! :)

4

2 回答 2

0

所以,感谢您的支持。我还修复了代码。我的第一个正确解决的 codeeval 问题:D

def multiples(x, n)
    m = 0
    while m < x
    m += n  
    end
    puts m
end     



 File.open(ARGV[0]).each_line do |line|
    x, n = line.split(',').map { |x| x.to_i }
    puts multiples(x, n)
 end
于 2015-02-23T15:11:54.297 回答
0
# You can place your method definitions and other things 
# needed to solve the problem right here.
# ...   

# Code to read in test cases : 
File.open(ARGV[0]).each_line do |line|
    # You should solve stuffs here and print to stdout.
    # Parse your input values from the line variable,
    # which will contain a single line from the input file.
    # And print the output to stdout (puts or print).
end

例如,问题是它要求您查找并打印(到标准输出)给定文件中所有数字对的总和。这些对将放置在文件内的各个行上。

假设输入文件(input.txt)将是这样的:

1,2
3,4
5,10

然后你可以(我不是告诉你应该,还有其他方法)编写解决方案(solution.rb)来解决它:

def add(a, b)
    a + b
end

File.open(ARGV[0]).each_line do |line|
    a, b = line.split(',').map { |x| x.to_i }
    puts add(a, b)
end

要在本地对其进行测试,请按以下方式调用它:

$ ruby solution.rb input.txt
于 2015-02-23T07:17:56.757 回答