From bc2bfd2c14e8588ffea19f359e53df55feed1069 Mon Sep 17 00:00:00 2001 From: Adam Russell Date: Sun, 29 Nov 2020 18:54:16 -0500 Subject: Prolog solution for Part 1 and Prolog blog. --- challenge-088/adam-russell/blog1.txt | 1 + challenge-088/adam-russell/prolog/ch-1.p | 28 ++++++++++++++++++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 challenge-088/adam-russell/blog1.txt create mode 100644 challenge-088/adam-russell/prolog/ch-1.p diff --git a/challenge-088/adam-russell/blog1.txt b/challenge-088/adam-russell/blog1.txt new file mode 100644 index 0000000000..982e0783c5 --- /dev/null +++ b/challenge-088/adam-russell/blog1.txt @@ -0,0 +1 @@ +http://www.rabbitfarm.com/cgi-bin/blosxom/prolog/2020/11/29 diff --git a/challenge-088/adam-russell/prolog/ch-1.p b/challenge-088/adam-russell/prolog/ch-1.p new file mode 100644 index 0000000000..ae22b0415c --- /dev/null +++ b/challenge-088/adam-russell/prolog/ch-1.p @@ -0,0 +1,28 @@ +/* + You are given an array of positive integers @N. + Write a script to return an array @M where $M[i] is + the product of all elements of @N except the index $N[i]. +*/ + +list_product([], 1). +list_product([L|Ls], P) :- + foldl(product_, Ls, L, P). + +product_(A, B, P) :- P is A*B. + +list_products(List, Products):- + length(List, L0), + L is L0 - 1, + list_products(List, L, [], Products). +list_products(_, -1, Products, Products). +list_products(List, Index, ProductsAccum, Products):- + nth0(Index, List, _, Remainder), + list_product(Remainder, Product), + NewIndex is Index - 1, + list_products(List, NewIndex, [Product|ProductsAccum], Products). + +main:- + list_products([5, 2, 1, 4, 3], Products), + write(Products), + halt. + \ No newline at end of file -- cgit From 4227c63624b68c731b4fdcdf973e0baabee82342 Mon Sep 17 00:00:00 2001 From: Adam Russell Date: Sun, 29 Nov 2020 18:58:16 -0500 Subject: cleaned up code --- challenge-088/adam-russell/prolog/ch-1.p | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/challenge-088/adam-russell/prolog/ch-1.p b/challenge-088/adam-russell/prolog/ch-1.p index ae22b0415c..01922cb3f1 100644 --- a/challenge-088/adam-russell/prolog/ch-1.p +++ b/challenge-088/adam-russell/prolog/ch-1.p @@ -3,12 +3,11 @@ Write a script to return an array @M where $M[i] is the product of all elements of @N except the index $N[i]. */ - +product_a_b(A, B, P):- + P is A*B. list_product([], 1). -list_product([L|Ls], P) :- - foldl(product_, Ls, L, P). - -product_(A, B, P) :- P is A*B. +list_product([H|T], P) :- + foldl(product_a_b, T, H, P). list_products(List, Products):- length(List, L0), -- cgit