theB3RV
theB3RV

Reputation: 924

Count the number of occurrences of a character in a list in prolog

walls(This) :- 
    append(This, NewMap),
    length(NewMap, N),
    numWalls(NewMap, W),
    W >= N/10.

numWalls([], _, 0).
numWalls('w'|Tail, W) :-
    W is W1 + 1,
    numWalls(Tail, W1).
numWalls(_|Tail, W):-
    numWalls(Tail, W).

I comment out line by line and get false until i take out the numWalls(NewMap,W), line. The append flattens a 2-dimensional array and length returns the proper length of the flattened map. We need to count how many times a 'w' appears in the list of lists and if more than 10% of the list is 'w' return True.


walls(Maps) :- 
    append(Maps, NewMap),
    length(NewMap, N),
    print(NewMap),
    numWalls(NewMap, W),
    print(W) .

numWalls([], 0).
numWalls(['w'|Tail], W) :-
    numWalls(Tail, W1),
    W1 is W-1.
numWalls([_|Tail], W):-
    numWalls(Tail, W).

"ERROR: is/2: Arguments are not sufficiently instantiated" Looks like the error is with my is statement?

Upvotes: 3

Views: 2602

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726509

It looks like you are missing some square brackets. Other than that minor syntax issue, your program logic is fine:

numWalls([], 0).
numWalls(['w'|Tail], W) :-
    numWalls(Tail, W1),
    W is W1 + 1.
numWalls([H|Tail], W):-
    H \= (w),
    numWalls(Tail, W).

EDIT: As false commented, the second rule needs to change against consuming a w by mistake, to avoid numWalls([w,w], 0). from succeeding.

Link to a demo on ideone.

Upvotes: 5

Related Questions