# count if a number on a list is less than a given number in prolog

0

Hello you will see the problem is that given for example a list [1,9,3,5,2,6,4,7,8] this takes each value from the list and says if when this number appears N has some value lower than it and will tell them where at the end everything will be added

• there are no smaller numbers after = 0

• 9 (Empty) - has at 3,5,2,6,4,7,8 afterwards = 7

• 3 - has 2 later = 1

• 5 - has the 2.4 subsequently = 2

• 2 - does not have minor numbers that happen it = 0

• 6 - has 4 later = 1

• 4 - does not have minor numbers after = 0

• 7 - does not have minor numbers after = 0

• 8 - does not have minor numbers after = 0

at the end adding all that would give 11

This is the function you create

``````menores(X,[],Aux):- Aux is 0+0.
menores(X,[H|T],Cuenta):- X>H-> Aux is 1+0; Aux is 0+0, menores(X,T,Aux), Cuenta is Aux.
``````

but these have been the results

``````?-
|    menores(1,[9,3,5,2,6,4,7,8],POP).
POP = 0 .

?- menores(3,[5,2,6,4,7,8],POP).
POP = 0.
``````

should give the second a 1 since this function is the first part that compares each value if it is smaller and how many and will return it to a function that will accumulate and will be responsible for getting the head and calling this function .

asked by Jose_Silva 05.12.2018 в 18:10
source

0

This is a simple implementation, I hope it helps you to start:

``````menores(_, [], 0).
menores(Num, [H|B], Menores):- Num > H, menores(Num, B, Retorno), Menores is Retorno + 1.
menores(Num, [H|B], Menores):- Num < H, menores(Num, B, Menores).
menores(Num, [Num|B], Menores):- menores(Num, B, Menores).
``````

here the value `Num` is compared with the first one in the list, if it is greater one is added, if the values of the list are not taken (the same if they are equal values).

source
0

It really works, the sentence of if confused me a little, I found out that someone wanted to know the number of numbers greater than a number N in a list and take their code and adapt it to my home and I practically Same as yours:

``````menor(_,[],0).
menor(N,[H|Q],X):- N>H, menor(N,Q,X1), X is X1+1.
menor(N,[H|Q],X):- N<H, menor(N,Q,X).
``````

Now I'm doing a function that calculates the distance manhattan, where for example in the matrix [[1,9,3], [5,2,6], [4,7,8]] I have to find the box nine "that is an empty square" and see that it is in the coordinate (1,2) and apply this:

d = abs (3-1) + abs (3-2) = 3

abs I know it's a function already defined in prolog, but to receive a list of lists and see their coordinates is what I'm thinking, do you know any notion of how I could do it?

Mathematically, if we take two points p and q in a grid with coordinates p = (p1, p2) and q = (q1, q2), the Manhattan distance between these points is the sum of the absolute values of the differences between the coordinates. That is to say: d (p, q) = | q1-p1 | + | q2-p2 |