%?- gtrace, juggle(2, [3]). %?- juggle(2, [3,3]). juggle(Hands, []) :- !, Hands > 1. juggle(Hands, Seq) :- Hands > 1, all_prods(Seq, 2, Prod), Prod1 is Prod + 1, try_sequence(0, Prod1, 0, [], Seq, Seq). try_sequence(N, N, _, _, _, _) :- !. try_sequence(N0, N, ID0, Air0, Seq0, Seq) :- N1 is N0 + 1, ( Seq0 = [S|Ss] -> ( select(Flying-N0, Air0, Air1) -> % re-throw a ball scheduled to arrive at this beat ( memberchk(_-N0, Air1) -> fail % two balls at once for this beat ; true ), Time1 is N0 + S, try_sequence(N1, N, ID0, [Flying-Time1|Air1], Ss, Seq) ; % create a new ball ID1 is ID0 + 1, Time1 is N0 + S, try_sequence(N1, N, ID1, [ID0-Time1|Air0], Ss, Seq) ) ; try_sequence(N0, N, ID0, Air0, Seq, Seq) % repeat period ). all_prods([], P, P). all_prods([A|As], P0, P) :- P1 is A*P0, all_prods(As, P1, P).