/* Floyd's triange (Rosetta code) in Picat. http://rosettacode.org/wiki/Floyd%27s_triangle """ Floyd's triangle lists the natural numbers in a right triangle aligned to the left where - the first row is just 1 - successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above. The first few lines of a Floyd triangle looks like this: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 The task is to: - Write a program to generate and display here the first n lines of a Floyd triangle. (Use n=5 and n=14 rows). - Ensure that when displayed in a monospace font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row. """ This Picat model was created by Hakan Kjellerstrand, hakank@gmail.com See also my Picat page: http://www.hakank.org/picat/ */ import util. % import cp. main => go. go => N = 5, println(floyd1(N)), nl, println(floyd2(N)), nl, println(floyd3(N)), nl. go2 => N = 14, println(floyd1(N)), nl, println(floyd2(N)), nl, println(floyd3(N)), nl. % last line of N=141. go3 => println(floyd1(141).split("\n").last()), nl. % calculate the numbers first and then format them floyd1(N) = S => M = [[J+SS : J in 1..I] : I in 1..N, SS=sum(1..I-1)], S = [slice(SS,2) : Row in M, SS = [to_fstring(to_fstring("%%%dd",M[N,I].to_string().length+1),E) : {E,I} in zip(Row,1..Row.length)].join('')].join("\n"). % Based on the Prolog version % (Picat don't have all SWI Prolog's nifty format options so we have to tweak a bit.) floyd2(N) = S => S = [], foreach(I in 1..N) SS = "", foreach(J in 1..I) Last = N * (N-1)/2+J, V = I * (I-1) // 2 + J, C = Last.to_string().length-1, SS := SS ++ to_fstring(to_fstring("%%%dd",C), V) end, S := S ++ slice(SS,2) ++ "\n" end. % % floyd2 a list comprehension % floyd3(N) = S => S = [[slice(SS,2) : J in 1..I, Last = N * (N-1)/2+J, V = I * (I-1) // 2 + J, C = Last.to_string().length-1, SS = to_fstring(to_fstring("%%%dd",C), V)].join(' ') : I in 1..N].join("\n").