[英]How to read by the number at each iteration of the loop in Ruby?
如何在循環的每次迭代中讀取數字? 動態工作很重要(不是一次讀取整行並轉換為數組),在每次迭代時,從文件字符串中取一個數字並使用它。 怎么做對了?
input.txt:
5
1 7 5 2 3
使用文件的第二行。
fin = File.open("input.txt", "r")
fout = File.open("output.txt", "w")
n = fin.readline.to_i
heap_min = Heap.new(:min)
heap_max = Heap.new(:max)
for i in 1..n
a = fin.read.to_i #code here <--
heap_max.push(a)
if heap_max.size > heap_min.size
tmp = heap_max.top
heap_max.pop
heap_min.push(tmp)
end
if heap_min.size > heap_max.size
tmp = heap_min.top
heap_min.pop
heap_max.push(tmp)
end
if heap_max.size == heap_min.size
heap_max.top > heap_min.top ? median = heap_min.top : median = heap_max.top
else
median = heap_max.top
end
fout.print(median, " ")
end
閱讀文件的第二行:
line2 = File.readlines('input.txt')[1]
將其轉換為整數數組:
array = line2.split(' ').map(&:to_i).compact
如果您100%確定您的文件按空格分隔數字,您可以嘗試這樣做:
a = fin.gets(' ', -1).to_i
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.