Solidity – How to Increase Mapping or Array Values Without Loop

arrayscontract-designmappingpythonsolidity

Would it be possible to increase all the values of a mapping or array (without a loop)?

Example:

mapping(address => uint) score;

uint[] values;

function increase_scores() public {
    // Example pseudo-code for mapping and array:
    score.all += 1; // ??
    values += 1; // Ex.Something like the python map(lambda x: x+1,list) ??
}

Edit: To provide more context, I have a mapping with users and scores. Every time I call the function increase_scores, I would like to increase the score of all the users of the mapping. Therefore, I wouldnt want to loop on the full array as I may run out of gas, if there are many users.

Edit: The map example of python is also not a good idea as at the end as it has to iterate over all the array or mapping..it will run out of gas too. There is no difference with the loop.

Best Answer

As Rob suggests, what you could do -since iterating a mapping is not possible, and if it was an array, it would be expensive- is to compute the values on the fly.

Say you have several scores mapped to addresses.

Address - Score

0x1 - 3

0x2 - 4

0x3 - 2

Your original intention was to iterate over every element of the mapping to increase the scores, which is not doable.

What you could do is to add a state variable uint scoreIncrement which keeps track of how many times the score has been increased for all scores.

function increase_scores() public {
    scoreIncrement++;
}

Then, you have a function which returns the score of an element, plus the scoreIncrement.

function getScore(address _a) public returns (uint){
  return scores[_a] + scoreIncrement;
}

So, instead of directly accessing an element of scores mapping, you would call this function.

You could add even more logic to this. You might not want to increase every single score that gets added in the future as well. So you might want to play with timestamps too or group addresses, so a given scoreIncrement only affects certain addresses and not all of them.

Related Topic