AF
1. Feel Free to ask and submit anything on Anyforum.in and get satisfactory answer
3. Our Experts are looking for yours ?.

corejava-programming: Program to find the election winner

 It's election day. Write a program that counts votes cast and prints the person who won. Input: 1st line will contain the number of candidates. The next lines will contain 1 vote per line. The vote will be the serial number of the candidate. So for ten candidates, possible inputs are 1-10. Keep taking input till you get 0. Inputs are such that the highest vote-getter has unique number of votes. Output: 1st line will contain the serial number of the candidate who won. 2nd line will contain the number of votes that he/she got. Sample input: 3 1 1 1 2 2 3 0 Sample output: 1 3 corejava x 352programming x 168 Posted On : 2017-11-27 17:17:58.0 Divesh 101180 5

 If we assume an array of size total candidates and position of the element represents the candidate, We can make it even more short and simple. No need to use Map or List and multiple for loops. One loop is enough which is being used to take the inputs. Please refer the below answer. import java.util.Scanner; public class ElectionWinner { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n=input.nextInt(); int max = 0; int winner=0; int vote=0; int temp=0; int[] votes=new int[n]; while ((vote=input.nextInt())!=0){ temp=vote-1; votes[temp]=votes[temp]+1; temp= votes[temp]; if(max

 import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class ElectionWinner { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n=input.nextInt(); int max = 0; int winner=0; int vote=0; int temp=0; Map votes = new HashMap(n); while ((vote=input.nextInt())!=0){ if(votes.containsKey(vote)) votes.put(vote, votes.get(vote)+1); else votes.put(vote, 1); temp= votes.get(vote); if(max

 import java.util.Scanner; import java.util.*; public class VoteCount{ public static void main(String [] args){ Scanner sc=new Scanner(System.in); int voter=sc.nextInt(); int votercount[]=new int[voter+1]; List li=new ArrayList(); int i=0,count=0,j,k; int vote=sc.nextInt(); while(vote!=0){ li.add(vote); vote=sc.nextInt(); } for(j=0;jmaxwinner){ maxwinner=votercount[i]; win=i; } } System.out.println(win); System.out.println(maxwinner); } } Posted On : 2017-12-04 17:04:49 Satisfied : 1 Yes  0 No Divesh 101180Reply This Thread 2
Hi Divesh,
If we assume an array of size total candidates and position of the element represents the candidate, We can make it even more short and simple. No need to use Map or List and multiple for loops. One loop is enough which is being used to take the inputs. Please refer the below answer.
Rishi Kumar
523  1882  22115
Posted On :2017-12-04 22:57:59.0