/* Jortsort (Rosetta code) in Picat. http://rosettacode.org/wiki/JortSort """ Note: jortSort is considered a work of satire. It achieves its result in an intentionally roundabout way. You are encouraged to write your solutions in the spirit of the original rather than trying to give the most concise or idiomatic solution. jortSort is a sorting toolset that makes the user do the work and guarantees efficiency because you don't have to sort ever again. It was originally presented by Jenn "Moneydollars" Schiffer at the prestigious JSConf [https://www.youtube.com/watch?v=pj4U_W0OFoE ]. jortSort is a function that takes a single array of comparable objects as its argument. It then sorts the array in ascending order and compares the sorted array to the originally provided array. If the arrays match (i.e. the original array was already sorted), the function returns true. If the arrays do not match (i.e. the original array was not sorted), the function returns false. """ This Picat model was created by Hakan Kjellerstrand, hakank@gmail.com See also my Picat page: http://www.hakank.org/picat/ */ main => go. go => List = [ [1,2,3,4,5], [2,3,4,5,1], [2], "jortsort", "jortsort".sort() ], foreach(L in List) println(testing=L), test(L,jortsort), test(L,jortsort2), test(L,jortsort3), test(L,jortsort4), test(L,jortsort5), test(L,jortsort6), nl end, nl. test(L,F) => printf("testing %w(%w): ", F,L), if call(F,L) then println(sorted) else println(not_sorted) end. % % direct approach % jortsort(X) => X == X.sort(). % % another approach, more like the original JS code % jortsort2(X) => Sorted = copy_term(X), Len = X.length, Check = true, while(Check = true) Swapped = false, foreach(I in 2..Len) if compare_terms(Sorted[I-1],Sorted[I]) > 0 then T := Sorted[I],Sorted[I] := Sorted[I-1],Sorted[I-1] := T, Swapped := true end end, if Swapped = false then Check := false end end, foreach(I in 1..X.len) if X[I] != Sorted[I] then printf("%w != %w at position %d! ",X[I], Sorted[I], I), false end end. % % We must of course include a recursive variant. % jortsort3(L) => jortsort3b(L,L.sort()). jortsort3b([],[]) => true. jortsort3b([H|T],[I|S]) => (H != I -> false ; jortsort3(T) % check the tail ). % % In a Rosetta code challenge there must also be % at least one list comprension approach. % % jortsort4(X) => sum([1 : {H,SS} in zip(X,X.sort()), H == SS]) == X.sort().len. % YAJS jortsort5(X), X == X.sort() ?=> X == X.sort(). jortsort5(X), X != X.sort() ?=> X == X.sort(). jortsort5(X), sorted==unsorted => X == X.sort(). jortsort6(X) => % count how many elements are less then this element % and compare with the sorted list L1 = [ sum([1 : J in 1..I-1, compare_terms(X[J],X[I]) < 0]) : I in 1..X.len], S = X.sort(), L2 = [ sum([1 : J in 1..I-1, compare_terms(S[J],S[I]) < 0]) : I in 1..S.len], L1 == L2.