Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
1.6 kB
1
Indexable
pragma solidity ^0.8.0;

contract Voting {
    // Structure for each candidate
    struct Candidate {
        string name;
        uint voteCount;
    }

    // Array of candidates
    Candidate[] public candidates;

    // Mapping to store voter addresses
    mapping(address => bool) public voters;

    // Event to signal when a vote is cast
    event VoteCast(address voter, uint candidateIndex);

    // Constructor to initialize candidates
    constructor(string[] memory _candidateNames) {
        for (uint i = 0; i < _candidateNames.length; i++) {
            candidates.push(Candidate({
                name: _candidateNames[i],
                voteCount: 0
            }));
        }
    }

    // Function to cast a vote for a candidate
    function castVote(uint _candidateIndex) public {
        require(!voters[msg.sender], "You have already voted");
        require(_candidateIndex < candidates.length, "Invalid candidate index");

        voters[msg.sender] = true;
        candidates[_candidateIndex].voteCount++;

        emit VoteCast(msg.sender, _candidateIndex);
    }

    // Function to get the winner of the election
    function getWinner() public view returns (string memory) {
        uint maxVotes = 0;
        uint winnerIndex = 0;

        for (uint i = 0; i < candidates.length; i++) {
            if (candidates[i].voteCount > maxVotes) {
                maxVotes = candidates[i].voteCount;
                winnerIndex = i;
            }
        }

        return candidates[winnerIndex].name;
    }
}