# Math problem. How to setup the rules

31 views

### Maxy Mustermann

Oct 24, 2016, 8:01:01 AM10/24/16
to SWI-Prolog
Hi,
i'm just learning prolog. While programming on a java project i Encounter a problem that i wanted to solve in prolog.

Maybe someone can help me at this.
Problem:
I got a String of Integers with a length of X.
This String can be represented with single-digit(0, 1 , 2 , 3, 4, ... 9)  or two-digit(10, 11, 12, ... , 99) numbers, maybe in a future step three-digit(100, 101, ... 999).

I want to print out how many possibilities there are to built this a String with the length of X.

1= single-digit
2= two-digit

So if X=2   there are 2 possible ways to create a String with a length of 2.
1 1
2

X=4     --> 5
1 1 1 1
1 1 2
1 2 1
2 1 1
2 2

X=5     --> 8
1 1 1 1 1
1 1 1 2
1 1 2 1
1 2 1 1
2 1 1 1
2 2 1
2 1 2
1 2 2

### Edison Mera Menendez

Nov 1, 2016, 10:54:40 AM11/1/16
to Maxy Mustermann, SWI-Prolog
Look at this 10-lines program:

pos(1).
pos(2).

sol(N, L) :-
between(1, N, I),
length(L, I),
maplist(pos, L),
sum_list(L, N).

nsol(N, L, C) :-
findall(P, sol(N, P), L),
length(L, C).

Example:

?- nsol(2, L, C).
L = [[2], [1, 1]],
C = 2.

?- nsol(4, L, C).
L = [[2, 2], [1, 1, 2], [1, 2, 1], [2, 1, 1], [1, 1, 1, 1]],
C = 5.

?- nsol(5, L, C).
L = [[1, 2, 2], [2, 1, 2], [2, 2, 1], [1, 1, 1, 2], [1, 1, 2, 1], [1, 2, 1|...], [2, 1|...], [1|...]],
C = 8.

?- nsol(10, L, C).
L = [[2, 2, 2, 2, 2], [1, 1, 2, 2, 2, 2], [1, 2, 1, 2, 2, 2], [1, 2, 2, 1, 2|...], [1, 2, 2, 2|...], [1, 2, 2|...], [2, 1|...], [2|...], [...|...]|...],
C = 89.

Perhaps there are more optimal implementations, but I figure it out quickly by using some library predicates.
Best Regards,

Edison Mera, CS PhD
PROSYN expert - Consultant
Process Design Center (PDC)
Catharinastraat 21F
NL-4811 XD. Breda.
The Netherlands.
Tel:     +31 (0)76 530 1904
me...@process-design-center.com
www.process-design-center.com

--
You received this message because you are subscribed to the Google Groups "SWI-Prolog" group.
To unsubscribe from this group and stop receiving emails from it, send an email to swi-prolog+unsubscribe@googlegroups.com.