Order two numerical lists: Difference between revisions
m →{{header|ALGOL 68}}: removed unused declaration |
→Nu: add |
||
(15 intermediate revisions by 12 users not shown) | |||
Line 17: | Line 17: | ||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang="11l">[1,2,1,3,2] < [1,2,0,4,4,0,0,0]</syntaxhighlight> |
||
=={{header|AArch64 Assembly}}== |
=={{header|AArch64 Assembly}}== |
||
{{works with|as|Raspberry Pi 3B version Buster 64 bits}} |
{{works with|as|Raspberry Pi 3B version Buster 64 bits}} |
||
<syntaxhighlight lang="aarch64 assembly"> |
|||
<lang AArch64 Assembly> |
|||
/* ARM assembly AARCH64 Raspberry PI 3B */ |
/* ARM assembly AARCH64 Raspberry PI 3B */ |
||
/* program orderlist64.s */ |
/* program orderlist64.s */ |
||
Line 172: | Line 172: | ||
.include "../includeARM64.inc" |
.include "../includeARM64.inc" |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|ACL2}}== |
=={{header|ACL2}}== |
||
Line 182: | Line 182: | ||
ACL2 !>(lexorder '(1 2 4) '(1 2 3)) |
ACL2 !>(lexorder '(1 2 4) '(1 2 3)) |
||
NIL</pre> |
NIL</pre> |
||
=={{header|Action!}}== |
|||
<syntaxhighlight lang="action!">INT FUNC Compare(INT ARRAY x INT xLen INT ARRAY y INT yLen) |
|||
INT i,len |
|||
len=xLen |
|||
IF len>yLen THEN |
|||
len=yLen |
|||
FI |
|||
FOR i=0 TO len-1 |
|||
DO |
|||
IF x(i)>y(i) THEN |
|||
RETURN (1) |
|||
ELSEIF x(i)<y(i) THEN |
|||
RETURN (-1) |
|||
FI |
|||
OD |
|||
IF xLen>yLen THEN |
|||
RETURN (1) |
|||
ELSEIF xLen<yLen THEN |
|||
RETURN (-1) |
|||
FI |
|||
RETURN (0) |
|||
BYTE FUNC Less(INT ARRAY x INT xLen INT ARRAY y INT yLen) |
|||
IF Compare(x,xLen,y,yLen)<0 THEN |
|||
RETURN (1) |
|||
FI |
|||
RETURN (0) |
|||
PROC PrintArray(INT ARRAY x INT len) |
|||
INT i |
|||
Put('[) |
|||
FOR i=0 TO len-1 |
|||
DO |
|||
PrintI(x(i)) |
|||
IF i<len-1 THEN |
|||
Put(' ) |
|||
FI |
|||
OD |
|||
Put(']) |
|||
RETURN |
|||
PROC Test(INT ARRAY x INT xLen INT ARRAY y INT yLen) |
|||
PrintArray(x,xLen) |
|||
IF Less(x,xLen,y,yLen) THEN |
|||
Print(" < ") |
|||
ELSE |
|||
Print(" >= ") |
|||
FI |
|||
PrintArray(y,yLen) PutE() |
|||
RETURN |
|||
PROC Main() |
|||
INT ARRAY a=[1 2 1 5 2] |
|||
INT ARRAY b=[1 2 1 5 2 2] |
|||
INT ARRAY c=[1 2 3 4 5] |
|||
INT ARRAY d=[1 2 3 4 5] |
|||
Test(a,5,b,6) |
|||
Test(b,6,a,5) |
|||
Test(b,6,c,5) |
|||
Test(c,5,b,6) |
|||
Test(c,5,d,5) |
|||
RETURN</syntaxhighlight> |
|||
{{out}} |
|||
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Order_two_numerical_lists.png Screenshot from Atari 8-bit computer] |
|||
<pre> |
|||
[1 2 1 5 2] < [1 2 1 5 2 2] |
|||
[1 2 1 5 2 2] >= [1 2 1 5 2] |
|||
[1 2 1 5 2 2] < [1 2 3 4 5] |
|||
[1 2 3 4 5] >= [1 2 1 5 2 2] |
|||
[1 2 3 4 5] >= [1 2 3 4 5] |
|||
</pre> |
|||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
Line 187: | Line 262: | ||
This also includes arrays of user defined types, using the type definition order from smallest to largest. |
This also includes arrays of user defined types, using the type definition order from smallest to largest. |
||
Demonstrated in the program below: |
Demonstrated in the program below: |
||
<syntaxhighlight lang="ada"> |
|||
<lang Ada> |
|||
with Ada.Text_IO; use Ada.Text_IO; |
with Ada.Text_IO; use Ada.Text_IO; |
||
procedure Order is |
procedure Order is |
||
Line 210: | Line 285: | ||
Put_Line (Boolean'Image (List6 > List7)); -- True |
Put_Line (Boolean'Image (List6 > List7)); -- True |
||
end Order; |
end Order; |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 221: | Line 296: | ||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
< |
<syntaxhighlight lang="algol68">BEGIN # compare lists (rows) of integers # |
||
# returns TRUE if there is an element in a that is < the corresponding # |
# returns TRUE if there is an element in a that is < the corresponding # |
||
# element in b and all previous elements are equal; FALSE otherwise # |
# element in b and all previous elements are equal; FALSE otherwise # |
||
Line 275: | Line 350: | ||
test( "list8", list8, "list7", list7, TRUE ) |
test( "list8", list8, "list7", list7, TRUE ) |
||
END</ |
END</syntaxhighlight> |
||
{{out}} |
|||
<pre> |
|||
list1 < list2 |
|||
list2 < list3 |
|||
list3 >= list4 |
|||
list5 >= list6 |
|||
list6 >= list7 |
|||
list7 >= list8 |
|||
list8 < list7 |
|||
</pre> |
|||
=={{header|ALGOL W}}== |
|||
{{Trans|ALGOL 68}} |
|||
<syntaxhighlight lang="algolw">begin % compare lists (rows) of integers % |
|||
% returns TRUE if there is an element in a that is < the corresponding % |
|||
% element in b and all previous elements are equal, FALSE otherwise % |
|||
% the bounds of a and b should aLb :: aUb and bLb :: bUb % |
|||
logical procedure iLT ( integer array a ( * ) |
|||
; integer value aLb, aUb |
|||
; integer array b ( * ) |
|||
; integer value bLb, bUb |
|||
) ; |
|||
begin |
|||
integer aPos, bPos; |
|||
logical equal; |
|||
aPos := aLb; |
|||
bPos := bLb; |
|||
equal := true; |
|||
while aPos <= aUb and bPos <= bUb and equal do begin |
|||
equal := a( aPos ) = b( bPos ); |
|||
if equal then begin |
|||
aPos := aPOs + 1; |
|||
bPos := bPos + 1 |
|||
end if_equal |
|||
end while_more_elements_and_equal ; |
|||
if not equal |
|||
then % there is an element in a and b that is not equal % |
|||
a( aPos ) < b( bPos ) |
|||
else % all elements are equal or one list is shorter % |
|||
% a is < b if a has fewer elements % |
|||
aPos > aUb and bPos <= bUb |
|||
end iLT ; |
|||
% tests a < b has the expected result % |
|||
procedure test ( string(5) value aName |
|||
; integer array a ( * ) |
|||
; integer value aLb, aUb |
|||
; string(5) value bName |
|||
; integer array b ( * ) |
|||
; integer value bLb, bUb |
|||
; logical value expected |
|||
) ; |
|||
begin |
|||
logical isLt; |
|||
isLt := iLT( a, aLb, aUb, b, bLb, bUb ); |
|||
write( aName, if isLt then " < " else " >= ", bName |
|||
, if isLt = expected then "" else ", NOT as expected" |
|||
) |
|||
end test ; |
|||
integer array list1, list3, list4 ( 1 :: 5 ); |
|||
integer array list2 ( 1 :: 6 ); |
|||
integer array list5 ( 1 :: 5 ); |
|||
integer array list6 ( 1 :: 4 ); |
|||
integer array list7 ( 1 :: 3 ); |
|||
integer array list8 ( 1 :: 1 ); |
|||
integer aPos; |
|||
% test cases as in the BBC basic sample % |
|||
aPos := 1; for i := 1, 2, 1, 5, 2 do begin list1( aPos ) := i; aPos := aPos + 1 end; |
|||
aPos := 1; for i := 1, 2, 1, 5, 2, 2 do begin list2( aPos ) := i; aPos := aPos + 1 end; |
|||
aPos := 1; for i := 1, 2, 3, 4, 5 do begin list3( aPos ) := i; aPos := aPos + 1 end; |
|||
aPos := 1; for i := 1, 2, 3, 4, 5 do begin list4( aPos ) := i; aPos := aPos + 1 end; |
|||
test( "list1", list1, 1, 5, "list2", list2, 1, 6, true ); |
|||
test( "list2", list2, 1, 6, "list3", list3, 1, 5, true ); |
|||
test( "list3", list3, 1, 5, "list4", list4, 1, 5, false ); |
|||
% additional test cases % |
|||
aPos := 1; for i := 9, 0, 2, 1, 0 do begin list5( aPos ) := i; aPos := aPos + 1 end; |
|||
aPos := 1; for i := 4, 0, 7, 7 do begin list6( aPos ) := i; aPos := aPos + 1 end; |
|||
aPos := 1; for i := 4, 0, 7 do begin list7( aPos ) := i; aPos := aPos + 1 end; |
|||
test( "list5", list5, 1, 5, "list6", list6, 1, 4, false ); |
|||
test( "list6", list6, 1, 4, "list7", list7, 1, 3, false ); |
|||
test( "list7", list7, 1, 3, "list8", list8, 1, 0, false ); |
|||
test( "list8", list8, 1, 0, "list7", list7, 1, 3, true ) |
|||
end.</syntaxhighlight> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 288: | Line 446: | ||
=={{header|Aime}}== |
=={{header|Aime}}== |
||
< |
<syntaxhighlight lang="aime">ordl(list a, b) |
||
{ |
{ |
||
integer i, l, o; |
integer i, l, o; |
||
Line 315: | Line 473: | ||
0; |
0; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|AppleScript}}== |
=={{header|AppleScript}}== |
||
Line 322: | Line 480: | ||
<= is not defined over lists in AppleScript |
<= is not defined over lists in AppleScript |
||
< |
<syntaxhighlight lang="applescript">-- <= for lists |
||
-- compare :: [a] -> [a] -> Bool |
-- compare :: [a] -> [a] -> Bool |
||
on compare(xs, ys) |
on compare(xs, ys) |
||
Line 365: | Line 523: | ||
missing value |
missing value |
||
end if |
end if |
||
end uncons</ |
end uncons</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<lang |
<syntaxhighlight lang="applescript">{false, true}</syntaxhighlight> |
||
---- |
---- |
||
Here's an iterative implementation: |
Here's an iterative implementation: |
||
< |
<syntaxhighlight lang="applescript">on listAComesBeforeListB(a, b) |
||
set aLength to (count a) |
set aLength to (count a) |
||
set bLength to (count b) |
set bLength to (count b) |
||
Line 404: | Line 562: | ||
end repeat |
end repeat |
||
return {a:a, b:b, | a < b |: listAComesBeforeListB(a, b)},</ |
return {a:a, b:b, | a < b |: listAComesBeforeListB(a, b)},</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Examples: |
Examples: |
||
< |
<syntaxhighlight lang="applescript">{a:{3, 5, 6, 5, 2, 1, 4}, b:{5, 8, 9, 2, 0, 1, 9, 0, 4, 10}, | a < b |:true} |
||
{a:{10, 9, 5, 8, 8, 4, 3}, b:{5, 10, 8, 9, 10, 8, 7, 8}, | a < b |:false} |
{a:{10, 9, 5, 8, 8, 4, 3}, b:{5, 10, 8, 9, 10, 8, 7, 8}, | a < b |:false} |
||
{a:{0, 10}, b:{0, 10}, | a < b |:false} |
{a:{0, 10}, b:{0, 10}, | a < b |:false} |
||
{a:{0, 10}, b:{0, 10, 5}, | a < b |:true}</ |
{a:{0, 10}, b:{0, 10, 5}, | a < b |:true}</syntaxhighlight> |
||
=={{header|ARM Assembly}}== |
=={{header|ARM Assembly}}== |
||
{{works with|as|Raspberry Pi}} |
{{works with|as|Raspberry Pi}} |
||
<syntaxhighlight lang="arm assembly"> |
|||
<lang ARM Assembly> |
|||
/* ARM assembly Raspberry PI */ |
/* ARM assembly Raspberry PI */ |
||
/* program orderlist.s */ |
/* program orderlist.s */ |
||
Line 570: | Line 728: | ||
pop {r0,r1,r2,r7,lr} @ restaur registers */ |
pop {r0,r1,r2,r7,lr} @ restaur registers */ |
||
bx lr @ return |
bx lr @ return |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Arturo}}== |
|||
<syntaxhighlight lang="rebol">compareLists: function [a,b][ |
|||
loop 0..min @[size a, size b] 'i [ |
|||
if a\[i] < b\[i] -> return true |
|||
if a\[i] > b\[i] -> return false |
|||
] |
|||
return less? size a size b |
|||
] |
|||
alias.infix '<=> 'compareLists |
|||
do [ |
|||
print [1 2 1 3 2] <=> [1 2 0 4 4 0 0 0] |
|||
]</syntaxhighlight> |
|||
{{out}} |
|||
<pre>false</pre> |
|||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
{{works with|AutoHotkey_L}} |
{{works with|AutoHotkey_L}} |
||
The function is overkill as we can just compare the list's ObjMaxIndex() |
The function is overkill as we can just compare the list's ObjMaxIndex() |
||
< |
<syntaxhighlight lang="ahk">List1 := [1,2,1,3,2] |
||
List2 := [1,2,0,4,4,0,0,0] |
List2 := [1,2,0,4,4,0,0,0] |
||
MsgBox % order(List1, List2) |
MsgBox % order(List1, List2) |
||
Line 581: | Line 759: | ||
order(L1, L2){ |
order(L1, L2){ |
||
return L1.MaxIndex() < L2.MaxIndex() |
return L1.MaxIndex() < L2.MaxIndex() |
||
}</ |
}</syntaxhighlight> |
||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
<syntaxhighlight lang="awk"> |
|||
<lang AWK> |
|||
# syntax: GAWK -f ORDER_TWO_NUMERICAL_LISTS.AWK |
# syntax: GAWK -f ORDER_TWO_NUMERICAL_LISTS.AWK |
||
BEGIN { |
BEGIN { |
||
Line 609: | Line 787: | ||
return(ans) |
return(ans) |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 620: | Line 798: | ||
=={{header|BASIC256}}== |
=={{header|BASIC256}}== |
||
{{trans|FreeBASIC}} |
{{trans|FreeBASIC}} |
||
<syntaxhighlight lang="basic256"> |
|||
<lang BASIC256> |
|||
arraybase 1 |
arraybase 1 |
||
dim list1(5): dim list2(6): dim list3(5): dim list4(5) |
dim list1(5): dim list2(6): dim list3(5): dim list4(5) |
||
Line 644: | Line 822: | ||
return l1 < l2 |
return l1 < l2 |
||
end function |
end function |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 653: | Line 831: | ||
=={{header|BBC BASIC}}== |
=={{header|BBC BASIC}}== |
||
'Ordered before' means 'less than' (see [[Talk:Order_two_numerical_lists|talk page]]). |
'Ordered before' means 'less than' (see [[Talk:Order_two_numerical_lists|talk page]]). |
||
< |
<syntaxhighlight lang="bbcbasic"> DIM list1(4) : list1() = 1, 2, 1, 5, 2 |
||
DIM list2(5) : list2() = 1, 2, 1, 5, 2, 2 |
DIM list2(5) : list2() = 1, 2, 1, 5, 2, 2 |
||
DIM list3(4) : list3() = 1, 2, 3, 4, 5 |
DIM list3(4) : list3() = 1, 2, 3, 4, 5 |
||
Line 671: | Line 849: | ||
IF list1(i%) < list2(i%) THEN = TRUE |
IF list1(i%) < list2(i%) THEN = TRUE |
||
IF list1(i%) > list2(i%) THEN = FALSE |
IF list1(i%) > list2(i%) THEN = FALSE |
||
= l1% < l2%</ |
= l1% < l2%</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 686: | Line 864: | ||
In that case the function outputs FALSE. |
In that case the function outputs FALSE. |
||
Notice that if the arguments are the same, evaluation of the sum produces the product of one of the terms and a factor two. This complicates the pattern a bit. |
Notice that if the arguments are the same, evaluation of the sum produces the product of one of the terms and a factor two. This complicates the pattern a bit. |
||
< |
<syntaxhighlight lang="bracmat">( 1 2 3 4 5:?List1 |
||
& 1 2 1 5 2 2:?List2 |
& 1 2 1 5 2 2:?List2 |
||
& 1 2 1 5 2:?List3 |
& 1 2 1 5 2:?List3 |
||
Line 709: | Line 887: | ||
& gt$(!List5,!List6) |
& gt$(!List5,!List6) |
||
& gt$(!List6,!List7) |
& gt$(!List6,!List7) |
||
);</ |
);</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>TRUE |
<pre>TRUE |
||
Line 719: | Line 897: | ||
=={{header|C}}== |
=={{header|C}}== |
||
< |
<syntaxhighlight lang="c">int list_cmp(int *a, int la, int *b, int lb) |
||
{ |
{ |
||
int i, l = la; |
int i, l = la; |
||
Line 729: | Line 907: | ||
if (la == lb) return 0; |
if (la == lb) return 0; |
||
return la > lb ? 1 : -1; |
return la > lb ? 1 : -1; |
||
}</ |
}</syntaxhighlight> |
||
This funciton returns one of three states, not a boolean. One can define boolean comparisons, such as <code>list_less_or_eq</code>, based on it:< |
This funciton returns one of three states, not a boolean. One can define boolean comparisons, such as <code>list_less_or_eq</code>, based on it:<syntaxhighlight lang="c">#define list_less_or_eq(a,b,c,d) (list_cmp(a,b,c,d) != 1)</syntaxhighlight> |
||
=={{header|C sharp|C#}}== |
=={{header|C sharp|C#}}== |
||
< |
<syntaxhighlight lang="csharp">namespace RosettaCode.OrderTwoNumericalLists |
||
{ |
{ |
||
using System; |
using System; |
||
Line 775: | Line 953: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>False</pre> |
<pre>False</pre> |
||
Line 781: | Line 959: | ||
=={{header|C++}}== |
=={{header|C++}}== |
||
The built-in comparison operators already do this: |
The built-in comparison operators already do this: |
||
< |
<syntaxhighlight lang="cpp">#include <iostream> |
||
#include <vector> |
#include <vector> |
||
Line 803: | Line 981: | ||
std::cout << std::boolalpha << (a < b) << std::endl; // prints "false" |
std::cout << std::boolalpha << (a < b) << std::endl; // prints "false" |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|clojure}}== |
=={{header|clojure}}== |
||
< |
<syntaxhighlight lang="clojure"> |
||
(defn lex? [a b] |
(defn lex? [a b] |
||
(compare a b)) |
(compare a b)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
< |
<syntaxhighlight lang="lisp">(defun list< (a b) |
||
(cond ((not b) nil) |
(cond ((not b) nil) |
||
((not a) t) |
((not a) t) |
||
((= (first a) (first b)) |
((= (first a) (first b)) |
||
(list< (rest a) (rest b))) |
(list< (rest a) (rest b))) |
||
(t (< (first a) (first b)))))</ |
(t (< (first a) (first b)))))</syntaxhighlight> |
||
Alternate version |
Alternate version |
||
< |
<syntaxhighlight lang="lisp">(defun list< (a b) |
||
(let ((x (find-if-not #'zerop (mapcar #'- a b)))) |
(let ((x (find-if-not #'zerop (mapcar #'- a b)))) |
||
(if x (minusp x) (< (length a) (length b)))))</ |
(if x (minusp x) (< (length a) (length b)))))</syntaxhighlight> |
||
=={{header|D}}== |
=={{header|D}}== |
||
The built-in comparison operators already do this: |
The built-in comparison operators already do this: |
||
< |
<syntaxhighlight lang="d">void main() { |
||
assert([1,2,1,3,2] >= [1,2,0,4,4,0,0,0]); |
assert([1,2,1,3,2] >= [1,2,0,4,4,0,0,0]); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Delphi}}== |
=={{header|Delphi}}== |
||
{{libheader| System.SysUtils}} |
{{libheader| System.SysUtils}} |
||
Line 836: | Line 1,014: | ||
{{Trans|Java}} |
{{Trans|Java}} |
||
This is not a full translate of [https://rosettacode.org/wiki/Order_two_numerical_lists#Java Java], just adaptation and aplication of method previus introduced. |
This is not a full translate of [https://rosettacode.org/wiki/Order_two_numerical_lists#Java Java], just adaptation and aplication of method previus introduced. |
||
<syntaxhighlight lang="delphi"> |
|||
<lang Delphi> |
|||
program Order_two_numerical_lists; |
program Order_two_numerical_lists; |
||
Line 871: | Line 1,049: | ||
'not', 'a', 'test'])); |
'not', 'a', 'test'])); |
||
readln; |
readln; |
||
end.</ |
end.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>TRUE |
<pre>TRUE |
||
Line 879: | Line 1,057: | ||
FALSE |
FALSE |
||
TRUE</pre> |
TRUE</pre> |
||
=={{header|EasyLang}}== |
|||
{{trans|C}} |
|||
<syntaxhighlight lang=text> |
|||
func listcmp a[] b[] . |
|||
for i to lower len a[] len b[] |
|||
if a[i] < b[i] |
|||
return -1 |
|||
elif a[i] > b[i] |
|||
return 1 |
|||
. |
|||
. |
|||
if len a[] < len b[] |
|||
return -1 |
|||
elif len a[] > len b[] |
|||
return 1 |
|||
. |
|||
return 0 |
|||
. |
|||
print listcmp [ 2 4 5 ] [ 2 3 1 ] |
|||
print listcmp [ 2 3 1 ] [ 2 3 1 ] |
|||
print listcmp [ 2 3 1 ] [ 2 3 1 3 ] |
|||
</syntaxhighlight> |
|||
=={{header|Ela}}== |
=={{header|Ela}}== |
||
< |
<syntaxhighlight lang="ela">[] <. _ = true |
||
_ <. [] = false |
_ <. [] = false |
||
(x::xs) <. (y::ys) | x == y = xs <. ys |
(x::xs) <. (y::ys) | x == y = xs <. ys |
||
| else = x < y |
| else = x < y |
||
[1,2,1,3,2] <. [1,2,0,4,4,0,0,0]</ |
[1,2,1,3,2] <. [1,2,0,4,4,0,0,0]</syntaxhighlight> |
||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
The built-in comparison functions already do this (not only for lists of numbers, but for any arbitrary data type). |
The built-in comparison functions already do this (not only for lists of numbers, but for any arbitrary data type). |
||
< |
<syntaxhighlight lang="elixir">iex(1)> [1,2,3] < [1,2,3,4] |
||
true |
true |
||
iex(2)> [1,2,3] < [1,2,4] |
iex(2)> [1,2,3] < [1,2,4] |
||
true</ |
true</syntaxhighlight> |
||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
Builtin. Example use from Erlang shell: |
Builtin. Example use from Erlang shell: |
||
<syntaxhighlight lang="erlang"> |
|||
<lang Erlang> |
|||
5> [1,2,3] < [1,2,3,4]. |
5> [1,2,3] < [1,2,3,4]. |
||
true |
true |
||
6> [1,2,3] < [1,2,4]. |
6> [1,2,3] < [1,2,4]. |
||
true |
true |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|F_Sharp|F#}}== |
=={{header|F_Sharp|F#}}== |
||
By using the Collection.Seq Module the static method Seq.compareWith fits our needs. |
By using the Collection.Seq Module the static method Seq.compareWith fits our needs. |
||
< |
<syntaxhighlight lang="fsharp">let inline cmp x y = if x < y then -1 else if x = y then 0 else 1 |
||
let before (s1 : seq<'a>) (s2 : seq<'a>) = (Seq.compareWith cmp s1 s2) < 0 |
let before (s1 : seq<'a>) (s2 : seq<'a>) = (Seq.compareWith cmp s1 s2) < 0 |
||
Line 925: | Line 1,125: | ||
([0; 0], [1]); |
([0; 0], [1]); |
||
] |
] |
||
|> List.iter (fun (x, y) -> printf "%A %s %A\n" x (if before x y then "< " else ">=") y)</ |
|> List.iter (fun (x, y) -> printf "%A %s %A\n" x (if before x y then "< " else ">=") y)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>[0] >= [] |
<pre>[0] >= [] |
||
Line 949: | Line 1,149: | ||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
{{trans|BBC BASIC}} |
{{trans|BBC BASIC}} |
||
< |
<syntaxhighlight lang="freebasic">Dim Shared list1(4) As Integer = {1, 2, 1, 5, 2} |
||
Dim Shared list2(5) As Integer = {1, 2, 1, 5, 2, 2} |
Dim Shared list2(5) As Integer = {1, 2, 1, 5, 2, 2} |
||
Dim Shared list3(4) As Integer = {1, 2, 3, 4, 5} |
Dim Shared list3(4) As Integer = {1, 2, 3, 4, 5} |
||
Line 970: | Line 1,170: | ||
If Orden(list3(), list4()) Then Print "list3<list4" Else Print "list3>=list4" |
If Orden(list3(), list4()) Then Print "list3<list4" Else Print "list3>=list4" |
||
Sleep</ |
Sleep</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 978: | Line 1,178: | ||
=={{header|Go}}== |
=={{header|Go}}== |
||
< |
<syntaxhighlight lang="go">package main |
||
import "fmt" |
import "fmt" |
||
Line 1,050: | Line 1,250: | ||
} |
} |
||
return b |
return b |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,082: | Line 1,282: | ||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
Solution: |
Solution: |
||
< |
<syntaxhighlight lang="groovy">class CList extends ArrayList implements Comparable { |
||
CList() { } |
CList() { } |
||
CList(Collection c) { super(c) } |
CList(Collection c) { super(c) } |
||
Line 1,091: | Line 1,291: | ||
comp ? comp[0] <=> comp[1] : this.size() <=> that.size() |
comp ? comp[0] <=> comp[1] : this.size() <=> that.size() |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Test: |
Test: |
||
< |
<syntaxhighlight lang="groovy">CList a, b; (a, b) = [[], []]; assert ! (a < b) |
||
b = [1] as CList; assert (a < b) |
b = [1] as CList; assert (a < b) |
||
a = [1] as CList; assert ! (a < b) |
a = [1] as CList; assert ! (a < b) |
||
Line 1,102: | Line 1,302: | ||
b = [2, -1, 0] as CList; assert ! (a < b) |
b = [2, -1, 0] as CList; assert ! (a < b) |
||
b = [2, -1, 0, -17] as CList; assert (a < b) |
b = [2, -1, 0, -17] as CList; assert (a < b) |
||
a = [2, 8, 0] as CList; assert ! (a < b)</ |
a = [2, 8, 0] as CList; assert ! (a < b)</syntaxhighlight> |
||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
The built-in comparison operators already do this: |
The built-in comparison operators already do this: |
||
< |
<syntaxhighlight lang="haskell">Prelude> [1,2,1,3,2] < [1,2,0,4,4,0,0,0] |
||
False</ |
False</syntaxhighlight> |
||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
List_llt is written in the style of all Icon/Unicon relational operators returning its right argument if successful and signaling failure otherwise. |
List_llt is written in the style of all Icon/Unicon relational operators returning its right argument if successful and signaling failure otherwise. |
||
< |
<syntaxhighlight lang="icon">procedure main() |
||
write( if list_llt([1,2,1,3,2],[1,2,0,4,4,0,0,0]) then "true" else "false" ) |
write( if list_llt([1,2,1,3,2],[1,2,0,4,4,0,0,0]) then "true" else "false" ) |
||
end |
end |
||
Line 1,122: | Line 1,322: | ||
else if L1[i] >> L2[i] then fail |
else if L1[i] >> L2[i] then fail |
||
if *L1 < *L2 then return L2 |
if *L1 < *L2 then return L2 |
||
end</ |
end</syntaxhighlight> |
||
=={{header|J}}== |
=={{header|J}}== |
||
Line 1,131: | Line 1,331: | ||
However numeric scalars sort ahead of vectors, i.e. are different from length one lists. |
However numeric scalars sort ahead of vectors, i.e. are different from length one lists. |
||
< |
<syntaxhighlight lang="j">before=: -.@(-: /:~)@,&<~</syntaxhighlight> |
||
< |
<syntaxhighlight lang="j">cmp=: {.@\:@,:&(,&__)</syntaxhighlight> |
||
Below demonstrates non-decreasing order cmp treats length one vector same as scalar |
Below demonstrates non-decreasing order cmp treats length one vector same as scalar |
||
<syntaxhighlight lang="j"> |
|||
<lang j> |
|||
cmp&.>"{~ ('';0;(,0);1;(,1);1 1) |
cmp&.>"{~ ('';0;(,0);1;(,1);1 1) |
||
┌─┬─┬─┬─┬─┬─┐ |
┌─┬─┬─┬─┬─┬─┐ |
||
Line 1,166: | Line 1,366: | ||
├─┼─┼─┼─┼─┼─┤ |
├─┼─┼─┼─┼─┼─┤ |
||
│0│0│0│0│0│0│ |
│0│0│0│0│0│0│ |
||
└─┴─┴─┴─┴─┴─┘</ |
└─┴─┴─┴─┴─┴─┘</syntaxhighlight> |
||
=={{header|Java}}== |
=={{header|Java}}== |
||
Line 1,172: | Line 1,372: | ||
{{trans|Common Lisp}} |
{{trans|Common Lisp}} |
||
There are a few methods here. The method named "ordered" which works on arrays is a translation of [[#Common Lisp|Common Lisp]]. The other two are loose translations of [[#Tcl|Tcl]] (some tweaks were needed to get the length checks to work out) and are probably better options. |
There are a few methods here. The method named "ordered" which works on arrays is a translation of [[#Common Lisp|Common Lisp]]. The other two are loose translations of [[#Tcl|Tcl]] (some tweaks were needed to get the length checks to work out) and are probably better options. |
||
< |
<syntaxhighlight lang="java5">import java.util.Arrays; |
||
import java.util.List; |
import java.util.List; |
||
Line 1,205: | Line 1,405: | ||
return i == first.length; |
return i == first.length; |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
Line 1,213: | Line 1,413: | ||
<= is already defined for numeric lists in JavaScript |
<= is already defined for numeric lists in JavaScript |
||
< |
<syntaxhighlight lang="javascript">(() => { |
||
'use strict'; |
'use strict'; |
||
Line 1,230: | Line 1,430: | ||
// --> [false, true] |
// --> [false, true] |
||
})() |
})() |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
<lang |
<syntaxhighlight lang="javascript">[false, true]</syntaxhighlight> |
||
=={{header|Joy}}== |
=={{header|Joy}}== |
||
<syntaxhighlight lang="joy"> |
|||
<lang Joy> |
|||
DEFINE order == |
DEFINE order == |
||
[equal] [false] |
[equal] [false] |
||
[[[[size] dip size <=] [[<=] mapr2 true [and] fold]] [i] map i and] |
[[[[size] dip size <=] [[<=] mapr2 true [and] fold]] [i] map i and] |
||
ifte. |
ifte. |
||
</syntaxhighlight> |
|||
</lang> |
|||
Using it: |
Using it: |
||
Line 1,254: | Line 1,454: | ||
=={{header|jq}}== |
=={{header|jq}}== |
||
jq's builtin comparison operators use lexicographic ordering for arrays in general, not just arrays of integers.< |
jq's builtin comparison operators use lexicographic ordering for arrays in general, not just arrays of integers.<syntaxhighlight lang="jq"> |
||
[1,2,3] < [1,2,3,4] # => true |
[1,2,3] < [1,2,3,4] # => true |
||
[1,2,3] < [1,2,4] # => true |
[1,2,3] < [1,2,4] # => true |
||
[1,2,3] < [1,2,3] # => false</ |
[1,2,3] < [1,2,3] # => false</syntaxhighlight> |
||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
{{works with|Julia|0.6}} |
{{works with|Julia|0.6}} |
||
< |
<syntaxhighlight lang="julia">function islexless(a::AbstractArray{<:Real}, b::AbstractArray{<:Real}) |
||
for (x, y) in zip(a, b) |
for (x, y) in zip(a, b) |
||
if x == y continue end |
if x == y continue end |
||
Line 1,274: | Line 1,474: | ||
println("List not sorted:\n - ", join(tests, "\n - ")) |
println("List not sorted:\n - ", join(tests, "\n - ")) |
||
sort!(tests; lt=islexless) |
sort!(tests; lt=islexless) |
||
println("List sorted:\n - ", join(tests, "\n - "))</ |
println("List sorted:\n - ", join(tests, "\n - "))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,295: | Line 1,495: | ||
=={{header|Klingphix}}== |
=={{header|Klingphix}}== |
||
< |
<syntaxhighlight lang="klingphix">include ..\Utilitys.tlhy |
||
( 1 2 3 ) ( 1 2 3 4 ) less ? |
( 1 2 3 ) ( 1 2 3 4 ) less ? |
||
Line 1,303: | Line 1,503: | ||
( 1 2 3 ) ( 1 2 4 ) less ? |
( 1 2 3 ) ( 1 2 4 ) less ? |
||
"End " input</ |
"End " input</syntaxhighlight> |
||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
< |
<syntaxhighlight lang="scala">// version 1.0.6 |
||
operator fun <T> List<T>.compareTo(other: List<T>): Int |
operator fun <T> List<T>.compareTo(other: List<T>): Int |
||
Line 1,333: | Line 1,533: | ||
println() |
println() |
||
for (i in 0 until lists.size - 1) println("list${i + 1} > list${i + 2} = ${lists[i] > lists[i + 1]}") |
for (i in 0 until lists.size - 1) println("list${i + 1} > list${i + 2} = ${lists[i] > lists[i + 1]}") |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,359: | Line 1,559: | ||
=={{header|Lasso}}== |
=={{header|Lasso}}== |
||
This is built into the Lasso comparison operators |
This is built into the Lasso comparison operators |
||
< |
<syntaxhighlight lang="lasso">local( |
||
first = array(1,2,1,3,2), |
first = array(1,2,1,3,2), |
||
second = array(1,2,0,4,4,0,0,0), |
second = array(1,2,0,4,4,0,0,0), |
||
Line 1,369: | Line 1,569: | ||
second = array(1,2,0,4,4,0,0,0), |
second = array(1,2,0,4,4,0,0,0), |
||
) |
) |
||
#first < #second</ |
#first < #second</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>false |
<pre>false |
||
Line 1,377: | Line 1,577: | ||
Uses standard '=' notation |
Uses standard '=' notation |
||
< |
<syntaxhighlight lang="logo">print [1 2] = [1 2] |
||
print [1 2] = [1 2 3] |
print [1 2] = [1 2 3] |
||
print [1 3] = [1 2] |
print [1 3] = [1 2] |
||
Line 1,384: | Line 1,584: | ||
make "list1 [1 2 3 4 5 6] |
make "list1 [1 2 3 4 5 6] |
||
make "list2 [1 2 3 4 5 7] |
make "list2 [1 2 3 4 5 7] |
||
print :list1 = :list2</ |
print :list1 = :list2</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
< |
<syntaxhighlight lang="logo">true |
||
false |
false |
||
false |
false |
||
false |
false |
||
false</ |
false</syntaxhighlight> |
||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
Line 1,397: | Line 1,597: | ||
In Lua tables with numerical indices are used as lists or arrays and they do not support comparison out-of-the-box, so a function is needed to implement the comparison: |
In Lua tables with numerical indices are used as lists or arrays and they do not support comparison out-of-the-box, so a function is needed to implement the comparison: |
||
< |
<syntaxhighlight lang="lua">function arraycompare(a, b) |
||
for i = 1, #a do |
for i = 1, #a do |
||
if b[i] == nil then |
if b[i] == nil then |
||
Line 1,407: | Line 1,607: | ||
end |
end |
||
return true |
return true |
||
end</ |
end</syntaxhighlight> |
||
Here is some demonstration code: |
Here is some demonstration code: |
||
< |
<syntaxhighlight lang="lua">function randomarray() |
||
local t = {} |
local t = {} |
||
for i = 1, math.random(1, 10) do |
for i = 1, math.random(1, 10) do |
||
Line 1,430: | Line 1,630: | ||
arraycompare(a, b) and "<=" or ">", |
arraycompare(a, b) and "<=" or ">", |
||
table.concat(b, ', '))) |
table.concat(b, ', '))) |
||
end</ |
end</syntaxhighlight> |
||
{{out}} (time used as random seed: 1413127434): |
{{out}} (time used as random seed: 1413127434): |
||
Line 1,447: | Line 1,647: | ||
=={{header|Maple}}== |
=={{header|Maple}}== |
||
< |
<syntaxhighlight lang="maple">orderLists := proc(num1,num2) |
||
local len1, len2,i: |
local len1, len2,i: |
||
len1,len2 := numelems(num1),numelems(num2): |
len1,len2 := numelems(num1),numelems(num2): |
||
Line 1,456: | Line 1,656: | ||
end do: |
end do: |
||
return evalb(len1 < len2): |
return evalb(len1 < len2): |
||
end proc:</ |
end proc:</syntaxhighlight> |
||
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
||
< |
<syntaxhighlight lang="mathematica">order[List1_, List2_] := With[{ |
||
L1 = List1[[1 ;; Min @@ Length /@ {List1, List2}]], |
L1 = List1[[1 ;; Min @@ Length /@ {List1, List2}]], |
||
L2 = List2[[1 ;; Min @@ Length /@ {List1, List2}]] |
L2 = List2[[1 ;; Min @@ Length /@ {List1, List2}]] |
||
Line 1,466: | Line 1,666: | ||
Length[List1] < Length[List2], |
Length[List1] < Length[List2], |
||
Thread[Order[L1, L2]] == 1 |
Thread[Order[L1, L2]] == 1 |
||
]]</ |
]]</syntaxhighlight> |
||
<pre>Example use: |
<pre>Example use: |
||
Line 1,475: | Line 1,675: | ||
=={{header|Maxima}}== |
=={{header|Maxima}}== |
||
< |
<syntaxhighlight lang="maxima">"<<"(a,b):=block([n:min(length(a),length(b))], |
||
catch(for i thru n do (if a[i]#b[i] then throw(is(a[i]<b[i]))), |
catch(for i thru n do (if a[i]#b[i] then throw(is(a[i]<b[i]))), |
||
throw(is(length(a)<length(b)))))$ |
throw(is(length(a)<length(b)))))$ |
||
Line 1,487: | Line 1,687: | ||
[1,2] << [1,2]; |
[1,2] << [1,2]; |
||
false</ |
false</syntaxhighlight> |
||
=={{header|Mercury}}== |
=={{header|Mercury}}== |
||
Line 1,493: | Line 1,693: | ||
For a particular numerical type, you can get away with |
For a particular numerical type, you can get away with |
||
< |
<syntaxhighlight lang="mercury">:- pred lt(list(int)::in, list(int)::in) is semidet. |
||
lt([], [_|_]). |
lt([], [_|_]). |
||
lt([H1|T1], [H2|T2]) :- H1 =< H2, T1 `lt` T2.</ |
lt([H1|T1], [H2|T2]) :- H1 =< H2, T1 `lt` T2.</syntaxhighlight> |
||
For a list of any numerical type, one way would be to use a typeclass: |
For a list of any numerical type, one way would be to use a typeclass: |
||
< |
<syntaxhighlight lang="mercury">:- pred lt(list(T)::in, list(T)::in) is semidet <= comparable(T). |
||
lt([], [_|_]). |
lt([], [_|_]). |
||
lt([H1|T1], [H2|T2]) :- H1 =< H2, T1 `lt` T2.</ |
lt([H1|T1], [H2|T2]) :- H1 =< H2, T1 `lt` T2.</syntaxhighlight> |
||
... which you would have to create: |
... which you would have to create: |
||
< |
<syntaxhighlight lang="mercury">:- module comparable. |
||
:- interface. |
:- interface. |
||
:- import_module int, float, integer, list. |
:- import_module int, float, integer, list. |
||
Line 1,531: | Line 1,731: | ||
% pred lt |
% pred lt |
||
% pred lte</ |
% pred lte</syntaxhighlight> |
||
Which would be used in this way - note the typeclass and the comparison operator. |
Which would be used in this way - note the typeclass and the comparison operator. |
||
< |
<syntaxhighlight lang="mercury">:- pred test(list(T), list(T), io, io) <= comparable(T). |
||
:- mode test(in, in, di, uo) is det. |
:- mode test(in, in, di, uo) is det. |
||
test(A, B) --> |
test(A, B) --> |
||
io.write(A), io.write_string(" < "), io.write(B), |
io.write(A), io.write_string(" < "), io.write(B), |
||
io.write_string(" : "), io.write_string(S), io.nl, |
io.write_string(" : "), io.write_string(S), io.nl, |
||
{ A < B -> S = "yes" ; S = "no" }.</ |
{ A < B -> S = "yes" ; S = "no" }.</syntaxhighlight> |
||
=={{header|Miranda}}== |
|||
<syntaxhighlight lang="miranda">main :: [sys_message] |
|||
main = [Stdout (lay (map show [ |
|||
order [1,2,1,3,2] [1,2,0,4,4,0,0,0], |
|||
order [1,2,0,4,4,0,0,0] [1,2,1,3,2]]))] |
|||
order :: [*]->[*]->bool |
|||
order as [] = True |
|||
order [] as = False |
|||
order (a:as) (b:bs) = a < b, if a ~= b |
|||
= order as bs, otherwise</syntaxhighlight> |
|||
{{out}} |
|||
<pre>False |
|||
True</pre> |
|||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
< |
<syntaxhighlight lang="nim">proc `<`[T](a, b: openarray[T]): bool = |
||
for i in 0 .. min(a.len, b.len): |
for i in 0 .. min(a.len, b.len): |
||
if a[i] < b[i]: return true |
if a[i] < b[i]: return true |
||
Line 1,549: | Line 1,764: | ||
return a.len < b.len |
return a.len < b.len |
||
echo([1,2,1,3,2] < [1,2,0,4,4,0,0,0])</ |
echo([1,2,1,3,2] < [1,2,0,4,4,0,0,0])</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>false</pre> |
<pre>false</pre> |
||
=={{header|Nu}}== |
|||
{{works with|Nushell|0.96.1}} |
|||
<syntaxhighlight lang="nu">def 'list lt' [b] { |
|||
let a = $in |
|||
$a | zip $b |
|||
| skip while { $in.0 == $in.1 } |
|||
| try { first } catch { [$a $b] | each { length } } |
|||
| $in.0 < $in.1 |
|||
} |
|||
[5 6 7 8] | list lt [5 6 8]</syntaxhighlight> |
|||
{{out}} |
|||
<pre>true</pre> |
|||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
The built-in comparison operators already do this for lists (although this is not documented): |
The built-in comparison operators already do this for lists (although this is not documented): |
||
< |
<syntaxhighlight lang="ocaml"># [1;2;1;3;2] < [1;2;0;4;4;0;0;0];; |
||
- : bool = false</ |
- : bool = false</syntaxhighlight> |
||
(Warning: However, the built-in comparison operators do not do this for arrays: |
(Warning: However, the built-in comparison operators do not do this for arrays: |
||
< |
<syntaxhighlight lang="ocaml"># [|1;2;1;3;2|] < [|1;2;0;4;4;0;0;0|];; |
||
- : bool = true</ |
- : bool = true</syntaxhighlight> |
||
) |
) |
||
But we could write it explicitly this way: |
But we could write it explicitly this way: |
||
< |
<syntaxhighlight lang="ocaml">let rec ordered_lists = function |
||
| x1::tl1, x2::tl2 -> |
| x1::tl1, x2::tl2 -> |
||
(match compare x1 x2 with |
(match compare x1 x2 with |
||
Line 1,573: | Line 1,802: | ||
| _ -> true) |
| _ -> true) |
||
| [], _ -> true |
| [], _ -> true |
||
| _ -> false</ |
| _ -> false</syntaxhighlight> |
||
Here is a small script to test this function: |
Here is a small script to test this function: |
||
< |
<syntaxhighlight lang="ocaml">(* copy-paste the code of ordered_lists here *) |
||
let make_num_list p n = |
let make_num_list p n = |
||
Line 1,596: | Line 1,825: | ||
print_num_list lst1; |
print_num_list lst1; |
||
print_num_list lst2; |
print_num_list lst2; |
||
Printf.printf "ordered: %B\n" (ordered_lists (lst1, lst2))</ |
Printf.printf "ordered: %B\n" (ordered_lists (lst1, lst2))</syntaxhighlight> |
||
Sample execution: |
Sample execution: |
||
Line 1,606: | Line 1,835: | ||
Also notice that the function <code>ordered_lists</code> will work with anything the function <code>Pervasives.compare</code> is able to compare (most OCaml types and structures made from the base types). In the prototype of this function below <code>'a list</code> means a list of anything: |
Also notice that the function <code>ordered_lists</code> will work with anything the function <code>Pervasives.compare</code> is able to compare (most OCaml types and structures made from the base types). In the prototype of this function below <code>'a list</code> means a list of anything: |
||
< |
<syntaxhighlight lang="ocaml">val ordered_lists : 'a list * 'a list -> bool</syntaxhighlight> |
||
=={{header|Oforth}}== |
=={{header|Oforth}}== |
||
Line 1,620: | Line 1,849: | ||
=={{header|Ol}}== |
=={{header|Ol}}== |
||
This sample very similar to Scheme, but implements proper tail recursion. So can test unlimited length lists. |
This sample very similar to Scheme, but implements proper tail recursion. So can test unlimited length lists. |
||
< |
<syntaxhighlight lang="scheme"> |
||
(define (lexorder a b) |
(define (lexorder a b) |
||
(cond |
(cond |
||
Line 1,635: | Line 1,864: | ||
(print (lexorder '(1 2 3) '(1 2 3))) ; => false |
(print (lexorder '(1 2 3) '(1 2 3))) ; => false |
||
(print (lexorder '(1 2 3) '(1 2 8))) ; => true |
(print (lexorder '(1 2 3) '(1 2 8))) ; => true |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
<lang |
<syntaxhighlight lang="parigp">lex(u,v)<1</syntaxhighlight> |
||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
< |
<syntaxhighlight lang="perl">use strict; |
||
use warnings; |
use warnings; |
||
Line 1,678: | Line 1,907: | ||
my $before = orderlists([@$first], [@$second]) ? 'true' : 'false'; |
my $before = orderlists([@$first], [@$second]) ? 'true' : 'false'; |
||
print "(@$first) comes before (@$second) : $before\n"; |
print "(@$first) comes before (@$second) : $before\n"; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,690: | Line 1,919: | ||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
Handled natively, eg ("?" is the shorthand print operator) |
Handled natively, eg ("?" is the shorthand print operator) |
||
<!--<syntaxhighlight lang="phix">(phixonline)--> |
|||
<lang Phix>?{1,2,3}<{1,2,3,4} -- 1 |
|||
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
|||
?{1,2,3,4}<{1,2,3} -- 0 |
|||
<span style="color: #0000FF;">?{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">}<{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">}</span> <span style="color: #000080;font-style:italic;">-- 1 (true under p2js)</span> |
|||
?{1,2,4}<{1,2,3} -- 0 |
|||
<span style="color: #0000FF;">?{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">}<{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">}</span> <span style="color: #000080;font-style:italic;">-- 0 (false "")</span> |
|||
?{1,2,3}<{1,2,3} -- 0 |
|||
<span style="color: #0000FF;">?{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">}<{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">}</span> <span style="color: #000080;font-style:italic;">-- 0 (false "")</span> |
|||
?{1,2,3}<{1,2,4} -- 1</lang> |
|||
<span style="color: #0000FF;">?{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">}<{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">}</span> <span style="color: #000080;font-style:italic;">-- 0 (false "")</span> |
|||
<span style="color: #0000FF;">?{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">}<{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">}</span> <span style="color: #000080;font-style:italic;">-- 1 (true "")</span> |
|||
<!--</syntaxhighlight>--> |
|||
Elements can be any mix of integers, floating point numbers, strings, or nested subsequences, with atoms ordered before sequences.<br> |
Elements can be any mix of integers, floating point numbers, strings, or nested subsequences, with atoms ordered before sequences.<br> |
||
If you want -1/0/+1 (instead of the true(1)/false(0) shown above), use the builtin compare() function. |
If you want -1/0/+1 (instead of the true(1)/false(0) shown above), use the builtin compare() function, and that will match under p2js. |
||
=={{header|Phixmonti}}== |
=={{header|Phixmonti}}== |
||
{{trans|Phix}} |
{{trans|Phix}} |
||
< |
<syntaxhighlight lang="phixmonti">include Utilitys.pmt |
||
def ? print nl enddef |
def ? print nl enddef |
||
Line 1,708: | Line 1,940: | ||
( 1 2 4 ) ( 1 2 3 ) < ? |
( 1 2 4 ) ( 1 2 3 ) < ? |
||
( 1 2 3 ) ( 1 2 3 ) < ? |
( 1 2 3 ) ( 1 2 3 ) < ? |
||
( 1 2 3 ) ( 1 2 4 ) < ?</ |
( 1 2 3 ) ( 1 2 4 ) < ?</syntaxhighlight> |
||
=={{header|Picat}}== |
|||
Picat has a built-in general comparison operator <code>@<</code>, which compares terms in lexicographic order (numeric lists as well as atoms, strings, variables, and structures). |
|||
<syntaxhighlight lang="picat">go => |
|||
Tests = [ |
|||
[[1,2,3], [1,2,3]], |
|||
[[1,2,3], [1,2,3,4]], |
|||
[[1,2,2], [1,2,3]], |
|||
[[1,2,4], [1,2,3]], |
|||
[1..10 , 1..8], |
|||
[[] , []], |
|||
[[] , [1]], |
|||
[[1] , [] ], |
|||
[[-1,2,3,6,5],[-1,2,3,5,6]], |
|||
[[-1,2,3,-5,6],[-1,2,3,-6,5]] |
|||
], |
|||
foreach([L1,L2] in Tests) |
|||
printf("%w @< %w: %w\n",L1,L2,cond(L1 @< L2,true,false)) |
|||
end, |
|||
nl.</syntaxhighlight> |
|||
In the Picat shell, the result is yes/no rather than true/false: |
|||
<pre> |
|||
Picat> [1,2,3] @< [1,2,3] |
|||
no |
|||
Picat> [1,2,3] @< [1,2,3,4] |
|||
yes</pre> |
|||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
The built-in comparison functions already do this (not only for lists of numbers, but for any arbitrary data type). |
The built-in comparison functions already do this (not only for lists of numbers, but for any arbitrary data type). |
||
< |
<syntaxhighlight lang="picolisp">: (> (1 2 0 4 4 0 0 0) (1 2 1 3 2)) |
||
-> NIL</ |
-> NIL</syntaxhighlight> |
||
=={{header|Pike}}== |
=={{header|Pike}}== |
||
< |
<syntaxhighlight lang="pike">int(0..1) order_array(array a, array b) |
||
{ |
{ |
||
if (!sizeof(a)) return true; |
if (!sizeof(a)) return true; |
||
Line 1,723: | Line 1,985: | ||
return order_array(a[1..], b[1..]); |
return order_array(a[1..], b[1..]); |
||
return a[0] < b[0]; |
return a[0] < b[0]; |
||
}</ |
}</syntaxhighlight> |
||
Pikes <code>Array.sort_array()</code> function can sort an array of arrays using the <code><</code> operator, but it will sort longer arrays before shorter ones. Therefore the above function is still needed if the intent is to use the comparison for a sort operation. |
Pikes <code>Array.sort_array()</code> function can sort an array of arrays using the <code><</code> operator, but it will sort longer arrays before shorter ones. Therefore the above function is still needed if the intent is to use the comparison for a sort operation. |
||
If the numbers are in 32bit signed integer range, the following works too: |
If the numbers are in 32bit signed integer range, the following works too: |
||
< |
<syntaxhighlight lang="pike">(string)a < (string)b;</syntaxhighlight> |
||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
< |
<syntaxhighlight lang="pl/i">lists: procedure options (main); /* 8 June 2014 */ |
||
declare a(10) fixed initial (1, 2, 3, 4, 5, 8, 9, 10, 16, 17), |
declare a(10) fixed initial (1, 2, 3, 4, 5, 8, 9, 10, 16, 17), |
||
Line 1,751: | Line 2,013: | ||
end compare; |
end compare; |
||
end lists;</ |
end lists;</syntaxhighlight> |
||
Results: |
Results: |
||
<pre> |
<pre> |
||
Line 1,760: | Line 2,022: | ||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
<syntaxhighlight lang="powershell"> |
|||
<lang PowerShell> |
|||
function order($as,$bs) { |
function order($as,$bs) { |
||
if($as -and $bs) { |
if($as -and $bs) { |
||
Line 1,770: | Line 2,032: | ||
} |
} |
||
"$(order @(1,2,1,3,2) @(1,2,0,4,4,0,0,0))" |
"$(order @(1,2,1,3,2) @(1,2,0,4,4,0,0,0))" |
||
</syntaxhighlight> |
|||
</lang> |
|||
<b>Output:</b> |
<b>Output:</b> |
||
<pre> |
<pre> |
||
Line 1,777: | Line 2,039: | ||
===Non-Recursive Version=== |
===Non-Recursive Version=== |
||
<syntaxhighlight lang="powershell"> |
|||
<lang PowerShell> |
|||
function Test-Order ([int[]]$ReferenceArray, [int[]]$DifferenceArray) |
function Test-Order ([int[]]$ReferenceArray, [int[]]$DifferenceArray) |
||
{ |
{ |
||
Line 1,794: | Line 2,056: | ||
return ($ReferenceArray.Count -lt $DifferenceArray.Count) -or (Compare-Object $ReferenceArray $DifferenceArray) -eq $null |
return ($ReferenceArray.Count -lt $DifferenceArray.Count) -or (Compare-Object $ReferenceArray $DifferenceArray) -eq $null |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
<syntaxhighlight lang="powershell"> |
|||
<lang PowerShell> |
|||
Test-Order -ReferenceArray 1, 2, 1, 3, 2 -DifferenceArray 1, 2, 0, 4, 4, 0, 0, 0 |
Test-Order -ReferenceArray 1, 2, 1, 3, 2 -DifferenceArray 1, 2, 0, 4, 4, 0, 0, 0 |
||
Test-Order -ReferenceArray 1, 2, 1, 3, 2 -DifferenceArray 1, 2, 2, 4, 4, 0, 0, 0 |
Test-Order -ReferenceArray 1, 2, 1, 3, 2 -DifferenceArray 1, 2, 2, 4, 4, 0, 0, 0 |
||
Line 1,801: | Line 2,063: | ||
Test-Order -ReferenceArray 1, 2 -DifferenceArray 1, 2, 3 |
Test-Order -ReferenceArray 1, 2 -DifferenceArray 1, 2, 3 |
||
Test-Order -ReferenceArray 1, 2 -DifferenceArray 1, 2 |
Test-Order -ReferenceArray 1, 2 -DifferenceArray 1, 2 |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
<pre> |
<pre> |
||
Line 1,812: | Line 2,074: | ||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
< |
<syntaxhighlight lang="purebasic">DataSection |
||
Array_1: |
Array_1: |
||
Data.i 5 ;element count |
Data.i 5 ;element count |
||
Line 1,882: | Line 2,144: | ||
CloseConsole() |
CloseConsole() |
||
EndIf |
EndIf |
||
</ |
</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>False |
<pre>False |
||
Line 1,892: | Line 2,154: | ||
=={{header|Python}}== |
=={{header|Python}}== |
||
The built-in comparison operators already do this: |
The built-in comparison operators already do this: |
||
< |
<syntaxhighlight lang="python">>>> [1,2,1,3,2] < [1,2,0,4,4,0,0,0] |
||
False</ |
False</syntaxhighlight> |
||
=={{header|Quackery}}== |
=={{header|Quackery}}== |
||
< |
<syntaxhighlight lang="quackery"> [ [ over [] = iff false done |
||
dup [] = iff true done |
dup [] = iff true done |
||
behead rot behead rot |
behead rot behead rot |
||
Line 1,907: | Line 2,169: | ||
' [ [ ] [ 1 ] [ 1 1 1 ] [ 1 2 ] [ 1 2 1 ] [ 2 ] [ 2 1 ] [ 2 1 1 ] ] |
' [ [ ] [ 1 ] [ 1 1 1 ] [ 1 2 ] [ 1 2 1 ] [ 2 ] [ 2 1 ] [ 2 1 1 ] ] |
||
shuffle sortwith []< echo</ |
shuffle sortwith []< echo</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,915: | Line 2,177: | ||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
< |
<syntaxhighlight lang="racket">#lang racket |
||
(define (lex<? a b) |
(define (lex<? a b) |
||
Line 1,924: | Line 2,186: | ||
(lex<? '(1 2 3 4 5) '(1 2 3 4 4)) ; -> #f |
(lex<? '(1 2 3 4 5) '(1 2 3 4 4)) ; -> #f |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
(formerly Perl 6) |
(formerly Perl 6) |
||
There is already a built-in comparison operator. |
There is already a built-in comparison operator. |
||
<lang |
<syntaxhighlight lang="raku" line>my @a = <1 2 4>; |
||
my @b = <1 2 4>; |
my @b = <1 2 4>; |
||
say @a," before ",@b," = ", @a before @b; |
say @a," before ",@b," = ", @a before @b; |
||
Line 1,945: | Line 2,207: | ||
my @b = flat @a.map: { Bool.pick ?? $_ !! (^100).roll((0..2).pick) } |
my @b = flat @a.map: { Bool.pick ?? $_ !! (^100).roll((0..2).pick) } |
||
say @a," before ",@b," = ", @a before @b; |
say @a," before ",@b," = ", @a before @b; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>1 2 4 before 1 2 4 = False |
<pre>1 2 4 before 1 2 4 = False |
||
Line 1,963: | Line 2,225: | ||
=={{header|Rascal}}== |
=={{header|Rascal}}== |
||
The built-in comparison operator already does this: |
The built-in comparison operator already does this: |
||
< |
<syntaxhighlight lang="rascal">rascal>[2,1,3] < [5,2,1,3] |
||
bool: true</ |
bool: true</syntaxhighlight> |
||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
Line 1,970: | Line 2,232: | ||
This example will also work with non-numeric strings. |
This example will also work with non-numeric strings. |
||
< |
<syntaxhighlight lang="rexx">/*REXX program determines if a list < previous list, and returns true or false. */ |
||
@.=; @.1 = 1 2 1 5 2 |
@.=; @.1 = 1 2 1 5 2 |
||
@.2 = 1 2 1 5 2 2 |
@.2 = 1 2 1 5 2 2 |
||
Line 1,993: | Line 2,255: | ||
end /*k*/ |
end /*k*/ |
||
if wx<wy then return 'true' /*handle case of equal (so far). */ |
if wx<wy then return 'true' /*handle case of equal (so far). */ |
||
return 'false' /* " " " " " " */</ |
return 'false' /* " " " " " " */</syntaxhighlight> |
||
{{out|output|:}} |
{{out|output|:}} |
||
<pre> |
<pre> |
||
Line 2,004: | Line 2,266: | ||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang="ring"> |
||
list1 = "1, 2, 1, 5, 2" |
list1 = "1, 2, 1, 5, 2" |
||
list2 = "5, 2, 1, 5, 2, 2" |
list2 = "5, 2, 1, 5, 2, 2" |
||
Line 2,024: | Line 2,286: | ||
func order alist, blist |
func order alist, blist |
||
return strcmp(alist, blist) |
return strcmp(alist, blist) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 2,030: | Line 2,292: | ||
list2>list3 |
list2>list3 |
||
list3=list4 |
list3=list4 |
||
</pre> |
|||
=={{header|RPL}}== |
|||
{{works with|HP|28}} |
|||
{| class="wikitable" ≪ |
|||
! RPL code |
|||
! Comment |
|||
|- |
|||
| |
|||
≪ → a b |
|||
≪ a SIZE b SIZE MIN LAST < |
|||
1 ROT '''FOR''' j |
|||
'''IF''' b j GET a j GET - '''THEN''' |
|||
LAST 0 > SWAP DROP |
|||
a SIZE 'j' STO |
|||
'''END''' |
|||
'''NEXT''' |
|||
≫ ≫ ‘<span style="color:blue">GR8R?</span>’ STO |
|||
| |
|||
<span style="color:blue">GR8R?</span> ''( [reals] [reals] → boolean ) '' |
|||
m = min(size(a),size(b)) ; res = (size(a)<size(b)) |
|||
loop for j=1 to m |
|||
if b[j]-a[j] ≠ 0 |
|||
res = (b[j]-a[j]>0) |
|||
break |
|||
end if |
|||
end loop, return res |
|||
. |
|||
|} |
|||
[1 2 1 5 2] [1 2 1 5 2 2] <span style="color:blue">GR8R?</span> |
|||
[1 2 1 5 2 2] [1 2 1 5 2] <span style="color:blue">GR8R?</span> |
|||
[1 2 1 5 2 2] [1 2 3 4 5] <span style="color:blue">GR8R?</span> |
|||
[1 2 3 4 5] [1 2 1 5 2 2] <span style="color:blue">GR8R?</span> |
|||
[1 2 3 4 5] [1 2 3 4 5] <span style="color:blue">GR8R?</span> |
|||
{{out}} |
|||
<pre> |
|||
5: 1 |
|||
4: 0 |
|||
3: 1 |
|||
2: 0 |
|||
1: 0 |
|||
</pre> |
</pre> |
||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
The built-in <code><=></code> operator already does this: |
The built-in <code><=></code> operator already does this: |
||
< |
<syntaxhighlight lang="ruby">>> ([1,2,1,3,2] <=> [1,2,0,4,4,0,0,0]) < 0 |
||
=> false</ |
=> false</syntaxhighlight> |
||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
<code>Vec<T></code> implements <code>Ord</code> when <code>T</code> does, so we can just compare them with <code><</code>. (Same with arrays and slices). |
<code>Vec<T></code> implements <code>Ord</code> when <code>T</code> does, so we can just compare them with <code><</code>. (Same with arrays and slices). |
||
< |
<syntaxhighlight lang="rust">vec![1, 2, 1, 3, 2] < vec![1, 2, 0, 4, 4, 0, 0, 0]</syntaxhighlight> |
||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
< |
<syntaxhighlight lang="scala">def lessThan1(a: List[Int], b: List[Int]): Boolean = |
||
if (b.isEmpty) false |
if (b.isEmpty) false |
||
else if (a.isEmpty) true |
else if (a.isEmpty) true |
||
else if (a.head != b.head) a.head < b.head |
else if (a.head != b.head) a.head < b.head |
||
else lessThan1(a.tail, b.tail)</ |
else lessThan1(a.tail, b.tail)</syntaxhighlight><syntaxhighlight lang="scala">def lessThan2(a: List[Int], b: List[Int]): Boolean = (a, b) match { |
||
case (_, Nil) => false |
case (_, Nil) => false |
||
case (Nil, _) => true |
case (Nil, _) => true |
||
case (a :: _, b :: _) if a != b => a < b |
case (a :: _, b :: _) if a != b => a < b |
||
case _ => lessThan2(a.tail, b.tail) |
case _ => lessThan2(a.tail, b.tail) |
||
}</ |
}</syntaxhighlight><syntaxhighlight lang="scala">def lessThan3(a: List[Int], b: List[Int]): Boolean = |
||
a.zipAll(b, Integer.MIN_VALUE, Integer.MIN_VALUE) |
a.zipAll(b, Integer.MIN_VALUE, Integer.MIN_VALUE) |
||
.find{case (a, b) => a != b} |
.find{case (a, b) => a != b} |
||
.map{case (a, b) => a < b} |
.map{case (a, b) => a < b} |
||
.getOrElse(false)</ |
.getOrElse(false)</syntaxhighlight><syntaxhighlight lang="scala">val tests = List( |
||
(List(1, 2, 3), List(1, 2, 3)) -> false, |
(List(1, 2, 3), List(1, 2, 3)) -> false, |
||
(List(3, 2, 1), List(3, 2, 1)) -> false, |
(List(3, 2, 1), List(3, 2, 1)) -> false, |
||
Line 2,068: | Line 2,371: | ||
assert(lessThan2(a, b) == c, test) |
assert(lessThan2(a, b) == c, test) |
||
assert(lessThan3(a, b) == c, test) |
assert(lessThan3(a, b) == c, test) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
< |
<syntaxhighlight lang="scheme">(define (lex<? a b) |
||
(cond ((null? b) #f) |
(cond ((null? b) #f) |
||
((null? a) #t) |
((null? a) #t) |
||
((= (car a) (car b)) (lex<? (cdr a) (cdr b))) |
((= (car a) (car b)) (lex<? (cdr a) (cdr b))) |
||
(else (< (car a) (car b)))))</ |
(else (< (car a) (car b)))))</syntaxhighlight> |
||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
The operator corresponding to the ordering described in this example is less than. |
The operator corresponding to the ordering described in this example is less than. |
||
< |
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i"; |
||
const proc: main is func |
const proc: main is func |
||
Line 2,092: | Line 2,395: | ||
writeln([] (1) < 0 times 0); # Any nonempty list is not less than the empty list --> FALSE |
writeln([] (1) < 0 times 0); # Any nonempty list is not less than the empty list --> FALSE |
||
writeln(0 times 0 < 0 times 0); # The empty list is not less than the empty list --> FALSE |
writeln(0 times 0 < 0 times 0); # The empty list is not less than the empty list --> FALSE |
||
end func;</ |
end func;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,108: | Line 2,411: | ||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
Built-in, via the comparison operator (`<=>`): |
Built-in, via the comparison operator (`<=>`): |
||
< |
<syntaxhighlight lang="ruby">func ordered(a, b) { |
||
(a <=> b) < 0 |
(a <=> b) < 0 |
||
} |
} |
||
Line 2,121: | Line 2,424: | ||
var before = ordered(a, b) |
var before = ordered(a, b) |
||
say "#{a} comes before #{b} : #{before}" |
say "#{a} comes before #{b} : #{before}" |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,130: | Line 2,433: | ||
=={{header|Standard ML}}== |
=={{header|Standard ML}}== |
||
< |
<syntaxhighlight lang="sml">- List.collate Int.compare ([1,2,1,3,2], [1,2,0,4,4,0,0,0]) = LESS; |
||
val it = false : bool</ |
val it = false : bool</syntaxhighlight> |
||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
< |
<syntaxhighlight lang="swift">let a = [1,2,1,3,2] |
||
let b = [1,2,0,4,4,0,0,0] |
let b = [1,2,0,4,4,0,0,0] |
||
println(lexicographicalCompare(a, b)) // this is "less than"</ |
println(lexicographicalCompare(a, b)) // this is "less than"</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,143: | Line 2,446: | ||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
< |
<syntaxhighlight lang="tcl">proc numlist< {A B} { |
||
foreach a $A b $B { |
foreach a $A b $B { |
||
if {$a<$b} { |
if {$a<$b} { |
||
Line 2,152: | Line 2,455: | ||
} |
} |
||
return 0 |
return 0 |
||
}</ |
}</syntaxhighlight> |
||
=={{header|TUSCRIPT}}== |
=={{header|TUSCRIPT}}== |
||
< |
<syntaxhighlight lang="tuscript"> |
||
$$ MODE TUSCRIPT |
$$ MODE TUSCRIPT |
||
MODE DATA |
MODE DATA |
||
Line 2,180: | Line 2,483: | ||
list1=VALUE(list2) |
list1=VALUE(list2) |
||
ENDLOOP |
ENDLOOP |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre style='height:30ex;overflow:scroll'> |
<pre style='height:30ex;overflow:scroll'> |
||
Line 2,196: | Line 2,499: | ||
=={{header|VBA}}== |
=={{header|VBA}}== |
||
< |
<syntaxhighlight lang="vb">Private Function order(list1 As Variant, list2 As Variant) As Boolean |
||
i = 1 |
i = 1 |
||
Do While list1(i) <= list2(i) |
Do While list1(i) <= list2(i) |
||
Line 2,215: | Line 2,518: | ||
Debug.Print order([{1, 2, 3, 4}], [{1,2,3}]) |
Debug.Print order([{1, 2, 3, 4}], [{1,2,3}]) |
||
Debug.Print order([{1, 2, 3}], [{1,2,3,4}]) |
Debug.Print order([{1, 2, 3}], [{1,2,3,4}]) |
||
End Sub</ |
End Sub</syntaxhighlight>{{out}} |
||
<pre>Onwaar |
<pre>Onwaar |
||
Onwaar |
Onwaar |
||
Line 2,221: | Line 2,524: | ||
=={{header|VBScript}}== |
=={{header|VBScript}}== |
||
<syntaxhighlight lang="vb"> |
|||
<lang vb> |
|||
Function order_list(arr1,arr2) |
Function order_list(arr1,arr2) |
||
order_list = "FAIL" |
order_list = "FAIL" |
||
Line 2,255: | Line 2,558: | ||
WScript.StdOut.WriteLine order_list(Array(0,0),Array(1)) |
WScript.StdOut.WriteLine order_list(Array(0,0),Array(1)) |
||
WScript.StdOut.WriteLine order_list(Array(1,2,1,3,2),Array(1,2,0,4,4,0,0,0)) |
WScript.StdOut.WriteLine order_list(Array(1,2,1,3,2),Array(1,2,0,4,4,0,0,0)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
Line 2,273: | Line 2,576: | ||
=={{header|Wart}}== |
=={{header|Wart}}== |
||
We'll simply overload <code><</code> for lists. |
We'll simply overload <code><</code> for lists. |
||
< |
<syntaxhighlight lang="python">def (a < b) :case (or list?.a list?.b) |
||
if not.b |
if not.b |
||
nil |
nil |
||
Line 2,281: | Line 2,584: | ||
(cdr.a < cdr.b) |
(cdr.a < cdr.b) |
||
:else |
:else |
||
(car.a < car.b)</ |
(car.a < car.b)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,295: | Line 2,598: | ||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
< |
<syntaxhighlight lang="wren">var orderLists = Fn.new { |l1, l2| |
||
var len = (l1.count <= l2.count) ? l1.count : l2.count |
var len = (l1.count <= l2.count) ? l1.count : l2.count |
||
for (i in 0...len) { |
for (i in 0...len) { |
||
Line 2,320: | Line 2,623: | ||
var res = orderLists.call(lists[i], lists[i+1]) |
var res = orderLists.call(lists[i], lists[i+1]) |
||
System.print("list[%(i)] < list[%(i+1)] -> %(res)") |
System.print("list[%(i)] < list[%(i+1)] -> %(res)") |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,342: | Line 2,645: | ||
</pre> |
</pre> |
||
=={{header|XPL0}}== |
|||
{{trans|ALGOL W}} |
|||
<syntaxhighlight lang "XPL0"> \Compare lists (rows) of integers. |
|||
\Returns TRUE if there is an element in A that is < the corresponding |
|||
\ element in B and all previous elements are equal, FALSE otherwise. |
|||
\The bounds of A and B should ALB :: AUB and BLB :: BUB. |
|||
function ILT ( A, ALB, AUB, B, BLB, BUB ); |
|||
integer A, ALB, AUB, B, BLB, BUB; |
|||
integer APos, BPos, Equal; |
|||
begin |
|||
APos := ALB; |
|||
BPos := BLB; |
|||
Equal := true; |
|||
while APos <= AUB and BPos <= BUB and Equal do begin |
|||
Equal := A( APos ) = B( BPos ); |
|||
if Equal then begin |
|||
APos := APos + 1; |
|||
BPos := BPos + 1 |
|||
end \if_Equal |
|||
end; \while_more_elements_and_Equal |
|||
if not Equal |
|||
then \there is an element in A and B that is not Equal |
|||
return A( APos ) < B( BPos ) |
|||
else \all elements are Equal or one list is shorter |
|||
\A is < B if A has fewer elements |
|||
return APos > AUB and BPos <= BUB |
|||
end; \ILT |
|||
\Tests A < B has the expected result |
|||
procedure Test ( AName, A, ALB, AUB, BName, B, BLB, BUB, Expected ); |
|||
integer AName, A, ALB, AUB, BName, B, BLB, BUB, Expected; |
|||
integer IsLt; |
|||
begin |
|||
IsLt := ILT( A, ALB, AUB, B, BLB, BUB ); |
|||
Text(0, AName); |
|||
Text(0, if IsLt then " < " else " >= "); |
|||
Text(0, BName); |
|||
Text(0, if IsLt = Expected then " " else ", NOT as expected"); |
|||
CrLf(0); |
|||
end; \test |
|||
integer List1, List2, List3, List4, List5, List6, List7, List8; |
|||
begin |
|||
\test cases as in the BBC basic sample |
|||
List1 := [0, 1, 2, 1, 5, 2]; |
|||
List2 := [0, 1, 2, 1, 5, 2, 2]; |
|||
List3 := [0, 1, 2, 3, 4, 5]; |
|||
List4 := [0, 1, 2, 3, 4, 5]; |
|||
Test( "List1", List1, 1, 5, "List2", List2, 1, 6, true ); |
|||
Test( "List2", List2, 1, 6, "List3", List3, 1, 5, true ); |
|||
Test( "List3", List3, 1, 5, "List4", List4, 1, 5, false ); |
|||
\additional test cases |
|||
List5 := [0, 9, 0, 2, 1, 0]; |
|||
List6 := [0, 4, 0, 7, 7]; |
|||
List7 := [0, 4, 0, 7]; |
|||
List8 := [0, 0]; |
|||
Test( "List5", List5, 1, 5, "List6", List6, 1, 4, false ); |
|||
Test( "List6", List6, 1, 4, "List7", List7, 1, 3, false ); |
|||
Test( "List7", List7, 1, 3, "List8", List8, 1, 0, false ); |
|||
Test( "List8", List8, 1, 0, "List7", List7, 1, 3, true ) |
|||
end</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
List1 < List2 |
|||
List2 < List3 |
|||
List3 >= List4 |
|||
List5 >= List6 |
|||
List6 >= List7 |
|||
List7 >= List8 |
|||
List8 < List7 |
|||
</pre> |
|||
=={{header|Yabasic}}== |
=={{header|Yabasic}}== |
||
{{trans|FreeBASIC}} |
{{trans|FreeBASIC}} |
||
< |
<syntaxhighlight lang="yabasic"> |
||
read num : dim list1(4) |
read num : dim list1(4) |
||
read num : dim list2(5) |
read num : dim list2(5) |
||
Line 2,372: | Line 2,746: | ||
data 1, 2, 3, 4, 5 |
data 1, 2, 3, 4, 5 |
||
data 1, 2, 3, 4, 5 |
data 1, 2, 3, 4, 5 |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Igual que la entrada de BBC BASIC. |
Igual que la entrada de BBC BASIC. |
||
</pre> |
</pre> |
||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
< |
<syntaxhighlight lang="zkl">fcn listLT(a,b){ |
||
a.walker().zip(b).filter1(fcn([(a,b)]){ a<b }) : // lazy |
a.walker().zip(b).filter1(fcn([(a,b)]){ a<b }) : // lazy |
||
if(_) return(True);; |
if(_) return(True);; |
||
a.len()<b.len() |
a.len()<b.len() |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
Latest revision as of 10:43, 13 August 2024
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
You are encouraged to solve this task according to the task description, using any language you may know.
Tasks in this category have to do with sorting collections of objects.
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
Heap sort | Merge sort | Patience sort | Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Write a function that orders two lists or arrays filled with numbers.
The function should accept two lists as arguments and return true
if the first list should be ordered before the second, and false
otherwise.
The order is determined by lexicographic order: Comparing the first element of each list.
If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements.
If the first list runs out of elements the result is true
.
If the second list or both run out of elements the result is false
.
Note: further clarification of lexicographical ordering is expounded on the talk page here and here.
11l
[1,2,1,3,2] < [1,2,0,4,4,0,0,0]
AArch64 Assembly
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program orderlist64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessResult1: .asciz "List1 < List2 \n" // message result
szMessResult2: .asciz "List1 => List2 \n" // message result
szCarriageReturn: .asciz "\n"
qTabList1: .quad 1,2,3,4,5
.equ NBELEMENTS1, (. - qTabList1) /8
qTabList2: .quad 1,2,1,5,2,2
.equ NBELEMENTS2, (. - qTabList2) /8
qTabList3: .quad 1,2,3,4,5
.equ NBELEMENTS3, (. - qTabList3) /8
qTabList4: .quad 1,2,3,4,5,6
.equ NBELEMENTS4, (. - qTabList4) /8
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdriTabList1
mov x1,NBELEMENTS1
ldr x2,qAdriTabList2
mov x3,NBELEMENTS2
bl listeOrder
cmp x0,0 // false ?
beq 1f // yes
ldr x0,qAdrszMessResult1 // list 1 < list 2
bl affichageMess // display message
b 2f
1:
ldr x0,qAdrszMessResult2
bl affichageMess // display message
2:
ldr x0,qAdriTabList1
mov x1,NBELEMENTS1
ldr x2,qAdriTabList3
mov x3,NBELEMENTS3
bl listeOrder
cmp x0,0 // false ?
beq 3f // yes
ldr x0,qAdrszMessResult1 // list 1 < list 2
bl affichageMess // display message
b 4f
3:
ldr x0,qAdrszMessResult2
bl affichageMess // display message
4:
ldr x0,qAdriTabList1
mov x1,NBELEMENTS1
ldr x2,qAdriTabList4
mov x3,NBELEMENTS4
bl listeOrder
cmp x0,0 // false ?
beq 5f // yes
ldr x0,qAdrszMessResult1 // list 1 < list 2
bl affichageMess // display message
b 6f
5:
ldr x0,qAdrszMessResult2
bl affichageMess // display message
6:
100: // standard end of the program
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform the system call
qAdriTabList1: .quad qTabList1
qAdriTabList2: .quad qTabList2
qAdriTabList3: .quad qTabList3
qAdriTabList4: .quad qTabList4
qAdrszMessResult1: .quad szMessResult1
qAdrszMessResult2: .quad szMessResult2
qAdrszCarriageReturn: .quad szCarriageReturn
/******************************************************************/
/* liste order */
/******************************************************************/
/* x0 contains the address of list 1 */
/* x1 contains list 1 size */
/* x2 contains the address of list 2 */
/* x3 contains list 2 size */
/* x0 returns 1 if list1 < list2 */
/* x0 returns 0 else */
listeOrder:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
cbz x1,99f // list 1 size = zero ?
cbz x3,98f // list 2 size = zero ?
mov x4,#0 // index list 1
mov x5,#0 // index list 2
1:
ldr x6,[x0,x4,lsl #3] // load list 1 element
ldr x8,[x2,x5,lsl #3] // load list 2 element
cmp x6,x8 // compar
bgt 4f
beq 2f // list 1 = list 2
add x4,x4,1 // increment index 1
cmp x4,x1 // end list ?
bge 5f
b 1b // else loop
2:
add x4,x4,1 // increment index 1
cmp x4,x1 // end list ?
bge 3f // yes -> verif size
add x5,x5,1 // else increment index 2
cmp x5,x3 // end list 2 ?
bge 4f
b 1b // else loop
3:
cmp x1,x3 // compar size
bge 4f // list 2 < list 1
blt 5f // list 1 < list 2
b 100f
4:
mov x0,#0 // list 1 > list 2
b 100f
5:
mov x0,#1 // list 1 < list 2
b 100f
98: // error
mov x0,-2
b 100f
99: // error
mov x0,-1
100:
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
ACL2
The built-in lexorder does this.
ACL2 !>(lexorder '(1 2 3) '(1 2 3 4)) T ACL2 !>(lexorder '(1 2 4) '(1 2 3)) NIL
Action!
INT FUNC Compare(INT ARRAY x INT xLen INT ARRAY y INT yLen)
INT i,len
len=xLen
IF len>yLen THEN
len=yLen
FI
FOR i=0 TO len-1
DO
IF x(i)>y(i) THEN
RETURN (1)
ELSEIF x(i)<y(i) THEN
RETURN (-1)
FI
OD
IF xLen>yLen THEN
RETURN (1)
ELSEIF xLen<yLen THEN
RETURN (-1)
FI
RETURN (0)
BYTE FUNC Less(INT ARRAY x INT xLen INT ARRAY y INT yLen)
IF Compare(x,xLen,y,yLen)<0 THEN
RETURN (1)
FI
RETURN (0)
PROC PrintArray(INT ARRAY x INT len)
INT i
Put('[)
FOR i=0 TO len-1
DO
PrintI(x(i))
IF i<len-1 THEN
Put(' )
FI
OD
Put('])
RETURN
PROC Test(INT ARRAY x INT xLen INT ARRAY y INT yLen)
PrintArray(x,xLen)
IF Less(x,xLen,y,yLen) THEN
Print(" < ")
ELSE
Print(" >= ")
FI
PrintArray(y,yLen) PutE()
RETURN
PROC Main()
INT ARRAY a=[1 2 1 5 2]
INT ARRAY b=[1 2 1 5 2 2]
INT ARRAY c=[1 2 3 4 5]
INT ARRAY d=[1 2 3 4 5]
Test(a,5,b,6)
Test(b,6,a,5)
Test(b,6,c,5)
Test(c,5,b,6)
Test(c,5,d,5)
RETURN
- Output:
Screenshot from Atari 8-bit computer
[1 2 1 5 2] < [1 2 1 5 2 2] [1 2 1 5 2 2] >= [1 2 1 5 2] [1 2 1 5 2 2] < [1 2 3 4 5] [1 2 3 4 5] >= [1 2 1 5 2 2] [1 2 3 4 5] >= [1 2 3 4 5]
Ada
This is already implemented in the built-in comparison operators for arrays of types that have a direct ordering. This also includes arrays of user defined types, using the type definition order from smallest to largest. Demonstrated in the program below:
with Ada.Text_IO; use Ada.Text_IO;
procedure Order is
type IntArray is array (Positive range <>) of Integer;
List1 : IntArray := (1, 2, 3, 4, 5);
List2 : IntArray := (1, 2, 1, 5, 2, 2);
List3 : IntArray := (1, 2, 1, 5, 2);
List4 : IntArray := (1, 2, 1, 5, 2);
type Animal is (Rat, Cat, Elephant);
type AnimalArray is array (Positive range <>) of Animal;
List5 : AnimalArray := (Cat, Elephant, Rat, Cat);
List6 : AnimalArray := (Cat, Elephant, Rat);
List7 : AnimalArray := (Cat, Cat, Elephant);
begin
Put_Line (Boolean'Image (List1 > List2)); -- True
Put_Line (Boolean'Image (List2 > List3)); -- True
Put_Line (Boolean'Image (List3 > List4)); -- False, equal
Put_Line (Boolean'Image (List5 > List6)); -- True
Put_Line (Boolean'Image (List6 > List7)); -- True
end Order;
- Output:
TRUE TRUE FALSE TRUE TRUE
ALGOL 68
BEGIN # compare lists (rows) of integers #
# returns TRUE if there is an element in a that is < the corresponding #
# element in b and all previous elements are equal; FALSE otherwise #
OP < = ( []INT a, b )BOOL:
IF INT a pos := LWB a;
INT b pos := LWB b;
BOOL equal := TRUE;
WHILE a pos <= UPB a AND b pos <= UPB b AND equal DO
equal := a[ a pos ] = b[ b pos ];
IF equal THEN
a pos +:= 1;
b pos +:= 1
FI
OD;
NOT equal
THEN
# there is an element in a and b that is not equal #
a[ a pos ] < b[ b pos ]
ELSE
# all elements are equal or one list is shorter #
# a is < b if a has fewer elements #
a pos > UPB a AND b pos <= UPB b
FI # < # ;
# tests a < b has the expected result #
PROC test = ( STRING a name, []INT a, STRING b name, []INT b, BOOL expected )VOID:
BEGIN
BOOL result = a < b;
print( ( a name, IF result THEN " < " ELSE " >= " FI, b name
, IF result = expected THEN "" ELSE ", NOT as expected" FI
, newline
)
)
END # test # ;
# test cases as in the BBC basic sample #
[]INT list1 = ( 1, 2, 1, 5, 2 );
[]INT list2 = ( 1, 2, 1, 5, 2, 2 );
[]INT list3 = ( 1, 2, 3, 4, 5 );
[]INT list4 = ( 1, 2, 3, 4, 5 );
test( "list1", list1, "list2", list2, TRUE );
test( "list2", list2, "list3", list3, TRUE );
test( "list3", list3, "list4", list4, FALSE );
# additional test cases #
[]INT list5 = ( 9, 0, 2, 1, 0 );
[]INT list6 = ( 4, 0, 7, 7 );
[]INT list7 = ( 4, 0, 7 );
[]INT list8 = ( );
test( "list5", list5, "list6", list6, FALSE );
test( "list6", list6, "list7", list7, FALSE );
test( "list7", list7, "list8", list8, FALSE );
test( "list8", list8, "list7", list7, TRUE )
END
- Output:
list1 < list2 list2 < list3 list3 >= list4 list5 >= list6 list6 >= list7 list7 >= list8 list8 < list7
ALGOL W
begin % compare lists (rows) of integers %
% returns TRUE if there is an element in a that is < the corresponding %
% element in b and all previous elements are equal, FALSE otherwise %
% the bounds of a and b should aLb :: aUb and bLb :: bUb %
logical procedure iLT ( integer array a ( * )
; integer value aLb, aUb
; integer array b ( * )
; integer value bLb, bUb
) ;
begin
integer aPos, bPos;
logical equal;
aPos := aLb;
bPos := bLb;
equal := true;
while aPos <= aUb and bPos <= bUb and equal do begin
equal := a( aPos ) = b( bPos );
if equal then begin
aPos := aPOs + 1;
bPos := bPos + 1
end if_equal
end while_more_elements_and_equal ;
if not equal
then % there is an element in a and b that is not equal %
a( aPos ) < b( bPos )
else % all elements are equal or one list is shorter %
% a is < b if a has fewer elements %
aPos > aUb and bPos <= bUb
end iLT ;
% tests a < b has the expected result %
procedure test ( string(5) value aName
; integer array a ( * )
; integer value aLb, aUb
; string(5) value bName
; integer array b ( * )
; integer value bLb, bUb
; logical value expected
) ;
begin
logical isLt;
isLt := iLT( a, aLb, aUb, b, bLb, bUb );
write( aName, if isLt then " < " else " >= ", bName
, if isLt = expected then "" else ", NOT as expected"
)
end test ;
integer array list1, list3, list4 ( 1 :: 5 );
integer array list2 ( 1 :: 6 );
integer array list5 ( 1 :: 5 );
integer array list6 ( 1 :: 4 );
integer array list7 ( 1 :: 3 );
integer array list8 ( 1 :: 1 );
integer aPos;
% test cases as in the BBC basic sample %
aPos := 1; for i := 1, 2, 1, 5, 2 do begin list1( aPos ) := i; aPos := aPos + 1 end;
aPos := 1; for i := 1, 2, 1, 5, 2, 2 do begin list2( aPos ) := i; aPos := aPos + 1 end;
aPos := 1; for i := 1, 2, 3, 4, 5 do begin list3( aPos ) := i; aPos := aPos + 1 end;
aPos := 1; for i := 1, 2, 3, 4, 5 do begin list4( aPos ) := i; aPos := aPos + 1 end;
test( "list1", list1, 1, 5, "list2", list2, 1, 6, true );
test( "list2", list2, 1, 6, "list3", list3, 1, 5, true );
test( "list3", list3, 1, 5, "list4", list4, 1, 5, false );
% additional test cases %
aPos := 1; for i := 9, 0, 2, 1, 0 do begin list5( aPos ) := i; aPos := aPos + 1 end;
aPos := 1; for i := 4, 0, 7, 7 do begin list6( aPos ) := i; aPos := aPos + 1 end;
aPos := 1; for i := 4, 0, 7 do begin list7( aPos ) := i; aPos := aPos + 1 end;
test( "list5", list5, 1, 5, "list6", list6, 1, 4, false );
test( "list6", list6, 1, 4, "list7", list7, 1, 3, false );
test( "list7", list7, 1, 3, "list8", list8, 1, 0, false );
test( "list8", list8, 1, 0, "list7", list7, 1, 3, true )
end.
- Output:
list1 < list2 list2 < list3 list3 >= list4 list5 >= list6 list6 >= list7 list7 >= list8 list8 < list7
Aime
ordl(list a, b)
{
integer i, l, o;
l = min(~a, ~b);
i = 0;
while (i < l) {
if (a[i] != b[i]) {
o = a[i] < b[i];
break;
}
i += 1;
}
i < l ? o : ~a <= ~b;
}
main(void)
{
o_(ordl(list(1, 2), list(1, 2)), "\n");
o_(ordl(list(1e2, 2), list(1e2, 2, 3)), "\n");
o_(ordl(list(1, 2, 3), list(1, 2)), "\n");
o_(ordl(list(.5, 4), list(.5, 2)), "\n");
o_(ordl(list(1, 4, 2, 3), list(1, 4, 2.1, 3)), "\n");
0;
}
AppleScript
<= is not defined over lists in AppleScript
-- <= for lists
-- compare :: [a] -> [a] -> Bool
on compare(xs, ys)
if length of xs = 0 then
true
else
if length of ys = 0 then
false
else
set {hx, txs} to uncons(xs)
set {hy, tys} to uncons(ys)
if hx = hy then
compare(txs, tys)
else
hx < hy
end if
end if
end if
end compare
-- TEST
on run
{compare([1, 2, 1, 3, 2], [1, 2, 0, 4, 4, 0, 0, 0]), ¬
compare([1, 2, 0, 4, 4, 0, 0, 0], [1, 2, 1, 3, 2])}
end run
---------------------------------------------------------------------------
-- GENERIC FUNCTION
-- uncons :: [a] -> Maybe (a, [a])
on uncons(xs)
if length of xs > 0 then
{item 1 of xs, rest of xs}
else
missing value
end if
end uncons
- Output:
{false, true}
Here's an iterative implementation:
on listAComesBeforeListB(a, b)
set aLength to (count a)
set bLength to (count b)
set i to 0
repeat
set i to i + 1
if (i > bLength) then
return false
else if (i > aLength) then
return true
else
set aVal to item i of a
set bVal to item i of b
if (aVal = bVal) then
else
return (bVal > aVal)
end if
end if
end repeat
end listAComesBeforeListB
-- Test code:
set a to {}
repeat (random number 10) times
set end of a to random number 10
end repeat
set b to {}
repeat (random number 10) times
set end of b to random number 10
end repeat
return {a:a, b:b, | a < b |: listAComesBeforeListB(a, b)},
- Output:
Examples:
{a:{3, 5, 6, 5, 2, 1, 4}, b:{5, 8, 9, 2, 0, 1, 9, 0, 4, 10}, | a < b |:true}
{a:{10, 9, 5, 8, 8, 4, 3}, b:{5, 10, 8, 9, 10, 8, 7, 8}, | a < b |:false}
{a:{0, 10}, b:{0, 10}, | a < b |:false}
{a:{0, 10}, b:{0, 10, 5}, | a < b |:true}
ARM Assembly
/* ARM assembly Raspberry PI */
/* program orderlist.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessResult1: .asciz "List1 < List2 \n" @ message result
szMessResult2: .asciz "List1 => List2 \n" @ message result
szCarriageReturn: .asciz "\n"
iTabList1: .int 1,2,3,4,5
.equ NBELEMENTS1, (. - iTabList1) /4
iTabList2: .int 1,2,1,5,2,2
.equ NBELEMENTS2, (. - iTabList2) /4
iTabList3: .int 1,2,3,4,5
.equ NBELEMENTS3, (. - iTabList3) /4
iTabList4: .int 1,2,3,4,5,6
.equ NBELEMENTS4, (. - iTabList4) /4
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r0,iAdriTabList1
mov r1,#NBELEMENTS1
ldr r2,iAdriTabList2
mov r3,#NBELEMENTS2
bl listeOrder
cmp r0,#0 @ false ?
beq 1f @ yes
ldr r0,iAdrszMessResult1 @ list 1 < list 2
bl affichageMess @ display message
b 2f
1:
ldr r0,iAdrszMessResult2
bl affichageMess @ display message
2:
ldr r0,iAdriTabList1
mov r1,#NBELEMENTS1
ldr r2,iAdriTabList3
mov r3,#NBELEMENTS3
bl listeOrder
cmp r0,#0 @ false ?
beq 3f @ yes
ldr r0,iAdrszMessResult1 @ list 1 < list 2
bl affichageMess @ display message
b 4f
3:
ldr r0,iAdrszMessResult2
bl affichageMess @ display message
4:
ldr r0,iAdriTabList1
mov r1,#NBELEMENTS1
ldr r2,iAdriTabList4
mov r3,#NBELEMENTS4
bl listeOrder
cmp r0,#0 @ false ?
beq 5f @ yes
ldr r0,iAdrszMessResult1 @ list 1 < list 2
bl affichageMess @ display message
b 6f
5:
ldr r0,iAdrszMessResult2
bl affichageMess @ display message
6:
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdriTabList1: .int iTabList1
iAdriTabList2: .int iTabList2
iAdriTabList3: .int iTabList3
iAdriTabList4: .int iTabList4
iAdrszMessResult1: .int szMessResult1
iAdrszMessResult2: .int szMessResult2
iAdrszCarriageReturn: .int szCarriageReturn
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of list 1 */
/* r1 contains list 1 size */
/* r2 contains the address of list 2 */
/* r3 contains list 2 size */
/* r0 returns 1 if list1 < list2 */
/* r0 returns 0 else */
listeOrder:
push {r1-r7,lr} @ save registres
cmp r1,#0 @ list 1 size = zero ?
moveq r0,#-1 @ yes -> error
beq 100f
cmp r3,#0 @ list 2 size = zero ?
moveq r0,#-2 @ yes -> error
beq 100f
mov r4,#0 @ index list 1
mov r5,#0 @ index list 2
1:
ldr r6,[r0,r4,lsl #2] @ load list 1 element
ldr r7,[r2,r5,lsl #2] @ load list 2 element
cmp r6,r7 @ compar
movgt r0,#0 @ list 1 > list 2 ?
bgt 100f
beq 2f @ list 1 = list 2
add r4,#1 @ increment index 1
cmp r4,r1 @ end list ?
movge r0,#1 @ yes -> ok list 1 < list 2
bge 100f
b 1b @ else loop
2:
add r4,#1 @ increment index 1
cmp r4,r1 @ end list ?
bge 3f @ yes -> verif size
add r5,#1 @ else increment index 2
cmp r5,r3 @ end list 2 ?
movge r0,#0 @ yes -> list 2 < list 1
bge 100f
b 1b @ else loop
3:
cmp r1,r3 @ compar size
movge r0,#0 @ list 2 < list 1
movlt r0,#1 @ list 1 < list 2
100:
pop {r1-r7,lr} @ restaur registers
bx lr @ return
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registres
mov r2,#0 @ counter length
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call systeme
pop {r0,r1,r2,r7,lr} @ restaur registers */
bx lr @ return
Arturo
compareLists: function [a,b][
loop 0..min @[size a, size b] 'i [
if a\[i] < b\[i] -> return true
if a\[i] > b\[i] -> return false
]
return less? size a size b
]
alias.infix '<=> 'compareLists
do [
print [1 2 1 3 2] <=> [1 2 0 4 4 0 0 0]
]
- Output:
false
AutoHotkey
The function is overkill as we can just compare the list's ObjMaxIndex()
List1 := [1,2,1,3,2]
List2 := [1,2,0,4,4,0,0,0]
MsgBox % order(List1, List2)
order(L1, L2){
return L1.MaxIndex() < L2.MaxIndex()
}
AWK
# syntax: GAWK -f ORDER_TWO_NUMERICAL_LISTS.AWK
BEGIN {
split("1,2,1,5,2",list1,",")
split("1,2,1,5,2,2",list2,",")
split("1,2,3,4,5",list3,",")
split("1,2,3,4,5",list4,",")
x = compare_array(list1,list2) ? "<" : ">=" ; printf("list1%slist2\n",x)
x = compare_array(list2,list3) ? "<" : ">=" ; printf("list2%slist3\n",x)
x = compare_array(list3,list4) ? "<" : ">=" ; printf("list3%slist4\n",x)
exit(0)
}
function compare_array(arr1,arr2, ans,i) {
ans = 0
for (i=1; i<=length(arr1); i++) {
if (arr1[i] != arr2[i]) {
ans = 1
break
}
}
if (length(arr1) != length(arr2)) {
ans = 1
}
return(ans)
}
- Output:
list1<list2 list2<list3 list3>=list4
BASIC256
arraybase 1
dim list1(5): dim list2(6): dim list3(5): dim list4(5)
list1 = {1, 2, 1, 5, 2}
list2 = {1, 2, 1, 5, 2, 2}
list3 = {1, 2, 3, 4, 5}
list4 = {1, 2, 3, 4, 5}
if Orden(list1[], list2[]) then print "list1 < list2" else print "list 1>= list2"
if Orden(list2[], list3[]) then print "list2 < list3" else print "list2 >= list3"
if Orden(list3[], list4[]) then print "list3 < list4" else print "list3 >= list4"
end
function Orden(listA[], listB[])
i = 0
l1 = listA[?]
l2 = listB[?]
while (listA[i] = listB[i]) and i < l1 and i < l2
i = i + 1
end while
if listA[?] < listB[?] then return True
if listA[?] > listB[?] then return False
return l1 < l2
end function
- Output:
Igual que la entrada de BBC BASIC.
BBC BASIC
'Ordered before' means 'less than' (see talk page).
DIM list1(4) : list1() = 1, 2, 1, 5, 2
DIM list2(5) : list2() = 1, 2, 1, 5, 2, 2
DIM list3(4) : list3() = 1, 2, 3, 4, 5
DIM list4(4) : list4() = 1, 2, 3, 4, 5
IF FNorder(list1(), list2()) PRINT "list1<list2" ELSE PRINT "list1>=list2"
IF FNorder(list2(), list3()) PRINT "list2<list3" ELSE PRINT "list2>=list3"
IF FNorder(list3(), list4()) PRINT "list3<list4" ELSE PRINT "list3>=list4"
END
DEF FNorder(list1(), list2())
LOCAL i%, l1%, l2%
l1% = DIM(list1(),1) : l2% = DIM(list2(),1)
WHILE list1(i%) = list2(i%) AND i% < l1% AND i% < l2%
i% += 1
ENDWHILE
IF list1(i%) < list2(i%) THEN = TRUE
IF list1(i%) > list2(i%) THEN = FALSE
= l1% < l2%
- Output:
list1<list2 list2<list3 list3>=list4
Bracmat
When evaluating a sum or a product, Bracmat creates an expression with a canonical order, which happens to be compatible with the order defined in this task.
In a pattern, only a sum or product on the left hand side (lhs) of the match (:
) operator is evaluated.
In the solution below we match a composition of the two function arguments into a sum of two terms with itself.
If the match expression succeeds, the lhs must already have been in canonical order before evaluation, which means that the first argument is smaller than the second argument.
In that case the function outputs FALSE.
Notice that if the arguments are the same, evaluation of the sum produces the product of one of the terms and a factor two. This complicates the pattern a bit.
( 1 2 3 4 5:?List1
& 1 2 1 5 2 2:?List2
& 1 2 1 5 2:?List3
& 1 2 1 5 2:?List4
& Cat Elephant Rat Cat:?List5
& Cat Elephant Rat:?List6
& Cat Cat Elephant:?List7
& ( gt
= first second
. !arg:(?first,?second)
& out
$ ( (.!first)+(.!second)
: ((.!first)+(.!second)|2*(.!first))
& FALSE
| TRUE
)
)
& gt$(!List1,!List2)
& gt$(!List2,!List3)
& gt$(!List3,!List4)
& gt$(!List4,!List5)
& gt$(!List5,!List6)
& gt$(!List6,!List7)
);
- Output:
TRUE TRUE FALSE FALSE TRUE TRUE
C
int list_cmp(int *a, int la, int *b, int lb)
{
int i, l = la;
if (l > lb) l = lb;
for (i = 0; i < l; i++) {
if (a[i] == b[i]) continue;
return (a[i] > b[i]) ? 1 : -1;
}
if (la == lb) return 0;
return la > lb ? 1 : -1;
}
This funciton returns one of three states, not a boolean. One can define boolean comparisons, such as list_less_or_eq
, based on it:
#define list_less_or_eq(a,b,c,d) (list_cmp(a,b,c,d) != 1)
C#
namespace RosettaCode.OrderTwoNumericalLists
{
using System;
using System.Collections.Generic;
internal static class Program
{
private static bool IsLessThan(this IEnumerable<int> enumerable,
IEnumerable<int> otherEnumerable)
{
using (
IEnumerator<int> enumerator = enumerable.GetEnumerator(),
otherEnumerator = otherEnumerable.GetEnumerator())
{
while (true)
{
if (!otherEnumerator.MoveNext())
{
return false;
}
if (!enumerator.MoveNext())
{
return true;
}
if (enumerator.Current == otherEnumerator.Current)
{
continue;
}
return enumerator.Current < otherEnumerator.Current;
}
}
}
private static void Main()
{
Console.WriteLine(
new[] {1, 2, 1, 3, 2}.IsLessThan(new[] {1, 2, 0, 4, 4, 0, 0, 0}));
}
}
}
- Output:
False
C++
The built-in comparison operators already do this:
#include <iostream>
#include <vector>
int main() {
std::vector<int> a;
a.push_back(1);
a.push_back(2);
a.push_back(1);
a.push_back(3);
a.push_back(2);
std::vector<int> b;
b.push_back(1);
b.push_back(2);
b.push_back(0);
b.push_back(4);
b.push_back(4);
b.push_back(0);
b.push_back(0);
b.push_back(0);
std::cout << std::boolalpha << (a < b) << std::endl; // prints "false"
return 0;
}
clojure
(defn lex? [a b]
(compare a b))
Common Lisp
(defun list< (a b)
(cond ((not b) nil)
((not a) t)
((= (first a) (first b))
(list< (rest a) (rest b)))
(t (< (first a) (first b)))))
Alternate version
(defun list< (a b)
(let ((x (find-if-not #'zerop (mapcar #'- a b))))
(if x (minusp x) (< (length a) (length b)))))
D
The built-in comparison operators already do this:
void main() {
assert([1,2,1,3,2] >= [1,2,0,4,4,0,0,0]);
}
Delphi
This is not a full translate of Java, just adaptation and aplication of method previus introduced.
program Order_two_numerical_lists;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.Generics.Defaults;
type
TArray = record
class function LessOrEqual<T>(first, second: TArray<T>): Boolean; static;
end;
class function TArray.LessOrEqual<T>(first, second: TArray<T>): Boolean;
begin
if Length(first) = 0 then
exit(true);
if Length(second) = 0 then
exit(false);
var comp := TComparer<T>.Default.Compare(first[0], second[0]);
if comp = 0 then
exit(LessOrEqual(copy(first, 1, length(first)), copy(second, 1, length(second))));
Result := comp < 0;
end;
begin
writeln(TArray.LessOrEqual<Integer>([1, 2, 3], [2, 3, 4]));
writeln(TArray.LessOrEqual<Integer>([2, 3, 4], [1, 2, 3]));
writeln(TArray.LessOrEqual<Integer>([1, 2], [1, 2, 3]));
writeln(TArray.LessOrEqual<Integer>([1, 2, 3], [1, 2]));
writeln(TArray.LessOrEqual<Char>(['a', 'c', 'b'], ['a', 'b', 'b']));
writeln(TArray.LessOrEqual<string>(['this', 'is', 'a', 'test'], ['this', 'is',
'not', 'a', 'test']));
readln;
end.
- Output:
TRUE FALSE TRUE FALSE FALSE TRUE
EasyLang
func listcmp a[] b[] .
for i to lower len a[] len b[]
if a[i] < b[i]
return -1
elif a[i] > b[i]
return 1
.
.
if len a[] < len b[]
return -1
elif len a[] > len b[]
return 1
.
return 0
.
print listcmp [ 2 4 5 ] [ 2 3 1 ]
print listcmp [ 2 3 1 ] [ 2 3 1 ]
print listcmp [ 2 3 1 ] [ 2 3 1 3 ]
Ela
[] <. _ = true
_ <. [] = false
(x::xs) <. (y::ys) | x == y = xs <. ys
| else = x < y
[1,2,1,3,2] <. [1,2,0,4,4,0,0,0]
Elixir
The built-in comparison functions already do this (not only for lists of numbers, but for any arbitrary data type).
iex(1)> [1,2,3] < [1,2,3,4]
true
iex(2)> [1,2,3] < [1,2,4]
true
Erlang
Builtin. Example use from Erlang shell:
5> [1,2,3] < [1,2,3,4].
true
6> [1,2,3] < [1,2,4].
true
F#
By using the Collection.Seq Module the static method Seq.compareWith fits our needs.
let inline cmp x y = if x < y then -1 else if x = y then 0 else 1
let before (s1 : seq<'a>) (s2 : seq<'a>) = (Seq.compareWith cmp s1 s2) < 0
[
([0], []);
([], []);
([], [0]);
([-1], [0]);
([0], [0]);
([0], [-1]);
([0], [0; -1]);
([0], [0; 0]);
([0], [0; 1]);
([0; -1], [0]);
([0; 0], [0]);
([0; 0], [1]);
]
|> List.iter (fun (x, y) -> printf "%A %s %A\n" x (if before x y then "< " else ">=") y)
- Output:
[0] >= [] [] >= [] [] < [0] [-1] < [0] [0] >= [0] [0] >= [-1] [0] < [0; -1] [0] < [0; 0] [0] < [0; 1] [0; -1] >= [0] [0; 0] >= [0] [0; 0] < [1]
Factor
All sequences respond to words in the math.order vocabulary.
IN: scratchpad { 2 3 } { 2 5 } before? . t
FreeBASIC
Dim Shared list1(4) As Integer = {1, 2, 1, 5, 2}
Dim Shared list2(5) As Integer = {1, 2, 1, 5, 2, 2}
Dim Shared list3(4) As Integer = {1, 2, 3, 4, 5}
Dim Shared list4(4) As Integer = {1, 2, 3, 4, 5}
Function Orden(listA() As Integer, listB() As Integer) As Boolean
Dim As Integer i = 0, l1, l2
l1 = Ubound(listA, 1)
l2 = Ubound(listB, 1)
While listA(i) = listB(i) And i < l1 And i < l2
i += 1
Wend
If listA(i) < listB(i) Then Return True
If listA(i) > listB(i) Then Return False
Return l1 < l2
End Function
If Orden(list1(), list2()) Then Print "list1<list2" Else Print "list1>=list2"
If Orden(list2(), list3()) Then Print "list2<list3" Else Print "list2>=list3"
If Orden(list3(), list4()) Then Print "list3<list4" Else Print "list3>=list4"
Sleep
- Output:
Igual que la entrada de BBC BASIC.
Go
package main
import "fmt"
// If your numbers happen to be in the range of Unicode code points (0 to 0x10ffff), this function
// satisfies the task:
func lessRune(a, b []rune) bool {
return string(a) < string(b) // see also bytes.Compare
}
// Otherwise, the following function satisfies the task for all integer
// and floating point types, by changing the type definition appropriately.
type numericType int
func lessNT(a, b []numericType) bool {
l := len(a)
if len(b) < l {
l = len(b)
}
for i := 0; i < l; i++ {
if a[i] != b[i] {
return a[i] < b[i]
}
}
return l < len(b)
}
var testCases = [][][]numericType{
{{0}, {}},
{{}, {}},
{{}, {0}},
{{-1}, {0}},
{{0}, {0}},
{{0}, {-1}},
{{0}, {0, -1}},
{{0}, {0, 0}},
{{0}, {0, 1}},
{{0, -1}, {0}},
{{0, 0}, {0}},
{{0, 0}, {1}},
}
func main() {
// demonstrate the general function
for _, tc := range testCases {
fmt.Printf("order %6s before %6s : %t\n",
fmt.Sprintf("%v", tc[0]),
fmt.Sprintf("%v", tc[1]),
lessNT(tc[0], tc[1]))
}
fmt.Println()
// demonstrate that the byte specific function gives identical results
// by offsetting test data to a printable range of characters.
for _, tc := range testCases {
a := toByte(tc[0])
b := toByte(tc[1])
fmt.Printf("order %6q before %6q : %t\n",
string(a),
string(b),
lessByte(a, b))
}
}
func toByte(a []numericType) []byte {
b := make([]byte, len(a))
for i, n := range a {
b[i] = 'b' + byte(n)
}
return b
}
- Output:
order [0] before [] : false order [] before [] : false order [] before [0] : true order [-1] before [0] : true order [0] before [0] : false order [0] before [-1] : false order [0] before [0 -1] : true order [0] before [0 0] : true order [0] before [0 1] : true order [0 -1] before [0] : false order [0 0] before [0] : false order [0 0] before [1] : true order "b" before "" : false order "" before "" : false order "" before "b" : true order "a" before "b" : true order "b" before "b" : false order "b" before "a" : false order "b" before "ba" : true order "b" before "bb" : true order "b" before "bc" : true order "ba" before "b" : false order "bb" before "b" : false order "bb" before "c" : true
Groovy
Solution:
class CList extends ArrayList implements Comparable {
CList() { }
CList(Collection c) { super(c) }
int compareTo(Object that) {
assert that instanceof List
def n = [this.size(), that.size()].min()
def comp = [this[0..<n], that[0..<n]].transpose().find { it[0] != it[1] }
comp ? comp[0] <=> comp[1] : this.size() <=> that.size()
}
}
Test:
CList a, b; (a, b) = [[], []]; assert ! (a < b)
b = [1] as CList; assert (a < b)
a = [1] as CList; assert ! (a < b)
b = [2] as CList; assert (a < b)
a = [2, -1, 0] as CList; assert ! (a < b)
b = [2, -1] as CList; assert ! (a < b)
b = [2, -1, 0] as CList; assert ! (a < b)
b = [2, -1, 0, -17] as CList; assert (a < b)
a = [2, 8, 0] as CList; assert ! (a < b)
Haskell
The built-in comparison operators already do this:
Prelude> [1,2,1,3,2] < [1,2,0,4,4,0,0,0]
False
Icon and Unicon
List_llt is written in the style of all Icon/Unicon relational operators returning its right argument if successful and signaling failure otherwise.
J
J's built-in comparator operates element-wise. To compare general sequences you can either box them and use sort. Or for numeric sequences append minus infinity and sort. However numeric scalars sort ahead of vectors, i.e. are different from length one lists.
before=: -.@(-: /:~)@,&<~
cmp=: {.@\:@,:&(,&__)
Below demonstrates non-decreasing order cmp treats length one vector same as scalar
cmp&.>"{~ ('';0;(,0);1;(,1);1 1)
┌─┬─┬─┬─┬─┬─┐
│0│1│1│1│1│1│
├─┼─┼─┼─┼─┼─┤
│0│0│0│1│1│1│
├─┼─┼─┼─┼─┼─┤
│0│0│0│1│1│1│
├─┼─┼─┼─┼─┼─┤
│0│0│0│0│0│1│
├─┼─┼─┼─┼─┼─┤
│0│0│0│0│0│1│
├─┼─┼─┼─┼─┼─┤
│0│0│0│0│0│0│
└─┴─┴─┴─┴─┴─┘
before&.>"{~ (0;1;'';(,0);(,1);1 1)
┌─┬─┬─┬─┬─┬─┐
│0│1│1│1│1│1│
├─┼─┼─┼─┼─┼─┤
│0│0│1│1│1│1│
├─┼─┼─┼─┼─┼─┤
│0│0│0│1│1│1│
├─┼─┼─┼─┼─┼─┤
│0│0│0│0│1│1│
├─┼─┼─┼─┼─┼─┤
│0│0│0│0│0│1│
├─┼─┼─┼─┼─┼─┤
│0│0│0│0│0│0│
└─┴─┴─┴─┴─┴─┘
Java
There are a few methods here. The method named "ordered" which works on arrays is a translation of Common Lisp. The other two are loose translations of Tcl (some tweaks were needed to get the length checks to work out) and are probably better options.
import java.util.Arrays;
import java.util.List;
public class ListOrder{
public static boolean ordered(double[] first, double[] second){
if(first.length == 0) return true;
if(second.length == 0) return false;
if(first[0] == second[0])
return ordered(Arrays.copyOfRange(first, 1, first.length),
Arrays.copyOfRange(second, 1, second.length));
return first[0] < second[0];
}
public static <T extends Comparable<? super T>> boolean ordered(List<T> first, List<T> second){
int i = 0;
for(; i < first.size() && i < second.size();i++){
int cmp = first.get(i).compareTo(second.get(i));
if(cmp == 0) continue;
if(cmp < 0) return true;
return false;
}
return i == first.size();
}
public static boolean ordered2(double[] first, double[] second){
int i = 0;
for(; i < first.length && i < second.length;i++){
if(first[i] == second[i]) continue;
if(first[i] < second[i]) return true;
return false;
}
return i == first.length;
}
}
JavaScript
ES6
<= is already defined for numeric lists in JavaScript
(() => {
'use strict';
// <= is already defined for lists in JS
// compare :: [a] -> [a] -> Bool
const compare = (xs, ys) => xs <= ys;
// TEST
return [
compare([1, 2, 1, 3, 2], [1, 2, 0, 4, 4, 0, 0, 0]),
compare([1, 2, 0, 4, 4, 0, 0, 0], [1, 2, 1, 3, 2])
];
// --> [false, true]
})()
- Output:
[false, true]
Joy
DEFINE order ==
[equal] [false]
[[[[size] dip size <=] [[<=] mapr2 true [and] fold]] [i] map i and]
ifte.
Using it:
[1 2] [1 2 3] order. # true [1 2] [1 3] order. # true [1 2] [1 2] order. # false [1 3] [1 2] order. # false [1 2 3] [1 2] order. # false
jq
jq's builtin comparison operators use lexicographic ordering for arrays in general, not just arrays of integers.
[1,2,3] < [1,2,3,4] # => true
[1,2,3] < [1,2,4] # => true
[1,2,3] < [1,2,3] # => false
Julia
function islexless(a::AbstractArray{<:Real}, b::AbstractArray{<:Real})
for (x, y) in zip(a, b)
if x == y continue end
return x < y
end
return length(a) < length(b)
end
using Primes, Combinatorics
tests = [[1, 2, 3], primes(10), 0:2:6, [-Inf, 0.0, Inf], [π, e, φ, catalan], [2015, 5], [-sqrt(50.0), 50.0 ^ 2]]
println("List not sorted:\n - ", join(tests, "\n - "))
sort!(tests; lt=islexless)
println("List sorted:\n - ", join(tests, "\n - "))
- Output:
List not sorted: - [1, 2, 3] - [2, 3, 5, 7] - 0:2:6 - [-Inf, 0.0, Inf] - [3.14159, 2.71828, 1.61803, 0.915966] - [2015, 5] - [-7.07107, 2500.0] List sorted: - [-Inf, 0.0, Inf] - [-7.07107, 2500.0] - 0:2:6 - [1, 2, 3] - [2, 3, 5, 7] - [3.14159, 2.71828, 1.61803, 0.915966] - [2015, 5]
Klingphix
include ..\Utilitys.tlhy
( 1 2 3 ) ( 1 2 3 4 ) less ?
( 1 2 3 4 ) ( 1 2 3 ) less ?
( 1 2 4 ) ( 1 2 3 ) less ?
( 1 2 3 ) ( 1 2 3 ) less ?
( 1 2 3 ) ( 1 2 4 ) less ?
"End " input
Kotlin
// version 1.0.6
operator fun <T> List<T>.compareTo(other: List<T>): Int
where T: Comparable<T>, T: Number {
for (i in 0 until this.size) {
if (other.size == i) return 1
when {
this[i] < other[i] -> return -1
this[i] > other[i] -> return 1
}
}
return if (this.size == other.size) 0 else -1
}
fun main(args: Array<String>) {
val lists = listOf(
listOf(1, 2, 3, 4, 5),
listOf(1, 2, 1, 5, 2, 2),
listOf(1, 2, 1, 5, 2),
listOf(1, 2, 1, 5, 2),
listOf(1, 2, 1, 3, 2),
listOf(1, 2, 0, 4, 4, 0, 0, 0),
listOf(1, 2, 0, 4, 4, 1, 0, 0)
)
for (i in 0 until lists.size) println("list${i + 1} : ${lists[i]}")
println()
for (i in 0 until lists.size - 1) println("list${i + 1} > list${i + 2} = ${lists[i] > lists[i + 1]}")
}
- Output:
list1 : [1, 2, 3, 4, 5] list2 : [1, 2, 1, 5, 2, 2] list3 : [1, 2, 1, 5, 2] list4 : [1, 2, 1, 5, 2] list5 : [1, 2, 1, 3, 2] list6 : [1, 2, 0, 4, 4, 0, 0, 0] list7 : [1, 2, 0, 4, 4, 1, 0, 0] list1 > list2 = true list2 > list3 = true list3 > list4 = false list4 > list5 = true list5 > list6 = true list6 > list7 = false
LabVIEW
This image is a VI Snippet, an executable image of LabVIEW code. The LabVIEW version is shown on the top-right hand corner. You can download it, then drag-and-drop it onto the LabVIEW block diagram from a file browser, and it will appear as runnable, editable code.
Lasso
This is built into the Lasso comparison operators
local(
first = array(1,2,1,3,2),
second = array(1,2,0,4,4,0,0,0),
)
#first < #second
local(
first = array(1,1,1,3,2),
second = array(1,2,0,4,4,0,0,0),
)
#first < #second
- Output:
false true
Lhogho
Uses standard '=' notation
print [1 2] = [1 2]
print [1 2] = [1 2 3]
print [1 3] = [1 2]
print [1 2 3] = [1 2]
make "list1 [1 2 3 4 5 6]
make "list2 [1 2 3 4 5 7]
print :list1 = :list2
- Output:
true
false
false
false
false
Lua
In Lua tables with numerical indices are used as lists or arrays and they do not support comparison out-of-the-box, so a function is needed to implement the comparison:
function arraycompare(a, b)
for i = 1, #a do
if b[i] == nil then
return true
end
if a[i] ~= b[i] then
return a[i] < b[1]
end
end
return true
end
Here is some demonstration code:
function randomarray()
local t = {}
for i = 1, math.random(1, 10) do
t[i] = math.random(1, 10)
end
return t
end
math.randomseed(os.time())
for i = 1, 10 do
local a = randomarray()
local b = randomarray()
print(
string.format("{%s} %s {%s}",
table.concat(a, ', '),
arraycompare(a, b) and "<=" or ">",
table.concat(b, ', ')))
end
- Output:
(time used as random seed
{10, 7, 4, 9, 10, 3, 5, 5, 5, 5} > {7, 4, 6, 4, 3, 5, 10} {5, 7} <= {6, 3, 7, 7, 7, 1} {4} <= {10, 10, 3, 8, 10, 5, 2, 5, 10, 6} {6} <= {6, 10, 2, 1, 9, 4, 5, 6, 9} {9, 5, 7, 5, 5, 7, 9, 5, 6, 8} > {4, 7, 3, 5, 1, 2, 1, 2} {10, 8, 6, 1, 8, 5, 4} > {1, 2} {9, 7} > {4, 1, 5, 2, 6, 1, 9, 3, 5} {5, 9, 7, 6, 10, 8} <= {9, 6, 9} {4, 3, 4, 6, 3, 6, 7, 2, 2, 5} > {3, 10, 6, 8, 1} {1, 5, 1, 5, 4} > {1, 3, 5, 3, 2, 10, 1}
Maple
orderLists := proc(num1,num2)
local len1, len2,i:
len1,len2 := numelems(num1),numelems(num2):
for i to min(len1,len2) do
if num1[i] <> num2[i] then
return evalb(num1[i]<num2[i]):
end if:
end do:
return evalb(len1 < len2):
end proc:
Mathematica /Wolfram Language
order[List1_, List2_] := With[{
L1 = List1[[1 ;; Min @@ Length /@ {List1, List2}]],
L2 = List2[[1 ;; Min @@ Length /@ {List1, List2}]]
},
If [Thread[Order[L1, L2]] == 0,
Length[List1] < Length[List2],
Thread[Order[L1, L2]] == 1
]]
Example use: order[ {1, 2, 1, 3, 2}, {1, 2, 0, 4, 4, 0, 0, 0} ] ->False order[ {1, 2}, {1, 2, 4, 4, 0, 0} ] ->True
Maxima
"<<"(a,b):=block([n:min(length(a),length(b))],
catch(for i thru n do (if a[i]#b[i] then throw(is(a[i]<b[i]))),
throw(is(length(a)<length(b)))))$
infix("<<")$
[1,2,3] << [1,2,4];
true
[1,2,3] << [1,2];
false
[1,2] << [1,2];
false
Mercury
For a particular numerical type, you can get away with
:- pred lt(list(int)::in, list(int)::in) is semidet.
lt([], [_|_]).
lt([H1|T1], [H2|T2]) :- H1 =< H2, T1 `lt` T2.
For a list of any numerical type, one way would be to use a typeclass:
:- pred lt(list(T)::in, list(T)::in) is semidet <= comparable(T).
lt([], [_|_]).
lt([H1|T1], [H2|T2]) :- H1 =< H2, T1 `lt` T2.
... which you would have to create:
:- module comparable.
:- interface.
:- import_module int, float, integer, list.
:- typeclass comparable(T) where [
pred '<'(T::in, T::in) is semidet,
pred '=<'(T::in, T::in) is semidet
].
:- instance comparable(int).
:- instance comparable(float).
:- instance comparable(integer).
:- instance comparable(list(T)) <= comparable(T).
:- implementation.
:- instance comparable(int) where [
pred('<'/2) is int.(<),
pred('=<'/2) is int.(=<)
].
% likewise for float and integer...
:- instance comparable(list(T)) <= comparable(T) where [
pred('<'/2) is lt, % the 'lt' above.
pred('=<'/2) is lte % 'lt' with: lte([], []).
].
% pred lt
% pred lte
Which would be used in this way - note the typeclass and the comparison operator.
:- pred test(list(T), list(T), io, io) <= comparable(T).
:- mode test(in, in, di, uo) is det.
test(A, B) -->
io.write(A), io.write_string(" < "), io.write(B),
io.write_string(" : "), io.write_string(S), io.nl,
{ A < B -> S = "yes" ; S = "no" }.
Miranda
main :: [sys_message]
main = [Stdout (lay (map show [
order [1,2,1,3,2] [1,2,0,4,4,0,0,0],
order [1,2,0,4,4,0,0,0] [1,2,1,3,2]]))]
order :: [*]->[*]->bool
order as [] = True
order [] as = False
order (a:as) (b:bs) = a < b, if a ~= b
= order as bs, otherwise
- Output:
False True
Nim
proc `<`[T](a, b: openarray[T]): bool =
for i in 0 .. min(a.len, b.len):
if a[i] < b[i]: return true
if a[i] > b[i]: return false
return a.len < b.len
echo([1,2,1,3,2] < [1,2,0,4,4,0,0,0])
- Output:
false
Nu
def 'list lt' [b] {
let a = $in
$a | zip $b
| skip while { $in.0 == $in.1 }
| try { first } catch { [$a $b] | each { length } }
| $in.0 < $in.1
}
[5 6 7 8] | list lt [5 6 8]
- Output:
true
OCaml
The built-in comparison operators already do this for lists (although this is not documented):
# [1;2;1;3;2] < [1;2;0;4;4;0;0;0];;
- : bool = false
(Warning: However, the built-in comparison operators do not do this for arrays:
# [|1;2;1;3;2|] < [|1;2;0;4;4;0;0;0|];;
- : bool = true
)
But we could write it explicitly this way:
let rec ordered_lists = function
| x1::tl1, x2::tl2 ->
(match compare x1 x2 with
| 0 -> ordered_lists (tl1, tl2)
| 1 -> false
| _ -> true)
| [], _ -> true
| _ -> false
Here is a small script to test this function:
(* copy-paste the code of ordered_lists here *)
let make_num_list p n =
let rec aux acc =
if Random.int p = 0 then acc
else aux (Random.int n :: acc)
in
aux []
let print_num_list lst =
List.iter (Printf.printf " %d") lst;
print_newline()
let () =
Random.self_init();
let lst1 = make_num_list 8 5 in
let lst2 = make_num_list 8 5 in
print_num_list lst1;
print_num_list lst2;
Printf.printf "ordered: %B\n" (ordered_lists (lst1, lst2))
Sample execution:
$ ocaml ordered_lists.ml 1 2 1 3 2 1 2 0 4 4 0 0 0 ordered: false
Also notice that the function ordered_lists
will work with anything the function Pervasives.compare
is able to compare (most OCaml types and structures made from the base types). In the prototype of this function below 'a list
means a list of anything:
val ordered_lists : 'a list * 'a list -> bool
Oforth
In Oforth, list comparison is already defined.
- Output:
[1,2,0,4,4,0,0,0] [1,2,1,3,2] <= . 1 ok
Ol
This sample very similar to Scheme, but implements proper tail recursion. So can test unlimited length lists.
(define (lexorder a b)
(cond
((null? b) #false)
((null? a) #true)
((< (car a) (car b)) #true)
((> (car a) (car b)) #false)
(else
(lexorder (cdr a) (cdr b)))))
(print (lexorder '(1 2 3) '(1 2 3 4))) ; => true
(print (lexorder '(1 2 4) '(1 2 3))) ; => false
(print (lexorder '(1 2 3) '(1 2))) ; => false
(print (lexorder '(1 2 3) '(1 2 3))) ; => false
(print (lexorder '(1 2 3) '(1 2 8))) ; => true
PARI/GP
lex(u,v)<1
Perl
use strict;
use warnings;
sub orderlists {
my ($firstlist, $secondlist) = @_;
my ($first, $second);
while (@{$firstlist}) {
$first = shift @{$firstlist};
if (@{$secondlist}) {
$second = shift @{$secondlist};
if ($first < $second) {
return 1;
}
if ($first > $second) {
return 0;
}
}
else {
return 0;
}
}
@{$secondlist} ? 1 : 0;
}
foreach my $pair (
[[1, 2, 4], [1, 2, 4]],
[[1, 2, 4], [1, 2, ]],
[[1, 2, ], [1, 2, 4]],
[[55,53,1], [55,62,83]],
[[20,40,51],[20,17,78,34]],
) {
my $first = $pair->[0];
my $second = $pair->[1];
my $before = orderlists([@$first], [@$second]) ? 'true' : 'false';
print "(@$first) comes before (@$second) : $before\n";
}
- Output:
(1 2 4) comes before (1 2 4) : false (1 2 4) comes before (1 2) : false (1 2) comes before (1 2 4) : true (55 53 1) comes before (55 62 83) : true (20 40 51) comes before (20 17 78 34) : false
Phix
Handled natively, eg ("?" is the shorthand print operator)
with javascript_semantics ?{1,2,3}<{1,2,3,4} -- 1 (true under p2js) ?{1,2,3,4}<{1,2,3} -- 0 (false "") ?{1,2,4}<{1,2,3} -- 0 (false "") ?{1,2,3}<{1,2,3} -- 0 (false "") ?{1,2,3}<{1,2,4} -- 1 (true "")
Elements can be any mix of integers, floating point numbers, strings, or nested subsequences, with atoms ordered before sequences.
If you want -1/0/+1 (instead of the true(1)/false(0) shown above), use the builtin compare() function, and that will match under p2js.
Phixmonti
include Utilitys.pmt
def ? print nl enddef
( 1 2 3 ) ( 1 2 3 4 ) < ?
( 1 2 3 4 ) ( 1 2 3 ) < ?
( 1 2 4 ) ( 1 2 3 ) < ?
( 1 2 3 ) ( 1 2 3 ) < ?
( 1 2 3 ) ( 1 2 4 ) < ?
Picat
Picat has a built-in general comparison operator @<
, which compares terms in lexicographic order (numeric lists as well as atoms, strings, variables, and structures).
go =>
Tests = [
[[1,2,3], [1,2,3]],
[[1,2,3], [1,2,3,4]],
[[1,2,2], [1,2,3]],
[[1,2,4], [1,2,3]],
[1..10 , 1..8],
[[] , []],
[[] , [1]],
[[1] , [] ],
[[-1,2,3,6,5],[-1,2,3,5,6]],
[[-1,2,3,-5,6],[-1,2,3,-6,5]]
],
foreach([L1,L2] in Tests)
printf("%w @< %w: %w\n",L1,L2,cond(L1 @< L2,true,false))
end,
nl.
In the Picat shell, the result is yes/no rather than true/false:
Picat> [1,2,3] @< [1,2,3] no Picat> [1,2,3] @< [1,2,3,4] yes
PicoLisp
The built-in comparison functions already do this (not only for lists of numbers, but for any arbitrary data type).
: (> (1 2 0 4 4 0 0 0) (1 2 1 3 2))
-> NIL
Pike
int(0..1) order_array(array a, array b)
{
if (!sizeof(a)) return true;
if (!sizeof(b)) return false;
if (a[0] == b[0])
return order_array(a[1..], b[1..]);
return a[0] < b[0];
}
Pikes Array.sort_array()
function can sort an array of arrays using the <
operator, but it will sort longer arrays before shorter ones. Therefore the above function is still needed if the intent is to use the comparison for a sort operation.
If the numbers are in 32bit signed integer range, the following works too:
(string)a < (string)b;
PL/I
lists: procedure options (main); /* 8 June 2014 */
declare a(10) fixed initial (1, 2, 3, 4, 5, 8, 9, 10, 16, 17),
b(15) fixed initial (5, 6, 7, 8, 9, 10, 11, 12, 15, 16, 17, 18, 20, 22, 23);
put skip list (compare(a, b));
put skip list (compare(b, a));
put skip list (compare(a, a));
compare: procedure (a, b) returns (bit (1));
declare (a, b)(*) fixed;
declare (i, m, n) fixed binary;
m = hbound(a,1); n = hbound(b,1);
do i = 1 to min(m, n);
return (a(i) < b(i));
end;
return (m < n);
end compare;
end lists;
Results:
'1'B (true) '0'B (false) '0'B
PowerShell
function order($as,$bs) {
if($as -and $bs) {
$a, $as = $as
$b, $bs = $bs
if($a -eq $b) {order $as $bs}
else{$a -lt $b}
} elseif ($bs) {$true} else {$false}
}
"$(order @(1,2,1,3,2) @(1,2,0,4,4,0,0,0))"
Output:
False
Non-Recursive Version
function Test-Order ([int[]]$ReferenceArray, [int[]]$DifferenceArray)
{
for ($i = 0; $i -lt $ReferenceArray.Count; $i++)
{
if ($ReferenceArray[$i] -lt $DifferenceArray[$i])
{
return $true
}
elseif ($ReferenceArray[$i] -gt $DifferenceArray[$i])
{
return $false
}
}
return ($ReferenceArray.Count -lt $DifferenceArray.Count) -or (Compare-Object $ReferenceArray $DifferenceArray) -eq $null
}
Test-Order -ReferenceArray 1, 2, 1, 3, 2 -DifferenceArray 1, 2, 0, 4, 4, 0, 0, 0
Test-Order -ReferenceArray 1, 2, 1, 3, 2 -DifferenceArray 1, 2, 2, 4, 4, 0, 0, 0
Test-Order -ReferenceArray 1, 2, 3 -DifferenceArray 1, 2
Test-Order -ReferenceArray 1, 2 -DifferenceArray 1, 2, 3
Test-Order -ReferenceArray 1, 2 -DifferenceArray 1, 2
- Output:
False True False True True
PureBasic
DataSection
Array_1:
Data.i 5 ;element count
Data.i 1, 2, 3, 4, 5 ;element data
Array_2:
Data.i 6
Data.i 1, 2, 1, 5, 2, 2
Array_3:
Data.i 5
Data.i 1, 2, 1, 5, 2
Array_4:
Data.i 5
Data.i 1, 2, 1, 5, 2
Array_5:
Data.i 4
Data.i 1, 2, 1, 6
Array_6:
Data.i 5
Data.i 1, 2, 1, 6, 2
EndDataSection
#False = 0
#True = 1
;helper subrountine to initialize a dataset, *dataPtr points to the elementcount followed by the element data
Procedure initArrayData(Array a(1), *dataPtr)
Protected elementCount = PeekI(*dataPtr)
Dim a(elementCount - 1)
For i = 0 To elementCount - 1
*dataPtr + SizeOf(Integer)
a(i) = PeekI(*dataPtr)
Next
EndProcedure
;helper subroutine that returns 'True' or 'False' for a boolean input
Procedure.s booleanText(b)
If b: ProcedureReturn "True": EndIf
ProcedureReturn "False"
EndProcedure
Procedure order(Array a(1), Array b(1))
Protected len_a = ArraySize(a()), len_b = ArraySize(b()), elementIndex
While elementIndex <= len_a And elementIndex <= len_b And a(elementIndex) = b(elementIndex)
elementIndex + 1
Wend
If (elementIndex > len_a And elementIndex <= len_b) Or (elementIndex <= len_b And a(elementIndex) <= b(elementIndex))
ProcedureReturn #True
EndIf
EndProcedure
Dim A_1(0): initArrayData(A_1(), ?Array_1)
Dim A_2(0): initArrayData(A_2(), ?Array_2)
Dim A_3(0): initArrayData(A_3(), ?Array_3)
Dim A_4(0): initArrayData(A_4(), ?Array_4)
Dim A_5(0): initArrayData(A_5(), ?Array_5)
Dim A_6(0): initArrayData(A_6(), ?Array_6)
If OpenConsole()
PrintN(booleanText(order(A_1(), A_2()))) ;False
PrintN(booleanText(order(A_2(), A_3()))) ;False
PrintN(booleanText(order(A_3(), A_4()))) ;False
PrintN(booleanText(order(A_4(), A_5()))) ;True
PrintN(booleanText(order(A_5(), A_6()))) ;True
Print(#crlf$ + #crlf$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf
- Output:
False False False True True
Python
The built-in comparison operators already do this:
>>> [1,2,1,3,2] < [1,2,0,4,4,0,0,0]
False
Quackery
[ [ over [] = iff false done
dup [] = iff true done
behead rot behead rot
2dup = iff
[ 2drop swap ] again
> ]
unrot 2drop ] is []< ( [ [ --> b )
' [ [ ] [ 1 ] [ 1 1 1 ] [ 1 2 ] [ 1 2 1 ] [ 2 ] [ 2 1 ] [ 2 1 1 ] ]
shuffle sortwith []< echo
- Output:
[ [ ] [ 1 ] [ 1 1 1 ] [ 1 2 ] [ 1 2 1 ] [ 2 ] [ 2 1 ] [ 2 1 1 ] ]
Racket
#lang racket
(define (lex<? a b)
(cond ((null? b) #f)
((null? a) #t)
((= (car a) (car b)) (lex<? (cdr a) (cdr b)))
(else (< (car a) (car b)))))
(lex<? '(1 2 3 4 5) '(1 2 3 4 4)) ; -> #f
Raku
(formerly Perl 6) There is already a built-in comparison operator.
my @a = <1 2 4>;
my @b = <1 2 4>;
say @a," before ",@b," = ", @a before @b;
@a = <1 2 4>;
@b = <1 2>;
say @a," before ",@b," = ", @a before @b;
@a = <1 2>;
@b = <1 2 4>;
say @a," before ",@b," = ", @a before @b;
for 1..10 {
my @a = flat (^100).roll((2..3).pick);
my @b = flat @a.map: { Bool.pick ?? $_ !! (^100).roll((0..2).pick) }
say @a," before ",@b," = ", @a before @b;
}
- Output:
1 2 4 before 1 2 4 = False 1 2 4 before 1 2 = False 1 2 before 1 2 4 = True 63 52 before 0 52 = False 17 75 24 before 31 75 24 = True 43 32 before 43 32 = False 73 84 before 2 84 = False 73 92 before 40 24 46 = False 16 24 before 41 24 = True 9 12 22 before 9 12 32 67 = True 81 23 before 81 23 = False 55 53 1 before 55 62 83 = True 20 40 51 before 20 17 78 34 = False
Rascal
The built-in comparison operator already does this:
rascal>[2,1,3] < [5,2,1,3]
bool: true
REXX
This REXX example uses the same lists as BBC BASIC.
This example will also work with non-numeric strings.
/*REXX program determines if a list < previous list, and returns true or false. */
@.=; @.1 = 1 2 1 5 2
@.2 = 1 2 1 5 2 2
@.3 = 1 2 3 4 5
@.4 = 1 2 3 4 5
/* [↓] compare a list to previous list*/
do j=2 while @.j\==''; p= j - 1 /*P: points to previous value in list.*/
if FNorder(@.p, @.j)=='true' then is= " < " /*use a more familiar glyph.*/
else is= " ≥ " /* " " " " " */
say
say right('['@.p"]", 40) is '['@.j"]"
end /*i*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
FNorder: procedure; parse arg x,y
wx= words(x); wy= words(y)
do k=1 for min(wx, wy)
a= word(x, k) /*get a value from X. */
b= word(y, k) /* " " " " Y. */
if a<b then return 'true'
else if a>b then return 'false'
end /*k*/
if wx<wy then return 'true' /*handle case of equal (so far). */
return 'false' /* " " " " " " */
- output:
[1 2 1 5 2] < [1 2 1 5 2 2] [1 2 1 5 2 2] < [1 2 3 4 5] [1 2 3 4 5] ≥ [1 2 3 4 5]
Ring
list1 = "1, 2, 1, 5, 2"
list2 = "5, 2, 1, 5, 2, 2"
list3 = "1, 2, 3, 4, 5"
list4 = "1, 2, 3, 4, 5"
if order(list1, list2) = 0 see "list1=list2" + nl
but order(list1, list2) < 0 see "list1<list2" + nl
else see "list1>list2" + nl ok
if order(list2, list3) = 0 see "list2=list3" + nl
but order(list2, list3) < 0 see "list2<list3" + nl
else see "list2>list3" + nl ok
if order(list3, list4) = 0 see "list3=list4" + nl
but order(list3, list4) < 0 see "list3<list4" + nl
else see "list3>list4" + nl ok
func order alist, blist
return strcmp(alist, blist)
Output:
list1<list2 list2>list3 list3=list4
RPL
RPL code | Comment |
---|---|
≪ → a b
≪ a SIZE b SIZE MIN LAST <
1 ROT FOR j
IF b j GET a j GET - THEN
LAST 0 > SWAP DROP
a SIZE 'j' STO
END
NEXT
≫ ≫ ‘GR8R?’ STO
|
GR8R? ( [reals] [reals] → boolean )
m = min(size(a),size(b)) ; res = (size(a)<size(b))
loop for j=1 to m
if b[j]-a[j] ≠ 0
res = (b[j]-a[j]>0)
break
end if
end loop, return res
.
|
[1 2 1 5 2] [1 2 1 5 2 2] GR8R? [1 2 1 5 2 2] [1 2 1 5 2] GR8R? [1 2 1 5 2 2] [1 2 3 4 5] GR8R? [1 2 3 4 5] [1 2 1 5 2 2] GR8R? [1 2 3 4 5] [1 2 3 4 5] GR8R?
- Output:
5: 1 4: 0 3: 1 2: 0 1: 0
Ruby
The built-in <=>
operator already does this:
>> ([1,2,1,3,2] <=> [1,2,0,4,4,0,0,0]) < 0
=> false
Rust
Vec<T>
implements Ord
when T
does, so we can just compare them with <
. (Same with arrays and slices).
vec![1, 2, 1, 3, 2] < vec![1, 2, 0, 4, 4, 0, 0, 0]
Scala
def lessThan1(a: List[Int], b: List[Int]): Boolean =
if (b.isEmpty) false
else if (a.isEmpty) true
else if (a.head != b.head) a.head < b.head
else lessThan1(a.tail, b.tail)
def lessThan2(a: List[Int], b: List[Int]): Boolean = (a, b) match {
case (_, Nil) => false
case (Nil, _) => true
case (a :: _, b :: _) if a != b => a < b
case _ => lessThan2(a.tail, b.tail)
}
def lessThan3(a: List[Int], b: List[Int]): Boolean =
a.zipAll(b, Integer.MIN_VALUE, Integer.MIN_VALUE)
.find{case (a, b) => a != b}
.map{case (a, b) => a < b}
.getOrElse(false)
val tests = List(
(List(1, 2, 3), List(1, 2, 3)) -> false,
(List(3, 2, 1), List(3, 2, 1)) -> false,
(List(1, 2, 3), List(3, 2, 1)) -> true,
(List(3, 2, 1), List(1, 2, 3)) -> false,
(List(1, 2), List(1, 2, 3)) -> true,
(List(1, 2, 3), List(1, 2)) -> false
)
tests.foreach{case test @ ((a, b), c) =>
assert(lessThan1(a, b) == c, test)
assert(lessThan2(a, b) == c, test)
assert(lessThan3(a, b) == c, test)
}
Scheme
(define (lex<? a b)
(cond ((null? b) #f)
((null? a) #t)
((= (car a) (car b)) (lex<? (cdr a) (cdr b)))
(else (< (car a) (car b)))))
Seed7
The operator corresponding to the ordering described in this example is less than.
$ include "seed7_05.s7i";
const proc: main is func
begin
writeln([] (1) < [] (1, 2)); # If the first list runs out of elements the result is TRUE.
writeln([] (1, 2) < [] (1)); # If the second list runs out of elements the result is FALSE.
writeln([] (1, 2) < [] (1, 2)); # If both lists run out of elements the result is FALSE.
writeln([] (1, 2, 3) < [] (1, 1, 3)); # The second element is greater than --> FALSE
writeln([] (1, 2, 3) < [] (1, 3, 3)); # The second element is less than --> TRUE
writeln(0 times 0 < [] (1)); # The empty list is less than any nonempty list --> TRUE
writeln([] (1) < 0 times 0); # Any nonempty list is not less than the empty list --> FALSE
writeln(0 times 0 < 0 times 0); # The empty list is not less than the empty list --> FALSE
end func;
- Output:
TRUE FALSE FALSE FALSE TRUE TRUE FALSE FALSE
Sidef
Built-in, via the comparison operator (`<=>`):
func ordered(a, b) {
(a <=> b) < 0
}
for p in [
Pair([1,2,4], [1,2,4]),
Pair([1,2,4], [1,2] ),
Pair([1,2], [1,2,4]),
] {
var a = p.first
var b = p.second
var before = ordered(a, b)
say "#{a} comes before #{b} : #{before}"
}
- Output:
[1, 2, 4] comes before [1, 2, 4] : false [1, 2, 4] comes before [1, 2] : false [1, 2] comes before [1, 2, 4] : true
Standard ML
- List.collate Int.compare ([1,2,1,3,2], [1,2,0,4,4,0,0,0]) = LESS;
val it = false : bool
Swift
let a = [1,2,1,3,2]
let b = [1,2,0,4,4,0,0,0]
println(lexicographicalCompare(a, b)) // this is "less than"
- Output:
false
Tcl
proc numlist< {A B} {
foreach a $A b $B {
if {$a<$b} {
return 1
} elseif {$a>$b} {
return 0
}
}
return 0
}
TUSCRIPT
$$ MODE TUSCRIPT
MODE DATA
$$ numlists=*
1'2'1'3'2
1'2'0'4'4'0'0'0
1'2'3'4'5
1'2'1'5'2'2
1'2'1'6
1'2'1'6'2
1'2'4
1'2'4
1'2
1'2'4
$$ MODE TUSCRIPT
list1="1'2'5'6'7"
LOOP n,list2=numlists
text=CONCAT (" ",list1," < ",list2)
IF (list1<list2) THEN
PRINT " true: ",text
ELSE
PRINT "false: ",text
ENDIF
list1=VALUE(list2)
ENDLOOP
- Output:
false: 1'2'5'6'7 < 1'2'1'3'2 false: 1'2'1'3'2 < 1'2'0'4'4'0'0'0 true: 1'2'0'4'4'0'0'0 < 1'2'3'4'5 false: 1'2'3'4'5 < 1'2'1'5'2'2 true: 1'2'1'5'2'2 < 1'2'1'6 true: 1'2'1'6 < 1'2'1'6'2 true: 1'2'1'6'2 < 1'2'4 false: 1'2'4 < 1'2'4 false: 1'2'4 < 1'2 true: 1'2 < 1'2'4
VBA
Private Function order(list1 As Variant, list2 As Variant) As Boolean
i = 1
Do While list1(i) <= list2(i)
i = i + 1
If i > UBound(list1) Then
order = True
Exit Function
End If
If i > UBound(list2) Then
order = False
Exit Function
End If
Loop
order = False
End Function
Public Sub main()
Debug.Print order([{1, 2, 3, 4}], [{1,2,0,1,2}])
Debug.Print order([{1, 2, 3, 4}], [{1,2,3}])
Debug.Print order([{1, 2, 3}], [{1,2,3,4}])
End Sub
- Output:
Onwaar Onwaar Waar
VBScript
Function order_list(arr1,arr2)
order_list = "FAIL"
n1 = UBound(arr1): n2 = UBound(arr2)
n = 0 : p = 0
If n1 > n2 Then
max = n2
Else
max = n1
End If
For i = 0 To max
If arr1(i) > arr2(i) Then
n = n + 1
ElseIf arr1(i) = arr2(i) Then
p = p + 1
End If
Next
If (n1 < n2 And n = 0) Or _
(n1 = n2 And n = 0 And p - 1 <> n1) Or _
(n1 > n2 And n = 0 And p = n2) Then
order_list = "PASS"
End If
End Function
WScript.StdOut.WriteLine order_list(Array(-1),Array(0))
WScript.StdOut.WriteLine order_list(Array(0),Array(0))
WScript.StdOut.WriteLine order_list(Array(0),Array(-1))
WScript.StdOut.WriteLine order_list(Array(0),Array(0,-1))
WScript.StdOut.WriteLine order_list(Array(0),Array(0,0))
WScript.StdOut.WriteLine order_list(Array(0),Array(0,1))
WScript.StdOut.WriteLine order_list(Array(0,-1),Array(0))
WScript.StdOut.WriteLine order_list(Array(0,0),Array(0))
WScript.StdOut.WriteLine order_list(Array(0,0),Array(1))
WScript.StdOut.WriteLine order_list(Array(1,2,1,3,2),Array(1,2,0,4,4,0,0,0))
- Output:
PASS FAIL FAIL PASS PASS PASS FAIL FAIL PASS FAIL
Wart
We'll simply overload <
for lists.
def (a < b) :case (or list?.a list?.b)
if not.b
nil
not.a
b
(car.a = car.b)
(cdr.a < cdr.b)
:else
(car.a < car.b)
- Output:
(< '(1 2 3) '(1 2 4)) => 4 (< '(1 2 4) '(1 2 3)) => nil (< '(1 2 3) '(1 2 3 4)) => (4) (< '(1 2 4) '(1 2 3 4)) => nil
Wren
var orderLists = Fn.new { |l1, l2|
var len = (l1.count <= l2.count) ? l1.count : l2.count
for (i in 0...len) {
if (l1[i] < l2[i]) return true
if (l1[i] > l2[i]) return false
}
return (l1.count < l2.count)
}
var lists = [
[1, 2, 3, 4, 5],
[1, 2, 1, 5, 2, 2],
[1, 2, 1, 5, 2],
[1, 2, 1, 5, 2],
[1, 2, 1, 3, 2],
[1, 2, 0, 4, 4, 0, 0, 0],
[1, 2, 0, 4, 4, 1, 0, 0],
[1, 2, 0, 4, 4, 1, 0, 1]
]
for (i in 0...lists.count) System.print("list[%(i)] : %(lists[i])")
System.print()
for (i in 0...lists.count-1) {
var res = orderLists.call(lists[i], lists[i+1])
System.print("list[%(i)] < list[%(i+1)] -> %(res)")
}
- Output:
list[0] : [1, 2, 3, 4, 5] list[1] : [1, 2, 1, 5, 2, 2] list[2] : [1, 2, 1, 5, 2] list[3] : [1, 2, 1, 5, 2] list[4] : [1, 2, 1, 3, 2] list[5] : [1, 2, 0, 4, 4, 0, 0, 0] list[6] : [1, 2, 0, 4, 4, 1, 0, 0] list[7] : [1, 2, 0, 4, 4, 1, 0, 1] list[0] < list[1] -> false list[1] < list[2] -> false list[2] < list[3] -> false list[3] < list[4] -> false list[4] < list[5] -> false list[5] < list[6] -> true list[6] < list[7] -> true
XPL0
\Compare lists (rows) of integers.
\Returns TRUE if there is an element in A that is < the corresponding
\ element in B and all previous elements are equal, FALSE otherwise.
\The bounds of A and B should ALB :: AUB and BLB :: BUB.
function ILT ( A, ALB, AUB, B, BLB, BUB );
integer A, ALB, AUB, B, BLB, BUB;
integer APos, BPos, Equal;
begin
APos := ALB;
BPos := BLB;
Equal := true;
while APos <= AUB and BPos <= BUB and Equal do begin
Equal := A( APos ) = B( BPos );
if Equal then begin
APos := APos + 1;
BPos := BPos + 1
end \if_Equal
end; \while_more_elements_and_Equal
if not Equal
then \there is an element in A and B that is not Equal
return A( APos ) < B( BPos )
else \all elements are Equal or one list is shorter
\A is < B if A has fewer elements
return APos > AUB and BPos <= BUB
end; \ILT
\Tests A < B has the expected result
procedure Test ( AName, A, ALB, AUB, BName, B, BLB, BUB, Expected );
integer AName, A, ALB, AUB, BName, B, BLB, BUB, Expected;
integer IsLt;
begin
IsLt := ILT( A, ALB, AUB, B, BLB, BUB );
Text(0, AName);
Text(0, if IsLt then " < " else " >= ");
Text(0, BName);
Text(0, if IsLt = Expected then " " else ", NOT as expected");
CrLf(0);
end; \test
integer List1, List2, List3, List4, List5, List6, List7, List8;
begin
\test cases as in the BBC basic sample
List1 := [0, 1, 2, 1, 5, 2];
List2 := [0, 1, 2, 1, 5, 2, 2];
List3 := [0, 1, 2, 3, 4, 5];
List4 := [0, 1, 2, 3, 4, 5];
Test( "List1", List1, 1, 5, "List2", List2, 1, 6, true );
Test( "List2", List2, 1, 6, "List3", List3, 1, 5, true );
Test( "List3", List3, 1, 5, "List4", List4, 1, 5, false );
\additional test cases
List5 := [0, 9, 0, 2, 1, 0];
List6 := [0, 4, 0, 7, 7];
List7 := [0, 4, 0, 7];
List8 := [0, 0];
Test( "List5", List5, 1, 5, "List6", List6, 1, 4, false );
Test( "List6", List6, 1, 4, "List7", List7, 1, 3, false );
Test( "List7", List7, 1, 3, "List8", List8, 1, 0, false );
Test( "List8", List8, 1, 0, "List7", List7, 1, 3, true )
end
- Output:
List1 < List2 List2 < List3 List3 >= List4 List5 >= List6 List6 >= List7 List7 >= List8 List8 < List7
Yabasic
read num : dim list1(4)
read num : dim list2(5)
read num : dim list3(4)
read num : dim list4(4)
if Orden(list1(), list2()) then print "list1 < list2" else print "list1 >= list2" : fi
if Orden(list2(), list3()) then print "list2 < list3" else print "list2 >= list3" : fi
if Orden(list3(), list4()) then print "list3 < list4" else print "list3 >= list4" : fi
end
sub Orden(listA(), listB())
i = 0
l1 = arraysize(listA(), 1)
l2 = arraysize(listB(), 1)
while listA(i) = listB(i) and i < l1 and i < l2
i = i + 1
wend
if listA(i) < listB(i) then return True : fi
if listA(i) > listB(i) then return False : fi
return l1 < l2
end sub
data 1, 2, 1, 5, 2
data 1, 2, 1, 5, 2, 2
data 1, 2, 3, 4, 5
data 1, 2, 3, 4, 5
- Output:
Igual que la entrada de BBC BASIC.
zkl
fcn listLT(a,b){
a.walker().zip(b).filter1(fcn([(a,b)]){ a<b }) : // lazy
if(_) return(True);;
a.len()<b.len()
}
- Output:
listLT(T(1,2,3),T(2,3,4)).println(); //-->True listLT(T(2,3,4),T(1,2,3)).println(); //-->False listLT(T(1,2),T(1,2,3,4)).println(); //-->True listLT(T(1,2,3,4),T(1,2,3)).println(); //-->False listLT(T(1,2,3),T(1,2,3)).println(); //-->False
- Programming Tasks
- Sorting Algorithms
- Solutions by Programming Task
- Classic CS problems and programs
- 11l
- AArch64 Assembly
- ACL2
- Action!
- Ada
- ALGOL 68
- ALGOL W
- Aime
- AppleScript
- ARM Assembly
- Arturo
- AutoHotkey
- AWK
- BASIC256
- BBC BASIC
- Bracmat
- C
- C sharp
- C++
- Clojure
- Common Lisp
- D
- Delphi
- System.SysUtils
- System.Generics.Defaults
- EasyLang
- Ela
- Elixir
- Erlang
- F Sharp
- Factor
- FreeBASIC
- Go
- Groovy
- Haskell
- Icon
- Unicon
- J
- Java
- JavaScript
- Joy
- Jq
- Julia
- Klingphix
- Kotlin
- LabVIEW
- Lasso
- Lhogho
- Lua
- Maple
- Mathematica
- Wolfram Language
- Maxima
- Mercury
- Miranda
- Nim
- Nu
- OCaml
- Oforth
- Ol
- PARI/GP
- Perl
- Phix
- Phixmonti
- Picat
- PicoLisp
- Pike
- PL/I
- PowerShell
- PureBasic
- Python
- Quackery
- Racket
- Raku
- Rascal
- REXX
- Ring
- RPL
- Ruby
- Rust
- Scala
- Scheme
- Seed7
- Sidef
- Standard ML
- Swift
- Tcl
- TUSCRIPT
- VBA
- VBScript
- Wart
- Wren
- XPL0
- Yabasic
- Zkl