Search code examples
loopsfor-loopadagnatada2012

Ada for loop isn't doing correct comparison


The simple program is to match the best candidate for a voter with several candidates. There are 10 imaginary topics which the imaginary voter answered; a "-1" means disagreement, a "0" means doesn't care, a "1" means agreement. The candidates also took the same survey on the same topics, and the same rules apply to them. If the voter OR the candidate voted a "0" for a particular topic, the total agreement value isn't affected. If the values between the voter and the candidate are same, this increments the agreement value. If the values are different, the agreement value is decremented. At the end, the candidates with the highest values are presented to the voter.

Here is an example terminal input for the program including the output:

Input:

0   0   0   1   1   1  -1  -1  -1   1
7
A   
1   1   1   1   1   1   1   1   1   1
B  
-1  -1  -1  -1  -1  -1  -1  -1  -1  -1
C   
1  -1   1  -1   1  -1   1  -1   1  -1
D   
1   0   1   0   1   0   1   0   1   0
E   
0  -1   0  -1   0  -1   0  -1   0  -1
F   
1   1   1   1   0   0   0   0   0   0
G   
0   0   0   1  -1   0   0  -1   1   1

Output: A, F, G

Using print statements, I was able to determine everything works fine, everywhere except the for loop which actually compares the voter values with the current candidate values:

            --inner loop to calculate match value by comparing incoming candidate values with voter array values
            COMPARE_Loop :
                    for J in Integer range 1 .. 10 loop

                    Get(NextVote);
                    if NextVote = 0 or VoterList(J) = 0 then
                            Put(VoterList(J));
                            --Do nothing
                    elsif NextVote = VoterList(J) then
                            Score := Score + 1;
                    else
                            Score := Score - 1;
                    end if;

            end loop COMPARE_Loop;

Everything else is verified to be taken in correctly, as well as maintaining the correct value throughout program, but the COMPARE_Loop won't compare the values correctly. I can't figure out why.


Solution

  • Reset Score to zero at before the start of COMPARE_loop, or else you will be adding or subtracting to the score from the previous candidate.

           --inner loop to calculate match value by comparing incoming candidate values with voter array values
            Score := 0;
            COMPARE_Loop :
                    for J in Integer range 1 .. 10 loop