'How to find occurrences of max number from an array in solidity?
I am working on a voting system and I need to find the winner. But I am considering a scenario where two members have got the same vote and they both are winners. Hence, I want to return the details of both the winners.
My code does give the answer but I need a better way to do it. Please find the code below-
struct PoliticalParty{
string name;
uint256 voteCount;
}
PoliticalParty[] public winners;
uint256 public winnercount;
function declareWinner()public onlyOwner returns(PoliticalParty[]memory)
{
require(votingState==State.Canceled||block.number>endBlock);
if(votingState==State.Canceled){
revert("Voting is canceled.");
}
else{
string memory_name="";
uint256 max_count=parties[0].voteCount;
for(uint256i=1;i<parties.length;i++){
if(parties[i].voteCount>max_count){
max_count=parties[i].voteCount;
}
}
for(uint256j=0;j<parties.length;j++){
if(max_count==parties[j].voteCount){
_name=parties[j].name;
winners.push(PoliticalParty({name:_name,voteCount:max_count}));
winnercount++;
}
}
return winners;
}
}
Solution 1:[1]
The question is crafted very poorly, however as far as i understand, you are looking for an algorithm to get the occurence count of the highest value.
If so, you could use something like this:
function freqOfMaxNum(uint256[] memory arr)
public
pure
returns (uint256, uint256)
{
uint256 max = 0;
uint256 frequenceOfMax = 0;
for (uint256 i = arr.length - 1; i > 0; i--) {
if (arr[i] > max) {
max = arr[i];
frequenceOfMax = 1;
} else if (arr[i] == max) {
frequenceOfMax++;
}
}
return (max, frequenceOfMax);
}
Solution 2:[2]
I could manage to optimize my code.
PoliticalParty[] public winners;
function declareWinner() public onlyOwner returns(PoliticalParty[] memory)
{
// the voting has been Canceled or Ended
require(votingState == State.Canceled || block.timestamp > votingEndTime);
if(votingState == State.Canceled){
revert("Voting canceled.");
}
else{
string memory _name="";
uint256 max_count=0;
for (uint256 i = 0; i < parties.length; i++) {
if (parties[i].voteCount>max_count) {
max_count = parties[i].voteCount;
_name=parties[i].name;
delete winners;
winners.push(PoliticalParty({name: _name, voteCount: max_count}));
}
else if (max_count==parties[i].voteCount) {
_name=parties[i].name;
winners.push(PoliticalParty({name:_name, voteCount: max_count}));
winnercount++;
}
}
return winners;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | keser |
Solution 2 | I J |