谁能告诉我这是什么代码?



谁能告诉我这是什么代码?尤其是这行代码,我看不懂这行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]++:为了计数

相关内容

  • 没有找到相关文章

最新更新