我有「陣列偶」的數組:查找數組最小「對」
[[time, distance], [time, distance], [time, distance], [time, distance], ...]
我想找到「對」與最小時間的索引,如果有多個「配對'的最小時間相同,以最小距離取對。
例如如果我有:
[[5, 5], [1,7], [2,6], [1,6]]
我想返回3.(即第4個元素的索引)。
我該怎麼做?
我有「陣列偶」的數組:查找數組最小「對」
[[time, distance], [time, distance], [time, distance], [time, distance], ...]
我想找到「對」與最小時間的索引,如果有多個「配對'的最小時間相同,以最小距離取對。
例如如果我有:
[[5, 5], [1,7], [2,6], [1,6]]
我想返回3.(即第4個元素的索引)。
我該怎麼做?
Array#sort
確實如你所願。
myarray = [[5, 5], [1,7], [2,6], [1,6]]
myarray.sort
#=> [[1, 6], [1, 7], [2, 6], [5, 5]]
所以,我們只需要在原始數組中匹配排序數組中第一個元素的元素。
ndx = myarray.index myarray.sort[0]
#=> 3
編輯:我最初使用太空飛船運營商,但意識到這是沒有必要的。
我不熟悉Ruby on Rails,但我寫了一點PHP代碼來實現你的目標。我希望你能從中提取出想法。
<?php
$timesAndDistances = [['t' => t1, 'd' => d1], ['t' => t2, 'd' => d2], ..., ['t' => tn, 'd' => dn]];
$lowestTime_withDistance = [['t' => null, 'd' => null, 'i' => null]];
foreach($timesAndDistances as $index => $timeAndDistance)
{
$time = $timeAndDistance['t'];
$distance = $timeAndDistance['d'];
if($lowestTime_withDistance[0]['t'] == null)
{
$lowestTime_withDistance[0] = ['t' => $time, 'd' => $distance, 'i' => $index];
}
else
{
if($lowestTime_withDistance[0]['t'] > $time){
$lowestTime_withDistance[0] = ['t' => $time, 'd' => $distance, 'i' => $index];
}
elseif ($lowestTime_withDistance[0]['t'] == $time)
{
$lowestTime_withDistance[] = ['t' => $time, 'd' => $distance, 'i' => $index];
}
}
}
if(count($lowestTime_withDistance) == 1)
{
echo 'Index of element with minimum time is ' . $lowestTime_withDistance[0]['i'];
}
elseif(count($lowestTime_withDistance) > 1){
$lowestDistance = [['d' => null, 'i' =>null]];
foreach($lowestTime_withDistance as $timeWithDistance)
{
if($lowestDistance[0]['d'] == null)
{
$lowestDistance[0] = ['d' => $timeWithDistance['d'], 'i' => $timeWithDistance['i']];
}
else
{
if($lowestDistance[0]['d'] > $timeWithDistance['d'])
{
$lowestDistance[0] = ['d' => $timeWithDistance['d'], 'i' => $timeWithDistance['i']];
}
elseif ($lowestDistance[0]['d'] == $timeWithDistance['d'])
{
$lowestDistance[] = ['d' => $timeWithDistance['d'], 'i' => $timeWithDistance['i']];
}
}
}
if(count($lowestDistance) == 1)
{
echo 'Index of element with minimum time and distance is ' . $lowestDistance[0]['i'];
}
elseif (count($lowestDistance) > 1)
{
foreach($lowestDistance as $aLowestDistance)
{
echo 'Index of an element with minimum time and distance is ' . $aLowestDistance['i'];
}
}
}
寫入快速代碼來實現這一點:
說陣列一個具有下列元素
[[5,5],[1,7],[2,6 ],[1,6]]
創建陣列的b中的副本:
B = A
B = [[5,5],[1,7],[2,6],[1,6]]
排序b
b = b.sort
b = [[1,6],[1,7],[2,6],[5,5]]
遍歷嵌套循環
最小= B [0]
索引= 0
a.each做| iter_orig |除非a.nil?
if iter_orig.eql?最小
break;
end
index ++;
末
末
看跌期權 「指數最小的時間/距離 - 」 +指數