-
Notifications
You must be signed in to change notification settings - Fork 6
/
Voting.sol
44 lines (36 loc) · 1.26 KB
/
Voting.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
pragma solidity ^0.4.6; //We have to specify what version of compiler this code will use
contract Voting {
/* mapping is equivalent to an associate array or hash
The key of the mapping is candidate name stored as type bytes32 and value is
an unsigned integer which used to store the vote count
*/
mapping (bytes32 => uint8) public votesReceived;
/* Solidity doesn't let you create an array of strings yet. We will use an array of bytes32 instead to store
the list of candidates
*/
bytes32[] public candidateList;
// Initialize all the contestants
function Voting(bytes32[] candidateNames) {
candidateList = candidateNames;
}
function totalVotesFor(bytes32 candidate) returns (uint8) {
require(validCandidate(candidate));
return votesReceived[candidate];
}
function voteForCandidate(bytes32 candidate) {
require(validCandidate(candidate));
votesReceived[candidate] += 1;
}
function validCandidate(bytes32 candidate) returns (bool) {
for(uint i = 0; i < candidateList.length; i++) {
if (candidateList[i] == candidate) {
return true;
}
}
return false;
}
// This function returns the list of candidates.
function getCandidateList() constant returns (bytes32[]) {
return candidateList;
}
}