Data update
This commit is contained in:
parent
07c7092a52
commit
61b93a2cd1
313 changed files with 6160 additions and 346 deletions
8
Task/ABC-problem/Insitux/abc-problem.insitux
Normal file
8
Task/ABC-problem/Insitux/abc-problem.insitux
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
(var find-idx #(when (let found (find % %1)) (idx %1 found)))
|
||||
(function in-block? c (when (let block-idx (find-idx (substr? (upper-case c)) rem-blocks)) (var! rem-blocks drop block-idx)))
|
||||
|
||||
(function can-make-word word
|
||||
(var rem-blocks ["BO" "XK" "DQ" "CP" "NA" "GT" "RE" "TG" "QD" "FS" "JW" "HU" "VI" "AN" "OB" "ER" "FS" "LY" "PC" "ZM"])
|
||||
(.. and (map in-block? word)))
|
||||
|
||||
(join ", " (map #(str % " => " (can-make-word %)) ["A" "bark" "Book" "TREAT" "Common" "squaD" "CoNFuSe"])) ; Notice case insensitivity
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
(load "@lib/simul.l")
|
||||
(symbols 'simul 'pico)
|
||||
(de sandpile (A B)
|
||||
(let
|
||||
(Grid (grid A A)
|
||||
Size (/ (inc A) 2)
|
||||
Center (get Grid Size Size)
|
||||
Done T )
|
||||
(for G Grid
|
||||
(for This G
|
||||
(=: V 0) ) )
|
||||
(with Center
|
||||
(=: V B)
|
||||
(while Done
|
||||
(off Done)
|
||||
(for G Grid
|
||||
(for This G
|
||||
(when (>= (: V) 4)
|
||||
(=: V (- (: V) 4))
|
||||
(on Done)
|
||||
(mapc
|
||||
'((Dir)
|
||||
(with (Dir This) (=: V (inc (: V)))) )
|
||||
'(north south west east) ) ) ) ) ) )
|
||||
(disp Grid 0
|
||||
'((This) (if (: V) (pack " " @ " ") " ")) ) ) )
|
||||
(sandpile 10 64)
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
deficient = 0
|
||||
perfect = 0
|
||||
abundant = 0
|
||||
|
||||
for n = 1 to 20000
|
||||
sum = SumProperDivisors(n)
|
||||
begin case
|
||||
case sum < n
|
||||
deficient += 1
|
||||
case sum = n
|
||||
perfect += 1
|
||||
else
|
||||
abundant += 1
|
||||
end case
|
||||
next
|
||||
|
||||
print "The classification of the numbers from 1 to 20,000 is as follows :"
|
||||
print
|
||||
print "Deficient = "; deficient
|
||||
print "Perfect = "; perfect
|
||||
print "Abundant = "; abundant
|
||||
end
|
||||
|
||||
function SumProperDivisors(number)
|
||||
if number < 2 then return 0
|
||||
sum = 0
|
||||
for i = 1 to number \ 2
|
||||
if number mod i = 0 then sum += i
|
||||
next i
|
||||
return sum
|
||||
end function
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
100 cls
|
||||
110 defic = 0
|
||||
120 perfe = 0
|
||||
130 abund = 0
|
||||
140 for n = 1 to 20000
|
||||
150 sump = SumProperDivisors(n)
|
||||
160 if sump < n then
|
||||
170 defic = defic+1
|
||||
180 else
|
||||
190 if sump = n then
|
||||
200 perfe = perfe+1
|
||||
210 else
|
||||
220 if sump > n then abund = abund+1
|
||||
230 endif
|
||||
240 endif
|
||||
250 next
|
||||
260 print "The classification of the numbers from 1 to 20,000 is as follows :"
|
||||
270 print
|
||||
280 print "Deficient = ";defic
|
||||
290 print "Perfect = ";perfe
|
||||
300 print "Abundant = ";abund
|
||||
310 end
|
||||
320 function SumProperDivisors(number)
|
||||
330 if number < 2 then SumProperDivisors = 0
|
||||
340 sum = 0
|
||||
350 for i = 1 to number/2
|
||||
360 if number mod i = 0 then sum = sum+i
|
||||
370 next i
|
||||
380 SumProperDivisors = sum
|
||||
390 end function
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
local fn SumProperDivisors( number as long ) as long
|
||||
long i, result, sum = 0
|
||||
|
||||
if number < 2 then exit fn = 0
|
||||
for i = 1 to number / 2
|
||||
if number mod i == 0 then sum += i
|
||||
next
|
||||
result = sum
|
||||
end fn = result
|
||||
|
||||
void local fn NumberCategories( limit as long )
|
||||
long i, sum, deficient = 0, perfect = 0, abundant = 0
|
||||
|
||||
for i = 1 to limit
|
||||
sum = fn SumProperDivisors(i)
|
||||
if sum < i then deficient++ : continue
|
||||
if sum == i then perfect++ : continue
|
||||
abundant++
|
||||
next
|
||||
printf @"\nClassification of integers from 1 to %ld is:\n", limit
|
||||
printf @"Deficient = %ld\nPerfect = %ld\nAbundant = %ld", deficient, perfect, abundant
|
||||
printf @"-----------------\nTotal = %ld\n", deficient + perfect + abundant
|
||||
end fn
|
||||
|
||||
CFTimeInterval t
|
||||
t = fn CACurrentMediaTime
|
||||
fn NumberCategories( 20000 )
|
||||
printf @"Compute time: %.3f ms",(fn CACurrentMediaTime-t)*1000
|
||||
|
||||
HandleEvents
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
Public Sub Main()
|
||||
|
||||
Dim sum As Integer, deficient As Integer, perfect As Integer, abundant As Integer
|
||||
|
||||
For n As Integer = 1 To 20000
|
||||
sum = SumProperDivisors(n)
|
||||
If sum < n Then
|
||||
deficient += 1
|
||||
Else If sum = n Then
|
||||
perfect += 1
|
||||
Else
|
||||
abundant += 1
|
||||
Endif
|
||||
Next
|
||||
|
||||
Print "The classification of the numbers from 1 to 20,000 is as follows : \n"
|
||||
Print "Deficient = "; deficient
|
||||
Print "Perfect = "; perfect
|
||||
Print "Abundant = "; abundant
|
||||
|
||||
End
|
||||
|
||||
Function SumProperDivisors(number As Integer) As Integer
|
||||
|
||||
If number < 2 Then Return 0
|
||||
Dim sum As Integer = 0
|
||||
For i As Integer = 1 To number \ 2
|
||||
If number Mod i = 0 Then sum += i
|
||||
Next
|
||||
Return sum
|
||||
|
||||
End Function
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
function sumProperDivisors(num)
|
||||
if num > 1 then
|
||||
sum = 1
|
||||
root = sqr(num)
|
||||
for i = 2 to root
|
||||
if num mod i = 0 then
|
||||
sum = sum + i
|
||||
if (i*i) <> num then sum = sum + num / i
|
||||
end if
|
||||
next i
|
||||
end if
|
||||
sumProperDivisors = sum
|
||||
end function
|
||||
|
||||
deficient = 0
|
||||
perfect = 0
|
||||
abundant = 0
|
||||
|
||||
print "The classification of the numbers from 1 to 20,000 is as follows :"
|
||||
|
||||
for n = 1 to 20000
|
||||
sump = sumProperDivisors(n)
|
||||
if sump < n then
|
||||
deficient = deficient +1
|
||||
else
|
||||
if sump = n then
|
||||
perfect = perfect +1
|
||||
else
|
||||
if sump > n then abundant = abundant +1
|
||||
end if
|
||||
end if
|
||||
next n
|
||||
|
||||
print "Deficient = "; deficient
|
||||
print "Perfect = "; perfect
|
||||
print "Abundant = "; abundant
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
LET lm = 20000
|
||||
DIM s(0)
|
||||
MAT REDIM s(lm)
|
||||
|
||||
FOR i = 1 TO lm
|
||||
LET s(i) = -32767
|
||||
NEXT i
|
||||
FOR i = 1 TO lm/2
|
||||
FOR j = i+i TO lm STEP i
|
||||
LET s(j) = s(j) +i
|
||||
NEXT j
|
||||
NEXT i
|
||||
|
||||
FOR i = 1 TO lm
|
||||
LET x = i - 32767
|
||||
IF s(i) < x THEN
|
||||
LET d = d +1
|
||||
ELSE
|
||||
IF s(i) = x THEN
|
||||
LET p = p +1
|
||||
ELSE
|
||||
LET a = a +1
|
||||
END IF
|
||||
END IF
|
||||
NEXT i
|
||||
|
||||
PRINT "The classification of the numbers from 1 to 20,000 is as follows :"
|
||||
PRINT
|
||||
PRINT "Deficient ="; d
|
||||
PRINT "Perfect ="; p
|
||||
PRINT "Abundant ="; a
|
||||
END
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
100 for m = 0 to 4
|
||||
110 print using "###";m;
|
||||
120 for n = 0 to 6
|
||||
130 if m = 4 and n = 1 then goto 160
|
||||
140 print using "######";ack(m,n);
|
||||
150 next n
|
||||
160 print
|
||||
170 next m
|
||||
180 end
|
||||
190 sub ack(m,n)
|
||||
200 if m = 0 then ack = n+1
|
||||
210 if m > 0 and n = 0 then ack = ack(m-1,1)
|
||||
220 if m > 0 and n > 0 then ack = ack(m-1,ack(m,n-1))
|
||||
230 end sub
|
||||
18
Task/Ackermann-function/True-BASIC/ackermann-function.basic
Normal file
18
Task/Ackermann-function/True-BASIC/ackermann-function.basic
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
FUNCTION ack(m, n)
|
||||
IF m = 0 THEN LET ack = n+1
|
||||
IF m > 0 AND n = 0 THEN LET ack = ack(m-1, 1)
|
||||
IF m > 0 AND n > 0 THEN LET ack = ack(m-1, ack(m, n-1))
|
||||
END FUNCTION
|
||||
|
||||
FOR m = 0 TO 4
|
||||
PRINT USING "###": m;
|
||||
FOR n = 0 TO 8
|
||||
! A(4, 1) OR higher will RUN OUT of stack memory (default 1M)
|
||||
! change n = 1 TO n = 2 TO calculate A(4, 2), increase stack!
|
||||
IF m = 4 AND n = 1 THEN EXIT FOR
|
||||
PRINT USING "######": ack(m, n);
|
||||
NEXT n
|
||||
PRINT
|
||||
NEXT m
|
||||
|
||||
END
|
||||
|
|
@ -2,24 +2,24 @@ import extensions;
|
|||
|
||||
class Extender : BaseExtender
|
||||
{
|
||||
prop object foo;
|
||||
object foo : prop;
|
||||
|
||||
constructor(object)
|
||||
{
|
||||
theObject := object
|
||||
}
|
||||
constructor(object)
|
||||
{
|
||||
this object := object
|
||||
}
|
||||
}
|
||||
|
||||
public program()
|
||||
{
|
||||
var object := 234;
|
||||
var object := 234;
|
||||
|
||||
// extending an object with a field
|
||||
object := new Extender(object);
|
||||
// extending an object with a field
|
||||
object := new Extender(object);
|
||||
|
||||
object.foo := "bar";
|
||||
object.foo := "bar";
|
||||
|
||||
console.printLine(object,".foo=",object.foo);
|
||||
console.printLine(object,".foo=",object.foo);
|
||||
|
||||
console.readChar()
|
||||
console.readChar()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,6 +2,8 @@ import system'routines;
|
|||
import extensions;
|
||||
import extensions'routines;
|
||||
|
||||
// --- Joinable --
|
||||
|
||||
joinable(former,later) = (former[former.Length - 1] == later[0]);
|
||||
|
||||
dispatcher = new
|
||||
|
|
@ -27,25 +29,27 @@ dispatcher = new
|
|||
}
|
||||
};
|
||||
|
||||
// --- AmbValueCollection ---
|
||||
|
||||
class AmbValueCollection
|
||||
{
|
||||
object theCombinator;
|
||||
object _combinator;
|
||||
|
||||
constructor new(params object[] args)
|
||||
{
|
||||
theCombinator := SequentialEnumerator.new(params args)
|
||||
_combinator := SequentialEnumerator.new(params args)
|
||||
}
|
||||
|
||||
seek(cond)
|
||||
{
|
||||
theCombinator.reset();
|
||||
_combinator.reset();
|
||||
|
||||
theCombinator.seekEach:(v => dispatcher.eval(v,cond))
|
||||
_combinator.seekEach:(v => dispatcher.eval(v,cond))
|
||||
}
|
||||
|
||||
do(f)
|
||||
{
|
||||
var result := theCombinator.get();
|
||||
var result := *_combinator;
|
||||
if (nil != result)
|
||||
{
|
||||
dispatcher.eval(result,f)
|
||||
|
|
@ -57,12 +61,16 @@ class AmbValueCollection
|
|||
}
|
||||
}
|
||||
|
||||
// --- ambOperator ---
|
||||
|
||||
singleton ambOperator
|
||||
{
|
||||
for(params object[] args)
|
||||
= AmbValueCollection.new(params args);
|
||||
}
|
||||
|
||||
// --- Program ---
|
||||
|
||||
public program()
|
||||
{
|
||||
try
|
||||
|
|
|
|||
10
Task/Amb/Insitux/amb.insitux
Normal file
10
Task/Amb/Insitux/amb.insitux
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
(function amb op res
|
||||
(filter #(= res (.. .. op args))
|
||||
(.. for vec (skip 2 args))))
|
||||
|
||||
(var safe= @(= (0 args)))
|
||||
(var predicate (comp vec (map (juxt 0 -1)) flatten (skip 1) (partition 2) (map (.. safe=)) (.. and)))
|
||||
|
||||
(amb predicate true ["the" "that" "a"] ["frog" "elephant" "thing"] ["walked" "treaded" "grows"] ["slowly" "quickly"])
|
||||
|
||||
;returns [["that" "thing" "grows" "slowly"]]
|
||||
|
|
@ -2,7 +2,7 @@ begin
|
|||
|
||||
comment - return n mod m;
|
||||
integer procedure mod(n, m);
|
||||
value n, q; integer n, m;
|
||||
value n, m; integer n, m;
|
||||
begin
|
||||
mod := n - m * entier(n / m);
|
||||
end;
|
||||
|
|
|
|||
|
|
@ -7,11 +7,12 @@ BEGIN # find amicable pairs p1, p2 where each is equal to the other's proper div
|
|||
OD
|
||||
OD;
|
||||
# find the amicable pairs up to 20 000 #
|
||||
FOR p1 TO UPB pd sum DO
|
||||
FOR p2 FROM p1 + 1 TO UPB pd sum DO
|
||||
IF pd sum[ p1 ] = p2 AND pd sum[ p2 ] = p1 THEN
|
||||
print( ( whole( p1, -6 ), " and ", whole( p2, -6 ), " are an amicable pair", newline ) )
|
||||
FOR p1 TO UPB pd sum - 1 DO
|
||||
INT pd sum p1 = pd sum[ p1 ];
|
||||
IF pd sum p1 > p1 AND pd sum p1 <= UPB pd sum THEN
|
||||
IF pd sum[ pd sum p1 ] = p1 THEN
|
||||
print( ( whole( p1, -6 ), " and ", whole( pd sum p1, -6 ), " are an amicable pair", newline ) )
|
||||
FI
|
||||
OD
|
||||
FI
|
||||
OD
|
||||
END
|
||||
|
|
|
|||
23
Task/Amicable-pairs/ALGOL-W/amicable-pairs.alg
Normal file
23
Task/Amicable-pairs/ALGOL-W/amicable-pairs.alg
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
begin % find amicable pairs p1, p2 where each is equal to the other's %
|
||||
% proper divisor sum %
|
||||
|
||||
integer MAX_NUMBER;
|
||||
MAX_NUMBER := 20000;
|
||||
|
||||
begin
|
||||
integer array pdSum( 1 :: MAX_NUMBER ); % table of proper divisors %
|
||||
for i := 1 until MAX_NUMBER do pdSum( i ) := 1;
|
||||
for i := 2 until MAX_NUMBER do begin
|
||||
for j := i + i step i until MAX_NUMBER do pdSum( j ) := pdSum( j ) + i
|
||||
end for_i ;
|
||||
|
||||
% find the amicable pairs up to 20 000 %
|
||||
for p1 := 1 until MAX_NUMBER - 1 do begin
|
||||
integer pdSumP1;
|
||||
pdSumP1 := pdSum( p1 );
|
||||
if pdSumP1 > p1 and pdSumP1 <= MAX_NUMBER and pdSum( pdSumP1 ) = p1 then begin
|
||||
write( i_w := 5, s_w := 0, p1, " and ", pdSumP1, " are an amicable pair" )
|
||||
end if_pdSumP1_gt_p1_and_le_MAX_NUMBER
|
||||
end for_p1
|
||||
end
|
||||
end.
|
||||
20
Task/Amicable-pairs/Chipmunk-Basic/amicable-pairs.basic
Normal file
20
Task/Amicable-pairs/Chipmunk-Basic/amicable-pairs.basic
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
100 cls : rem 10 HOME for Applesoft BASIC
|
||||
110 print "The pairs of amicable numbers below 20,000 are :"
|
||||
120 print
|
||||
130 size = 18500
|
||||
140 for n = 1 to size
|
||||
150 m = amicable(n)
|
||||
160 if m > n and amicable(m) = n then
|
||||
170 print using "#####";n;
|
||||
180 print " and ";
|
||||
190 print using "#####";m
|
||||
200 endif
|
||||
210 next
|
||||
220 end
|
||||
230 function amicable(nr)
|
||||
240 suma = 1
|
||||
250 for d = 2 to sqr(nr)
|
||||
260 if nr mod d = 0 then suma = suma+d+nr/d
|
||||
270 next
|
||||
280 amicable = suma
|
||||
290 end function
|
||||
29
Task/Amicable-pairs/FutureBasic/amicable-pairs.basic
Normal file
29
Task/Amicable-pairs/FutureBasic/amicable-pairs.basic
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
local fn Sigma( n as long ) as long
|
||||
long i, root, sum = 1
|
||||
|
||||
if n == 1 then exit fn = 0
|
||||
root = sqr(n)
|
||||
for i = 2 to root
|
||||
if ( n mod i == 0 ) then sum += i + n/i
|
||||
next
|
||||
if root * root == n then sum -= root
|
||||
end fn = sum
|
||||
|
||||
void local fn CalculateAmicablePairs( limit as long )
|
||||
long i, m
|
||||
|
||||
printf @"\nAmicable pairs through %ld are:\n", limit
|
||||
for i = 2 to limit
|
||||
m = fn Sigma(i)
|
||||
if ( m > i )
|
||||
if ( fn Sigma(m) == i ) then printf @"%6ld and %ld", i, m
|
||||
end if
|
||||
next
|
||||
end fn
|
||||
|
||||
CFTimeInterval t
|
||||
t = fn CACurrentMediaTime
|
||||
fn CalculateAmicablePairs( 20000 )
|
||||
printf @"\nCompute time: %.3f ms",(fn CACurrentMediaTime-t)*1000
|
||||
|
||||
HandleEvents
|
||||
33
Task/Amicable-pairs/Gambas/amicable-pairs.gambas
Normal file
33
Task/Amicable-pairs/Gambas/amicable-pairs.gambas
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
Public sum[19999] As Integer
|
||||
|
||||
Public Sub Main()
|
||||
|
||||
Dim n As Integer, f As Integer
|
||||
|
||||
For n = 0 To 19998
|
||||
sum[n] = SumProperDivisors(n)
|
||||
Next
|
||||
|
||||
Print "The pairs of amicable numbers below 20,000 are :\n"
|
||||
|
||||
For n = 0 To 19998
|
||||
' f = SumProperDivisors(n)
|
||||
f = sum[n]
|
||||
If f <= n Or f < 1 Or f > 19999 Then Continue
|
||||
If f = sum[n] And n = sum[f] Then
|
||||
Print Format$(Str$(n), "#####"); " And "; Format$(Str$(sum[n]), "#####")
|
||||
End If
|
||||
Next
|
||||
|
||||
End
|
||||
|
||||
Function SumProperDivisors(number As Integer) As Integer
|
||||
|
||||
If number < 2 Then Return 0
|
||||
Dim sum As Integer = 0
|
||||
For i As Integer = 1 To number \ 2
|
||||
If number Mod i = 0 Then sum += i
|
||||
Next
|
||||
Return sum
|
||||
|
||||
End Function
|
||||
15
Task/Amicable-pairs/Lua/amicable-pairs-2.lua
Normal file
15
Task/Amicable-pairs/Lua/amicable-pairs-2.lua
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
MAX_NUMBER = 20000
|
||||
sumDivs = {} -- table of proper divisors
|
||||
for i = 1, MAX_NUMBER do sumDivs[ i ] = 1 end
|
||||
for i = 2, MAX_NUMBER do
|
||||
for j = i + i, MAX_NUMBER, i do
|
||||
sumDivs[ j ] = sumDivs[ j ] + i
|
||||
end
|
||||
end
|
||||
|
||||
for n = 2, MAX_NUMBER do
|
||||
m = sumDivs[n]
|
||||
if m > n then
|
||||
if sumDivs[m] == n then print(n, m) end
|
||||
end
|
||||
end
|
||||
17
Task/Amicable-pairs/MiniScript/amicable-pairs.mini
Normal file
17
Task/Amicable-pairs/MiniScript/amicable-pairs.mini
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
// find amicable pairs p1, p2 where each is equal to the other's proper divisor sum
|
||||
|
||||
MAX_NUMBER = 20000
|
||||
pdSum = [1] * ( MAX_NUMBER + 1 ) // table of proper divisors
|
||||
for i in range( 2, MAX_NUMBER )
|
||||
for j in range( i + i, MAX_NUMBER, i )
|
||||
pdSum[ j ] += i
|
||||
end for
|
||||
end for
|
||||
// find the amicable pairs up to 20 000
|
||||
ap = []
|
||||
for p1 in range( 1, MAX_NUMBER - 1 )
|
||||
pdSumP1 = pdSum[ p1 ]
|
||||
if pdSumP1 > p1 and pdSumP1 <= MAX_NUMBER and pdSum[ pdSumP1 ] == p1 then
|
||||
print str( p1 ) + " and " + str( pdSumP1 ) + " are an amicable pair"
|
||||
end if
|
||||
end for
|
||||
34
Task/Amicable-pairs/PL-I-80/amicable-pairs-2.pli
Normal file
34
Task/Amicable-pairs/PL-I-80/amicable-pairs-2.pli
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
amicable: procedure options (main);
|
||||
|
||||
%replace
|
||||
search_limit by 20000;
|
||||
|
||||
dcl sumf( 1 : search_limit ) fixed bin;
|
||||
dcl (a, b, found) fixed bin;
|
||||
|
||||
put skip list ('Searching for amicable pairs up to ');
|
||||
put edit (search_limit) (f(5));
|
||||
|
||||
do a = 1 to search_limit; sumf( a ) = 1; end;
|
||||
do a = 2 to search_limit;
|
||||
do b = a + a to search_limit by a;
|
||||
sumf( b ) = sumf( b ) + a;
|
||||
end;
|
||||
end;
|
||||
|
||||
found = 0;
|
||||
do a = 2 to search_limit;
|
||||
b = sumf(a);
|
||||
if (b > a) then
|
||||
do;
|
||||
if (sumf(b) = a) then
|
||||
do;
|
||||
found = found + 1;
|
||||
put skip edit (a,b) (f(7));
|
||||
end;
|
||||
end;
|
||||
end;
|
||||
put skip list (found, ' pairs were found');
|
||||
stop;
|
||||
|
||||
end amicable;
|
||||
|
|
@ -30,8 +30,9 @@ END;
|
|||
|
||||
/* TEST EACH PAIR */
|
||||
DO I=2 TO 20$000;
|
||||
DO J=I+1 TO 20$000;
|
||||
IF DIV$SUM(I)=J AND DIV$SUM(J)=I THEN DO;
|
||||
J = DIVSUM(I);
|
||||
IF J > I AND J <= 20$000 THEN DO;
|
||||
IF DIV$SUM(J) = I THEN DO;
|
||||
CALL PRINT$NUMBER(I);
|
||||
CALL PRINT(.', $');
|
||||
CALL PRINT$NUMBER(J);
|
||||
|
|
|
|||
19
Task/Amicable-pairs/QBasic/amicable-pairs.basic
Normal file
19
Task/Amicable-pairs/QBasic/amicable-pairs.basic
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
FUNCTION amicable (nr)
|
||||
suma = 1
|
||||
FOR d = 2 TO SQR(nr)
|
||||
IF nr MOD d = 0 THEN suma = suma + d + nr / d
|
||||
NEXT
|
||||
amicable = suma
|
||||
END FUNCTION
|
||||
|
||||
PRINT "The pairs of amicable numbers below 20,000 are :"
|
||||
PRINT
|
||||
|
||||
size = 18500
|
||||
FOR n = 1 TO size
|
||||
m = amicable(n)
|
||||
IF m > n AND amicable(m) = n THEN
|
||||
PRINT USING "##### and #####"; n; m
|
||||
END IF
|
||||
NEXT
|
||||
END
|
||||
19
Task/Amicable-pairs/True-BASIC/amicable-pairs.basic
Normal file
19
Task/Amicable-pairs/True-BASIC/amicable-pairs.basic
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
FUNCTION amicable(nr)
|
||||
LET suma = 1
|
||||
FOR d = 2 TO SQR(nr)
|
||||
IF REMAINDER(nr, d) = 0 THEN
|
||||
LET suma = suma + d + nr / d
|
||||
END IF
|
||||
NEXT d
|
||||
LET amicable = suma
|
||||
END FUNCTION
|
||||
|
||||
PRINT "The pairs of amicable numbers below 20,000 are :"
|
||||
PRINT
|
||||
|
||||
LET size = 18500
|
||||
FOR n = 1 TO size
|
||||
LET m = amicable(n)
|
||||
IF m > n AND amicable(m) = n THEN PRINT USING "##### and #####": n, m
|
||||
NEXT n
|
||||
END
|
||||
129
Task/Arithmetic-Rational/C++/arithmetic-rational-2.cpp
Normal file
129
Task/Arithmetic-Rational/C++/arithmetic-rational-2.cpp
Normal file
|
|
@ -0,0 +1,129 @@
|
|||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <iostream>
|
||||
#include <numeric>
|
||||
#include <stdexcept>
|
||||
|
||||
class Rational {
|
||||
public:
|
||||
/// Constructors ///
|
||||
Rational() : numer(0), denom(1) {}
|
||||
|
||||
Rational(const int64_t number) : numer(number), denom(1) {}
|
||||
|
||||
Rational(const int64_t& numerator, const int64_t& denominator) : numer(numerator), denom(denominator) {
|
||||
if ( numer == 0 ) {
|
||||
denom = 1;
|
||||
} else if ( denom == 0 ) {
|
||||
throw std::invalid_argument("Denominator cannot be zero: " + denom);
|
||||
} else if ( denom < 0 ) {
|
||||
numer = -numer;
|
||||
denom = -denom;
|
||||
}
|
||||
|
||||
int64_t divisor = std::gcd(numerator, denom);
|
||||
numer = numer / divisor;
|
||||
denom = denom / divisor;
|
||||
}
|
||||
|
||||
Rational(const Rational& other) : numer(other.numer), denom(other.denom) {}
|
||||
|
||||
/// Operators ///
|
||||
Rational& operator=(const Rational& other) {
|
||||
if ( *this != other ) { numer = other.numer; denom = other.denom; }
|
||||
return *this;
|
||||
}
|
||||
|
||||
bool operator!=(const Rational& other) const { return ! ( *this == other ); }
|
||||
|
||||
bool operator==(const Rational& other) const {
|
||||
if ( numer == other.numer && denom == other.denom ) { return true; }
|
||||
return false;
|
||||
}
|
||||
|
||||
Rational& operator+=(const Rational& other) {
|
||||
*this = Rational(numer* other.denom + other.numer * denom, denom * other.denom);
|
||||
return *this;
|
||||
}
|
||||
|
||||
Rational operator+(const Rational& other) const { return Rational(*this) += other; }
|
||||
|
||||
Rational& operator-=(const Rational& other) {
|
||||
Rational temp(other);
|
||||
temp.numer = -temp.numer;
|
||||
return *this += temp;
|
||||
}
|
||||
Rational operator-(const Rational& other) const { return Rational(*this) -= other; }
|
||||
|
||||
Rational& operator*=(const Rational& other) {
|
||||
*this = Rational(numer * other.numer, denom * other.denom);
|
||||
return *this;
|
||||
}
|
||||
|
||||
Rational operator*(const Rational& other) const { return Rational(*this) *= other; };
|
||||
|
||||
Rational& operator/=(const Rational other) {
|
||||
Rational temp(other.denom, other.numer);
|
||||
*this *= temp;
|
||||
return *this;
|
||||
}
|
||||
|
||||
Rational operator/(const Rational& other) const { return Rational(*this) /= other; };
|
||||
|
||||
bool operator<(const Rational& other) const { return numer * other.denom < denom * other.numer; }
|
||||
|
||||
bool operator<=(const Rational& other) const { return ! ( other < *this ); }
|
||||
|
||||
bool operator>(const Rational& other) const { return other < *this; }
|
||||
|
||||
bool operator>=(const Rational& other) const { return ! ( *this < other ); }
|
||||
|
||||
Rational operator-() const { return Rational(-numer, denom); }
|
||||
|
||||
Rational& operator++() { numer += denom; return *this; }
|
||||
|
||||
Rational operator++(int) { Rational temp = *this; ++*this; return temp; }
|
||||
|
||||
Rational& operator--() { numer -= denom; return *this; }
|
||||
|
||||
Rational operator--(int) { Rational temp = *this; --*this; return temp; }
|
||||
|
||||
friend std::ostream& operator<<(std::ostream& outStream, const Rational& other) {
|
||||
outStream << other.numer << "/" << other.denom;
|
||||
return outStream;
|
||||
}
|
||||
|
||||
/// Methods ///
|
||||
Rational reciprocal() const { return Rational(denom, numer); }
|
||||
|
||||
Rational positive() const { return Rational(abs(numer), denom); }
|
||||
|
||||
int64_t to_integer() const { return numer / denom; }
|
||||
|
||||
double to_double() const { return (double) numer / denom; }
|
||||
|
||||
int64_t hash() const { return std::hash<int64_t>{}(numer) ^ std::hash<int64_t>{}(denom); }
|
||||
|
||||
private:
|
||||
int64_t numer;
|
||||
int64_t denom;
|
||||
};
|
||||
|
||||
int main() {
|
||||
std::cout << "Perfect numbers less than 2^19:" << std::endl;
|
||||
const int32_t limit = 1 << 19;
|
||||
for ( int32_t candidate = 2; candidate < limit; ++candidate ) {
|
||||
Rational sum = Rational(1, candidate);
|
||||
int32_t square_root = (int32_t) sqrt(candidate);
|
||||
for ( int32_t factor = 2; factor <= square_root; ++factor ) {
|
||||
if ( candidate % factor == 0 ) {
|
||||
sum += Rational(1, factor);
|
||||
sum += Rational(1, candidate / factor);
|
||||
}
|
||||
}
|
||||
|
||||
if ( sum == Rational(1) ) {
|
||||
std::cout << candidate << std::endl;
|
||||
}
|
||||
}
|
||||
}
|
||||
47
Task/Ascending-primes/FutureBasic/ascending-primes.basic
Normal file
47
Task/Ascending-primes/FutureBasic/ascending-primes.basic
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
local fn IsPrime( n as NSUInteger ) as BOOL
|
||||
BOOL isPrime = YES
|
||||
NSUInteger i
|
||||
|
||||
if n < 2 then exit fn = NO
|
||||
if n = 2 then exit fn = YES
|
||||
if n mod 2 == 0 then exit fn = NO
|
||||
for i = 3 to int(n^.5) step 2
|
||||
if n mod i == 0 then exit fn = NO
|
||||
next
|
||||
end fn = isPrime
|
||||
|
||||
void local fn AscendingPrimes( limit as long )
|
||||
long i, n, mask, num, count = 0
|
||||
|
||||
for i = 0 to limit -1
|
||||
n = 0 : mask = i : num = 1
|
||||
while ( mask )
|
||||
if mask & 1 then n = n * 10 + num
|
||||
mask = mask >> 1
|
||||
num++
|
||||
wend
|
||||
mda(i) = n
|
||||
next
|
||||
|
||||
mda_sort @"compare:"
|
||||
|
||||
for i = 1 to mda_count (0) - 1
|
||||
n = mda_integer(i)
|
||||
if ( fn IsPrime( n ) )
|
||||
printf @"%10ld\b", n
|
||||
count++
|
||||
if count mod 10 == 0 then print
|
||||
end if
|
||||
next
|
||||
printf @"\n\tThere are %ld ascending primes.", count
|
||||
end fn
|
||||
|
||||
window 1, @"Ascending Primes", ( 0, 0, 780, 230 )
|
||||
print
|
||||
|
||||
CFTimeInterval t
|
||||
t = fn CACurrentMediaTime
|
||||
fn AscendingPrimes( 512 )
|
||||
printf @"\n\tCompute time: %.3f ms\n",(fn CACurrentMediaTime-t)*1000
|
||||
|
||||
HandleEvents
|
||||
16
Task/Attractive-numbers/Insitux/attractive-numbers.insitux
Normal file
16
Task/Attractive-numbers/Insitux/attractive-numbers.insitux
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
(function primes n
|
||||
(let find-range (range 2 (inc n))
|
||||
check-nums (range 2 (-> n ceil sqrt inc))
|
||||
skip-each-after #(skip-each % (skip %1 %2))
|
||||
muls (xmap #(drop 0 (skip-each-after (dec %1) % find-range)) check-nums))
|
||||
(remove (flatten muls) find-range))
|
||||
(function distinct-factor n
|
||||
(filter @(div? n) (primes n)))
|
||||
(function factor n
|
||||
(map (fn t (find (div? n) (map @(** t) (range (round (sqrt n)) 0)))) (distinct-factor n)))
|
||||
(function decomposed-factors n
|
||||
(map (fn dist t (repeat dist (/ (logn t) (logn dist)))) (distinct-factor n) (factor n)))
|
||||
(var prime? @((primes %)))
|
||||
|
||||
(var attract-num? (comp decomposed-factors flatten len prime?))
|
||||
(filter attract-num? (range 121))
|
||||
18
Task/Bell-numbers/FutureBasic/bell-numbers.basic
Normal file
18
Task/Bell-numbers/FutureBasic/bell-numbers.basic
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
local fn BellNumbers( limit as long )
|
||||
long j, n = 1
|
||||
|
||||
mda(0) = 1
|
||||
printf @"%2llu. %19llu", n, mda_integer(0)
|
||||
while ( n < limit )
|
||||
mda(n) = mda(0)
|
||||
for j = n to 1 step -1
|
||||
mda(j - 1) = mda_integer(j - 1) + mda_integer(j)
|
||||
next
|
||||
n++
|
||||
printf @"%2llu. %19llu", n, mda_integer(0)
|
||||
wend
|
||||
end fn
|
||||
|
||||
fn BellNumbers( 25 )
|
||||
|
||||
HandleEvents
|
||||
195
Task/Best-shuffle/AArch64-Assembly/best-shuffle.aarch64
Normal file
195
Task/Best-shuffle/AArch64-Assembly/best-shuffle.aarch64
Normal file
|
|
@ -0,0 +1,195 @@
|
|||
/* ARM assembly AARCH64 Raspberry PI 3B */
|
||||
/* program shuffleperf64.s */
|
||||
/************************************/
|
||||
/* Constantes */
|
||||
/************************************/
|
||||
/* for this file see task include a file in language AArch64 assembly*/
|
||||
.include "../includeConstantesARM64.inc"
|
||||
|
||||
/************************************/
|
||||
/* Initialized data */
|
||||
/************************************/
|
||||
.data
|
||||
szMessString: .asciz "String :\n"
|
||||
szString1: .asciz "abracadabra"
|
||||
.equ LGSTRING1, . - szString1 - 1
|
||||
szString2: .asciz "seesaw"
|
||||
.equ LGSTRING2, . - szString2 - 1
|
||||
szString3: .asciz "elk"
|
||||
.equ LGSTRING3, . - szString3 - 1
|
||||
szString4: .asciz "grrrrrr"
|
||||
.equ LGSTRING4, . - szString4 - 1
|
||||
szString5: .asciz "up"
|
||||
.equ LGSTRING5, . - szString5 - 1
|
||||
szString6: .asciz "a"
|
||||
.equ LGSTRING6, . - szString6 - 1
|
||||
szCarriageReturn: .asciz "\n"
|
||||
szMessStart: .asciz "Program 64 bits start.\n"
|
||||
.align 4
|
||||
qGraine: .quad 123456789
|
||||
/************************************/
|
||||
/* UnInitialized data */
|
||||
/************************************/
|
||||
.bss
|
||||
sZoneConv: .skip 24
|
||||
sBuffer: .skip 80
|
||||
/************************************/
|
||||
/* code section */
|
||||
/************************************/
|
||||
.text
|
||||
.global main
|
||||
main:
|
||||
ldr x0,qAdrszMessStart
|
||||
bl affichageMess
|
||||
ldr x0,qAdrszString1 // string address
|
||||
mov x1,#LGSTRING1 // string length
|
||||
ldr x2,qAdrsBuffer // result address
|
||||
bl testshuffle // call test
|
||||
ldr x0,qAdrszString2
|
||||
mov x1,#LGSTRING2
|
||||
ldr x2,qAdrsBuffer
|
||||
bl testshuffle
|
||||
ldr x0,qAdrszString3
|
||||
mov x1,#LGSTRING3
|
||||
ldr x2,qAdrsBuffer
|
||||
bl testshuffle
|
||||
ldr x0,qAdrszString4
|
||||
mov x1,#LGSTRING4
|
||||
ldr x2,qAdrsBuffer
|
||||
bl testshuffle
|
||||
ldr x0,qAdrszString5
|
||||
mov x1,#LGSTRING5
|
||||
ldr x2,qAdrsBuffer
|
||||
bl testshuffle
|
||||
ldr x0,qAdrszString6
|
||||
mov x1,#LGSTRING6
|
||||
ldr x2,qAdrsBuffer
|
||||
bl testshuffle
|
||||
100: // standard end of the program
|
||||
mov x0, #0 // return code
|
||||
mov x8, #EXIT // request to exit program
|
||||
svc 0 // perform system call
|
||||
qAdrszMessString: .quad szMessString
|
||||
qAdrsBuffer: .quad sBuffer
|
||||
qAdrszString1: .quad szString1
|
||||
qAdrszString2: .quad szString2
|
||||
qAdrszString3: .quad szString3
|
||||
qAdrszString4: .quad szString4
|
||||
qAdrszString5: .quad szString5
|
||||
qAdrszString6: .quad szString6
|
||||
qAdrszCarriageReturn: .quad szCarriageReturn
|
||||
qAdrszMessStart: .quad szMessStart
|
||||
/******************************************************************/
|
||||
/* test shuffle strings */
|
||||
/******************************************************************/
|
||||
/* x0 contains the address of the string */
|
||||
/* x1 contains string length */
|
||||
/* x2 contains result area */
|
||||
testshuffle:
|
||||
stp x1,lr,[sp,-16]! // register save
|
||||
stp x2,x3,[sp,-16]!
|
||||
stp x4,x5,[sp,-16]!
|
||||
stp x6,x7,[sp,-16]!
|
||||
mov x3,x0 // display string
|
||||
bl affichageMess
|
||||
ldr x0,qAdrszCarriageReturn
|
||||
bl affichageMess
|
||||
mov x0,x3
|
||||
bl shufflestrings
|
||||
mov x0,x2 // display result string
|
||||
bl affichageMess
|
||||
ldr x0,qAdrszCarriageReturn
|
||||
bl affichageMess
|
||||
mov x4,#0 // string index
|
||||
mov x0,#0 // score
|
||||
1: // compute score loop
|
||||
ldrb w6,[x3,x4]
|
||||
ldrb w5,[x2,x4]
|
||||
cmp x6,x5
|
||||
add x6,x0,1
|
||||
csel x0,x6,x0,eq // equal -> increment score
|
||||
add x4,x4,#1
|
||||
cmp x4,x1
|
||||
blt 1b
|
||||
ldr x1,qAdrsZoneConv
|
||||
bl conversion10 // conversion score in decimal
|
||||
ldr x0,qAdrsZoneConv
|
||||
bl affichageMess
|
||||
ldr x0,qAdrszCarriageReturn
|
||||
bl affichageMess
|
||||
ldr x0,qAdrszCarriageReturn
|
||||
bl affichageMess
|
||||
100:
|
||||
ldp x6,x7,[sp],16
|
||||
ldp x4,x5,[sp],16
|
||||
ldp x2,x3,[sp],16
|
||||
ldp x1,lr,[sp],16
|
||||
ret
|
||||
qAdrsZoneConv: .quad sZoneConv
|
||||
/******************************************************************/
|
||||
/* shuffle strings algorithme Fisher-Yates */
|
||||
/******************************************************************/
|
||||
/* x0 contains the address of the string */
|
||||
/* x1 contains string length */
|
||||
/* x2 contains address result string */
|
||||
shufflestrings:
|
||||
stp x1,lr,[sp,-16]! // TODO: save à completer
|
||||
stp x2,x3,[sp,-16]!
|
||||
stp x4,x5,[sp,-16]!
|
||||
mov x3,#0
|
||||
1: // loop copy string in result
|
||||
ldrb w4,[x0,x3]
|
||||
strb w4,[x2,x3]
|
||||
add x3,x3,#1
|
||||
cmp x3,x1
|
||||
ble 1b
|
||||
sub x1,x1,#1 // last element
|
||||
2:
|
||||
mov x0,x1
|
||||
bl genereraleas // call random
|
||||
ldrb w4,[x2,x1] // load byte string index loop
|
||||
ldrb w3,[x2,x0] // load byte string random index
|
||||
strb w3,[x2,x1] // and exchange
|
||||
strb w4,[x2,x0]
|
||||
subs x1,x1,#1
|
||||
cmp x1,#1
|
||||
bge 2b
|
||||
|
||||
100:
|
||||
ldp x4,x5,[sp],16
|
||||
ldp x2,x3,[sp],16
|
||||
ldp x1,lr,[sp],16
|
||||
ret
|
||||
|
||||
/***************************************************/
|
||||
/* Generation random number */
|
||||
/***************************************************/
|
||||
/* x0 contains limit */
|
||||
genereraleas:
|
||||
stp x1,lr,[sp,-16]! // save registers
|
||||
stp x2,x3,[sp,-16]! // save registers
|
||||
ldr x1,qAdrqGraine
|
||||
ldr x2,[x1]
|
||||
ldr x3,qNbDep1
|
||||
mul x2,x3,x2
|
||||
ldr x3,qNbDep2
|
||||
add x2,x2,x3
|
||||
str x2,[x1] // maj de la graine pour l appel suivant
|
||||
cmp x0,#0
|
||||
beq 100f
|
||||
udiv x3,x2,x0
|
||||
msub x0,x3,x0,x2 // résult = remainder
|
||||
|
||||
100: // end function
|
||||
ldp x2,x3,[sp],16 // restaur 2 registers
|
||||
ldp x1,lr,[sp],16 // restaur 2 registers
|
||||
ret // return to address lr x30
|
||||
qAdrqGraine: .quad qGraine
|
||||
qNbDep1: .quad 0x0019660d
|
||||
qNbDep2: .quad 0x3c6ef35f
|
||||
|
||||
/***************************************************/
|
||||
/* ROUTINES INCLUDE */
|
||||
/***************************************************/
|
||||
/* for this file see task include a file in language AArch64 assembly*/
|
||||
.include "../includeARM64.inc"
|
||||
176
Task/Best-shuffle/ARM-Assembly/best-shuffle.arm
Normal file
176
Task/Best-shuffle/ARM-Assembly/best-shuffle.arm
Normal file
|
|
@ -0,0 +1,176 @@
|
|||
/* ARM assembly Raspberry PI */
|
||||
/* program shuffleperf.s */
|
||||
/************************************/
|
||||
/* Constantes */
|
||||
/************************************/
|
||||
/* for this file see task include a file in language ARM assembly*/
|
||||
.include "../constantes.inc"
|
||||
|
||||
/************************************/
|
||||
/* Initialized data */
|
||||
/************************************/
|
||||
.data
|
||||
szMessString: .asciz "String :\n"
|
||||
szString1: .asciz "abracadabra"
|
||||
.equ LGSTRING1, . - szString1 - 1
|
||||
szString2: .asciz "seesaw"
|
||||
.equ LGSTRING2, . - szString2 - 1
|
||||
szString3: .asciz "elk"
|
||||
.equ LGSTRING3, . - szString3 - 1
|
||||
szString4: .asciz "grrrrrr"
|
||||
.equ LGSTRING4, . - szString4 - 1
|
||||
szString5: .asciz "up"
|
||||
.equ LGSTRING5, . - szString5 - 1
|
||||
szString6: .asciz "a"
|
||||
.equ LGSTRING6, . - szString6 - 1
|
||||
szCarriageReturn: .asciz "\n"
|
||||
.align 4
|
||||
iGraine: .int 1234567
|
||||
/************************************/
|
||||
/* UnInitialized data */
|
||||
/************************************/
|
||||
.bss
|
||||
sZoneConv: .skip 24
|
||||
sBuffer: .skip 80
|
||||
/************************************/
|
||||
/* code section */
|
||||
/************************************/
|
||||
.text
|
||||
.global main
|
||||
main:
|
||||
ldr r0,iAdrszString1 @ string address
|
||||
mov r1,#LGSTRING1 @ string length
|
||||
ldr r2,iAdrsBuffer @ result address
|
||||
bl testshuffle @ call test
|
||||
ldr r0,iAdrszString2
|
||||
mov r1,#LGSTRING2
|
||||
ldr r2,iAdrsBuffer
|
||||
bl testshuffle
|
||||
ldr r0,iAdrszString3
|
||||
mov r1,#LGSTRING3
|
||||
ldr r2,iAdrsBuffer
|
||||
bl testshuffle
|
||||
ldr r0,iAdrszString4
|
||||
mov r1,#LGSTRING4
|
||||
ldr r2,iAdrsBuffer
|
||||
bl testshuffle
|
||||
ldr r0,iAdrszString5
|
||||
mov r1,#LGSTRING5
|
||||
ldr r2,iAdrsBuffer
|
||||
bl testshuffle
|
||||
ldr r0,iAdrszString6
|
||||
mov r1,#LGSTRING6
|
||||
ldr r2,iAdrsBuffer
|
||||
bl testshuffle
|
||||
100: @ standard end of the program
|
||||
mov r0, #0 @ return code
|
||||
mov r7, #EXIT @ request to exit program
|
||||
svc 0 @ perform system call
|
||||
iAdrszMessString: .int szMessString
|
||||
iAdrsBuffer: .int sBuffer
|
||||
iAdrszString1: .int szString1
|
||||
iAdrszString2: .int szString2
|
||||
iAdrszString3: .int szString3
|
||||
iAdrszString4: .int szString4
|
||||
iAdrszString5: .int szString5
|
||||
iAdrszString6: .int szString6
|
||||
iAdrszCarriageReturn: .int szCarriageReturn
|
||||
/******************************************************************/
|
||||
/* test shuffle strings */
|
||||
/******************************************************************/
|
||||
/* r0 contains the address of the string */
|
||||
/* r1 contains string length */
|
||||
/* r2 contains result area */
|
||||
testshuffle:
|
||||
push {r1-r6,lr} @ save registers
|
||||
mov r3,r0 @ display string
|
||||
bl affichageMess
|
||||
ldr r0,iAdrszCarriageReturn
|
||||
bl affichageMess
|
||||
mov r0,r3
|
||||
bl shufflestrings
|
||||
mov r0,r2 @ display result string
|
||||
bl affichageMess
|
||||
ldr r0,iAdrszCarriageReturn
|
||||
bl affichageMess
|
||||
mov r4,#0 @ string index
|
||||
mov r0,#0 @ score
|
||||
1: @ compute score loop
|
||||
ldrb r6,[r3,r4]
|
||||
ldrb r5,[r2,r4]
|
||||
cmp r6,r5
|
||||
addeq r0,r0,#1 @ equal -> increment score
|
||||
add r4,r4,#1
|
||||
cmp r4,r1
|
||||
blt 1b
|
||||
ldr r1,iAdrsZoneConv
|
||||
bl conversion10 @ conversion score in decimal
|
||||
ldr r0,iAdrsZoneConv
|
||||
bl affichageMess
|
||||
ldr r0,iAdrszCarriageReturn
|
||||
bl affichageMess
|
||||
ldr r0,iAdrszCarriageReturn
|
||||
bl affichageMess
|
||||
100:
|
||||
pop {r1-r6,pc} @ restaur registers
|
||||
iAdrsZoneConv: .int sZoneConv
|
||||
/******************************************************************/
|
||||
/* shuffle strings algorithme Fisher-Yates */
|
||||
/******************************************************************/
|
||||
/* r0 contains the address of the string */
|
||||
/* r1 contains string length */
|
||||
/* r2 contains address result string */
|
||||
shufflestrings:
|
||||
push {r1-r4,lr} @ save registers
|
||||
mov r3,#0
|
||||
1: @ loop copy string in result
|
||||
ldrb r4,[r0,r3]
|
||||
strb r4,[r2,r3]
|
||||
add r3,r3,#1
|
||||
cmp r3,r1
|
||||
ble 1b
|
||||
sub r1,r1,#1 @ last element
|
||||
2:
|
||||
mov r0,r1 @ limit random number
|
||||
bl genereraleas @ call random
|
||||
ldrb r4,[r2,r1] @ load byte string index loop
|
||||
ldrb r3,[r2,r0] @ load byte string random index
|
||||
strb r3,[r2,r1] @ and exchange
|
||||
strb r4,[r2,r0]
|
||||
subs r1,r1,#1
|
||||
cmp r1,#1
|
||||
bge 2b
|
||||
|
||||
100:
|
||||
pop {r1-r4,pc} @ restaur registers
|
||||
|
||||
/***************************************************/
|
||||
/* Generation random number */
|
||||
/***************************************************/
|
||||
/* r0 contains limit */
|
||||
genereraleas:
|
||||
push {r1-r4,lr} @ save registers
|
||||
ldr r4,iAdriGraine
|
||||
ldr r2,[r4]
|
||||
ldr r3,iNbDep1
|
||||
mul r2,r3,r2
|
||||
ldr r3,iNbDep1
|
||||
add r2,r2,r3
|
||||
str r2,[r4] @ maj de la graine pour l appel suivant
|
||||
cmp r0,#0
|
||||
beq 100f
|
||||
mov r1,r0 @ divisor
|
||||
mov r0,r2 @ dividende
|
||||
bl division
|
||||
mov r0,r3 @ résult = remainder
|
||||
|
||||
100: @ end function
|
||||
pop {r1-r4,pc} @ restaur registers
|
||||
iAdriGraine: .int iGraine
|
||||
iNbDep1: .int 0x343FD
|
||||
iNbDep2: .int 0x269EC3
|
||||
/***************************************************/
|
||||
/* ROUTINES INCLUDE */
|
||||
/***************************************************/
|
||||
/* for this file see task include a file in language ARM assembly*/
|
||||
.include "../affichage.inc"
|
||||
45
Task/Bifid-cipher/Applesoft-BASIC/bifid-cipher.basic
Normal file
45
Task/Bifid-cipher/Applesoft-BASIC/bifid-cipher.basic
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
100 A$ = "ATTACKATDAWN": GOSUB 160"REPORT
|
||||
110 K$ = "BGWKZQPNDSIOAXEFCLUMTHYVR"
|
||||
120 A$ = "FLEEATONCE": GOSUB 160"REPORT
|
||||
130 K$ = " .'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123"
|
||||
140 A$ = "THE INVASION WILL START ON THE FIRST OF JANUARY 2023.": GOSUB 160"REPORT
|
||||
150 END
|
||||
|
||||
REM REPORT
|
||||
160 GOSUB 200"ENCRYPT
|
||||
165 PRINT M$M$"FOR "W" X "W" POLYBIUS:":M$ = CHR$ (13): FOR I = 1 TO W: PRINT , MID$ (K$,(I - 1) * W + 1,W): NEXT
|
||||
170 PRINT "ENCRYPTED: "E$
|
||||
180 GOSUB 300"DECRYPT
|
||||
190 PRINT "DECRYPTED: "U$;: RETURN
|
||||
|
||||
REM ENCRYPT A$ RETURNS E$
|
||||
200 GOSUB 400:L = LEN (A$):E$ = "":U$ = "": IF NOT L THEN RETURN
|
||||
210 FOR I = 1 TO L
|
||||
220 C = ASC ( MID$ (A$,I,1)): IF X(C) AND Y(C) THEN U$ = U$ + CHR$ (C)
|
||||
230 NEXT I
|
||||
240 L = LEN (U$): IF NOT L THEN RETURN
|
||||
250 FOR I = 1 TO L:C = ASC ( MID$ (U$,I,1)):A(I) = X(C):A(I + L) = Y(C): NEXT I
|
||||
260 FOR I = 1 TO L * 2 STEP 2:E$ = E$ + MID$ (K$,(A(I) - 1) * W + A(I + 1),1): NEXT I
|
||||
270 RETURN
|
||||
|
||||
REM DECRYPT E$ RETURNS U$
|
||||
300 GOSUB 400:L = LEN (E$):U$ = "": IF NOT L THEN RETURN
|
||||
310 FOR I = 1 TO L:C = ASC ( MID$ (E$,I)):B(I * 2 - 1) = X(C):B(I * 2) = Y(C): NEXT I
|
||||
320 FOR I = 1 TO L:U$ = U$ + MID$ (K$,(B(I) - 1) * W + B(L + I),1): NEXT I
|
||||
330 RETURN
|
||||
|
||||
REM POLYBIUS K$ RETURNS X(255),Y(255)
|
||||
400 IF K$ = P$ AND LEN (K$) THEN RETURN
|
||||
410 IF XY THEN FOR I = 0 TO 255:X(I) = 0:Y(I) = 0: NEXT I
|
||||
420 IF NOT XY THEN DIM X(255),Y(255),A(512),B(512):XY = 1
|
||||
430 IF K$ = "" THEN FOR I = 1 TO 25:K$ = K$ + CHR$ (I + 64 + (I > 9)): NEXT I
|
||||
440 L = LEN (K$):W = INT ( SQR (L - 1) + 1):I = 1:N = 1:K = ASC ("0")
|
||||
450 FOR X = 1 TO W
|
||||
460 FOR Y = 1 TO W
|
||||
470 C$ = MID$ (K$,I,1): IF C$ = "" THEN FOR C = K TO 255: IF X(C) THEN NEXT C: STOP
|
||||
480 IF C$ = "" THEN C$ = CHR$ (C):K$ = K$ + C$:K = C + 1
|
||||
490 C = ASC (C$):Y(C) = Y:X(C) = X:I = I + 1: IF C$ = "J" THEN N = 0
|
||||
500 NEXT Y,X
|
||||
510 IF N THEN Y( ASC ("J")) = Y( ASC ("I")):X( ASC ("J")) = X( ASC ("I"))
|
||||
520 P$ = K$
|
||||
530 RETURN
|
||||
73
Task/Bifid-cipher/Lua/bifid-cipher.lua
Normal file
73
Task/Bifid-cipher/Lua/bifid-cipher.lua
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
function transcipher (cipher, message, decipher)
|
||||
local message = message:gsub("%s+", ""):upper()
|
||||
local xStr, yStr, s, char = "", "", ""
|
||||
for pos = 1, #message do
|
||||
char = message:sub(pos, pos)
|
||||
for x = 1, #cipher do
|
||||
for y = 1, #cipher[x] do
|
||||
if cipher[x][y] == char then
|
||||
s = s .. x .. y
|
||||
xStr = xStr .. x
|
||||
yStr = yStr .. y
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
if decipher then
|
||||
xStr, yStr = s:sub(1, #s/2), s:sub(#s/2 + 1, #s)
|
||||
else
|
||||
s = xStr .. yStr
|
||||
end
|
||||
local result, x, y = ""
|
||||
local limit = decipher and #s/2 or #s
|
||||
local step = decipher and 1 or 2
|
||||
for pos = 1, limit, step do
|
||||
x = tonumber(s:sub(pos, pos))
|
||||
y = decipher and
|
||||
tonumber(s:sub(pos + #s/2, pos + #s/2)) or
|
||||
tonumber(s:sub(pos + 1, pos + 1))
|
||||
result = result .. cipher[x][y]
|
||||
end
|
||||
return result
|
||||
end
|
||||
|
||||
local RCbifid = {
|
||||
{"A", "B", "C", "D", "E"},
|
||||
{"F", "G", "H", "I", "K"},
|
||||
{"L", "M", "N", "O", "P"},
|
||||
{"Q", "R", "S", "T", "U"},
|
||||
{"V", "W", "X", "Y", "Z"}
|
||||
}
|
||||
|
||||
local wikibifid = {
|
||||
{"B", "G", "W", "K", "Z"},
|
||||
{"Q", "P", "N", "D", "S"},
|
||||
{"I", "O", "A", "X", "E"},
|
||||
{"F", "C", "L", "U", "M"},
|
||||
{"T", "H", "Y", "V", "R"}
|
||||
}
|
||||
|
||||
local mybifid = {
|
||||
{"A", "B", "C", "D", "E", "F"},
|
||||
{"G", "H", "I", "J", "K", "L"},
|
||||
{"M", "N", "O", "P", "Q", "R"},
|
||||
{"S", "T", "U", "V", "W", "X"},
|
||||
{"Y", "Z", "1", "2", "3", "4"},
|
||||
{"5", "6", "7", "8", "9", "0"}
|
||||
}
|
||||
|
||||
local testCases = {
|
||||
{RCbifid, "ATTACKATDAWN"},
|
||||
{wikibifid, "FLEEATONCE"},
|
||||
{wikibifid, "ATTACKATDAWN",},
|
||||
{mybifid, "The invasion will start on the first of January"}
|
||||
}
|
||||
|
||||
local msg
|
||||
for task, case in pairs(testCases) do
|
||||
print("\nTask " .. task)
|
||||
msg = transcipher(case[1], case[2])
|
||||
print("Encoded message: " .. msg)
|
||||
msg = transcipher(case[1], msg, true)
|
||||
print("Decoded message: " .. msg)
|
||||
end
|
||||
46
Task/Binary-search/MACRO-11/binary-search.macro11
Normal file
46
Task/Binary-search/MACRO-11/binary-search.macro11
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
.TITLE BINRTA
|
||||
.MCALL .TTYOUT,.PRINT,.EXIT
|
||||
; TEST CODE
|
||||
BINRTA::CLR R5
|
||||
1$: MOV R5,R0
|
||||
ADD #'0,R0
|
||||
.TTYOUT
|
||||
MOV R5,R0
|
||||
MOV #DATA,R1
|
||||
MOV #DATEND,R2
|
||||
JSR PC,BINSRC
|
||||
BEQ 2$
|
||||
.PRINT #4$
|
||||
BR 3$
|
||||
2$: .PRINT #5$
|
||||
3$: INC R5
|
||||
CMP R5,#^D10
|
||||
BLT 1$
|
||||
.EXIT
|
||||
4$: .ASCII / NOT/
|
||||
5$: .ASCIZ / FOUND/
|
||||
.EVEN
|
||||
|
||||
; TEST DATA
|
||||
DATA: .WORD 1, 2, 3, 5, 7
|
||||
DATEND = . + 2
|
||||
|
||||
; BINARY SEARCH
|
||||
; INPUT: R0 = VALUE, R1 = LOW PTR, R2 = HIGH PTR
|
||||
; OUTPUT: ZF SET IF VALUE FOUND; R1 = INSERTION POINT
|
||||
BINSRC: BR 3$
|
||||
1$: MOV R1,R3
|
||||
ADD R2,R3
|
||||
ROR R3
|
||||
CMP (R3),R0
|
||||
BGE 2$
|
||||
ADD #2,R3
|
||||
MOV R3,R1
|
||||
BR 3$
|
||||
2$: SUB #2,R3
|
||||
MOV R3,R2
|
||||
3$: CMP R2,R1
|
||||
BGE 1$
|
||||
CMP (R1),R0
|
||||
RTS PC
|
||||
.END BINRTA
|
||||
70
Task/Binary-search/Modula-2/binary-search.mod2
Normal file
70
Task/Binary-search/Modula-2/binary-search.mod2
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
MODULE BinarySearch;
|
||||
|
||||
FROM STextIO IMPORT
|
||||
WriteLn, WriteString;
|
||||
FROM SWholeIO IMPORT
|
||||
WriteInt;
|
||||
|
||||
TYPE
|
||||
TArray = ARRAY [0 .. 9] OF INTEGER;
|
||||
|
||||
CONST
|
||||
A = TArray{-31, 0, 1, 2, 2, 4, 65, 83, 99, 782}; (* Sorted data *)
|
||||
|
||||
VAR
|
||||
X: INTEGER;
|
||||
|
||||
PROCEDURE DoBinarySearch(A: ARRAY OF INTEGER; X: INTEGER): INTEGER;
|
||||
VAR
|
||||
L, H, M: INTEGER;
|
||||
BEGIN
|
||||
L := 0; H := HIGH(A);
|
||||
WHILE L <= H DO
|
||||
M := L + (H - L) / 2;
|
||||
IF A[M] < X THEN
|
||||
L := M + 1
|
||||
ELSIF A[M] > X THEN
|
||||
H := M - 1
|
||||
ELSE
|
||||
RETURN M
|
||||
END
|
||||
END;
|
||||
RETURN -1
|
||||
END DoBinarySearch;
|
||||
|
||||
PROCEDURE DoBinarySearchRec(A: ARRAY OF INTEGER; X, L, H: INTEGER): INTEGER;
|
||||
VAR
|
||||
M: INTEGER;
|
||||
BEGIN
|
||||
IF H < L THEN
|
||||
RETURN -1
|
||||
END;
|
||||
M := L + (H - L) / 2;
|
||||
IF A[M] > X THEN
|
||||
RETURN DoBinarySearchRec(A, X, L, M - 1)
|
||||
ELSIF A[M] < X THEN
|
||||
RETURN DoBinarySearchRec(A, X, M + 1, H)
|
||||
ELSE
|
||||
RETURN M
|
||||
END
|
||||
END DoBinarySearchRec;
|
||||
|
||||
PROCEDURE WriteResult(X, IndX: INTEGER);
|
||||
BEGIN
|
||||
WriteInt(X, 1);
|
||||
IF IndX >= 0 THEN
|
||||
WriteString(" is at index ");
|
||||
WriteInt(IndX, 1);
|
||||
WriteString(".")
|
||||
ELSE
|
||||
WriteString(" is not found.")
|
||||
END;
|
||||
WriteLn
|
||||
END WriteResult;
|
||||
|
||||
BEGIN
|
||||
X := 2;
|
||||
WriteResult(X, DoBinarySearch(A, X));
|
||||
X := 5;
|
||||
WriteResult(X, DoBinarySearchRec(A, X, 0, HIGH(A)));
|
||||
END BinarySearch.
|
||||
|
|
@ -0,0 +1 @@
|
|||
dog$ = "Benjamin":Dog$ = "Samba":DOG$ = "Bernie":III = 254 * (DOG$ = dog$ AND Dog$ = DOG$) + 1: PRINT MID$ ("There is just one dog",256 - III) MID$ ("The three dogs are",III)" named " MID$ (dog$ + ", " + Dog$ + " and ",III)DOG$"."
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
10 dog$ = "Benjamin"
|
||||
20 dog$ = "Smokey"
|
||||
30 dog$ = "Samba"
|
||||
40 dog$ = "Bernie"
|
||||
50 print "There is just one dog, named ";dog$
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
include "cowgol.coh";
|
||||
|
||||
var dog := "Benjamin";
|
||||
var Dog := "Samba";
|
||||
var DOG := "Bernie";
|
||||
|
||||
print("There are three dogs named ");
|
||||
print(dog);
|
||||
print(", ");
|
||||
print(Dog);
|
||||
print(", and ");
|
||||
print(DOG);
|
||||
print(".\n");
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
void main() {
|
||||
String dog = "Benjamin", doG = "Smokey", Dog = "Samba", DOG = "Bernie";
|
||||
|
||||
print("The four dogs are named $dog, $doG, $Dog and $DOG");
|
||||
}
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
proc main() void:
|
||||
*char dog = "Benjamin",
|
||||
Dog = "Samba",
|
||||
DOG = "Bernie";
|
||||
|
||||
writeln("There are three dogs named ",
|
||||
dog, ", ", Dog, ", and ", DOG, ".")
|
||||
corp
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
10 dog$ = "Benjamin"
|
||||
20 dog$ = "Smokey"
|
||||
30 dog$ = "Samba"
|
||||
40 dog$ = "Bernie"
|
||||
50 print "There is just one dog, named ";dog$
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
10 dog$ = "Benjamin"
|
||||
20 dog$ = "Smokey"
|
||||
30 dog$ = "Samba"
|
||||
40 dog$ = "Bernie"
|
||||
50 print "There is just one dog, named ";dog$
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
10 let d$ = "Benjamin"
|
||||
20 let D$ = "Samba"
|
||||
30 print "There is just one dog, named "; d$
|
||||
40 end
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
.ds dog Benjamin
|
||||
.ds Dog Samba
|
||||
.ds DOG Bernie
|
||||
The three dogs are named \*[dog], \*[Dog] and \*[DOG].
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
10 let d$ = "Benjamin"
|
||||
20 let D$ = "Samba"
|
||||
30 print "There is just one dog, named "; d$
|
||||
40 end
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
PROGRAM "Case-sensitivity"
|
||||
VERSION "0.0000"
|
||||
|
||||
DECLARE FUNCTION Entry ()
|
||||
|
||||
FUNCTION Entry ()
|
||||
dog$ = "Benjamin"
|
||||
dog$ = "Smokey"
|
||||
dog$ = "Samba"
|
||||
dog$ = "Bernie"
|
||||
|
||||
PRINT "There is just one dog, named "; dog$
|
||||
END FUNCTION
|
||||
END PROGRAM
|
||||
|
|
@ -1,5 +1,6 @@
|
|||
dog$ = "Benjamin"
|
||||
doG$ = "Smokey"
|
||||
Dog$ = "Samba"
|
||||
DOG$ = "Bernie"
|
||||
print "The three dogs are named ", dog$, ", ", Dog$, " and ", DOG$
|
||||
print "The four dogs are named ", dog$, ", ", doG$, ", ", Dog$, " and ", DOG$
|
||||
end
|
||||
|
|
|
|||
|
|
@ -5,5 +5,5 @@ The algorithm is described in [http://www.mountainvistasoft.com/chaocipher/Actua
|
|||
|
||||
|
||||
;Task:
|
||||
Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
|
||||
Code the algorithm in your language and test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
|
||||
<br><br>
|
||||
|
|
|
|||
10
Task/Command-line-arguments/C3/command-line-arguments.c3
Normal file
10
Task/Command-line-arguments/C3/command-line-arguments.c3
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
import std::io;
|
||||
|
||||
fn void main(String[] args)
|
||||
{
|
||||
io::printfn("This program is named %s.", args[0]);
|
||||
for (int i = 1; i < args.len; i++)
|
||||
{
|
||||
io::printfn("the argument #%d is %s\n", i, args[i]);
|
||||
}
|
||||
}
|
||||
10
Task/Comments/Insitux/comments.insitux
Normal file
10
Task/Comments/Insitux/comments.insitux
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
;this is a comment; and using semicolons here is fine
|
||||
|
||||
(+ 2 2) ;this is a comment
|
||||
|
||||
"this string will be ignored if in the top scope
|
||||
which can also stretch across
|
||||
multiple lines"
|
||||
|
||||
(do "if you're desperate, using do will make sure this string will not be returned also"
|
||||
(+ 2 2))
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
local fn ListObjectsAreIdentical( array as CFArrayRef ) as BOOL
|
||||
BOOL result = NO
|
||||
|
||||
CFSetRef set = fn SetWithArray( array )
|
||||
result = ( fn SetCount( set ) <= 1 )
|
||||
end fn = result
|
||||
|
||||
local fn ListIsInLexicalOrder( array as CFArrayRef ) as BOOL
|
||||
BOOL result = NO
|
||||
|
||||
CFArrayRef sortedArray = fn ArraySortedArrayUsingSelector( array, @"compare:" )
|
||||
result = fn ArrayIsEqual( array, sortedArray )
|
||||
end fn = result
|
||||
|
||||
void local fn ListTest
|
||||
long i
|
||||
|
||||
CFArrayRef listA = @[@"aaa", @"aaa", @"aaa", @"aaa"]
|
||||
CFArrayRef listB = @[@"aaa", @"aab", @"aba", @"baa"]
|
||||
CFArrayRef listC = @[@"caa", @"aab", @"aca", @"abc"]
|
||||
CFArrayRef lists = @[listA, listB, listC]
|
||||
|
||||
for i = 0 to 2
|
||||
CFArrayRef temp = lists[i]
|
||||
printf @"Input array elements: %@ %@ %@ %@", temp[0], temp[1], temp[2], temp[3]
|
||||
if ( fn ListObjectsAreIdentical( temp ) )
|
||||
printf @"List elements are lexically equal."
|
||||
else
|
||||
printf @"List elements not lexically equal."
|
||||
end if
|
||||
if ( fn ListIsInLexicalOrder( temp ) == YES )
|
||||
printf @"List elements are in ascending order."
|
||||
else
|
||||
printf @"List elements not in ascending order."
|
||||
end if
|
||||
CFArrayRef sorted = fn ArraySortedArrayUsingSelector( temp, @"compare:" )
|
||||
printf @"List elements sorted in ascending order: %@ %@ %@ %@", sorted[0], sorted[1], sorted[2], sorted[3]
|
||||
print
|
||||
next
|
||||
end fn
|
||||
|
||||
fn ListTest
|
||||
|
||||
HandleEvents
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
CFStringRef iStr, jStr
|
||||
long i, j
|
||||
|
||||
iStr = input @"Enter one positive integer: "
|
||||
jStr = input @"Enter other positive integer: "
|
||||
i = fn StringIntegerValue(iStr)
|
||||
j = fn StringIntegerValue(jStr)
|
||||
mda (0, 0) = {i, j}
|
||||
mda (i, j) = i * j
|
||||
printf @"mda(%ld, %ld) = %ld", i, j, mda_integer (i, j)
|
||||
|
||||
HandleEvents
|
||||
47
Task/Descending-primes/FutureBasic/descending-primes.basic
Normal file
47
Task/Descending-primes/FutureBasic/descending-primes.basic
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
local fn IsPrime( n as NSUInteger ) as BOOL
|
||||
BOOL isPrime = YES
|
||||
NSUInteger i
|
||||
|
||||
if n < 2 then exit fn = NO
|
||||
if n = 2 then exit fn = YES
|
||||
if n mod 2 == 0 then exit fn = NO
|
||||
for i = 3 to int(n^.5) step 2
|
||||
if n mod i == 0 then exit fn = NO
|
||||
next
|
||||
end fn = isPrime
|
||||
|
||||
void local fn DesecendingPrimes( limit as long )
|
||||
long i, n, mask, num, count = 0
|
||||
|
||||
for i = 0 to limit -1
|
||||
n = 0 : mask = i : num = 9
|
||||
while ( mask )
|
||||
if mask & 1 then n = n * 10 + num
|
||||
mask = mask >> 1
|
||||
num--
|
||||
wend
|
||||
mda(i) = n
|
||||
next
|
||||
|
||||
mda_sort @"compare:"
|
||||
|
||||
for i = 1 to mda_count (0) - 1
|
||||
n = mda_integer(i)
|
||||
if ( fn IsPrime( n ) )
|
||||
printf @"%10ld\b", n
|
||||
count++
|
||||
if count mod 10 == 0 then print
|
||||
end if
|
||||
next
|
||||
printf @"\n\n\tThere are %ld descending primes.", count
|
||||
end fn
|
||||
|
||||
window 1, @"Desecending Primes", ( 0, 0, 780, 230 )
|
||||
print
|
||||
|
||||
CFTimeInterval t
|
||||
t = fn CACurrentMediaTime
|
||||
fn DesecendingPrimes( 512 )
|
||||
printf @"\n\tCompute time: %.3f ms\n",(fn CACurrentMediaTime-t)*1000
|
||||
|
||||
HandleEvents
|
||||
|
|
@ -16,3 +16,8 @@ Optionally, see what the result is when only a single corner is in contact (ther
|
|||
:::* (0,0),(1,0),(0,1) and (1,0),(2,0),(1,1)
|
||||
<br><br>
|
||||
|
||||
;Related tasks
|
||||
* [[Check_if_two_polygons_overlap|Check if two polygons overlap]]
|
||||
* [[Check_if_a_polygon_overlaps_with_a_rectangle|Check if a polygon overlaps with a rectangle]]
|
||||
<br><br>
|
||||
|
||||
|
|
|
|||
189
Task/Dining-philosophers/Python/dining-philosophers-2.py
Normal file
189
Task/Dining-philosophers/Python/dining-philosophers-2.py
Normal file
|
|
@ -0,0 +1,189 @@
|
|||
"""Dining philosophers with multiprocessing module."""
|
||||
import multiprocessing as mp
|
||||
import random
|
||||
import time
|
||||
|
||||
# Dining philosophers. See also comments at the threading
|
||||
# version. Improvements, modifications:
|
||||
# Support variable number of philosophers.
|
||||
# "More deterministic" randomization by prealocating the schedules.
|
||||
# Use scaling to allow faster runs producing results that are
|
||||
# essentially the same.
|
||||
# Collect statistics on wait times.
|
||||
|
||||
SCALE = 0.2
|
||||
THINK = (3, 13)
|
||||
DINE = (1, 10)
|
||||
|
||||
class Philosopher(mp.Process):
|
||||
"""Independently running philosopher processes."""
|
||||
def __init__(self, idx, name, run_flag, chopstick_left, chopstick_right,
|
||||
stats, schedule_think, schedule_dine):
|
||||
mp.Process.__init__(self)
|
||||
self.idx = idx
|
||||
self.name = name
|
||||
self.run_flag = run_flag
|
||||
self.chopstick_left = chopstick_left
|
||||
self.chopstick_right = chopstick_right
|
||||
self.stats = stats
|
||||
self.schedule_think = schedule_think
|
||||
self.schedule_dine = schedule_dine
|
||||
self.counter = 0
|
||||
self.num_dined = 0
|
||||
self.hungry_time_total = 0.0
|
||||
self.hungry_time_max = 0.0
|
||||
|
||||
def run(self):
|
||||
while self.run_flag.value and self.counter < len(self.schedule_think):
|
||||
# Philosopher is thinking (but really is sleeping).
|
||||
time.sleep(self.schedule_think[self.counter]*SCALE)
|
||||
duration = -time.perf_counter()
|
||||
print(f'{self.name} is hungry', flush=True)
|
||||
self.get_chopsticks2()
|
||||
duration += time.perf_counter()
|
||||
self.hungry_time_total += duration
|
||||
self.hungry_time_max = max(self.hungry_time_max, duration)
|
||||
self.dining()
|
||||
# Populate self.stats:
|
||||
self.stats.put({'name': self.name,
|
||||
'num_dined': self.num_dined,
|
||||
'hungry_time_total': self.hungry_time_total,
|
||||
'hungry_time_max': self.hungry_time_max})
|
||||
|
||||
def get_chopsticks(self):
|
||||
"""Use swaps and do not hold on to chopsticks."""
|
||||
chopstick1, chopstick2 = self.chopstick_left, self.chopstick_right
|
||||
|
||||
while True:
|
||||
chopstick1.acquire(True)
|
||||
locked = chopstick2.acquire(False)
|
||||
if locked:
|
||||
return
|
||||
chopstick1.release()
|
||||
print(f'{self.name} swaps chopsticks', flush=True)
|
||||
chopstick1, chopstick2 = chopstick2, chopstick1
|
||||
|
||||
def get_chopsticks0(self):
|
||||
"""Naive greedy implementation to trigger deadlock."""
|
||||
self.chopstick_left.acquire(True)
|
||||
time.sleep(0.1)
|
||||
self.chopstick_right.acquire(True)
|
||||
|
||||
def get_chopsticks1(self):
|
||||
"""Break the symmetry by having one philosopher to be left handed."""
|
||||
if self.idx == 0:
|
||||
chopstick1, chopstick2 = self.chopstick_left, self.chopstick_right
|
||||
else:
|
||||
chopstick1, chopstick2 = self.chopstick_right, self.chopstick_left
|
||||
chopstick1.acquire(True)
|
||||
locked = chopstick2.acquire(False)
|
||||
if not locked:
|
||||
chopstick1.release()
|
||||
chopstick2.acquire(True)
|
||||
chopstick1.acquire(True)
|
||||
|
||||
def get_chopsticks2(self):
|
||||
"""Break the symmetry by having the even numbered philosophers to be
|
||||
left handed."""
|
||||
if self.idx == 0:
|
||||
chopstick1, chopstick2 = self.chopstick_left, self.chopstick_right
|
||||
else:
|
||||
chopstick1, chopstick2 = self.chopstick_right, self.chopstick_left
|
||||
chopstick1.acquire(True)
|
||||
locked = chopstick2.acquire(False)
|
||||
if not locked:
|
||||
chopstick1.release()
|
||||
chopstick2.acquire(True)
|
||||
chopstick1.acquire(True)
|
||||
|
||||
def dining(self):
|
||||
"""Dining with two chopsticks."""
|
||||
print(f'{self.name} starts eating', flush=True)
|
||||
self.num_dined += 1
|
||||
time.sleep(self.schedule_dine[self.counter]*SCALE)
|
||||
self.counter += 1
|
||||
print(f'{self.name} finishes eating and leaves to think.', flush=True)
|
||||
self.chopstick_left.release()
|
||||
self.chopstick_right.release()
|
||||
|
||||
def performance_report(stats):
|
||||
"""Print some stats about the wait times."""
|
||||
print("Performance report:")
|
||||
for queue in stats:
|
||||
data = queue.get()
|
||||
print(f"Philosopher {data['name']} dined {data['num_dined']} times. ")
|
||||
print(f" Total wait : {data['hungry_time_total'] / SCALE}")
|
||||
print(f" Max wait : {data['hungry_time_max'] / SCALE}")
|
||||
if data['num_dined'] > 0:
|
||||
print(f" Average wait: "
|
||||
f"{data['hungry_time_total'] / data['num_dined']/SCALE}")
|
||||
|
||||
def generate_philosophers(names, run_flag, chopsticks, stats, max_dine):
|
||||
"""Gebnerate a list of philosophers with random schedules."""
|
||||
num = len(names)
|
||||
philosophers = [Philosopher(i, names[i], run_flag,
|
||||
chopsticks[i % num],
|
||||
chopsticks[(i+1) % num],
|
||||
stats[i],
|
||||
[random.uniform(THINK[0], THINK[1])
|
||||
for j in range(max_dine)],
|
||||
[random.uniform(DINE[0], DINE[1])
|
||||
for j in range(max_dine)])
|
||||
for i in range(num)]
|
||||
return philosophers
|
||||
|
||||
def generate_philosophers0(names, run_flag, chopsticks, stats,
|
||||
schedule_think, schedule_dine):
|
||||
"""Allows the use of a predetermined thinking and dining schedule.
|
||||
This may aid in triggering a deadlock."""
|
||||
num = len(names)
|
||||
philosophers = [Philosopher(i, names[i], run_flag,
|
||||
chopsticks[i % num],
|
||||
chopsticks[(i+1) % num],
|
||||
stats[i],
|
||||
schedule_think[i],
|
||||
schedule_dine[i])
|
||||
for i in range(num)]
|
||||
return philosophers
|
||||
|
||||
def dining_philosophers(philosopher_names=(('Aristotle', 'Kant',
|
||||
'Buddha', 'Marx', 'Russel')),
|
||||
num_sec=100, max_dine=100):
|
||||
"""Main routine."""
|
||||
num = len(philosopher_names)
|
||||
chopsticks = [mp.Lock() for n in range(num)]
|
||||
random.seed(507129)
|
||||
run_flag = mp.Value('b', True)
|
||||
stats = [mp.Queue() for n in range(num)]
|
||||
|
||||
philosophers = generate_philosophers(philosopher_names, run_flag,
|
||||
chopsticks, stats, max_dine)
|
||||
|
||||
# Use the following when trying to trigger a deadlock in conjunction with
|
||||
# get_chopsticks0():
|
||||
#philosophers = generate_philosophers0(philosopher_names, run_flag,
|
||||
# chopsticks, stats, [3]*max_dine,
|
||||
# [5]*max_dine)
|
||||
|
||||
for phi in philosophers:
|
||||
phi.start()
|
||||
time.sleep(num_sec*SCALE)
|
||||
run_flag.value = False
|
||||
print("Now we're finishing.", flush=True)
|
||||
# We want to allow the philosophers to finish their meal. In fact,
|
||||
# we even allow them to still start eating if they are presently
|
||||
# hungry. This means we may need to wait at most num*DINE[1].
|
||||
wait_time = num*DINE[1]
|
||||
while wait_time >= 0 and sum(p.is_alive() for p in philosophers) > 0:
|
||||
time.sleep(1)
|
||||
wait_time -= 1.0
|
||||
if wait_time < 0:
|
||||
for phi in philosophers:
|
||||
if phi.is_alive():
|
||||
print(f"Ooops, {phi.name} has not finished!!")
|
||||
phi.terminate()
|
||||
return 1
|
||||
performance_report(stats)
|
||||
|
||||
if __name__ == '__main__':
|
||||
dining_philosophers()
|
||||
70
Task/Duffinian-numbers/FutureBasic/duffinian-numbers.basic
Normal file
70
Task/Duffinian-numbers/FutureBasic/duffinian-numbers.basic
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
local fn IsPrime( n as NSUInteger ) as BOOL
|
||||
BOOL isPrime = YES
|
||||
NSUInteger i
|
||||
|
||||
if n < 2 then exit fn = NO
|
||||
if n = 2 then exit fn = YES
|
||||
if n mod 2 == 0 then exit fn = NO
|
||||
for i = 3 to int(n^.5) step 2
|
||||
if n mod i == 0 then exit fn = NO
|
||||
next
|
||||
end fn = isPrime
|
||||
|
||||
local fn GCD( a as long, b as long ) as long
|
||||
long r
|
||||
|
||||
if ( a == 0 ) then r = b else r = fn GCD( b mod a, a )
|
||||
end fn = r
|
||||
|
||||
local fn SumDiv( num as NSUInteger ) as NSUInteger
|
||||
NSUInteger div = 2, sum = 0, quot, result
|
||||
|
||||
while (1)
|
||||
quot = num / div
|
||||
if ( div > quot ) then result = 0 : exit while
|
||||
if ( num mod div == 0 )
|
||||
sum += div
|
||||
if ( div != quot ) then sum += quot
|
||||
end if
|
||||
div++
|
||||
wend
|
||||
result = sum + 1
|
||||
end fn = result
|
||||
|
||||
local fn IsDuffinian( n as NSUInteger) as BOOL
|
||||
BOOL result = NO
|
||||
|
||||
if ( fn IsPrime(n) == NO and fn GCD( fn SumDiv(n), n ) == 1 ) then exit fn = YES
|
||||
end fn = result
|
||||
|
||||
local fn FindDuffinians
|
||||
long c = 0, n = 4
|
||||
|
||||
print "First 50 Duffinian numbers:"
|
||||
do
|
||||
if ( fn IsDuffinian(n) )
|
||||
printf @"%4d \b", n
|
||||
c++
|
||||
if ( c mod 10 == 0 ) then print
|
||||
end if
|
||||
n++
|
||||
until ( c >= 50 )
|
||||
|
||||
c = 0 : n = 4
|
||||
printf @"\n\nFirst 56 Duffinian triplets:"
|
||||
do
|
||||
if ( fn IsDuffinian(n) and fn IsDuffinian(n + 1) and fn IsDuffinian(n + 2) )
|
||||
printf @" [%6ld %6ld %6ld] \b", n, n+1, n+2
|
||||
c++
|
||||
if ( c mod 4 == 0 ) then print
|
||||
end if
|
||||
n++
|
||||
until ( c >= 56 )
|
||||
end fn
|
||||
|
||||
CFTimeInterval t
|
||||
t = fn CACurrentMediaTime
|
||||
fn FindDuffinians
|
||||
printf @"\nCompute time: %.3f ms",(fn CACurrentMediaTime-t)*1000
|
||||
|
||||
HandleEvents
|
||||
60
Task/Emirp-primes/FutureBasic/emirp-primes.basic
Normal file
60
Task/Emirp-primes/FutureBasic/emirp-primes.basic
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
local fn IsPrime( n as NSUInteger ) as BOOL
|
||||
BOOL isPrime = YES
|
||||
NSUInteger i
|
||||
|
||||
if n < 2 then exit fn = NO
|
||||
if n = 2 then exit fn = YES
|
||||
if n mod 2 == 0 then exit fn = NO
|
||||
for i = 3 to int(n^.5) step 2
|
||||
if n mod i == 0 then exit fn = NO
|
||||
next
|
||||
end fn = isPrime
|
||||
|
||||
|
||||
local fn ReverseNumber( n as NSUInteger ) as NSUInteger
|
||||
NSInteger sum = 0
|
||||
|
||||
if n < 10 then exit fn = n
|
||||
while ( n > 0 )
|
||||
sum = 10 * sum + ( n mod 10 )
|
||||
n /= 10
|
||||
wend
|
||||
end fn = sum
|
||||
|
||||
|
||||
local fn IsEmirp( n as NSUInteger ) as BOOL
|
||||
BOOL result = NO
|
||||
NSUInteger r = fn ReverseNumber(n)
|
||||
if r != n and fn IsPrime(n) and fn IsPrime(r) then result = YES
|
||||
end fn = result
|
||||
|
||||
|
||||
local fn GetEmirpPrimes
|
||||
NSUInteger count = 0, i = 13
|
||||
|
||||
printf @"\nThe first 20 Emirp primes are:"
|
||||
do
|
||||
if fn IsEmirp(i) then printf @"%4lu\b", i : count++
|
||||
i += 2
|
||||
until ( count == 20 )
|
||||
|
||||
printf @"\n\nThe Emirp primes between 7700 and 8000 are:"
|
||||
i = 7701
|
||||
while ( i < 8000 )
|
||||
if fn IsEmirp(i) then printf @"%5lu\b", i
|
||||
i += 2
|
||||
wend
|
||||
|
||||
i = 13 : count = 0
|
||||
while (1)
|
||||
if fn IsEmirp(i) then count++
|
||||
if count = 10000 then exit while
|
||||
i += 2
|
||||
wend
|
||||
printf @"\n\nThe 10,000th Emirp prime is: %lu", i
|
||||
|
||||
end fn
|
||||
|
||||
fn GetEmirpPrimes
|
||||
|
||||
HandleEvents
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
begin % find elements of the Euclid-Mullin sequence: starting from 2, %
|
||||
% the next element is the smallest prime factor of 1 + the product %
|
||||
% of the previous elements %
|
||||
integer product;
|
||||
write( "2" );
|
||||
product := 2;
|
||||
for i := 2 until 8 do begin
|
||||
integer nextV, p;
|
||||
logical found;
|
||||
nextV := product + 1;
|
||||
% find the first prime factor of nextV %
|
||||
p := 3;
|
||||
found := false;
|
||||
while p * p <= nextV and not found do begin
|
||||
found := nextV rem p = 0;
|
||||
if not found then p := p + 2
|
||||
end while_p_squared_le_nextV_and_not_found ;
|
||||
if found then nextV := p;
|
||||
writeon( i_w := 1, s_w := 0, " ", nextV );
|
||||
product := product * nextV
|
||||
end for_i
|
||||
end.
|
||||
24
Task/Euclid-Mullin-sequence/AWK/euclid-mullin-sequence-2.awk
Normal file
24
Task/Euclid-Mullin-sequence/AWK/euclid-mullin-sequence-2.awk
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
# find elements of the Euclid-Mullin sequence: starting from 2,
|
||||
# the next element is the smallest prime factor of 1 + the product
|
||||
# of the previous elements
|
||||
BEGIN {
|
||||
printf( "2" );
|
||||
product = 2;
|
||||
for( i = 2; i <= 8; i ++ )
|
||||
{
|
||||
nextV = product + 1;
|
||||
# find the first prime factor of nextV
|
||||
p = 3;
|
||||
found = 0;
|
||||
while( p * p <= nextV && ! ( found = nextV % p == 0 ) )
|
||||
{
|
||||
p += 2;
|
||||
}
|
||||
if( found )
|
||||
{
|
||||
nextV = p;
|
||||
}
|
||||
printf( " %d", nextV );
|
||||
product *= nextV
|
||||
}
|
||||
}
|
||||
|
|
@ -15,7 +15,7 @@ var (
|
|||
five = big.NewInt(5)
|
||||
six = big.NewInt(6)
|
||||
ten = big.NewInt(10)
|
||||
max = big.NewInt(100000)
|
||||
k100 = big.NewInt(100000)
|
||||
)
|
||||
|
||||
func pollardRho(n, c *big.Int) *big.Int {
|
||||
|
|
@ -51,7 +51,7 @@ func pollardRho(n, c *big.Int) *big.Int {
|
|||
return d
|
||||
}
|
||||
|
||||
func smallestPrimeFactorWheel(n *big.Int) *big.Int {
|
||||
func smallestPrimeFactorWheel(n, max *big.Int) *big.Int {
|
||||
if n.ProbablyPrime(15) {
|
||||
return n
|
||||
}
|
||||
|
|
@ -82,13 +82,13 @@ func smallestPrimeFactorWheel(n *big.Int) *big.Int {
|
|||
}
|
||||
|
||||
func smallestPrimeFactor(n *big.Int) *big.Int {
|
||||
s := smallestPrimeFactorWheel(n)
|
||||
s := smallestPrimeFactorWheel(n, k100)
|
||||
if s != nil {
|
||||
return s
|
||||
}
|
||||
c := big.NewInt(1)
|
||||
s = new(big.Int).Set(n)
|
||||
for n.Cmp(max) > 0 {
|
||||
for {
|
||||
d := pollardRho(n, c)
|
||||
if d.Cmp(zero) == 0 {
|
||||
if c.Cmp(ten) == 0 {
|
||||
|
|
@ -96,20 +96,21 @@ func smallestPrimeFactor(n *big.Int) *big.Int {
|
|||
}
|
||||
c.Add(c, one)
|
||||
} else {
|
||||
// can't be sure PR will find the smallest prime factor first
|
||||
if d.Cmp(s) < 0 {
|
||||
s.Set(d)
|
||||
}
|
||||
n.Quo(n, d)
|
||||
if n.ProbablyPrime(5) {
|
||||
if n.Cmp(s) < 0 {
|
||||
return n
|
||||
// get the smallest prime factor of 'd'
|
||||
factor := smallestPrimeFactorWheel(d, d)
|
||||
// check whether n/d has a smaller prime factor
|
||||
s = smallestPrimeFactorWheel(n.Quo(n, d), factor)
|
||||
if s != nil {
|
||||
if s.Cmp(factor) < 0 {
|
||||
return s
|
||||
} else {
|
||||
return factor
|
||||
}
|
||||
return s
|
||||
} else {
|
||||
return factor
|
||||
}
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func main() {
|
||||
|
|
|
|||
20
Task/Euclid-Mullin-sequence/Lua/euclid-mullin-sequence-1.lua
Normal file
20
Task/Euclid-Mullin-sequence/Lua/euclid-mullin-sequence-1.lua
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
-- find elements of the Euclid-Mullin sequence: starting from 2,
|
||||
-- the next element is the smallest prime factor of 1 + the product
|
||||
-- of the previous elements
|
||||
do
|
||||
io.write( "2" )
|
||||
local product = 2
|
||||
for i = 2, 8 do
|
||||
local nextV = product + 1
|
||||
-- find the first prime factor of nextV
|
||||
local p = 3
|
||||
local found = false
|
||||
while p * p <= nextV and not found do
|
||||
found = nextV % p == 0
|
||||
if not found then p = p + 2 end
|
||||
end
|
||||
if found then nextV = p end
|
||||
io.write( " ", nextV )
|
||||
product = product * nextV
|
||||
end
|
||||
end
|
||||
24
Task/Euclid-Mullin-sequence/Lua/euclid-mullin-sequence-2.lua
Normal file
24
Task/Euclid-Mullin-sequence/Lua/euclid-mullin-sequence-2.lua
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
function gcd(a,b)
|
||||
while b~=0 do
|
||||
a,b=b,a%b
|
||||
end
|
||||
return math.abs(a)
|
||||
end
|
||||
function pollard_rho(n)
|
||||
local x, y, d = 2, 2, 1
|
||||
local g = function(x) return (x*x+1) % n end
|
||||
while d == 1 do
|
||||
x = g(x)
|
||||
y = g(g(y))
|
||||
d = gcd(math.abs(x-y),n)
|
||||
end
|
||||
if d == n then return d end
|
||||
return math.min(d, math.floor( n/d ) )
|
||||
end
|
||||
|
||||
local ar, product = {2}, 2
|
||||
repeat
|
||||
ar[ #ar + 1 ] = pollard_rho( product + 1 )
|
||||
product = product * ar[ #ar ]
|
||||
until #ar >= 8
|
||||
print( table.concat(ar, " ") )
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
// find elements of the Euclid-Mullin sequence: starting from 2,
|
||||
// the next element is the smallest prime factor of 1 + the product
|
||||
// of the previous elements
|
||||
seq = [2]
|
||||
product = 2
|
||||
for i in range( 2, 8 )
|
||||
nextV = product + 1
|
||||
// find the first prime factor of nextV
|
||||
p = 3
|
||||
found = false
|
||||
while p * p <= nextV and not found
|
||||
found = nextV % p == 0
|
||||
if not found then p = p + 2
|
||||
end while
|
||||
if found then nextV = p
|
||||
seq.push( nextV )
|
||||
product = product * nextV
|
||||
end for
|
||||
print seq.join( " ")
|
||||
18
Task/Euclid-Mullin-sequence/Ring/euclid-mullin-sequence.ring
Normal file
18
Task/Euclid-Mullin-sequence/Ring/euclid-mullin-sequence.ring
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
// find elements of the Euclid-Mullin sequence: starting from 2,
|
||||
// the next element is the smallest prime factor of 1 + the product
|
||||
// of the previous elements
|
||||
see "2"
|
||||
product = 2
|
||||
for i = 2 to 8
|
||||
nextV = product + 1
|
||||
// find the first prime factor of nextV
|
||||
p = 3
|
||||
found = false
|
||||
while p * p <= nextV and not found
|
||||
found = ( nextV % p ) = 0
|
||||
if not found p = p + 2 ok
|
||||
end
|
||||
if found nextV = p ok
|
||||
see " " + nextV
|
||||
product = product * nextV
|
||||
next
|
||||
15
Task/Euclid-Mullin-sequence/Ruby/euclid-mullin-sequence.rb
Normal file
15
Task/Euclid-Mullin-sequence/Ruby/euclid-mullin-sequence.rb
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
def pollard_rho(n)
|
||||
x, y, d = 2, 2, 1
|
||||
g = proc{|x|(x*x+1) % n}
|
||||
while d == 1 do
|
||||
x = g[x]
|
||||
y = g[g[y]]
|
||||
d = (x-y).abs.gcd(n)
|
||||
end
|
||||
return d if d == n
|
||||
[d, n/d].compact.min
|
||||
end
|
||||
|
||||
ar = [2]
|
||||
ar << pollard_rho(ar.inject(&:*)+1) until ar.size >= 16
|
||||
puts ar.join(", ")
|
||||
|
|
@ -4,33 +4,9 @@ var zero = BigInt.zero
|
|||
var one = BigInt.one
|
||||
var two = BigInt.two
|
||||
var ten = BigInt.ten
|
||||
var max = BigInt.new(100000)
|
||||
var k100 = BigInt.new(100000)
|
||||
|
||||
var pollardRho = Fn.new { |n, c|
|
||||
var g = Fn.new { |x, y| (x*x + c) % n }
|
||||
var x = two
|
||||
var y = two
|
||||
var z = one
|
||||
var d = max + one
|
||||
var count = 0
|
||||
while (true) {
|
||||
x = g.call(x, n)
|
||||
y = g.call(g.call(y, n), n)
|
||||
d = (x - y).abs % n
|
||||
z = z * d
|
||||
count = count + 1
|
||||
if (count == 100) {
|
||||
d = BigInt.gcd(z, n)
|
||||
if (d != one) break
|
||||
z = one
|
||||
count = 0
|
||||
}
|
||||
}
|
||||
if (d == n) return zero
|
||||
return d
|
||||
}
|
||||
|
||||
var smallestPrimeFactorWheel = Fn.new { |n|
|
||||
var smallestPrimeFactorWheel = Fn.new { |n, max|
|
||||
if (n.isProbablePrime(5)) return n
|
||||
if (n % 2 == zero) return BigInt.two
|
||||
if (n % 3 == zero) return BigInt.three
|
||||
|
|
@ -47,23 +23,22 @@ var smallestPrimeFactorWheel = Fn.new { |n|
|
|||
}
|
||||
|
||||
var smallestPrimeFactor = Fn.new { |n|
|
||||
var s = smallestPrimeFactorWheel.call(n)
|
||||
var s = smallestPrimeFactorWheel.call(n, k100)
|
||||
if (s) return s
|
||||
var c = one
|
||||
s = n
|
||||
while (n > max) {
|
||||
var d = pollardRho.call(n, c)
|
||||
while (true) {
|
||||
var d = BigInt.pollardRho(n, 2, c)
|
||||
if (d == 0) {
|
||||
if (c == ten) Fiber.abort("Pollard Rho doesn't appear to be working.")
|
||||
c = c + one
|
||||
} else {
|
||||
// can't be sure PR will find the smallest prime factor first
|
||||
s = BigInt.min(s, d)
|
||||
n = n / d
|
||||
if (n.isProbablePrime(2)) return BigInt.min(s, n)
|
||||
// get the smallest prime factor of 'd'
|
||||
var factor = smallestPrimeFactorWheel.call(d, d)
|
||||
// check whether n/d has a smaller prime factor
|
||||
s = smallestPrimeFactorWheel.call(n/d, factor)
|
||||
return s ? BigInt.min(s, factor) : factor
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
var k = 16
|
||||
|
|
|
|||
|
|
@ -2,45 +2,38 @@
|
|||
|
||||
import "./gmp" for Mpz
|
||||
|
||||
var max = Mpz.from(100000)
|
||||
var k100 = Mpz.from(100000)
|
||||
|
||||
var smallestPrimeFactorWheel = Fn.new { |n|
|
||||
var smallestPrimeFactorTrial = Fn.new { |n, max|
|
||||
if (n.probPrime(15) > 0) return n
|
||||
if (n.isEven) return Mpz.two
|
||||
if (n.isDivisibleUi(3)) return Mpz.three
|
||||
if (n.isDivisibleUi(5)) return Mpz.five
|
||||
var k = Mpz.from(7)
|
||||
var i = 0
|
||||
var inc = [4, 2, 4, 2, 4, 6, 2, 6]
|
||||
var k = Mpz.one
|
||||
while (k * k <= n) {
|
||||
if (n.isDivisible(k)) return k
|
||||
k.add(inc[i])
|
||||
k.nextPrime
|
||||
if (k > max) return null
|
||||
i = (i + 1) % 8
|
||||
if (n.isDivisible(k)) return k
|
||||
}
|
||||
}
|
||||
|
||||
var smallestPrimeFactor = Fn.new { |n|
|
||||
var s = smallestPrimeFactorWheel.call(n)
|
||||
var s = smallestPrimeFactorTrial.call(n, k100)
|
||||
if (s) return s
|
||||
var c = Mpz.one
|
||||
s = n.copy()
|
||||
while (n > max) {
|
||||
while (true) {
|
||||
var d = Mpz.pollardRho(n, 2, c)
|
||||
if (d.isZero) {
|
||||
if (c == 100) Fiber.abort("Pollard Rho doesn't appear to be working.")
|
||||
c.inc
|
||||
} else {
|
||||
// can't be sure PR will find the smallest prime factor first
|
||||
s.min(d)
|
||||
n.div(d)
|
||||
if (n.probPrime(5) > 0) return Mpz.min(s, n)
|
||||
// get the smallest prime factor of 'd'
|
||||
var factor = smallestPrimeFactorTrial.call(d, d)
|
||||
// check whether n/d has a smaller prime factor
|
||||
s = smallestPrimeFactorTrial.call(n/d, factor)
|
||||
return s ? Mpz.min(s, factor) : factor
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
var k = 19
|
||||
var k = 27
|
||||
System.print("First %(k) terms of the Euclid–Mullin sequence:")
|
||||
System.print(2)
|
||||
var prod = Mpz.two
|
||||
|
|
|
|||
65
Task/Execute-Brain-/Commodore-BASIC/execute-brain-.basic
Normal file
65
Task/Execute-Brain-/Commodore-BASIC/execute-brain-.basic
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
100 REM BRAINF*CK FOR COMMODORE BASIC
|
||||
110 DB=0:REM SET TO 1 FOR DEBUGGING
|
||||
120 P$=""
|
||||
130 READ C$
|
||||
140 P$=P$+C$
|
||||
150 IF LEN(C$)<>0 THEN 130
|
||||
160 REM PAIR UP BRACKETS INTO B%
|
||||
170 DIM B%(LEN(P$))
|
||||
180 REM TRACK OPEN BRACKETS IN O%
|
||||
190 DIM O%(INT(LEN(P$)/2)):O=0
|
||||
200 FOR I=1 TO LEN(P$)
|
||||
210 : I$=MID$(P$,I,1)
|
||||
220 : IF I$="[" THEN O%(O)=I:O=O+1
|
||||
230 : IF I$<>"]" THEN 270
|
||||
240 : IF O=0 THEN PRINT "UNMATCHED BRACKET AT"I". ABORTING.":END
|
||||
250 : O=O-1:M=O%(O)
|
||||
260 : B%(I)=M:B%(M)=I
|
||||
270 NEXT I
|
||||
280 IF O THEN PRINT "UNMATCHED BRACKETS AT EOF. ABORTING.":END
|
||||
290 REM SET MS TO NUMBER OF MEMORY CELLS NEEDED.
|
||||
300 REM THE BF SPEC REQUIRES 30000, WHICH WILL WORK ON C64 OR 48K+ PET.
|
||||
310 AN UNEXPANDED VIC-20 WILL HANDLE 1000, A C-16 9000. THE DEMO ONLY NEEDS 4.
|
||||
320 MS=4:DIM M%(MS/2-1):MP=0
|
||||
330 REM FUNCTION TO READ BYTE AT CELL N
|
||||
340 DEF FNMP(N)=INT(M%(INT(N/2)) / (1+255*(N AND 1))) AND 255
|
||||
350 FOR I=1 TO LEN(P$)
|
||||
360 : IF MP<0 OR MP>=MS THEN PRINT "ERROR: MP OUT OF RANGE AT"I:END
|
||||
370 : IF DB THEN PRINT "IP:"I"("I$") MP: "MP"("FNMP(MP)")"
|
||||
380 : I$=MID$(P$,I,1)
|
||||
390 : IF I$<>"[" THEN 420
|
||||
400 : IF FNMP(MP)=0 THEN I=B%(I)
|
||||
410 : GOTO 530
|
||||
420 : IF I$<>"]" THEN 450
|
||||
430 : IF FNMP(MP) THEN I=B%(I)
|
||||
440 : GOTO 530
|
||||
450 : IF I$="<" THEN MP=MP-1:GOTO 530
|
||||
460 : IF I$=">" THEN MP=MP+1:GOTO 530
|
||||
470 : IF I$="-" THEN V=FNMP(MP)-1:GOTO 560
|
||||
480 : IF I$="+" THEN V=FNMP(MP)+1:GOTO 560
|
||||
490 : IF I$="." THEN PRINTCHR$(FNMP(MP));:GOTO 530
|
||||
500 : IF I$<>"," THEN 530
|
||||
510 : GET K$:IF K$="" THEN 510
|
||||
520 : V=ASC(K$):GOTO 560
|
||||
530 NEXT I
|
||||
540 END
|
||||
550 REM UPDATE CELL AT MP WITH VALUE IN V
|
||||
560 M=INT(MP/2):O=M%(M):V=V AND 255
|
||||
570 N0=(O AND -256)+V
|
||||
580 N1=(V*256+(O AND 255))
|
||||
590 M%(M) = (MP AND 1)*N1 - ((MP AND 1)=0)*N0
|
||||
600 GOTO 530
|
||||
610 REM HELLO, WORLD PROGRAM
|
||||
620 DATA "+++++++++[>++++++++<-]>."
|
||||
630 DATA "---."
|
||||
640 DATA "+++++++..+++."
|
||||
650 DATA ">>++++[<+++++++++++>-]<."
|
||||
660 DATA ">++++[<--->-]<."
|
||||
670 DATA "<++++++++."
|
||||
680 DATA "--------."
|
||||
690 DATA "+++."
|
||||
700 DATA "------."
|
||||
710 DATA "--------."
|
||||
720 DATA ">>[++][<+++++++>-]<+."
|
||||
730 DATA ">++++++++++."
|
||||
740 DATA ""
|
||||
73
Task/Execute-Brain-/TRS-80-BASIC/execute-brain-.basic
Normal file
73
Task/Execute-Brain-/TRS-80-BASIC/execute-brain-.basic
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
100 REM BRAINF*CK FOR TRS-80 LEVEL II BASIC
|
||||
103 DB=0:REM SET TO 1 FOR DEBUGGING
|
||||
105 REM FIRST MAKE SURE WE HAVE ENOUGH STRING HEAP FOR PROGRAM
|
||||
110 READ C$:C=LEN(C$):IF C>M THEN M=C
|
||||
120 PS=PS+C
|
||||
130 IF C THEN 110
|
||||
135 REM ALLOCATE THE HEAP
|
||||
140 CLEAR 2*(PS+M)
|
||||
145 REM RE-READ PROGRAM, REMEMBERING IT THIS TIME
|
||||
150 RESTORE
|
||||
160 P$=""
|
||||
170 READ C$
|
||||
180 P$=P$+C$
|
||||
190 IF LEN(C$)<>0 THEN 170
|
||||
195 REM PAIR UP BRACKETS INTO B%
|
||||
200 DIM B%(LEN(P$))
|
||||
205 REM TRACK OPEN BRACKETS IN O%
|
||||
210 DIM O%(INT(LEN(P$)/2)):O=0
|
||||
220 FOR I=1 TO LEN(P$)
|
||||
230 : I$=MID$(P$,I,1)
|
||||
240 : IF I$="(" OR I$="[" THEN O%(O)=I:O=O+1
|
||||
250 : IF I$<>")" AND I$<>"]" THEN 290
|
||||
260 : IF O=0 THEN PRINT "UNMATCHED BRACKET AT"I". ABORTING.":END
|
||||
270 : O=O-1:M=O%(O)
|
||||
280 : B%(I)=M:B%(M)=I
|
||||
290 NEXT I
|
||||
300 IF O THEN PRINT "UNMATCHED BRACKETS AT EOF. ABORTING.":END
|
||||
303 REM SET MS TO NUMBER OF MEMORY CELLS NEEDED
|
||||
305 REM THE BF SPEC REQUIRES 30000, WHICH DOES WORK ON A SYSTEM WITH 48K RAM.
|
||||
307 REM THE DEMO HELLO-WORLD PROGRAM ONLY REQUIRES 4 CELLS.
|
||||
310 MS=4:DIM M%(MS/2-1):MP=0
|
||||
313 REM FUNCTION TO READ BYTE AT CELL N
|
||||
315 DEF FNMP(N)=INT(M%(INT(N/2)) / (1+255*(N AND 1))) AND 255
|
||||
320 FOR I=1 TO LEN(P$)
|
||||
323 : IF MP<0 OR MP>=MS THEN PRINT "ERROR: MP OUT OF RANGE AT"I:END
|
||||
327 : IF DB THEN PRINT "IP:"I"("I$") MP:"MP"("FNMP(MP)")"
|
||||
330 : I$=MID$(P$,I,1)
|
||||
340 : IF I$<>"(" AND I$<>"[" THEN 370
|
||||
350 : IF FNMP(MP)=0 THEN I=B%(I)
|
||||
360 : GOTO 480
|
||||
370 : IF I$<>")" AND I$<>"]" THEN 400
|
||||
380 : IF FNMP(MP) THEN I=B%(I)
|
||||
390 : GOTO 480
|
||||
400 : IF I$="<" THEN MP=MP-1:GOTO 480
|
||||
410 : IF I$=">" THEN MP=MP+1:GOTO 480
|
||||
420 : IF I$="-" THEN V=FNMP(MP)-1:GOTO 500
|
||||
430 : IF I$="+" THEN V=FNMP(MP)+1:GOTO 500
|
||||
440 : IF I$="." THEN ?CHR$(FNMP(MP));:GOTO 480
|
||||
450 : IF I$<>"," THEN 480
|
||||
460 : K$=INKEY$:IF K$="" THEN 460
|
||||
470 : V=ASC(K$):GOTO 500
|
||||
480 NEXT I
|
||||
490 END
|
||||
495 REM UPDATE CELL AT MP WITH VALUE IN V
|
||||
500 M=INT(MP/2):O=M%(M):V=V AND 255
|
||||
510 N0=(O AND -256)+V
|
||||
520 N1=(V*256+(O AND 255))
|
||||
530 M%(M) = (MP AND 1)*N1 - ((MP AND 1)=0)*N0
|
||||
540 GOTO 480
|
||||
545 REM HELLO, WORLD PROGRAM
|
||||
570 DATA "+++++++++[>++++++++<-]>."
|
||||
580 DATA "<+++++[>+++++<-]>++++."
|
||||
590 DATA "+++++++..+++."
|
||||
600 DATA ">>++++[<+++++++++++>-]<."
|
||||
610 DATA ">++++[<--->-]<."
|
||||
620 DATA "<++++++++."
|
||||
630 DATA "--------."
|
||||
640 DATA "+++."
|
||||
650 DATA "------."
|
||||
660 DATA "--------."
|
||||
670 DATA ">>[++][<+++++++>-]<+."
|
||||
680 DATA ">++++++++++."
|
||||
690 DATA ""
|
||||
|
|
@ -0,0 +1,53 @@
|
|||
local fn IsPrime( n as NSUInteger ) as BOOL
|
||||
BOOL isPrime = YES
|
||||
NSUInteger i
|
||||
|
||||
if n < 2 then exit fn = NO
|
||||
if n = 2 then exit fn = YES
|
||||
if n mod 2 == 0 then exit fn = NO
|
||||
for i = 3 to int(n^.5) step 2
|
||||
if n mod i == 0 then exit fn = NO
|
||||
next
|
||||
end fn = isPrime
|
||||
|
||||
|
||||
local fn ExtensiblePrimes
|
||||
long c = 0, n = 2, count = 0, track = 0
|
||||
|
||||
printf @"The first 20 prime numbers are: "
|
||||
while ( c < 20 )
|
||||
if ( fn IsPrime(n) )
|
||||
printf @"%ld \b", n
|
||||
c++
|
||||
end if
|
||||
n++
|
||||
wend
|
||||
|
||||
printf @"\n\nPrimes between 100 and 150 include: "
|
||||
for n = 100 to 150
|
||||
if ( fn IsPrime(n) ) then printf @"%ld \b", n
|
||||
next
|
||||
|
||||
printf @"\n\nPrimes beween 7,700 and 8,000 include: "
|
||||
c = 0
|
||||
for n = 7700 to 8000
|
||||
if ( fn IsPrime(n) ) then c += fn IsPrime(n) : printf @"%ld \b", n : count++ : track++
|
||||
if count = 10 then print : count = 0
|
||||
next
|
||||
printf @"There are %ld primes beween 7,700 and 8,000.", track
|
||||
|
||||
printf @"\nThe 10,000th prime is: "
|
||||
c = 0 : n = 1
|
||||
while ( c < 10000 )
|
||||
n++
|
||||
c += fn IsPrime(n)
|
||||
wend
|
||||
printf @"%ld", n
|
||||
end fn
|
||||
|
||||
CFTimeInterval t
|
||||
|
||||
t = fn CACurrentMediaTime
|
||||
fn ExtensiblePrimes
|
||||
printf @"\nCompute time: %.3f ms",(fn CACurrentMediaTime-t)*100
|
||||
HandleEvents
|
||||
142
Task/Filter/AArch64-Assembly/filter.aarch64
Normal file
142
Task/Filter/AArch64-Assembly/filter.aarch64
Normal file
|
|
@ -0,0 +1,142 @@
|
|||
/* ARM assembly AARCH64 Raspberry PI 3B */
|
||||
/* program filterdes64.s */
|
||||
|
||||
/************************************/
|
||||
/* Constantes */
|
||||
/************************************/
|
||||
/* for this file see task include a file in language AArch64 assembly*/
|
||||
.include "../includeConstantesARM64.inc"
|
||||
|
||||
/************************************/
|
||||
/* Initialized data */
|
||||
/************************************/
|
||||
.data
|
||||
szMessResult: .asciz "Start array : "
|
||||
szMessResultFil: .asciz "Filter array : "
|
||||
szMessResultdest: .asciz "Same array : "
|
||||
szMessStart: .asciz "Program 64 bits start.\n"
|
||||
szCarriageReturn: .asciz "\n"
|
||||
szFiller: .asciz " "
|
||||
.align 4
|
||||
arrayNumber: .quad 1,2,3,4,5,6,7,8,9,10
|
||||
.equ LGARRAY, (. - arrayNumber) / 8
|
||||
/************************************/
|
||||
/* UnInitialized data */
|
||||
/************************************/
|
||||
.bss
|
||||
.align 4
|
||||
arrayNumberFil: .skip 8 * LGARRAY // result array
|
||||
sZoneConv: .skip 24
|
||||
/************************************/
|
||||
/* code section */
|
||||
/************************************/
|
||||
.text
|
||||
.global main
|
||||
main:
|
||||
ldr x0,qAdrszMessStart // display start message
|
||||
bl affichageMess
|
||||
ldr x0,qAdrszMessResult // display message
|
||||
bl affichageMess
|
||||
ldr x5,qAdrarrayNumber // start array address
|
||||
mov x4,#0 // index
|
||||
|
||||
1:
|
||||
ldr x0,[x5,x4,lsl #3] // load a value
|
||||
ldr x1,qAdrsZoneConv
|
||||
bl conversion10 // décimal conversion
|
||||
ldr x0,qAdrsZoneConv
|
||||
bl affichageMess // display value
|
||||
ldr x0,qAdrszFiller
|
||||
bl affichageMess
|
||||
add x4,x4,#1 // increment index
|
||||
cmp x4,#LGARRAY // end array ?
|
||||
blt 1b // no -> loop
|
||||
ldr x0,qAdrszCarriageReturn
|
||||
bl affichageMess
|
||||
|
||||
ldr x6,qAdrarrayNumberFil // adrress result array
|
||||
mov x4,#0 // index
|
||||
mov x3,#0 // index result
|
||||
2:
|
||||
ldr x0,[x5,x4,lsl #3] // load a value
|
||||
tst x0,#1 // odd ?
|
||||
bne 3f
|
||||
str x0,[x6,x3,lsl #3] // no -> store in result array
|
||||
add x3,x3,#1 // and increment result index
|
||||
3:
|
||||
add x4,x4,#1 // increment array index
|
||||
cmp x4,#LGARRAY // end ?
|
||||
blt 2b // no -> loop
|
||||
|
||||
ldr x0,qAdrszMessResultFil
|
||||
bl affichageMess
|
||||
mov x4,#0 // init index
|
||||
|
||||
4: // display filter result array
|
||||
ldr x0,[x6,x4,lsl #3]
|
||||
ldr x1,qAdrsZoneConv
|
||||
bl conversion10
|
||||
ldr x0,qAdrsZoneConv
|
||||
bl affichageMess
|
||||
ldr x0,qAdrszFiller
|
||||
bl affichageMess
|
||||
add x4,x4,#1
|
||||
cmp x4,x3
|
||||
blt 4b
|
||||
ldr x0,qAdrszCarriageReturn
|
||||
bl affichageMess
|
||||
|
||||
// array destruction
|
||||
mov x4,#0 // index
|
||||
mov x3,#0 // index result
|
||||
5:
|
||||
ldr x0,[x5,x4,lsl #3] // load a value
|
||||
tst x0,#1 // odd ?
|
||||
bne 7f
|
||||
cmp x3,x4 // index = no store
|
||||
beq 6f
|
||||
str x0,[x5,x3,lsl #3] // store in free item on same array
|
||||
6:
|
||||
add x3,x3,#1 // and increment result index
|
||||
7:
|
||||
add x4,x4,#1 // increment array index
|
||||
cmp x4,#LGARRAY // end ?
|
||||
blt 5b // no -> loop
|
||||
|
||||
ldr x0,qAdrszMessResultdest
|
||||
bl affichageMess
|
||||
mov x4,#0 // init index
|
||||
|
||||
8: // display array
|
||||
ldr x0,[x5,x4,lsl #3]
|
||||
ldr x1,qAdrsZoneConv
|
||||
bl conversion10
|
||||
ldr x0,qAdrsZoneConv
|
||||
bl affichageMess
|
||||
ldr x0,qAdrszFiller
|
||||
bl affichageMess
|
||||
add x4,x4,#1
|
||||
cmp x4,x3
|
||||
blt 8b
|
||||
ldr x0,qAdrszCarriageReturn
|
||||
bl affichageMess
|
||||
|
||||
|
||||
100: // standard end of the program
|
||||
mov x0, #0 // return code
|
||||
mov x8, #EXIT // request to exit program
|
||||
svc 0 // perform the system call
|
||||
qAdrszCarriageReturn: .quad szCarriageReturn
|
||||
qAdrszMessStart: .quad szMessStart
|
||||
qAdrarrayNumber: .quad arrayNumber
|
||||
qAdrszMessResult: .quad szMessResult
|
||||
qAdrarrayNumberFil: .quad arrayNumberFil
|
||||
qAdrszMessResultFil: .quad szMessResultFil
|
||||
qAdrszMessResultdest: .quad szMessResultdest
|
||||
qAdrsZoneConv: .quad sZoneConv
|
||||
qAdrszFiller: .quad szFiller
|
||||
/***************************************************/
|
||||
/* ROUTINES INCLUDE */
|
||||
/***************************************************/
|
||||
/* for this file see task include a file in language AArch64 assembly*/
|
||||
.include "../includeARM64.inc"
|
||||
144
Task/Filter/ARM-Assembly/filter.arm
Normal file
144
Task/Filter/ARM-Assembly/filter.arm
Normal file
|
|
@ -0,0 +1,144 @@
|
|||
/* ARM assembly Raspberry PI */
|
||||
/* program filterdes.s */
|
||||
|
||||
/************************************/
|
||||
/* Constantes */
|
||||
/************************************/
|
||||
/* for constantes see task include a file in arm assembly */
|
||||
.include "../constantes.inc"
|
||||
|
||||
/************************************/
|
||||
/* Initialized data */
|
||||
/************************************/
|
||||
.data
|
||||
szMessResult: .asciz "Start array : "
|
||||
szMessResultFil: .asciz "Filter array : "
|
||||
szMessResultdest: .asciz "Same array : "
|
||||
szMessStart: .asciz "Program 32 bits start.\n"
|
||||
szCarriageReturn: .asciz "\n"
|
||||
.align 4
|
||||
arrayNumber: .int 1,2,3,4,5,6,7,8,9,10
|
||||
.equ LGARRAY, (. - arrayNumber) / 4
|
||||
/************************************/
|
||||
/* UnInitialized data */
|
||||
/************************************/
|
||||
.bss
|
||||
.align 4
|
||||
arrayNumberFil: .skip 4 * LGARRAY @ result array
|
||||
sZoneConv: .skip 24
|
||||
/************************************/
|
||||
/* code section */
|
||||
/************************************/
|
||||
.text
|
||||
.global main
|
||||
main:
|
||||
ldr r0,iAdrszMessStart @ display start message
|
||||
bl affichageMess
|
||||
ldr r0,iAdrszMessResult @ display message
|
||||
bl affichageMess
|
||||
ldr r5,iAdrarrayNumber @ start array address
|
||||
mov r4,#0 @ index
|
||||
|
||||
1:
|
||||
ldr r0,[r5,r4,lsl #2] @ load a value
|
||||
ldr r1,iAdrsZoneConv
|
||||
bl conversion10 @ décimal conversion
|
||||
add r1,r1,r0 @ compute address end number
|
||||
add r1,#2 @ add two characters
|
||||
mov r0,#0 @ for limit the size of display number
|
||||
strb r0,[r1] @ to store a final zero
|
||||
ldr r0,iAdrsZoneConv
|
||||
bl affichageMess @ display value
|
||||
add r4,r4,#1 @ increment index
|
||||
cmp r4,#LGARRAY @ end array ?
|
||||
blt 1b @ no -> loop
|
||||
ldr r0,iAdrszCarriageReturn
|
||||
bl affichageMess
|
||||
|
||||
ldr r6,iAdrarrayNumberFil @ adrress result array
|
||||
mov r4,#0 @ index
|
||||
mov r3,#0 @ index result
|
||||
2:
|
||||
ldr r0,[r5,r4,lsl #2] @ load a value
|
||||
tst r0,#1 @ odd ?
|
||||
streq r0,[r6,r3,lsl #2] @ no -> store in result array
|
||||
addeq r3,r3,#1 @ and increment result index
|
||||
add r4,r4,#1 @ increment array index
|
||||
cmp r4,#LGARRAY @ end ?
|
||||
blt 2b @ no -> loop
|
||||
|
||||
ldr r0,iAdrszMessResultFil
|
||||
bl affichageMess
|
||||
mov r4,#0 @ init index
|
||||
|
||||
3: @ display filter result array
|
||||
ldr r0,[r6,r4,lsl #2]
|
||||
ldr r1,iAdrsZoneConv
|
||||
bl conversion10
|
||||
add r1,r1,r0
|
||||
add r1,#2
|
||||
mov r0,#0
|
||||
strb r0,[r1]
|
||||
ldr r0,iAdrsZoneConv
|
||||
bl affichageMess
|
||||
add r4,r4,#1
|
||||
cmp r4,r3
|
||||
blt 3b
|
||||
ldr r0,iAdrszCarriageReturn
|
||||
bl affichageMess
|
||||
|
||||
@ array destruction
|
||||
mov r4,#0 @ index
|
||||
mov r3,#0 @ index result
|
||||
4:
|
||||
ldr r0,[r5,r4,lsl #2] @ load a value
|
||||
tst r0,#1 @ even ?
|
||||
bne 6f
|
||||
cmp r3,r4 @ index = no store
|
||||
beq 5f
|
||||
str r0,[r5,r3,lsl #2] @ store in free item on same array
|
||||
5:
|
||||
add r3,r3,#1 @ and increment result index
|
||||
6:
|
||||
add r4,r4,#1 @ increment array index
|
||||
cmp r4,#LGARRAY @ end ?
|
||||
blt 4b @ no -> loop
|
||||
|
||||
ldr r0,iAdrszMessResultdest
|
||||
bl affichageMess
|
||||
mov r4,#0 @ init index
|
||||
|
||||
7: @ display array
|
||||
ldr r0,[r5,r4,lsl #2]
|
||||
ldr r1,iAdrsZoneConv
|
||||
bl conversion10
|
||||
add r1,r1,r0
|
||||
add r1,#2
|
||||
mov r0,#0
|
||||
strb r0,[r1]
|
||||
ldr r0,iAdrsZoneConv
|
||||
bl affichageMess
|
||||
add r4,r4,#1
|
||||
cmp r4,r3
|
||||
blt 7b
|
||||
ldr r0,iAdrszCarriageReturn
|
||||
bl affichageMess
|
||||
|
||||
|
||||
100: @ standard end of the program
|
||||
mov r0, #0 @ return code
|
||||
mov r7, #EXIT @ request to exit program
|
||||
svc 0 @ perform the system call
|
||||
iAdrszCarriageReturn: .int szCarriageReturn
|
||||
iAdrszMessStart: .int szMessStart
|
||||
iAdrarrayNumber: .int arrayNumber
|
||||
iAdrszMessResult: .int szMessResult
|
||||
iAdrarrayNumberFil: .int arrayNumberFil
|
||||
iAdrszMessResultFil: .int szMessResultFil
|
||||
iAdrszMessResultdest: .int szMessResultdest
|
||||
iAdrsZoneConv: .int sZoneConv
|
||||
/***************************************************/
|
||||
/* ROUTINES INCLUDE */
|
||||
/***************************************************/
|
||||
/* for this file see task include a file in language ARM assembly*/
|
||||
.include "../affichage.inc"
|
||||
|
|
@ -0,0 +1,75 @@
|
|||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public final class FirstClassEnvironments {
|
||||
|
||||
public static void main(String[] aArgs) {
|
||||
code();
|
||||
}
|
||||
|
||||
private static void code() {
|
||||
do {
|
||||
for ( int job = 0; job < JOBS; job++ ) {
|
||||
switchTo(job);
|
||||
hailstone();
|
||||
}
|
||||
System.out.println();
|
||||
} while ( ! allDone() );
|
||||
|
||||
System.out.println(System.lineSeparator() + "Counts:");
|
||||
for ( int job = 0; job < JOBS; job++ ) {
|
||||
switchTo(job);
|
||||
System.out.print(String.format("%4d", count));
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
private static boolean allDone() {
|
||||
for ( int job = 0; job < JOBS; job++ ) {
|
||||
switchTo(job);
|
||||
if ( sequence > 1 ) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void hailstone() {
|
||||
System.out.print(String.format("%4d", sequence));
|
||||
if ( sequence == 1 ) {
|
||||
return;
|
||||
}
|
||||
|
||||
count += 1;
|
||||
sequence = ( sequence % 2 == 1 ) ? 3 * sequence + 1 : sequence / 2;
|
||||
}
|
||||
|
||||
private static void switchTo(int aID) {
|
||||
if ( aID != currentId ) {
|
||||
environments.get(currentId).seq = sequence;
|
||||
environments.get(currentId).count = count;
|
||||
currentId = aID;
|
||||
}
|
||||
|
||||
sequence = environments.get(aID).seq;
|
||||
count = environments.get(aID).count;
|
||||
}
|
||||
|
||||
private static class Environment {
|
||||
|
||||
public Environment(int aSeq, int aCount) {
|
||||
seq = aSeq; count = aCount;
|
||||
}
|
||||
|
||||
private int seq, count;
|
||||
|
||||
}
|
||||
|
||||
private static int sequence, count, currentId;
|
||||
private static List<Environment> environments =
|
||||
IntStream.rangeClosed(1, 12).mapToObj( i -> new Environment(i, 0 ) ).collect(Collectors.toList());
|
||||
|
||||
private static final int JOBS = 12;
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
import java.util.List;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.Function;
|
||||
|
||||
public class FirstClassFunctionsUseNumbersAnalogously {
|
||||
|
||||
public static void main(String[] args) {
|
||||
final double x = 2.0, xi = 0.5,
|
||||
y = 4.0, yi = 0.25,
|
||||
z = x + y, zi = 1.0 / ( x + y );
|
||||
|
||||
List<Double> list = List.of( x, y, z );
|
||||
List<Double> inverseList = List.of( xi, yi, zi );
|
||||
|
||||
BiFunction<Double, Double, Function<Double, Double>> multiplier = (a, b) -> product -> a * b * product;
|
||||
|
||||
for ( int i = 0; i < list.size(); i++ ) {
|
||||
Function<Double, Double> multiply = multiplier.apply(list.get(i), inverseList.get(i));
|
||||
final double argument = (double) ( i + 1 );
|
||||
System.out.println(multiply.apply(argument));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -3,9 +3,9 @@ Write a program that prints the integers from '''1''' to ''
|
|||
|
||||
|
||||
But:
|
||||
:* for multiples of three, print '''Fizz''' (instead of the number)
|
||||
:* for multiples of five, print '''Buzz''' (instead of the number)
|
||||
:* for multiples of both three and five, print '''FizzBuzz''' (instead of the number)
|
||||
:* for multiples of three, print '''Fizz''' instead of the number;
|
||||
:* for multiples of five, print '''Buzz''' instead of the number;
|
||||
:* for multiples of both three and five, print '''FizzBuzz''' instead of the number.
|
||||
|
||||
|
||||
The ''FizzBuzz'' problem was presented as the lowest level of comprehension required to illustrate adequacy.
|
||||
|
|
|
|||
1
Task/Flatten-a-list/Insitux/flatten-a-list.insitux
Normal file
1
Task/Flatten-a-list/Insitux/flatten-a-list.insitux
Normal file
|
|
@ -0,0 +1 @@
|
|||
(flatten [[1] 2 [[3 4] 5] [[[]]] [[[6]]] 7 8 []])
|
||||
50
Task/Fortunate-numbers/C++/fortunate-numbers.cpp
Normal file
50
Task/Fortunate-numbers/C++/fortunate-numbers.cpp
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <iostream>
|
||||
#include <set>
|
||||
#include <vector>
|
||||
|
||||
std::vector<int32_t> prime_numbers(const int32_t& limit) {
|
||||
const int32_t half_limit = ( limit % 2 == 0 ) ? limit / 2 : 1 + limit / 2;
|
||||
std::vector<bool> composite(half_limit, false);
|
||||
for ( int32_t i = 1, p = 3; i < half_limit; p += 2, ++i ) {
|
||||
if ( ! composite[i] ) {
|
||||
for ( int32_t a = i + p; a < half_limit; a += p ) {
|
||||
composite[a] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<int32_t> primes{2};
|
||||
for ( int32_t i = 1, p = 3; i < half_limit; p += 2, ++i ) {
|
||||
if ( ! composite[i] ) {
|
||||
primes.push_back(p);
|
||||
}
|
||||
}
|
||||
return primes;
|
||||
}
|
||||
|
||||
bool contains(const std::vector<int32_t>& list, const int32_t& n) {
|
||||
return std::find(list.begin(), list.end(), n) != list.end();
|
||||
}
|
||||
|
||||
int main() {
|
||||
std::vector<int32_t> primes = prime_numbers(250'000'000);
|
||||
std::set<int32_t> fortunates;
|
||||
int32_t primorial = 1;
|
||||
int32_t index = 0;
|
||||
|
||||
while ( fortunates.size() < 8 ) {
|
||||
primorial *= primes[index++];
|
||||
int32_t candidate = 3;
|
||||
while ( ! contains(primes, primorial + candidate) ) {
|
||||
candidate += 2;
|
||||
}
|
||||
fortunates.emplace(candidate);
|
||||
}
|
||||
|
||||
std::cout << "The first 8 distinct fortunate numbers are:" << std::endl;
|
||||
for ( const int32_t& fortunate : fortunates ) {
|
||||
std::cout << fortunate << " ";
|
||||
}
|
||||
}
|
||||
41
Task/Fortunate-numbers/Java/fortunate-numbers.java
Normal file
41
Task/Fortunate-numbers/Java/fortunate-numbers.java
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
import java.math.BigInteger;
|
||||
import java.util.BitSet;
|
||||
import java.util.NavigableSet;
|
||||
import java.util.TreeSet;
|
||||
|
||||
public final class FortunateNumbers {
|
||||
|
||||
public static void main(String[] aArgs) {
|
||||
BitSet primes = primeSieve(400);
|
||||
NavigableSet<Integer> fortunates = new TreeSet<Integer>();
|
||||
BigInteger primorial = BigInteger.ONE;
|
||||
|
||||
for ( int prime = 2; prime >= 0; prime = primes.nextSetBit(prime + 1) ) {
|
||||
primorial = primorial.multiply(BigInteger.valueOf(prime));
|
||||
int candidate = 3;
|
||||
while ( ! primorial.add(BigInteger.valueOf(candidate)).isProbablePrime(CERTAINTY_LEVEL) ) {
|
||||
candidate += 2;
|
||||
}
|
||||
fortunates.add(candidate);
|
||||
}
|
||||
|
||||
System.out.println("The first 50 distinct fortunate numbers are:");
|
||||
for ( int i = 0; i < 50; i++ ) {
|
||||
System.out.print(String.format("%4d%s", fortunates.pollFirst(), ( i % 10 == 9 ? "\n" : "" )));
|
||||
}
|
||||
}
|
||||
|
||||
private static BitSet primeSieve(int aNumber) {
|
||||
BitSet sieve = new BitSet(aNumber + 1);
|
||||
sieve.set(2, aNumber + 1);
|
||||
for ( int i = 2; i <= Math.sqrt(aNumber); i = sieve.nextSetBit(i + 1) ) {
|
||||
for ( int j = i * i; j <= aNumber; j = j + i ) {
|
||||
sieve.clear(j);
|
||||
}
|
||||
}
|
||||
return sieve;
|
||||
}
|
||||
|
||||
private static final int CERTAINTY_LEVEL = 10;
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
(-> (map char-code "az")
|
||||
(adj _ inc)
|
||||
(.. range)
|
||||
(map char-code))
|
||||
30
Task/Goldbachs-comet/BASIC256/goldbachs-comet.basic
Normal file
30
Task/Goldbachs-comet/BASIC256/goldbachs-comet.basic
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
#arraybase 1
|
||||
print "The first 100 G numbers are:"
|
||||
|
||||
col = 1
|
||||
for n = 4 to 202 step 2
|
||||
print rjust(string(g(n)), 4);
|
||||
if col mod 10 = 0 then print
|
||||
col += 1
|
||||
next n
|
||||
|
||||
print : print "G(1000000) = "; g(1000000)
|
||||
end
|
||||
|
||||
function isPrime(v)
|
||||
if v <= 1 then return False
|
||||
for i = 2 to int(sqrt(v))
|
||||
if v mod i = 0 then return False
|
||||
next i
|
||||
return True
|
||||
end function
|
||||
|
||||
function g(n)
|
||||
cont = 0
|
||||
if n mod 2 = 0 then
|
||||
for i = 2 to (1/2) * n
|
||||
if isPrime(i) = 1 and isPrime(n - i) = 1 then cont += 1
|
||||
next i
|
||||
end if
|
||||
g = cont
|
||||
end function
|
||||
76
Task/Goldbachs-comet/Java/goldbachs-comet.java
Normal file
76
Task/Goldbachs-comet/Java/goldbachs-comet.java
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
import java.awt.Color;
|
||||
import java.awt.Graphics;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
|
||||
public final class GoldbachsComet {
|
||||
|
||||
public static void main(String[] aArgs) {
|
||||
initialisePrimes(2_000_000);
|
||||
|
||||
System.out.println("The first 100 Goldbach numbers:");
|
||||
for ( int n = 2; n < 102; n++ ) {
|
||||
System.out.print(String.format("%3d%s", goldbachFunction(2 * n), ( n % 10 == 1 ? "\n" : "" )));
|
||||
}
|
||||
|
||||
System.out.println();
|
||||
System.out.println("The 1,000,000th Goldbach number = " + goldbachFunction(1_000_000));
|
||||
|
||||
createImage();
|
||||
}
|
||||
|
||||
private static void createImage() {
|
||||
final int width = 1040;
|
||||
final int height = 860;
|
||||
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
|
||||
Graphics graphics = image.getGraphics();
|
||||
graphics.setColor(Color.WHITE);
|
||||
graphics.fillRect(0, 0, width, height);
|
||||
|
||||
List<Color> colours = List.of( Color.BLUE, Color.GREEN, Color.RED );
|
||||
for ( int n = 2; n < 2002; n++ ) {
|
||||
graphics.setColor(colours.get(n % 3));
|
||||
graphics.fillOval(n / 2, height - 5 * goldbachFunction(2 * n), 10, 10);
|
||||
}
|
||||
|
||||
try {
|
||||
ImageIO.write(image, "png", new File("GoldbachsCometJava.png"));
|
||||
} catch (IOException ioe) {
|
||||
ioe.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private static int goldbachFunction(int aNumber) {
|
||||
if ( aNumber <= 2 || aNumber % 2 == 1 ) {
|
||||
throw new AssertionError("Argument must be even and greater than 2: " + aNumber);
|
||||
}
|
||||
|
||||
int result = 0;
|
||||
for ( int i = 1; i <= aNumber / 2; i++ ) {
|
||||
if ( primes[i] && primes[aNumber - i] ) {
|
||||
result += 1;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void initialisePrimes(int aLimit) {
|
||||
primes = new boolean[aLimit];
|
||||
for ( int i = 2; i < aLimit; i++ ) {
|
||||
primes[i] = true;
|
||||
}
|
||||
|
||||
for ( int n = 2; n < Math.sqrt(aLimit); n++ ) {
|
||||
for ( int k = n * n; k < aLimit; k += n ) {
|
||||
primes[k] = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean[] primes;
|
||||
|
||||
}
|
||||
47
Task/Gotchas/Java/gotchas.java
Normal file
47
Task/Gotchas/Java/gotchas.java
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
public final class Gotchas {
|
||||
|
||||
public static void main(String[] aArgs) {
|
||||
// Gotcha 1: An integer argument to a Collection, such as a List, sets the capacity of the Collection,
|
||||
// but does not fill the Collection with elements.
|
||||
List<Integer> numbers = new ArrayList<Integer>(100);
|
||||
// The above list has the capacity to hold 100 elements, but is currently empty.
|
||||
|
||||
// Setting the element with index 3 to a value of 42 will create a runtime exception,
|
||||
// because the list has length 0, and this element does not yet exist.
|
||||
numbers.set(3, 42);
|
||||
// The gotcha is only revealed when a runtime exception is thrown.
|
||||
System.out.println(numbers);
|
||||
// java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 0
|
||||
|
||||
// Gotcha 2: Copying a Collection in a simple manner works,
|
||||
// but means that changes to the original Collection are reflected in the copy,
|
||||
// which is not normally the desired outcome.
|
||||
Set<String> letters = new HashSet<String>();
|
||||
letters.add("a"); letters.add("b"); letters.add("c");
|
||||
|
||||
// Create a copy of the set.
|
||||
Set<String> copy = letters;
|
||||
// The two sets are identical.
|
||||
System.out.println(letters + " :: " + copy);
|
||||
|
||||
// Add an element to the set 'letters'.
|
||||
letters.add("d");
|
||||
// The same letter has been added to the set 'copy'.
|
||||
// Both sets now contain the same 4 letters.
|
||||
System.out.println(letters + " :: " + copy);
|
||||
// In a program this can cause mysterious results which can be difficult to debug.
|
||||
|
||||
// The correct way to copy a Collection is to use a copy constructor as shown below.
|
||||
Set<String> correctCopy = new HashSet<String>(letters);
|
||||
letters.add("e");
|
||||
|
||||
// The set 'correctCopy' only contains its original 4 letters.
|
||||
System.out.println(letters + " :: " + correctCopy);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -1,15 +1,56 @@
|
|||
window 1, @"Greatest Common Divisor", (0,0,480,270)
|
||||
begin enum 1 // Object tags
|
||||
_fldA
|
||||
_ansA
|
||||
_fldB
|
||||
_ansB
|
||||
_rand
|
||||
end enum
|
||||
|
||||
local fn gcd( a as short, b as short ) as short
|
||||
short result
|
||||
void local fn BuildMacInterface //15-line GUI
|
||||
window 1, @"Greatest Common Divisor", ( 0, 0, 380, 130 ), NSWindowStyleMaskTitled + NSWindowStyleMaskClosable
|
||||
textfield _fldA,,, ( 20, 89, 156, 21 )
|
||||
ControlSetAlignment( _fldA, NSTextAlignmentRight )
|
||||
ControlSetFormat( _fldA, @"0123456789", Yes, 18, 0 )
|
||||
textfield _fldB,,, ( 20, 57, 156, 24 )
|
||||
ControlSetAlignment( _fldB, NSTextAlignmentRight )
|
||||
ControlSetFormat( _fldB, @"0123456789", Yes, 18, 0 )
|
||||
textlabel _ansA, @"= ", ( 182, 91, 185, 16 )
|
||||
textlabel _ansB, @"= ", ( 182, 62, 185, 16 )
|
||||
button _rand,,,@"Random demo", ( 129, 13, 122, 32 )
|
||||
menu 1,,, @"File" : menu 1,0,, @"Close", @"w" : MenuItemSetAction(1,0,@"performClose:")
|
||||
editmenu 2
|
||||
WindowMakeFirstResponder( 1, _fldA )
|
||||
end fn
|
||||
|
||||
if ( b != 0 )
|
||||
result = fn gcd( b, a mod b)
|
||||
else
|
||||
result = abs(a)
|
||||
end if
|
||||
end fn = result
|
||||
local fn GCD( a as long, b as long ) as long //the requested function
|
||||
while b
|
||||
long c = a mod b
|
||||
a = b : b = c
|
||||
wend
|
||||
end fn = a
|
||||
|
||||
print fn gcd( 6, 9 )
|
||||
void local fn DoDialog( ev as Long, tag as long ) //This makes it interactive
|
||||
long a, b, c
|
||||
select ev
|
||||
case _textFieldDidchange //Find GCD of edit fields' contents
|
||||
a = fn ControlIntegerValue( _fldA )
|
||||
b = fn ControlIntegerValue( _fldB )
|
||||
if a + b == 0 then textlabel _ansA, @"=" : textlabel _ansB, @"=" : exit fn
|
||||
c = fn GCD( a, b )
|
||||
textlabel _ansA, fn stringwithformat(@"= %ld x %ld", c, a / c )
|
||||
textlabel _ansB, fn stringwithformat(@"= %ld x %ld", c, b / c )
|
||||
case _btnclick //Fill edit fields with random content, then process
|
||||
select tag
|
||||
case _rand
|
||||
c = rnd(65536)
|
||||
textfield _fldA,,str( c * rnd(65536) )
|
||||
textfield _fldB,,str( c * rnd(65536) )
|
||||
fn DoDialog( _textFieldDidchange, 0 )
|
||||
end select
|
||||
case _windowWillClose : end
|
||||
end select
|
||||
end fn
|
||||
|
||||
HandleEvents
|
||||
fn BuildMacInterface
|
||||
on dialog fn doDialog
|
||||
handleevents
|
||||
|
|
|
|||
39
Task/HTTPS-Authenticated/Java/https-authenticated.java
Normal file
39
Task/HTTPS-Authenticated/Java/https-authenticated.java
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
import java.io.IOException;
|
||||
import java.net.Authenticator;
|
||||
import java.net.PasswordAuthentication;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.net.http.HttpResponse.BodyHandlers;
|
||||
|
||||
public final class HTTPSAuthenticated {
|
||||
|
||||
public static void main(String[] aArgs) throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpClient client = HttpClient.newBuilder()
|
||||
.authenticator( new MyAuthenticator() )
|
||||
.build();
|
||||
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.GET()
|
||||
.uri( new URI("https://postman-echo.com/basic-auth") ) // This website requires authentication
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
|
||||
|
||||
System.out.println("Status: " + response.statusCode());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
final class MyAuthenticator extends Authenticator {
|
||||
|
||||
@Override
|
||||
protected PasswordAuthentication getPasswordAuthentication() {
|
||||
String username = "kingkong";
|
||||
String password = "test1234";
|
||||
return new PasswordAuthentication(username, password.toCharArray());
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,41 @@
|
|||
import java.io.BufferedInputStream;
|
||||
import java.io.FileInputStream;
|
||||
import java.net.URI;
|
||||
import java.net.URL;
|
||||
import java.security.KeyStore;
|
||||
import java.util.Scanner;
|
||||
|
||||
import javax.net.ssl.HttpsURLConnection;
|
||||
import javax.net.ssl.KeyManagerFactory;
|
||||
import javax.net.ssl.SSLContext;
|
||||
|
||||
public final class HTTPSClientAuthenticated {
|
||||
|
||||
public static void main(String[] aArgs) throws Exception {
|
||||
final String keyStorePath = "the/path/to/keystore"; // The key store contains the client's certificate
|
||||
final String keyStorePassword = "my-password";
|
||||
|
||||
SSLContext sslContext = getSSLContext(keyStorePath, keyStorePassword);
|
||||
URL url = new URI("https://somehost.com").toURL();
|
||||
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
|
||||
connection.setSSLSocketFactory(sslContext.getSocketFactory());
|
||||
|
||||
// Obtain response from the url
|
||||
BufferedInputStream response = (BufferedInputStream) connection.getInputStream();
|
||||
try ( Scanner scanner = new Scanner(response) ) {
|
||||
String responseBody = scanner.useDelimiter("\\A").next();
|
||||
System.out.println(responseBody);
|
||||
}
|
||||
}
|
||||
|
||||
private static SSLContext getSSLContext(String aPath, String aPassword) throws Exception {
|
||||
KeyStore keyStore = KeyStore.getInstance("pkcs12");
|
||||
keyStore.load( new FileInputStream(aPath), aPassword.toCharArray());
|
||||
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("PKIX");
|
||||
keyManagerFactory.init(keyStore, aPassword.toCharArray());
|
||||
SSLContext sslContext = SSLContext.getInstance("TLS");
|
||||
sslContext.init(keyManagerFactory.getKeyManagers(), null, null);
|
||||
return sslContext;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -11,3 +11,4 @@ repeat with n from 2 to 99999
|
|||
set end of nums to n
|
||||
end if
|
||||
end repeat
|
||||
return {|number(s) giving longest sequence length|:nums, |length of sequence|:longestLength}
|
||||
|
|
|
|||
11
Task/Halt-and-catch-fire/Java/halt-and-catch-fire.java
Normal file
11
Task/Halt-and-catch-fire/Java/halt-and-catch-fire.java
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
public final class HaltAndCatchFire {
|
||||
|
||||
public static void main(String[] aArgs) {
|
||||
// Any one of the lines below, when uncommented, will cause a program halt.
|
||||
|
||||
// throw new AssertionError("Stop now!");
|
||||
// System.out.println(0/0);
|
||||
// Runtime.getRuntime().exit(1);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -1,7 +1,6 @@
|
|||
import std::io;
|
||||
|
||||
fn int main()
|
||||
fn void main()
|
||||
{
|
||||
io::println("Hello, World!");
|
||||
return 0;
|
||||
io::printn("Hello, World!");
|
||||
}
|
||||
|
|
|
|||
20
Task/Hex-words/APL/hex-words.apl
Normal file
20
Task/Hex-words/APL/hex-words.apl
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
∇HexWords;todec;digroot;displayrow;words;distinct4
|
||||
todec←16⊥9+'abcdef'∘⍳
|
||||
digroot←(+/10⊥⍣¯1⊢)⍣(10≥⊢)
|
||||
displayrow←{⍵ n (digroot⊢n←todec ⍵)}
|
||||
|
||||
words←((~∊)∘⎕TC⊆⊢)⊃⎕NGET'unixdict.txt'
|
||||
words←(words∧.∊¨⊂⊂'abcdef')/words
|
||||
words←(4≤≢¨words)/words
|
||||
words←words[⍋digroot∘todec¨words]
|
||||
|
||||
distinct4←(4≤≢∘∪¨words)/words
|
||||
distinct4←distinct4[⍒todec¨distinct4]
|
||||
|
||||
⎕←(⍕≢words),' hex words with at least 4 letters in unixdict.txt:'
|
||||
⎕←↑displayrow¨words
|
||||
⎕←''
|
||||
|
||||
⎕←(⍕≢distinct4),' hex words with at least 4 distinct letters:'
|
||||
⎕←↑displayrow¨distinct4
|
||||
∇
|
||||
71
Task/Hex-words/C++/hex-words.cpp
Normal file
71
Task/Hex-words/C++/hex-words.cpp
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <fstream>
|
||||
#include <iomanip>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <unordered_set>
|
||||
#include <vector>
|
||||
|
||||
struct Item {
|
||||
std::string word;
|
||||
int32_t number;
|
||||
int32_t digital_root;
|
||||
};
|
||||
|
||||
void display(const std::vector<Item>& items) {
|
||||
std::cout << " Word Decimal value Digital root" << std::endl;
|
||||
std::cout << "----------------------------------------" << std::endl;
|
||||
for ( const Item& item : items ) {
|
||||
std::cout << std::setw(7) << item.word << std::setw(15) << item.number
|
||||
<< std::setw(12) << item.digital_root << std::endl;
|
||||
}
|
||||
std::cout << "\n" << "Total count: " << items.size() << "\n" << std::endl;
|
||||
}
|
||||
|
||||
int32_t digital_root(int32_t number) {
|
||||
int32_t result = 0;
|
||||
while ( number > 0 ) {
|
||||
result += number % 10;
|
||||
number /= 10;
|
||||
}
|
||||
return ( result <= 9 ) ? result : digital_root(result);
|
||||
}
|
||||
|
||||
bool contains_only(const std::string& word, const std::unordered_set<char>& acceptable) {
|
||||
return std::all_of(word.begin(), word.end(),
|
||||
[acceptable](char ch) { return acceptable.find(ch) != acceptable.end(); });
|
||||
}
|
||||
|
||||
int main() {
|
||||
const std::unordered_set<char> hex_digits{ 'a', 'b', 'c', 'd', 'e', 'f' };
|
||||
std::vector<Item> items;
|
||||
|
||||
std::fstream file_stream;
|
||||
file_stream.open("unixdict.txt");
|
||||
std::string word;
|
||||
while ( file_stream >> word ) {
|
||||
if ( word.length() >= 4 && contains_only(word, hex_digits)) {
|
||||
const int32_t value = std::stoi(word, 0, 16);
|
||||
int32_t root = digital_root(value);
|
||||
items.push_back(Item(word, value, root));
|
||||
}
|
||||
}
|
||||
|
||||
auto compare = [](Item a, Item b) {
|
||||
return ( a.digital_root == b.digital_root ) ? a.word < b.word : a.digital_root < b.digital_root;
|
||||
};
|
||||
std::sort(items.begin(), items.end(), compare);
|
||||
display(items);
|
||||
|
||||
std::vector<Item> filtered_items;
|
||||
for ( const Item& item : items ) {
|
||||
if ( std::unordered_set<char>(item.word.begin(), item.word.end()).size() >= 4 ) {
|
||||
filtered_items.push_back(item);
|
||||
}
|
||||
}
|
||||
|
||||
auto comp = [](Item a, Item b) { return a.number > b.number; };
|
||||
std::sort(filtered_items.begin(), filtered_items.end(), comp);
|
||||
display(filtered_items);
|
||||
}
|
||||
62
Task/Hex-words/Java/hex-words.java
Normal file
62
Task/Hex-words/Java/hex-words.java
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public final class HexWords {
|
||||
|
||||
public static void main(String[] aArgs) throws IOException {
|
||||
Set<Character> hexDigits = Set.of( 'a', 'b', 'c', 'd', 'e', 'f' );
|
||||
|
||||
List<Item> items = Files.lines(Path.of("unixdict.txt"))
|
||||
.filter( word -> word.length() >= 4 )
|
||||
.filter( word -> word.chars().allMatch( ch -> hexDigits.contains((char) ch) ) )
|
||||
.map( word -> { final int value = Integer.parseInt(word, 16);
|
||||
return new Item(word, value, digitalRoot(value));
|
||||
} )
|
||||
.collect(Collectors.toList());
|
||||
|
||||
Collections.sort(items, Comparator.comparing(Item::getDigitalRoot).thenComparing(Item::getWord));
|
||||
display(items);
|
||||
|
||||
List<Item> filteredItems = items.stream()
|
||||
.filter( item -> item.aWord.chars().mapToObj( ch -> (char) ch ).collect(Collectors.toSet()).size() >= 4 )
|
||||
.collect(Collectors.toList());
|
||||
|
||||
Collections.sort(filteredItems, Comparator.comparing(Item::getNumber).reversed());
|
||||
display(filteredItems);
|
||||
}
|
||||
|
||||
private static int digitalRoot(int aNumber) {
|
||||
int result = 0;
|
||||
while ( aNumber > 0 ) {
|
||||
result += aNumber % 10;
|
||||
aNumber /= 10;
|
||||
}
|
||||
return ( result <= 9 ) ? result : digitalRoot(result);
|
||||
}
|
||||
|
||||
private static void display(List<Item> aItems) {
|
||||
System.out.println(" Word Decimal value Digital root");
|
||||
System.out.println("----------------------------------------");
|
||||
for ( Item item : aItems ) {
|
||||
System.out.println(String.format("%7s%15d%12d", item.aWord, item.aNumber, item.aDigitalRoot));
|
||||
}
|
||||
System.out.println(System.lineSeparator() + "Total count: " + aItems.size() + System.lineSeparator());
|
||||
}
|
||||
|
||||
private static record Item(String aWord, int aNumber, int aDigitalRoot) {
|
||||
|
||||
public String getWord() { return aWord; }
|
||||
|
||||
public int getNumber() { return aNumber; }
|
||||
|
||||
public int getDigitalRoot() { return aDigitalRoot; }
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
89
Task/Hex-words/Lua/hex-words.lua
Normal file
89
Task/Hex-words/Lua/hex-words.lua
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
-- Import http namespace from socket library
|
||||
http = require("socket.http")
|
||||
|
||||
-- Download the page at url and return as string
|
||||
function getFromWeb (url)
|
||||
local body, statusCode, headers, statusText = http.request(url)
|
||||
if statusCode == 200 then
|
||||
return body
|
||||
else
|
||||
error(statusText)
|
||||
end
|
||||
end
|
||||
|
||||
-- Return a boolean to show whether word is a hexword
|
||||
function isHexWord (word)
|
||||
local hexLetters, ch = "abcdef"
|
||||
for pos = 1, #word do
|
||||
ch = word:sub(pos, pos)
|
||||
if not string.find(hexLetters, ch) then return false end
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
-- Return the sum of the digits in num
|
||||
function sumDigits (num)
|
||||
local sum, nStr, digit = 0, tostring(num)
|
||||
for pos = 1, #nStr do
|
||||
digit = tonumber(nStr:sub(pos, pos))
|
||||
sum = sum + digit
|
||||
end
|
||||
return sum
|
||||
end
|
||||
|
||||
-- Return the digital root of x
|
||||
function digitalRoot (x)
|
||||
while x > 9 do
|
||||
x = sumDigits(x)
|
||||
end
|
||||
return x
|
||||
end
|
||||
|
||||
-- Return a table from built from the lines of the string dct
|
||||
-- Each table entry contains the digital root, word and base 10 conversion
|
||||
function buildTable (dct)
|
||||
local t, base10 = {}
|
||||
for line in dct:gmatch("[^\n]+") do
|
||||
if # line > 3 and isHexWord(line) then
|
||||
base10 = (tonumber(line, 16))
|
||||
table.insert(t, {digitalRoot(base10), line, base10})
|
||||
end
|
||||
end
|
||||
table.sort(t, function (a,b) return a[1] < b[1] end)
|
||||
return t
|
||||
end
|
||||
|
||||
-- Return a boolean to show whether str has at least 4 distinct characters
|
||||
function fourDistinct (str)
|
||||
local distinct, ch = ""
|
||||
for pos = 1, #str do
|
||||
ch = str:sub(pos, pos)
|
||||
if not string.match(distinct, ch) then
|
||||
distinct = distinct .. ch
|
||||
end
|
||||
end
|
||||
return #distinct > 3
|
||||
end
|
||||
|
||||
-- Unpack each entry in t and print to the screen
|
||||
function showTable (t)
|
||||
print("\n\nRoot\tWord\tBase 10")
|
||||
print("====\t====\t=======")
|
||||
for i, v in ipairs(t) do
|
||||
print(unpack(v))
|
||||
end
|
||||
print("\nTable length: " .. #t)
|
||||
end
|
||||
|
||||
-- Main procedure
|
||||
local dict = getFromWeb("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt")
|
||||
local hexWords = buildTable(dict)
|
||||
showTable(hexWords)
|
||||
local hexWords2 = {}
|
||||
for k, v in pairs(hexWords) do
|
||||
if fourDistinct(v[2]) then
|
||||
table.insert(hexWords2, v)
|
||||
end
|
||||
end
|
||||
table.sort(hexWords2, function (a, b) return a[3] > b[3] end)
|
||||
showTable(hexWords2)
|
||||
60
Task/History-variables/C++/history-variables.cpp
Normal file
60
Task/History-variables/C++/history-variables.cpp
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
#include <deque>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
|
||||
template <typename T>
|
||||
class with_history {
|
||||
public:
|
||||
with_history(const T& element) {
|
||||
history.push_front(element);
|
||||
}
|
||||
|
||||
T get() {
|
||||
return history.front();
|
||||
}
|
||||
|
||||
void set(const T& element) {
|
||||
history.push_front(element);
|
||||
}
|
||||
|
||||
std::deque<T> get_history() {
|
||||
return std::deque<T>(history);
|
||||
}
|
||||
|
||||
T rollback() {
|
||||
if ( history.size() > 1 ) {
|
||||
history.pop_front();
|
||||
}
|
||||
return history.front();
|
||||
}
|
||||
|
||||
private:
|
||||
std::deque<T> history;
|
||||
};
|
||||
|
||||
int main() {
|
||||
with_history<double> number(1.2345);
|
||||
std::cout << "Current value of number: " << number.get() << std::endl;
|
||||
|
||||
number.set(3.4567);
|
||||
number.set(5.6789);
|
||||
|
||||
std::cout << "Historical values of number: ";
|
||||
for ( const double& value : number.get_history() ) {
|
||||
std::cout << value << " ";
|
||||
}
|
||||
std::cout << std::endl << std::endl;
|
||||
|
||||
with_history<std::string> word("Goodbye");
|
||||
word.set("Farewell");
|
||||
word.set("Hello");
|
||||
|
||||
std::cout << word.get() << std::endl;
|
||||
word.rollback();
|
||||
std::cout << word.get() << std::endl;
|
||||
word.rollback();
|
||||
std::cout << word.get() << std::endl;
|
||||
word.rollback();
|
||||
std::cout << word.get() << std::endl;
|
||||
word.rollback();
|
||||
}
|
||||
28
Task/Hofstadter-Q-sequence/Lua/hofstadter-q-sequence.lua
Normal file
28
Task/Hofstadter-Q-sequence/Lua/hofstadter-q-sequence.lua
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
function hofstadter (limit)
|
||||
local Q = {1, 1}
|
||||
for n = 3, limit do
|
||||
Q[n] = Q[n - Q[n - 1]] + Q[n - Q[n - 2]]
|
||||
end
|
||||
return Q
|
||||
end
|
||||
|
||||
function countDescents (t)
|
||||
local count = 0
|
||||
for i = 2, #t do
|
||||
if t[i] < t[i - 1] then
|
||||
count = count + 1
|
||||
end
|
||||
end
|
||||
return count
|
||||
end
|
||||
|
||||
local noError, hofSeq = pcall(hofstadter, 1e5)
|
||||
if noError == false then
|
||||
print("The sequence could not be calculated up to the specified limit.")
|
||||
os.exit()
|
||||
end
|
||||
for i = 1, 10 do
|
||||
io.write(hofSeq[i] .. " ")
|
||||
end
|
||||
print("\n" .. hofSeq[1000])
|
||||
print(countDescents(hofSeq))
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue