Hackerrank:加上减号

时间:2018-04-07 13:29:07

标签: javascript

我试图在数组中找到正,负和零的分数,但函数没有返回任何东西。你可以帮我吗

var noOfPostive = 0;
var noOfNegative = 0;
var noOfZero = 0;

function plusMinus(arr) {
  /*
   * Write your code here.
   
   */
  var length = arr.length;

  for (var i = 0; i < arr.length; i++) {
    if (i > 0) {
      noOfPostive += 1;
    } else if (i < 0) {
      noOfNegative += 1;
    } else {
      noOfZero += 1;
    }


    var FractionOfPostive = noOfPostive / length;
    var FractionOfNegative = noOfNegative / length;
    var FractionOfZero = noOfZero / length;
    return FractionOfPostive, FractionOfPostive, FractionOfZero;

  }
}

plusMinus([-4,3,-9,0,4,1]);

20 个答案:

答案 0 :(得分:2)

我使用reduce()来获得结果,并结合Math.sign()将返回0,1或-1,具体取决于数字是0,正数还是负数。下面将返回一个数组数组,每个数组都包含+,0, - 的标识符作为第一个元素,而分数作为第二个元素。

&#13;
&#13;
function plusMinus(arr) {
  return Object.entries(arr.reduce((a, b) => {
    let sign = Math.sign(b);
    a[sign] = (a[sign] || 0) + 1;
    return a;
  }, {})).map(e => [e[0], e[1] / arr.length]);
}

console.log(plusMinus([-4, 3, -9, 0, 4, 1]));
&#13;
&#13;
&#13;

答案 1 :(得分:1)

function plusMinus(arr) {
    let decimal = 6;
    let length = arr.length;
    let positive = arr.filter(val => val > 0).length;
    let negative = arr.filter(val => val < 0).length;
    let zero = arr.filter(val => val == 0).length;

    function findRatio(num) {
        return console.log(parseFloat(num / length).toPrecision(decimal));
    }
    
    findRatio(positive);
    findRatio(negative);
    findRatio(zero);
}

答案 2 :(得分:1)

function plusMinus($arr) {
$countArr = count($arr);
$positive = 0;
$negative = 0;
$zero = 0;
for($i = 0; $i < $countArr; $i++){
    if($arr[$i] > 0){
        $positive += 1;
    }
    if($arr[$i] === 0){
        $zero += 1;
    }
    if($arr[$i] < 0){
        $negative += 1;
    }
}
$fractionPositive = number_format($positive/$countArr, 6);
$fractionNegative = number_format($negative/$countArr, 6);
$fractionZero = number_format($zero/$countArr, 6);

printf("%f\n%f\n%f",$fractionPositive, $fractionNegative, $fractionZero);

}

答案 3 :(得分:1)

我用Python编写了这个简单的代码,首先从用户那里获取数组元素的编号,然后再获取数组元素。 在此之后,仅进行比较并且计数器增加。

代码如下:

pos=0
neg=0
z=0

n = int(input().strip())
arr = [int(arr_temp) for arr_temp in input().strip().split(' ')]


for num in arr:
    if num>0:
        pos+=1

    elif num == 0:
        z+=1
    elif num<0:
        neg+=1

print(pos/n)
print(neg/n)
print(z/n)

答案 4 :(得分:0)

var arr = [-4, 3, -9, 0, 4, 1];



function plusMinus(arr) {
  var n = arr.length;
  var positive = 0,
    negative = 0,
    zero = 0;

  for (var i = 0; i < n; i++) {
    if (arr[i] > 0) {
      positive += 1;
    } else if (arr[i] < 0) {
      negative += 1;
    } else {
      zero += 1;
    }
  }

  var pos = positive / n;
  var neg = negative / n;
  var zer = zero / n;
  console.log(pos.toFixed(6) + "\n" + neg.toFixed(6) + "\n" + zer.toFixed(6));
}

plusMinus(arr);

答案 5 :(得分:0)

我不太喜欢 if-else 条件,所以我在这里使用了 switch case

