最终项目:传感器移植
Coddy 面向 Java 开发者的 Ruby 课程的第 48 课,共 48 课。
挑战
简单移植参考程序。Above(limit)#accept?(n) 会接受严格大于 limit 的 n。Sensor(policy)#feed(token) 会解析一个可选符号,后面跟一个或多个 ASCII 数字,中间不能有空格或其他字符;并且只接受 -1000000 到 1000000 之间的整数。无效 token 会使 invalid 加 1;被 policy 接受的有效 token 会使 accepted 加 1,并累加到 total。被拒绝的有效 token 不会改变任何计数。summary 会返回 accepted、invalid 和 total,三者之间以空格分隔。输入的第一行是 limit;剩余每一行都是一个 token,行尾换行符会被移除。三个计数器的初始值均为 0。自定义 policy 对象也必须能够使用。
让 solve(input) 返回文本,不要打印。锁定的驱动程序会在返回的文本末尾加一个换行符并打印,同时独立检查必需的公共 API。
你的代码写在 exercise.rb、above.rb 和 sensor.rb 中。main.rb 包含提供的输入/输出代码,不能编辑。
输入范围:数据行最多 1000 行。库存代码只包含小写 ASCII 字母,每个库存增量都在 -1000000 到 1000000 之间。对于传感器移植,第一行的 limit 在 -1000000 到 1000000 之间;token 是否有效遵循上述解析器约定。
以下是 Java 参考程序。使用要求的 Ruby API 实现相同行为。
import java.io.*;
import java.math.BigInteger;
public class Main {
interface Policy { boolean accepts(int value); }
static class Above implements Policy {
final int limit;
Above(int limit) { this.limit = limit; }
public boolean accepts(int value) { return value > limit; }
}
static class Sensor {
final Policy policy;
BigInteger accepted = BigInteger.ZERO;
BigInteger invalid = BigInteger.ZERO;
BigInteger total = BigInteger.ZERO;
Sensor(Policy policy) { this.policy = policy; }
void feed(String token) {
if (!token.matches("[+-]?[0-9]+")) { invalid = invalid.add(BigInteger.ONE); return; }
BigInteger value = new BigInteger(token);
if (value.abs().compareTo(BigInteger.valueOf(1000000)) > 0) invalid = invalid.add(BigInteger.ONE);
else if (policy.accepts(value.intValue())) {
accepted = accepted.add(BigInteger.ONE);
total = total.add(value);
}
}
String summary() { return accepted + " " + invalid + " " + total; }
}
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
Sensor sensor = new Sensor(new Above(Integer.parseInt(reader.readLine())));
String line;
while ((line = reader.readLine()) != null) sensor.feed(line);
System.out.println(sensor.summary());
}
}亲手试试
require_relative 'exercise'
require_relative 'above'
require_relative 'sensor'
def check(value)
raise 'Public API check failed' unless value
end
check(Above.new(4).accept?(5) && !Above.new(4).accept?(4))
policy = Object.new
def policy.accept?(n); n.even?; end
s = Sensor.new(policy)
["2", "-4", "3", "x", "4\n", "1000001"].each { |t| s.feed(t) }
check(s.summary == "2 3 -2" && s.summary == "2 3 -2")
puts solve(STDIN.read)
面向 Java 开发者的 Ruby中的所有课
自己练习: Ruby 在线编译器