DWQA QuestionsCategory: ProgramTake the times of occurrence, how to calculate the speed?
Ten forty-eight asked 4 days ago
Let arr = ['841 ',' 458 ',' 232 ',' 101 ',' 676 ',...] // an array of 500 members with random three digits

//Want to write a function like this, specify the number, specify the location, specify the characters,
//Calculate the above array, in the specified number of members, the number of occurrences of the specified character in the specified position

Function calcnum (quantity, position, character){
    ...
}

//Of the first four members, the second position is' 3 '. There are several
calcNum(4, 2, '3') -> 1

//Of the first three members, the third position is' 1 '. There are several
calcNum(3, 3, '1') -> 1

//Of the first five members, the third position is' 1 '. There are several
calcNum(5, 3, '1') -> 2

The speed of single calculation is OK, but it’s very slow

for (i=1; i<=500; i++){
    calcNum(i, 3, '1')
}

Can a great God calculate faster?

crp205 replied 4 days ago

Calcnum (n, 3, ‘1’) depends on the result of calcnum (n – 1, 3, ‘1’). You can cache the result

3 Answers
Best Answer
asseek answered 4 days ago

The solution is to first process the data into more readable objects to avoid repeated calculation

let arr = ['841', '458', '232', '101', '676'];

let data = arr.reduce((d, str, index) => {
  str.split('').forEach((v, i) => {
    i += 1;
    if (!d[i]) d[i] = {};
    if (!d[i][v]) d[i][v] = [];
    d[i][v].push(index);
  });
  return d;
}, {});

function calcNum(start, i, v) {
  const ary = data[i] && data[i][v] ? data[i][v] : [];
  if (ary.length) {
    const index = ary.findIndex(_i => _i >= start);
    return ary.length - (index > -1 ? index : 0);
  }
  return 0;
}
krun answered 4 days ago

Can you tell me what you are asking for first?
You thisforIs the calculation result accumulated or what?
If it is:

let count = 0
for (i=1; i<=500; i++){
    count += calcNum(i, 3, '1')
}
// count

So it’s equivalent to

*Pos: position, target: character
count = arr.reduce((p, c) => p = p * 2 + (c.split("")[pos - 1] === target ? 1 : 0), 0)

If it is:

for (i=1; i<=500; i++){
    let count = calcNum(i, 3, '1')
    //Use count only in loops
}

Cache can be used as the comment says:

let cache = 0
for (i=0; i<500; i++){
    let count = cache + (arr[i].split("")[pos - 1] === target ? 1 : 0)
    //Use count only in loops
    cache = count
}
Lucky charm answered 4 days ago

It can only traverse the time complexity O (m n). The number of occurrences in the first m members n is the size of the whole array
Another method is to store the results of FN (n-1) according to FN (n) = FN (n-1) + X, and use space complexity to replace time complexity
Choose which one to look at the scene and brush the algorithm without wasting time on this simple algorithm.