Sort primes from list to a list: Difference between revisions
Thundergnat (talk | contribs) m syntax highlighting fixup automation |
Added Quackery. |
||
Line 447: | Line 447: | ||
{{Out}} |
{{Out}} |
||
<pre>[2, 7, 13, 43, 103]</pre> |
<pre>[2, 7, 13, 43, 103]</pre> |
||
=={{header|Quackery}}== |
|||
<code>eratosthenes</code> and <code>isprime</code> are defined at [[Sieve of Eratosthenes#Quackery]]. |
|||
<syntaxhighlight lang="Quackery"> ' [ 2 43 81 122 63 13 7 95 103 ] |
|||
sort |
|||
dup -1 peek eratosthenes |
|||
[] swap witheach |
|||
[ dup isprime iff join else drop ] |
|||
echo</syntaxhighlight> |
|||
{{out}} |
|||
<pre>[ 2 7 13 43 103 ]</pre> |
|||
=={{header|Raku}}== |
=={{header|Raku}}== |
Revision as of 00:31, 24 October 2022
- Task
Let given list:
Primes = [2,43,81,122,63,13,7,95,103]
Show on this page the ascending ordered list of primes from given list.
ALGOL 68
BEGIN # extract the elements of a list that are prime and sort them #
PR read "primes.incl.a68" PR # include prime utilities #
PR read "rows.incl.a68" PR # include row (array) utilities #
# list of numbers required by the task #
[]INT list = ( 2, 43, 81, 122, 63, 13, 7, 95, 103 );
[ 1 : UPB list ]INT prime list;
# count the nunber of primes in list and assign the primes to prime list #
INT p count := 0;
FOR i TO UPB list DO
IF is probably prime( list[ i ] ) THEN
# have a prime #
prime list[ p count +:= 1 ] := list[ i ]
FI
OD;
print( ( "prime elements of: " ) );
SHOW list;
print( ( newline, " are: " ) );
SHOW ( QUICKSORT prime list FROMELEMENT 1 TOELEMENT p count )[ 1 : p count ]
END
- Output:
Prime elements of: 2 43 81 122 63 13 7 95 103 are: 2 7 13 43 103
AutoHotkey
Primes := [2,43,81,122,63,13,7,95,103]
t := [], result := []
for i, n in Primes
if isPrime(n)
t[n, i] := true
for n, obj in t
for i, v in obj
result.push(n)
isPrime(n){
Loop, % floor(sqrt(n))
v := A_Index = 1 ? n : mod(n,A_Index) ? v : v "," A_Index "," n//A_Index
Return (v = n)
}
- Output:
[2, 7, 13, 43, 103]
AWK
# syntax: GAWK -f SORT_PRIMES_FROM_LIST_TO_A_LIST.AWK
BEGIN {
PROCINFO["sorted_in"] = "@val_num_asc"
split("2,43,81,122,63,13,7,95,103",arr,",")
for (i in arr) {
if (is_prime(arr[i])) {
printf("%d ",arr[i])
}
}
printf("\n")
exit(0)
}
function is_prime(n, d) {
d = 5
if (n < 2) { return(0) }
if (n % 2 == 0) { return(n == 2) }
if (n % 3 == 0) { return(n == 3) }
while (d*d <= n) {
if (n % d == 0) { return(0) }
d += 2
if (n % d == 0) { return(0) }
d += 4
}
return(1)
}
- Output:
2 7 13 43 103
BASIC
BASIC256
arraybase 1
global temp
function isPrime(v)
if v < 2 then return False
if v mod 2 = 0 then return v = 2
if v mod 3 = 0 then return v = 3
d = 5
while d * d <= v
if v mod d = 0 then return False else d += 2
end while
return True
end function
subroutine sort(array)
for i = 1 to array[?]
for j = i + 1 to array[?]
if temp[i] > temp[j] then
t = temp[i] : temp[i] = temp[j] : temp[j] = t
end if
next j
next i
end subroutine
subroutine showArray(array)
txt$ = ""
print "[";
for n = 1 to array[?]
txt$ &= string(array[n]) & ","
next n
txt$ = left(txt$,length(txt$)-1)
txt$ &= "]"
print txt$
end subroutine
dim Primes(9)
Primes[1] = 2
Primes[2] = 43
Primes[3] = 81
Primes[4] = 122
Primes[5] = 63
Primes[6] = 13
Primes[7] = 7
Primes[8] = 95
Primes[9] = 103
c = 1
for n = 1 to Primes[?]
if isprime(Primes[n]) then
redim temp(c)
temp[c] = Primes[n]
c += 1
end if
next n
call sort(temp)
call showArray(temp)
end
- Output:
Igual que la entrada de FreeBASIC.
FreeBASIC
Dim Shared As Integer temp()
Function isPrime(Byval ValorEval As Integer) As Boolean
If ValorEval <= 1 Then Return False
For i As Integer = 2 To Int(Sqr(ValorEval))
If ValorEval Mod i = 0 Then Return False
Next i
Return True
End Function
Sub sort(array() As Integer)
For i As Integer = Lbound(array) To Ubound(array)
For j As Integer = i + 1 To Ubound(array)
If temp(i) > temp(j) Then Swap temp(i), temp(j)
Next j
Next i
End Sub
Sub showArray(array() As Integer)
Dim As String txt = ""
Print "[";
For n As Integer = Lbound(array) To Ubound(array)
txt &= Str(array(n)) & ","
Next n
txt = Left(txt,Len(txt)-1)
txt &= "]"
Print txt
End Sub
Dim As Integer Primes(1 To 9) = {2,43,81,122,63,13,7,95,103}
Dim As Integer c = 0
For n As Integer = Lbound(Primes) To Ubound(Primes)
If isprime(Primes(n)) Then
Redim Preserve temp(c)
temp(c) = Primes(n)
c += 1
End If
Next n
sort(temp())
showArray(temp())
Sleep
- Output:
[2,7,13,43,103]
Yabasic
dim Primes(9)
Primes(1) = 2
Primes(2) = 43
Primes(3) = 81
Primes(4) = 122
Primes(5) = 63
Primes(6) = 13
Primes(7) = 7
Primes(8) = 95
Primes(9) = 103
c = 1
for n = 1 to arraysize(Primes(),1)
if isPrime(Primes(n)) then
redim temp(c)
temp(c) = Primes(n)
c = c + 1
end if
next n
sort(temp)
showArray(temp)
end
sub isPrime(v)
if v < 2 then return False : fi
if mod(v, 2) = 0 then return v = 2 : fi
if mod(v, 3) = 0 then return v = 3 : fi
d = 5
while d * d <= v
if mod(v, d) = 0 then return False else d = d + 2 : fi
wend
return True
end sub
sub sort(array)
for i = 1 to arraysize(temp(),1)
for j = i + 1 to arraysize(temp(),1)
if temp(i) > temp(j) then
t = temp(i) : temp(i) = temp(j) : temp(j) = t
end if
next j
next i
end sub
sub showArray(array)
local txt$ //= ""
print "[";
for n = 1 to arraysize(temp(),1)
txt$ = txt$ + str$(temp(n)) + ","
next n
txt$ = left$(txt$,len(txt$)-1)
txt$ = txt$ + "]"
print txt$
end sub
- Output:
Igual que la entrada de FreeBASIC.
F#
This task uses Extensible Prime Generator (F#)
// Primes from a list. Nigel Galloway: Januuary 23rd., 2022
[2;43;81;122;63;13;7;95;103]|>List.filter isPrime|>List.sort|>List.iter(printf "%d "); printfn ""
- Output:
2 7 13 43 103
Factor
USING: math.primes prettyprint sequences sorting ;
{ 2 43 81 122 63 13 7 95 103 } [ prime? ] filter natural-sort .
- Output:
{ 2 7 13 43 103 }
Go
package main
import (
"fmt"
"rcu"
"sort"
)
func main() {
list := []int{2, 43, 81, 122, 63, 13, 7, 95, 103}
var primes []int
for _, e := range list {
if rcu.IsPrime(e) {
primes = append(primes, e)
}
}
sort.Ints(primes)
fmt.Println(primes)
}
- Output:
[2 7 13 43 103]
J
This is a filter (on primality) and a sort (though we could first sort then filter if we preferred):
/:~ (#~ 1&p:)2,43,81,122,63,13,7,95,103
2 7 13 43 103
jq
Works with gojq, the Go implementation of jq
See Erdős-primes#jq for a suitable definition of `is_prime` as used here.
def lst: [2, 43, 81, 122, 63, 13, 7, 95, 103];
lst | map( select(is_prime) ) | sort
- Output:
[2,7,13,43,103]
Julia
julia> using Primes
julia> sort(filter(isprime, [2,43,81,122,63,13,7,95,103]))
5-element Vector{Int64}:
2
7
13
43
103
Mathematica /Wolfram Language
Sort[Select[{2, 43, 81, 122, 63, 13, 7, 95, 103}, PrimeQ]]
- Output:
{2, 7, 13, 43, 103}
Perl
#!/usr/bin/perl
use strict; # https://rosettacode.org/wiki/Sort_primes_from_list_to_a_list
use warnings;
use ntheory qw( is_prime );
use List::AllUtils qw( nsort_by );
print "@{[ nsort_by {$_} grep is_prime($_), 2,43,81,122,63,13,7,95,103 ]}\n";
- Output:
2 7 13 43 103
Phix
You could also use unique() instead of sort(), since that (by default) performs a sort() internally anyway. It wouldn't be any slower, might even be better, also it does not really make much difference here whether you filter() before or after the sort(), though of course some more expensive filtering operations might be faster given fewer items.
with javascript_semantics pp(sort(filter({2,43,81,122,63,13,7,95,103},is_prime)))
- Output:
{2,7,13,43,103}
Python
Python: Procedural
print("working...")
print("Primes are:")
def isprime(m):
for i in range(2,int(m**0.5)+1):
if m%i==0:
return False
return True
Primes = [2,43,81,122,63,13,7,95,103]
Temp = []
for n in range(len(Primes)):
if isprime(Primes[n]):
Temp.append(Primes[n])
Temp.sort()
print(Temp)
print("done...")
- Output:
working... Primes are: [2, 7, 13, 43, 103] done...
Python: Functional
'''Prime elements in rising order'''
# primeElementsSorted :: [Int] -> [Int]
def primeElementsSorted(xs):
'''The prime elements of xs in rising order'''
return sorted(x for x in xs if isPrime(x))
# ------------------------- TEST -------------------------
# main :: IO ()
def main():
'''Filtered elements of given list in rising order'''
print(
primeElementsSorted([
2, 43, 81, 122, 63, 13, 7, 95, 103
])
)
# ----------------------- GENERIC ------------------------
# isPrime :: Int -> Bool
def isPrime(n):
'''True if n is prime.'''
if n in (2, 3):
return True
if 2 > n or 0 == n % 2:
return False
if 9 > n:
return True
if 0 == n % 3:
return False
def p(x):
return 0 == n % x or 0 == n % (2 + x)
return not any(map(p, range(5, 1 + int(n ** 0.5), 6)))
# MAIN ---
if __name__ == '__main__':
main()
- Output:
[2, 7, 13, 43, 103]
Quackery
eratosthenes
and isprime
are defined at Sieve of Eratosthenes#Quackery.
' [ 2 43 81 122 63 13 7 95 103 ]
sort
dup -1 peek eratosthenes
[] swap witheach
[ dup isprime iff join else drop ]
echo
- Output:
[ 2 7 13 43 103 ]
Raku
put <2 43 81 122 63 13 7 95 103>.grep( &is-prime ).sort
- Output:
2 7 13 43 103
Of course "ascending" is a little ambiguous. That ^^^ is numerically. This vvv is lexicographically.
put <2 43 81 122 63 13 7 95 103>.grep( &is-prime ).sort: ~*
- Output:
103 13 2 43 7
Ring
load "stdlibcore.ring"
? "working"
Primes = [2,43,81,122,63,13,7,95,103]
Temp = []
for n = 1 to len(Primes)
if isprime(Primes[n])
add(Temp,Primes[n])
ok
next
Temp = sort(Temp)
showarray(Temp)
? "done..."
func showArray(array)
txt = ""
see "["
for n = 1 to len(array)
txt = txt + array[n] + ","
next
txt = left(txt,len(txt)-1)
txt = txt + "]"
? txt
- Output:
working Primes are: [2,7,13,43,103] done...
Sidef
var arr = [2,43,81,122,63,13,7,95,103]
say arr.grep{.is_prime}.sort
- Output:
[2, 7, 13, 43, 103]
Wren
import "./math" for Int
var lst = [2, 43, 81, 122, 63, 13, 7, 95, 103]
System.print(lst.where { |e| Int.isPrime(e) }.toList.sort())
- Output:
[2, 7, 13, 43, 103]
XPL0
include xpllib;
int Primes, Smallest, I, SI;
def Len=9, Inf=1000;
[Primes:= [2,43,81,122,63,13,7,95,103];
repeat Smallest:= Inf;
for I:= 0 to Len-1 do
if Primes(I) < Smallest then
[Smallest:= Primes(I); SI:= I];
Primes(SI):= Inf; \cross off
if IsPrime(Smallest) then
[IntOut(0, Smallest); ChOut(0, ^ )];
until Smallest = Inf;
]
- Output:
2 7 13 43 103