ruby比较字符串(带符号)以查找最接近的整数匹配

ruby比较字符串(带符号)以查找最接近的整数匹配,ruby,Ruby,我有一个数组,它遵循由冒号、lat、lng分隔的时间戳格式。我还有另一个时间戳数组。我试图比较阵列并找到最接近的匹配,然后返回相应的lat和lng timestampArr=["3,18,9,24,34","2,27,7,22,49"] gpsArr=["3:15:9:24:36,33.6789,78.8908","3:17:9:2:34,33.7,88.9"] #output expected: ["33.7,88.9","33.6789,78.8908"] #first timestamp

我有一个数组,它遵循由冒号、lat、lng分隔的时间戳格式。我还有另一个时间戳数组。我试图比较阵列并找到最接近的匹配,然后返回相应的lat和lng

timestampArr=["3,18,9,24,34","2,27,7,22,49"]
gpsArr=["3:15:9:24:36,33.6789,78.8908","3:17:9:2:34,33.7,88.9"]
#output expected: ["33.7,88.9","33.6789,78.8908"]
#first timestamp in timestampArr matches 2nd timestamp in gpsArr so return that lat,lng
我的代码:

def closest_float(xs, value)
  xs.min_by { |x| (x.to_f - value).abs }
end

    def getGPSforTime(timeArr.gpsFilepath)
     text=text.each_slice(7).to_a #5 for timestamp(sep ,) +lat+lng
        gpsTimes=Array.new
        finalArr=Array.new
        text.each{|x|
            timeSinceEpoch=Time.new('2014',x[0].to_i,x[1].to_i,x[2].to_i,x[3].to_i,x[4].to_i,"+09:00")
            timeSinceEpoch=timeSinceEpoch.to_i
            gpsTimes.push("#{timeSinceEpoch}")#ts(sep :)
        }
    timeArr.each{|x|
        x=x.split(",")
        timeSinceEpoch=Time.new('2014',x[0].to_i,x[1].to_i,x[2].to_i,x[3].to_i,x[4].to_i,"+09:00")
        timeSinceEpoch=timeSinceEpoch.to_i
        gpsClosestTime=closest_float(gpsTimes, timeSinceEpoch)
        finalArr.push(text[gpsTimes.index(gpsClosestTime)][5],text[gpsTimes.index(gpsClosestTime)][6])
    }
return finalArr
end
我的代码在这一点上完全不起作用了。有人能提供一个比我想做的更简单的解决方案吗


时间戳格式是:月:日:小时:分钟:秒。

我不得不对代码进行一些修改,以使其正常工作,主要是我获取子字符串的方式出现问题。以下是我的最终解决方案:

def closest_int(xs, value)
 return xs.min_by { |x| 
  (x.to_i - value.to_i).abs 
  }
end

def getGPSforTime(timeArr,gpsFilePath)
    text=File.open(gpsFilePath).read 
    text=text.gsub ':',',' #to account for newer versions with colon
    text=text.split(',')
    text=text.each_slice(7).to_a #5 for timestamp(sep ,) +lat+lng
    gpsTimes=Array.new
    gps=Array.new
    finalArr=Array.new
    text.each{|x|
        gpsTimes.push("#{x[0]}#{x[1]}#{x[2]}#{x[3]}#{x[4]}")#ts(sep :)
        gps.push("#{x[5]},#{x[6]}")
    }
timeArr.each{|x|
    x=x.split(":")
    time="#{x[0]}#{x[1]}#{x[2]}#{x[3]}#{x[4]}"
    gpsClosestTime=closest_int(gpsTimes, time)
    puts "#{time} closest to: #{gpsClosestTime}"
    finalArr.push("#{text[gpsTimes.index(gpsClosestTime)][5]},#{text[gpsTimes.index(gpsClosestTime)][6]}")
}

return finalArr
end

2件事:你需要了解拆分和加入+我需要理解你所说的结束是什么意思,才能真正给你一个解决方案。是绝对时间吗?如何定义时间戳数组的整数匹配?这是矢量数据。在数学中,你通常会减去两个向量来计算它们的位移,然后计算它的绝对值。我用代码顶部最接近的浮点函数减去这两个向量。是的,这是绝对时间。我将编辑我的帖子,以便更清楚地解释时间戳