简体   繁体   English

如何比较两个数组的元素

[英]How to compare the elements of two arrays

It's a hackerrank problem这是一个hackerrank问题

Please click the above link to see the problem请点击以上链接查看问题

I'm quite new (a beginner) been having a tough time with this.我是新手(初学者)对此感到很困难。

This is what my current code looks like:这是我当前的代码的样子:

function solve(a, b) {
    var A = "";
    var B = "";

    for(var i=0; i<a.length; i++) {
        for(var j=0; j<b.length; j++) {
            if(a[i] > b[j]) {
                A = 1;
                B = "";
            }
            if(a[i] = b[j]) {
                A = "";
                B = "";
            }
            if(a[i] < b[j]) {
                A = "";
                B = 1;
            }
        }
    }
}

Assuming you want to add 1 to array a and add 1 to array b whenever one is higher than the other on the same position.假设您要在数组 a 中加 1,并在数组 b 中在同一位置上的一个比另一个高时加 1。 Also assuming both arrays are the same length.还假设两个数组的长度相同。

function solve(a, b) {
    var A = 0;
    var B = 0;

        for(var i=0; i<a.length; i++) {
            if(a[i] > b[i]) {
                A++; //add 1 point to a
            }
            else if(a[i] == b[i]) {
                //do nothing (this isn't needed, but I'll leave it to understanding purposes)
            }
            else if(a[i] < b[i]) {
                B++; // add 1 point to b
            }
        }
        var newArray = [A, B];
        return newArray;
    }

So the cleanest code, in this case, would be:因此,在这种情况下,最干净的代码将是:

function solve(a, b) {
    var A = 0;
    var B = 0;

    for(var i=0; i<a.length; i++) {
        if(a[i] > b[i]) {
            A++; //add 1 point to a
        }
        else if(a[i] < b[i]) {
            B++; // add 1 point to b
        }
    }
    var newArray = [A, B];
    return newArray;
}

I'm also assuming you want to return this to somewhere, otherwise "A" and "B" won't be useful as they won't get out of the function ever.我还假设您想将其返回到某个地方,否则“A”和“B”将没有用,因为它们永远不会退出函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM