我手上有一个非常简单的Ada项目 . 任务是收集“选民”投票并将其与每个“候选人”得分进行比较,并确定哪个候选人最适合选民 .
输入看起来像这样,然后输出应该输出:
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
到目前为止,我有一个程序,将每位候选人的选票与选民的投票进行比较 . 我知道我需要做什么,因为我以前用Java做过,但我不知道如何在Ada中接受输入 . 这是我到目前为止所拥有的 .
with Ada.Text_IO, Ada.Integer_Text_IO;
use Ada.Text_IO, Ada.Integer_Text_IO;
procedure Candidates is
-- take an array of candidates and determine which candidate best matches
-- the user's votes, then return those candidates
Number_Of_Candidates: Integer;
subtype VoterArray_Index is Integer range 1..10;
subtype CandidatesArray_Index is Integer range 1..Number_Of_Candidates;
type VoterArray is array(VoterArray_Index) of Integer;
type CandidatesArray is array(Character range 'A' .. 'Z') of array;
type Best_CandidatesArray is array(CandidatesArray_Index) of array;
Voter: VoterArray;
Candidates: CandidatesArray;
Best_Candidates: Best_CandidatesArray;
function Get_Input() is
-- get the input and put it into the correct arrays
Current_Line : string;
begin
Get(Current_Line);
function Get_Best_Score(CandidatesArray: in out CandidatesArray) is
-- go through the arrays and find the best score
SameAnswers: Integer;
DifferentAnswers: Integer;
BestScore: Integer;
subtype CandidateArray is array(VoterArray_Index) of Integer;
Candidate: CandidateArray;
begin
for I in CandidatesArray_Index loop
Candidate := Candidates(I);
for J in VoterArray_Index loop
if Candidate(J) /= 0 and Voter(J) /= 0 then
if Candidate(J) /= Voter(J) then
DifferentAnswers := DifferentAnswers + 1
else
SameAnswers := SameAnswers + 1
end if;
end if;
end loop;
if SameAnswers - DifferentAnswers >= BestScore then
Best_Candidates(I) := Candidate;
end if;
SameAnswers := 0;
DifferentAnswers := 0;
end loop;
end Get_Best_Score;
正如您所看到的,我不确定如何获取数字并将它们放入数组中 . 如果你有任何建议或不同的方式我应该去做的事情,我全都听见了 .
提前致谢 .
2 回答
您可以使用流来读取数据:
Integer'Read( STREAM_HANDLE, VARIABLE )
另一种选择是通过Get为数组的每个元素读取值,我建议使用辅助函数,以防需要调整处理格式更改的过程:
和
由于文件中给出了行数,因此constrained array必须足够大以容纳所有可能的元素 . 相反,您可以声明unconstrained array:
稍后,当您知道实际计数时,您只能分配数组实际所需的空间 . 该声明将
Candidates
放在nested scope的堆栈中:或者,您可以allocate space on the heap:
在任何一种情况下,您都可以根据需要访问数组元素:
附录:此方法假设候选人姓名是连续的
Character
. 作为替代方案,考虑一个Candidate_Record
数组,其中每个Name
都从文件中读取: