The D\'Hondt method is an algorithm that is used to allocate seats to parties in
ID: 3661718 • Letter: T
Question
The D'Hondt method is an algorithm that is used to allocate seats to parties in electrons, based on their number of votes. In general, te number of seats for each party should be proportional to the number of votes received; however, achieving exact proportionally is often not possible. In the D'Hondt method, the seats are assigned to parties one by one, to the party has the highest quotient, q, given by q = V/s + 1. where V is the number of votes the party received and s id the seats assigned to the party so far, If two quotients of two parties are identical, the seat is assigned to the party with the highest number of votes, and we assume that no two parties have an identical number of votes. Create a function which takes a vector of number of votes for N parties as input as well as the number of seats, and returns the seat assignment computed using the D'Hondt method as described above.Explanation / Answer
Good wishes,
First let me give you the Solution template:
function seatsAllocated = dhondt(votes, seats)
N=length(votes)
for j = 1:N
seatsAllocated(i)=0;
end
while( seats>0)
maxi=0;
for i = 1:N
q= votes(i)/ ( seatsAllocated(i)+1 );
if( maxi<q)
maxi=q;
pos=i;
end
elseif( maxi == q)
maxi=q;
if( votes(i) > votes(i-1))
pos=i;
end
else
pos=i-1;
end
end
end
seatsAllocated(pos)= seatsAllocated(pos)+1;
seats=seats-1;
maxi=0;
end
end
Explaination of the Solution template:
In the above function 'dhondt' , it is clear that the function takes vector 'votes' and 'seats' as inputs, these represent the data as mentioned in the question.
Then initially i found out the length N of the vector 'votes' so that i can create that much space for vector 'seatsAllocated' and initialize all to zero.
Then i used while loop to to execute the code for each seat. For each seat i ran a for loop to first find out the
quotient value for each value in votes vector and its corresponding value in seatsAllocated vector i.e.
q=votes(i)/ ( seatsAllocated(i)+1 )
I checked to see which pair is having maximum value for 'q' and then placed that value in 'maxi' and saved the corresponding vector position in 'p'. If two pairs have same value the one with highest value in votes vector is considered.
After getting 'p' value that parties value in seatsAllocated vector is incremented.
Again maxi is reset to zero and same process is repeated for next iteration of while loop i.e. for the next seat.
when all the seats are allocated the value of seats reach zero and while loop ends.
Finally seatsAllocated vector contains number of seats assigned to each of the N parties.
Hope this is clear.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.