function plusMinus(arr) {
    
    let totalPos=0, totalNe=0, totalZe=0, arrLen = arr.length;
    
    for(let value of arr){
        
        switch(true){
           
           case (value > 0):
            totalPos++;
            break;
            
            case (value < 0):
            totalNe++;
            break;             
            
            case (value == 0):
            totalZe++;
            break;           
        }
        
    }
    
    console.log(`${(totalPos/arrLen).toFixed(6)} \n ${(totalNe/arrLen).toFixed(6)} \n ${(totalZe/arrLen).toFixed(6)}`);

}

plusMinus([-4,3,-9,0,4,1]);

答案 6 :(得分:0)

我使用Math.sign()使代码更加简单,请查看

// Complete the plusMinus function below.
function plusMinus(arr) {
    let neg= arr.filter(elem => Math.sign(elem)=== -1).length/arr.length;
    let pos= arr.filter(elem => Math.sign(elem)=== 1).length/arr.length;
    let zer = arr.filter(elem => Math.sign(elem)=== 0).length/arr.length;

    return console.log(pos+ '\n' + neg+ '\n' + zer)

}

Math.sign()对于正数返回1,对于负数返回-1,对于零返回0,

所以在这里我使用array.filter()方法来过滤那些分别为正负和零的元素,显然filter()返回一个新数组,所以我将返回数组的长度除以长度为输入数组并将其直接存储在变量中。而已。荣誉

答案 7 :(得分:0)

这是一个简单的解决方案,涉及使用for-of循环,array destructuringtemplate literals

function plusMinus(arr) {

    let count = [0, 0, 0];

    let [count1, count2, count3] = count;  

    let length = arr.length;
        
    for (let val of arr) {      
    
      if (val > 0) { 

          count1++

      } 
      else if (val < 0) { 

          count2++ 
      } 
      else {

          count3++

      }

    }

 console.log(`${(count1/length).toFixed(6)}\n ${(count2/length).toFixed(6)}\n ${(count3/length).toFixed(6)}`);         
}

plusMinus([-4,3,-9,0,4,1]);

答案 8 :(得分:0)

