Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- public class ElectionSimulator {
- //Constants
- public static final int NUM_SIMS = 5;
- public static final int NUM_DISTS = 10;
- public static final double POLL_AVG = .52;
- public static final double POLL_ERR = .05;
- public static void main(String[] args){
- //Randomness creation
- Random rand = new Random();
- //Welcome Message
- System.out.println("Welcome to the Election Simulator!");
- System.out.println("Running " + NUM_SIMS + " simulations of " + NUM_DISTS + " districts.");
- System.out.print("Our candidate is polling at " + (POLL_AVG * 100) + "% with a ");
- System.out.println((POLL_ERR * 100) + "% margin of error.");
- System.out.println("");
- //Initialization
- int voteSum = 0; // total count of votes through all ten districts
- int myVote = 0; // total votes for candidate A
- int actualNum = 0; // actual num votes for each district
- int index = 0;
- int urVote = 0; // tots for cand B
- int turnOut1 = 0;
- double pollAcu = 0.0;
- double poll = 0.0;
- int plus = 0;
- int minus = 0;
- double totalAverage = 0;
- //Simulation
- for(int i = 1; i <= NUM_SIMS; i++) {
- myVote = 0;
- urVote = 0;
- voteSum = 0;
- for(int j = 1; j <= NUM_DISTS; j++) {
- turnOut1 = rand.nextInt(1000) + 1;
- pollAcu = rand.nextGaussian() * 0.5 * POLL_ERR;
- poll = pollAcu + POLL_AVG; //percentage voter A receives
- actualNum = turnOut1;
- myVote = myVote + (int)(poll * actualNum);
- voteSum = voteSum + turnOut1;
- urVote = urVote + (int)((1-poll) * actualNum);
- } //inner for for loop
- urVote = voteSum - myVote;
- double myPer = myVote / (double) voteSum;
- myPer = myPer * 100;
- totalAverage = totalAverage + myPer;
- boolean win = myPer >= 50.00;
- double roundedMyPer = (double) Math.round(myPer * 100) / 100;
- index = index + 1;
- plus = myVote / 100;
- minus = urVote / 100;
- System.out.println("Running simulation #" + index + ":"); //still need to make a for loop for the simulation number
- System.out.println(" Win? " + win);
- System.out.print(" Results: " + myVote + " (" + roundedMyPer + "%)");
- System.out.println(" - " + (urVote) + " " +"(" + (100 - roundedMyPer) + "%)");
- System.out.print(" Visualization: " );
- for(int k = 0; k < plus; k++){
- System.out.print("+");
- } // plus for loop end
- System.out.println("");
- System.out.print(" ");
- for(int o = 0; o < minus; o++){
- System.out.print("-");
- } // minus for loop end
- System.out.println("");
- } // outer for loop end
- //Outro
- System.out.println();
- System.out.println("Average vote percentage: " + Math.round((double)(totalAverage/NUM_SIMS) * 100.0) / 100.0 + "%");
- } // main method end
- } // public class end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement