请检查以下代码并解释为什么当我在输入中多次提供相同的9位数电话号码时,for循环无限运行。 我正在更改嵌套for循环中 numberData 的内容但不应该是一个问题,并且在 numberData 中嵌套for循环之后完成元素的推送,所以我我很困惑,为什么它的发生可以解释任何人:
var str = "00:01:07,400-234-090\n00:05:01,701-080-080\n00:05:00,400-234-090\n00:01:06,701-080-080\n00:01:06,701-080-000"
console.log(solution(str))
function solution(S) {
var totalCost = 0
var lineArray = S.split('\n')
var numberData = []
/*{
number = 0,
duration = 0,
cost = 0
}*/
console.log(lineArray)
for (var i = 0; i < lineArray.length; i++) {
console.log(lineArray.length, i);
var dataArray = lineArray[i].split(',')
var number = dataArray[1]
var duration = dataArray[0]
var timeArray = duration.split(':')
var hours = +(timeArray[0])
var min = +(timeArray[1])
var sec = +(timeArray[2])
var numberPresent = false
var totalDuration = hours * 60 * 60 + min * 60 + sec //in Seconds
var cost = 0;
if (min < 5) {
cost = min * 60 + sec
} else {
if (sec == 0)
cost = min * 150
else
cost = (min + 1) * 150
}
for (var i = 0; i < numberData.length; i++) {
if (numberData[i].number == number) {
numberData[i].duration += totalDuration
numberData[i].cost += cost
numberPresent = true
}
}
if (!numberPresent)
numberData.push({
number: number,
duration: totalDuration,
cost: cost
})
}
var maxDurationIndex = 0
totalCost += numberData[0].cost
for (var i = 1; i < numberData.length; i++) {
if (numberData[i].duration > numberData[maxDurationIndex])
maxDurationIndex = i;
if (numberData[i].duration == numberData[maxDurationIndex]) {
var currentNumericNumber = getNumericNumber(numberData[i])
var maxIndexNumber = getNumericNumber(numberData[maxDurationIndex])
if (currentNumericNumber > maxIndexNumber)
maxDurationIndex = i;
}
totalCost += numberData[i].cost
}
totalCost = totalCost - (+numberData[maxDurationIndex].cost)
return totalCost
function getNumericNumber(numberString) {
var numberArray = numberString.split('-')
var string = '';
for (var i = 0; i < numberArray.length; i++) {
string += numberArray[i];
}
return +string;
}
}
您可以通过在输入中提供不同的电话号码来测试它,然后它可以完美运行。
答案 0 :(得分:3)
您的内循环在外循环的每次迭代中将i
的值重置为numberData.length
。在numberData
j
上使用不同的内部循环变量,如 for(var j=0; j<numberData.length; j++)
{
if(numberData[j].number == number)
{
numberData[j].duration+= totalDuration
numberData[j].cost +=cost
numberPresent = true
}
}
filter
或者只使用map
和numberPresent = numberData.filter( s => s.number == number ).map( s => {
s.duration += totalDuration;
s.cost += cost;
return s;
}).length > 0
locate pyspark/find_spark_home.py