0

I am trying to sort through a list of deaths and find the county with the highest amount of deaths. what i have working so far is - when given a List, the program will correctly display the highest number of deaths and and the lowest number of deaths. What I want it to output is the name of the county assosiated with that death count. for example, right now my program:

county(a).
county(b).

countyDeaths(a,45).
countyDeaths(b,0).

start :-
  max_deaths([4,0,0,19,1,3,5,45,14,2,27,14], MaxNumberDeaths),
  min_deaths([4,0,0,19,1,3,5,45,14,2,27,14], MinNumberDeaths),
  show_results(MaxNumberDeaths, MinNumberDeaths).

max_deaths([Head|Tail], Max) :-
  max_deaths(Tail, Value),
  Head > Value,
  Max is Head.
max_deaths([Head|Tail], Max) :-
  max_deaths(Tail, Value),
  Head =< Value,
  Max is Value.
max_deaths([], 0).

min_deaths([Head|Tail], Min) :-
  min_deaths(Tail, Value),
  Head < Value,
  Min is Head.
min_deaths([Head|Tail], Min) :-
  min_deaths(Tail, Value),
  Head >= Value,
  Min is Value.
min_deaths([], 0).

show_results(MaxNumberDeaths, MinNumberDeaths) :-
  write("The max number of deaths is: "),
  writeln(MaxNumberDeaths),
  write("The min number of deaths is: "),
  writeln(MinNumberDeaths).

outputs:

?- start.
The max number of deaths is: 45
The min number of deaths is: 0 

which is correct - but I want it to output:

The county with the highest amount of deaths is county "a" with a total of 45 deaths.

When I tried to put the counties into the list in order to be sorted through, it wouldn't allow that data type to be put into the list. Is there anyway for me to allow the list to find the number associated with the county name?

Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135

1 Answers1

0

Assuming that your countyDeaths/2 is a set of facts relating county name to the number of deaths in that county, you could do something like this:

county_deaths(a,45).
county_deaths(b,0).
% . . .
county_deaths(z,19).

start :-
  findall( N , county_deaths(_,N), [N|Ns] ) ,
  min_max( Ns , N , N , Min, Max ) ,
  display_max(Max),
  display_min(Min)
  .

min_max( []     , Min , Max , Min , Max ) .
min_max( [N|Ns] , X   , Y   , Min , Max ) :- N < X , !, min_max(Ns,N,Y,Min,Max) .
min_max( [N|Ns] , X   , Y   , Min , Max ) :- N > Y , !, min_max(Ns,X,N,Min,Max) .
min_max( [_|Ns] , X   , Y   , Min , Max ) :-            min_max(Ns,X,Y,Min,Max) .

% multiple counties could have the same number of deaths, so
% we use findall/3 to enumerate all counties with the specified
% number of deaths.

display_max(N) :-
  findall(C,county_deaths(C,N),Cs) ,
  writeln(max_deaths:Cs:N)
  .

display_min(N) :-
  findall(C,county_deaths(C,N),Cs) ,
  writeln(min_deaths:Cs:N)
  .
Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135