Friday, 15 July 2011

prolog - Generate list of numbers to fit certain criteria -


I had a predicate for creating a list of numbers,

  gener_numbers (0 , []). Generated_num (n, [head | tail]): - N & gt; 0, is head N, N1N -1, generated_ number (N1, tail).  

I am trying to modify it so that these numbers increase X and Y to a limit. The conditions are that 1 & lt; X & LT; Y and S = X + Y and S < 100 .

I am struggling to work, how to do it, I have tried, but it is not right anywhere.

  gener_numbers (1, []). Yield_number (x, [[head, y, s] | tail)): - x> gt; 1, Head X is, Y is x1, sx + y, x1 x -1, generated_ number (x1, tail).  

I have S & gt; 100 but he stopped the code from working at all.

My later output was [1,2,3], [2,4, 6], [39, 12], [20,25,45] . Obviously these are some examples, in reality there will be 1000s.

I think I might need to recurse twice. Add 1 to X while adding 1 to 20 until the extent does not reach the limit, add 1 to X and keep adding 1 to 1, until it reaches the limit and make sure to do it again and again That every possible pair has been created.

There are a few ways for this approach to formulate tremendous force to iterate on one of the two pairs in the equation For the base layer is the second layer. This solution will provide the first list in the order of the total amount, then X :

  with the value of gen_numbers (maxSum, the result): - MaxSum> 1, gen_numbers (2, maxim, 1, result). Gen_numbers (Yoga, Yoga, Yoga, []). % 'Yoga' has reached the maximum value value (points, maxms, yoga, results): -% 'X' has reached the maximum value  

By counting down instead, I can forward the list and retain tail recurrence without the use of an assist list. I was compelled by X and yoga and y is different

A cleaner approach to use the CLPFD library and the terms To specify the constraints of:

 : - use_module (library (CLPFD)). Yoga (yoga, [x, y, s]): - [x, y] these 1. SUM, yoga ([x, y], # = and lieutenant; yoga), label ([x, y]) S X + Y. gen_numbers (maxim, result): - Search ([x, y, s], equation (maxim, [x, y, s]), result).  

Here, equation / 2 presents one of each solution at a time, and findall / 3 collects them . This solution is easily scalable to make more resolution.


No comments:

Post a Comment