Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

find the median of a list 1

Status
Not open for further replies.

12071982

IS-IT--Management
Nov 10, 2008
6
MT
Can anyone explain me how this routine works I want to know
how routine understands if there is an even number of elements or odd number of elements. thanks

median(!list,!median)
median_2(!list,!list,!median)

$clauses

median(List, Median) :-
median_2(List, List, Median).

median_2([_], [Z|_], odd(Z)).
median_2([_,_], [X,Y|_], even(X,Y)).
median_2([_,_|[X3|List]], [_|Remainder], Median) :-
median_2([X3|List], Remainder, Median).



 
It's just a trick.
To get the median element of a list, you must remove an element at the beginning and at the end of this list, so you remove 2 elements OK ?
Now every time you remove 2 elements of the first list, you remove only one element of the second, so you reach the median element this way.
At the end of the process, if it leaves only one element in the first list, the first element of the second list is the median otherwise, the first 2 elements of the second list are the medan !
 
thnx joel76 that makes much more sense for me than the prolog syntex
 
just a tip

first make the sum of that list. And then count the number of elements and then obtain the median.
 
To count the length of the list, you must go through it, it's not necessary to get the median.
With the describe method you traverse the half of the list, with your method you traverse one and half.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top