首先,当您使用for循环数组时,实际上是将index存储在i中,因此您仍需要检查{{1}处的值在index

array

其次,您的let value = arr[ i ] 语句return循环,所以它在返回之前甚至没有运行过一次。

第三,您的返回值必须是单个值或对象,因此您不能for,因为只返回return a, b, c;

请参阅以下所有上述内容。另请注意,我已将变量移至c定义内 - 如果您运行此函数两​​次,它将始终将其值重置为零,因此它不会继续增加数量(您的数字将在大于1之后变大)一次运行)。我还在块中使用了function个变量(例如letlet i - 这些变量并没有特别做,但是它们与范围和内存有关。阻止,使用let value,但不要过于担心。

&#13;
&#13;
let
&#13;
&#13;
&#13;

答案 9 :(得分:0)

这里的结果是[正,负,零]个计数,在forEach循环中,相应的值在递增。

DRIVER

答案 10 :(得分:0)

以下功能有效:

function plusMinus(arr) {
    let zero = parseFloat(arr.filter(val = > val == 0).length / arr.length).toPrecision(6)
    let pos = parseFloat(arr.filter(val = > val > 0).length / arr.length).toPrecision(6)
    let neg = parseFloat(arr.filter(val = > val < 0).length / arr.length).toPrecision(6)
    console.log(pos)
    console.log(neg)
    console.log(zero)
}

答案 11 :(得分:0)

此解决方案有效。我必须创建一个附加函数来处理四舍五入

function plusMinus(arr) {
    let length = arr.length
    let positive = 0
    let negative = 0
    let zero = 0
    for (let i = 0; i < length; i++){
        if (arr[i] > 0) {
            positive++
        }
        else if (arr[i] < 0) {
            negative++
        }
        else if (arr[i] == 0) {
            zero++
        }
    }

    const ratioPositive = round((positive / length))
    const ratioNegative = round((negative / length))
    const ratioZero = round((zero / length))

    console.log( ratioPositive + "\n" + ratioNegative + "\n" + ratioZero )

}

function round(value) {
    return Number(value).toFixed(6);
  }

plusMinus([-4, 3, -9, 0, 4, 1])

输出:

0.500000
0.333333
0.166667

答案 12 :(得分:0)

这是一个简单而快速的解决方案:

您可以使用过滤器函数在数组中进行迭代,并仅使用满足条件的数字来获得新数组;正数(n> 0),负数(n <0)和中性数(n == 0)。在同一个变量中,您可以计算返回数组的大小,然后将其除以原始数组的大小,这样就得到了分数,必须使用toFixed(6)将其格式化为仅小数点后6位,并在要求的格式。

function plusMinus(arr) {
    let positive = arr.filter(number => number > 0).length / arr.length;
    let negative = arr.filter(number => number < 0).length / arr.length;;
    let zeronums = arr.filter(number => number == 0).length / arr.length;;
    return console.log(positive.toFixed(6) + '\n' + negative.toFixed(6) + '\n' + zeronums.toFixed(6))
}

答案 13 :(得分:0)

这是什么

function plusMinus(arr) {
    let positive = 0;
    let negative = 0;
    let zero = 0;
    const length = arr.length;

    for (let i = 0; i < arr.length; i++){
        if (arr[i] > 0) {
            positive +=1
        } else if (arr[i] < 0) {
            negative += 1
        } else {
            zero += 1
       }
     }
function log(a, b, c) {
    console.log(a);
    console.log(b);
    console.log(c);
}

const positiveRatio = (positive / length).toFixed(6);
const negativeRatio = (negative / length).toFixed(6);
const zeroRatio = (zero / length).toFixed(6);

return log(positiveRatio, negativeRatio, zeroRatio)
}

答案 14 :(得分:0)

您需要在代码中执行一些修复。您的代码中存在以下拼写错误。

不准确的退货声明:

返回无法发送多个变量的结果。您需要将结果存储在数组中并将数组发送回调用者。

不检查数组值:

for counter, myLine in enumerate(textList): thematch=re.sub(searchedSTR,RepX,myLine) matches = re.findall(searchedSTR, myLine, re.MULTILINE | re.IGNORECASE) if len(matches) > 0: # add one record for the match (add one because line numbers start with 1) d[matches[0]].append(counter + 1) self.textEdit_PDFpreview.insertHtml(str(thematch)) ''' loop over the selected file and extract 3 values: ==> name of file ==> searched expression ==> number of occurence ''' for match, positions in d.items(): listMetaData = [{"file Name":fileName,"searched Word":match,"number of occurence":len(positions)}] jsondata = json.dumps(listMetaData) print("in the for loop ==>jsondata: \n{0}".format(jsondata)) ''' create a folder called 'search_result' that includes all the result of the searching as JSON file where the system check if the folder exist will continue if not the system create the folder insode the folder the file will be created as ==> today_searchResult.js ''' if not(os.path.exists("./search_result")): try: #print(os.mkdir("./search_result")) #print(searchResultFoder) today = datetime.date.today() fileName = "{}_searchResult.json".format(today) #fpJ = os.path.join(os.mkdir("./search_result"),fileName) #print(fpJ) with open(fileName,"w") as jsf: jsf.write(jsondata) print("finish writing") except Exception as e: print(e) 并不意味着什么。如果您需要检查数组值是否为正,那么您需要执行

if(i>0)

错位了for循环的最后一个大括号:

你的for循环中也有拼写错误。您已将for循环扩展到函数的末尾。这意味着您在for循环内的正数或负数。这意味着它们将在每次迭代期间松开先前的计算结果。

&#13;
&#13;
if(arr[i]>0)
&#13;
&#13;
&#13;

考虑不使用For-Loop:

在这里你已经看到你错位了for循环的最后一个大括号。因此你得到了意想不到的结果。有时会出现问题。为了避免使用for循环,你可以使用ES6 Generator functions代替for for loop.This是解决这个问题的功能方法。

var noOfPostive = 0;
var noOfNegative = 0;
var noOfZero = 0;

function plusMinus(arr) {
  /*
   * Write your code here.
   
   */
  var length = arr.length
  var result = []
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] > 0) {
      noOfPostive += 1;
    } else if (arr[i] < 0) {
      noOfNegative += 1;
    } else {
      noOfZero += 1;
    }

    }
    var FractionOfPostive = parseFloat(noOfPostive / length);
    var FractionOfNegative = parseFloat(noOfNegative / length);
    var FractionOfZero = parseFloat(noOfZero / length);

	result.push(FractionOfPostive,FractionOfNegative,FractionOfZero)
    return result;

  
}

