0

I have a voting contract and I am trying to find out the best way to get the winner key. Here is my code.

pragma solidity ^0.4.25;

contract Voting {
  mapping (int => uint8) public votesReceived;
  int[5] candidateList = [int(0),1,2,3,4];
  uint[] votes;

  function totalVotesFor(int candidate) view public returns (uint8) {
    require(validCandidate(candidate));
    return votesReceived[candidate];
  }

  function voteForCandidate(int candidate) public {
    require(validCandidate(candidate));
    votesReceived[candidate] += 1;
  }

  function validCandidate(int candidate) view public returns (bool) {
    for(uint i = 0; i < candidateList.length; i++) {
      if (candidateList[i] == candidate) {
        votes.push(votesReceived[candidate]);
        return true;
      }
    }
    return false;
  }
}

votesReceived keeps track of number of votes that each candidate has received but I am unable to figure out a way to get the key with most votes.

0

You can't iterate over a mapping so you also can't directly find out its contents.

But I guess you've already noticed this and you have a separate array with the candidate IDs. So what you can do is simply iterate over the candidateList and check how many votes each candidate has in their mapping and get the one with highest votes.

If this causes performance issues (as it definitely will with bigger amount of candidates) you can improve performance by updating a separate variable which keeps track of which candidate has the most votes (and how many) so every time someone votes you check if the total votes for that candidate exceed the previous high and you can update the data.

Furthermore your validCandidate looks rather strange and the contract wouldn't even compile - variable votes doesn't exist.

| improve this answer | |
  • Really sorry about that. I edited my code to have votes array. I can loop through candidateList and look for votesReceived[n] but what's the best way to find out the max/min in solidity? – Tom Cider Mar 25 at 6:39
  • There is no built-in functionality for finding min/max. You just have to loop through and keep track of which is the max/min. – Lauri Peltonen Mar 25 at 6:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.