How to find duplicate entry in Solidity array

Viewed 603

I'm writing a function that is supposed to receive an array of uint's and I want to make a requirement that none of the elements in the array be the same and that all of the elements in the array be part of the pre-selected elements to belong in an array. So far I have:

    function vote(uint[] memory proposals) external
    {
        Voter storage sender = voters[msg.sender];
        require(sender.weight != 0, "Has no right to vote.");
        require(!sender.voted, "Already voted.");
        mapping(uint => bool) duplicateVotes;
        require(!duplicateVotes, "Cannot vote for a proposal more than once.");
        sender.voted = true;
        sender.vote = proposals;

        proposals[proposals].voteCount += sender.weight;
    }

But I get an error:

The data location must be "storage", "memory" or "calldata" for variable, but none was given.

But I think this error is just a symptom of a larger problem. Can anyone help me figure out a solution to this problem?

1 Answers

I think u want to achieve that same person does not vote twice but the way you are doing is computationally expensive and this will cost too much gas. Instead, crate a mapping to keep track if voter has voted before:

 mapping(address=>bool) peopleWhoVoted;

also you want to keep array of voters

 address[] public listOfVoters;

So in your vote function, make sure that caller of this function-msg.sender is not in the peopleWhoVoted mapping

    function vote(pass argument) public {
       // msg.sender is globally available, it is function caller
       require(!peopleWhoVoted[msg.sender],"this caller already voted")
       // now u are sure that this caller did not vote before
       // so u can add the function caller to the array
       listOfVoters.push(msg.sender)
   }
Related