console.log(plusMinus([-4,3,-9,0,4,1]));

答案 15 :(得分:-1)

const plusMinus = function (num, arr) {
let positives = 0, negatives = 0, zeros = 0;
for(let i = 0; i < arr.length; i++) {
    if (arr[i] > 0) {
        positives ++
    } else if (arr[i] < 0) {
        negatives ++
    } else if(arr[i] === 0) {
        zeros ++
    }
}
 console.log((positives / arr.length).toFixed(6));
 console.log((negatives / arr.length).toFixed(6));
 console.log((zeros / arr.length).toFixed(6));
};

plusMinus(6, [-4, 3, -9, 0, 4, 1]);

答案 16 :(得分:-1)

function plusMinus(arr) {

    let positives = 0
    let negatives = 0
    let zeros = 0
    const length=arr.length

    for (var i = 0; i < arr.length;i++){
        if (arr[i] > 0) {
            positives++
        } else if (arr[i] < 0) {
            negatives++
        } else {
            zeros ++
        }
    }

    const positiveRatio = Number(positives / length).toFixed(6)
    const negativeRatio = Number(negatives / length).toFixed(6)
    const zeroRatio = Number(zeros / length).toFixed(6)

    console.log(positiveRatio)
    console.log(negativeRatio)
    console.log(zeroRatio)
}

答案 17 :(得分:-1)

function plusMinus(arr) {
    let no_positive = 0
    let no_negative = 0
    let no_zero = 0
    
    for (let i=0; i<arr.length; i++) {
        if (arr[i] < 0) {
            no_negative++
        } 
        
        if (arr[i]>0) {
            no_positive++
        } 

        if (arr[i]==0) {
            no_zero++
        }
    }
    var posRatio = (no_positive/arr.length).toFixed(6);
    var negRatio = (no_negative/arr.length).toFixed(6);
    var zeroRatio = (no_zero/arr.length).toFixed(6);
    console.log(posRatio)
    console.log(negRatio)
    console.log(zeroRatio)
}

答案 18 :(得分:-1)

您的 for 循环中存在问题。您需要通过检查循环中索引变量的数组值来编写 if 语句。您可以将您的解决方案与以下解决方案进行比较。

function plusMinus(arr) {
  let plus = 0;
  let minus = 0;
  let zero = 0;
  const arrLen = arr.length;
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] > 0) {
        plus++;
    } else if (arr[i] < 0) {
        minus++;
    }
    else {
        zero++;
    }
  }

  return console.log(
    (plus / arrLen).toFixed(6) +
    "\n" +
    (minus / arrLen).toFixed(6) +
    "\n" +
    (zero / arrLen).toFixed(6) + 
    "\n"
  );

}

答案 19 :(得分:-1)

function plusMinus(arr) {
    let n=arr.length;
    let poscount=0
    let negcount=0
    let zerocounnt=0
    for(let i=0;i<n;i++){
        if(arr[i]>0){
            poscount+=1
        }else if(arr[i]<0){
            negcount+=1
        }else{
            zerocounnt+=1
        }       
    }
    console.log((poscount/n).toFixed(6))
    console.log((negcount/n).toFixed(6))
    console.log((zerocounnt/n).toFixed(6))
}
plusMinus([-4 3 -9 0 4 1])