簡體   English   中英

誰能告訴我這個代碼是干什么用的?

[英]can anyone tell me what is this code for?

誰能告訴我這個代碼是干什么用的? 尤其是這行代碼,我看不懂這行ctr[arr[i] - 1]++

 function array_element_mode(arr) { var ctr = [], ans = 0; for (var i = 0; i < 10; i++) { ctr.push(0); } for (var i = 0; i < arr.length; i++) { // what is this code for?? ctr[arr[i] - 1]++; if (ctr[arr[i] - 1] > ctr[ans]) { ans = arr[i] - 1; } } return ans + 1; } console.log(array_element_mode([1, 2, 3, 2, 2, 8, 1, 9]))

我相信這個函數應該返回數組的數學模式。

我剛剛在您的函數中添加/修復了一些變量名稱。 這仍然是一個糟糕的實現,但我希望編輯能讓你更清楚它的作用。

function array_element_mode2(arr) {
    var center = [],
      mode = 0;
  
    for (let i = 0; i < 10; i++) {
      center.push(0);
    }
    for (let i = 0; i < arr.length; i++) {
        const priorElementOfArr = arr[i] - 1; 
        center[priorElementOfArr]++;
      if (center[priorElementOfArr] > center[mode]) {
        mode = priorElementOfArr;
      }
    }
    return mode + 1;
  }

我重命名了變量並拆分了ctr[arr[i] - 1]++; 分成兩行。 這個函數應該找到在給定的整數數組中出現最多的數字。

但是如果兩個或多個整數出現相同的次數並且數組包含 0,它就不會起作用。

 /* * Goal: Find the number which appears most in a given array of integers * Solution: In the ctr array store the number apperences in the following way * ctr[0] appearances of "1" in the array * ctr[1] appearances of "2" in the array * ctr[2] appearances of "3" in the array * ... */ function array_element_mode(arr) { var ctr = [], ans = 0; // fill the ctr array with nulls for (var i = 0; i < 10; i++) { ctr.push(0); } for (var i = 0; i < arr.length; i++) { //////////// here the ctr[arr[i] - 1]++; is splitted into 2 lines // for each array member "find" the correct index to increase const convertArrayMemberToIndexForCtr = arr[i] - 1; // increase the correct index by one ctr[convertArrayMemberToIndexForCtr]++; /////////// // check if the increased index if larger then current answer and if so // store it as the new result if (ctr[convertArrayMemberToIndexForCtr] > ctr[ans]) { ans = convertArrayMemberToIndexForCtr; } } // return the result, but not the index we created before (on line 25), but the real number that is in the array (add the +1 we subtracted before) return ans + 1; } console.log('working example'); console.log(array_element_mode([1, 2, 3, 2, 2, 8, 1, 9])); console.log('this wont work, it shows that "3" is the result, ignoring the "2"'); console.log(array_element_mode([3, 3, 3, 2, 2, 2, 5, 9])); console.log('this wont work as index arr[i] - 1 would then be 0-1=-1'); console.log(array_element_mode([0, 1, 1, 0, 0, 4, 5, 9])); console.log('this wont work, all integers are only once in the array'); console.log(array_element_mode([1, 2, 3, 4, 5, 6, 7, 8]));

我認為這個函數是找出數組中哪個元素的個數最多

ctr[arr[i] - 1]++:為了計數

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM