Data Update

This commit is contained in:
Ingy döt Net 2023-07-18 13:51:12 -07:00
parent e50b5c3114
commit 633b36288a
206 changed files with 4762 additions and 965 deletions

View file

@ -0,0 +1,143 @@
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Set;
import java.util.stream.Collectors;
public final class Puzzle15Solver {
public static void main(String[] aArgs) {
List<Integer> start = List.of( 15, 14, 1, 6, 9, 11, 4, 12, 0, 10, 7, 3, 13, 8, 5, 2 );
final int zeroIndex = 8;
Puzzle initial = new Puzzle(start, new ArrayList<String>(), zeroIndex, 0);
openSet.add(initial);
System.out.println("Solving the 15 puzzle:");
initial.display();
while ( solution == null ) {
search();
}
System.out.println(solution.moves.stream().collect(Collectors.joining("")));
System.out.println("Number of steps: " + solution.moves.size());
System.out.println("Number of puzzle states checked: " + closedSet.size());
}
private static void search() {
Puzzle current = openSet.poll();
closedSet.add(current);
final int zeroIndex = current.zeroIndex;
final int row = zeroIndex / 4;
final int column = zeroIndex % 4;
if ( column > 0 ) {
Puzzle nextPuzzle = current.clone();
nextPuzzle.makeMove(Move.LEFT);
}
if ( column < 3 ) {
Puzzle nextPuzzle = current.clone();
nextPuzzle.makeMove(Move.RIGHT);
}
if ( row > 0 ) {
Puzzle nextPuzzle = current.clone();
nextPuzzle.makeMove(Move.UP);
}
if ( row < 3 ) {
Puzzle nextPuzzle = current.clone();
nextPuzzle.makeMove(Move.DOWN);
}
}
private enum Move {
LEFT("L", -1), RIGHT("R", +1), UP("U", -4), DOWN("D", +4);
private Move(String aSymbol, int aStep) {
symbol = aSymbol;
step = aStep;
}
private String symbol;
private Integer step;
}
private static class Puzzle {
public Puzzle(List<Integer> aTiles, List<String> aMoves, int aZeroIndex, int aSearchDepth) {
tiles = aTiles;
moves = aMoves;
zeroIndex = aZeroIndex;
searchDepth = aSearchDepth;
}
public void makeMove(Move aMove) {
Integer temp = tiles.get(zeroIndex + aMove.step);
tiles.set(zeroIndex + aMove.step, 0);
tiles.set(zeroIndex, temp);
zeroIndex += aMove.step;
moves.add(aMove.symbol);
if ( ! closedSet.contains(this) ) {
openSet.add(this);
if ( tiles.equals(Puzzle.GOAL) ) {
solution = this;
}
}
}
public long heuristic() {
int distance = 0;
for ( int i = 0; i < tiles.size(); i++ ) {
final int tile = tiles.get(i);
if ( tile > 0 ) {
distance += Math.abs( ( i / 4 ) - ( tile - 1 ) / 4 ) + Math.abs( ( i % 4 ) - ( tile - 1 ) % 4 );
}
}
return distance + searchDepth;
}
public Puzzle clone() {
return new Puzzle(new ArrayList<Integer>(tiles), new ArrayList<String>(moves), zeroIndex, searchDepth + 1);
}
public void display() {
for ( int i = 0; i < tiles.size(); i++ ) {
System.out.print(String.format("%s%2d%s",
( i % 4 == 0 ) ? "[" : "", tiles.get(i), ( i % 4 == 3 ) ? "]\n" : " "));
}
System.out.println();
}
@Override
public boolean equals(Object aObject) {
return switch(aObject) {
case Puzzle puzzle -> tiles.equals(puzzle.tiles);
case Object object -> false;
};
}
@Override
public int hashCode() {
int hash = 3;
hash = 23 * hash + tiles.hashCode();
hash = 23 * hash + zeroIndex;
return hash;
}
private List<Integer> tiles;
private List<String> moves;
private int zeroIndex;
private int searchDepth;
private static final List<Integer> GOAL = List.of( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0 );
}
private static Queue<Puzzle> openSet =
new PriorityQueue<Puzzle>( (one, two) -> Long.compare(one.heuristic(), two.heuristic()) );
private static Set<Puzzle> closedSet = new HashSet<Puzzle>();
private static Puzzle solution;
}

View file

@ -7,7 +7,7 @@ import extensions;
class ExpressionTree
{
object theTree;
object _tree;
constructor(s)
{
@ -18,40 +18,40 @@ class ExpressionTree
var node := new DynamicStruct();
ch =>
$43 { node.Level := level + 1; node.Operation := __subj add } // +
$45 { node.Level := level + 1; node.Operation := __subj subtract } // -
$42 { node.Level := level + 2; node.Operation := __subj multiply } // *
$47 { node.Level := level + 2; node.Operation := __subj divide } // /
$40 { level.append(10); ^ self } // (
$41 { level.reduce(10); ^ self } // )
$43 { node.Level := level + 1; node.Operation := mssg add } // +
$45 { node.Level := level + 1; node.Operation := mssg subtract } // -
$42 { node.Level := level + 2; node.Operation := mssg multiply } // *
$47 { node.Level := level + 2; node.Operation := mssg divide } // /
$40 { level.append(10); ^ self } // (
$41 { level.reduce(10); ^ self } // )
: {
node.Leaf := ch.toString().toReal();
node.Level := level + 3
};
if (nil == theTree)
if (nil == _tree)
{
theTree := node
_tree := node
}
else
{
if (theTree.Level >= node.Level)
if (_tree.Level >= node.Level)
{
node.Left := theTree;
node.Right := nilValue;
node.Left := _tree;
node.Right := nil;
theTree := node
_tree := node
}
else
{
var top := theTree;
while ((nilValue != top.Right)&&(top.Right.Level < node.Level))
{ top := top.Right };
var top := _tree;
while ((nil != top.Right)&&(top.Right.Level < node.Level))
{ top := top.Right };
node.Left := top.Right;
node.Right := nilValue;
node.Left := top.Right;
node.Right := nil;
top.Right := node
top.Right := node
}
}
}
@ -59,7 +59,7 @@ class ExpressionTree
eval(node)
{
if (node.containsProperty(subjconst Leaf))
if (node.containsProperty(mssg Leaf))
{
^ node.Leaf
}
@ -75,14 +75,14 @@ class ExpressionTree
}
get Value()
<= eval(theTree);
<= eval(_tree);
readLeaves(list, node)
{
if (nil == node)
{ InvalidArgumentException.raise() };
if (node.containsProperty(subjconst Leaf))
if (node.containsProperty(mssg Leaf))
{
list.append(node.Leaf)
}
@ -94,7 +94,7 @@ class ExpressionTree
}
readLeaves(list)
<= readLeaves(list,theTree);
<= readLeaves(list,_tree);
}
// --- Game ---
@ -112,10 +112,10 @@ class TwentyFourGame
{
theNumbers := new object[]
{
1 + randomGenerator.eval:9,
1 + randomGenerator.eval:9,
1 + randomGenerator.eval:9,
1 + randomGenerator.eval:9
1 + randomGenerator.nextInt:9,
1 + randomGenerator.nextInt:9,
1 + randomGenerator.nextInt:9,
1 + randomGenerator.nextInt:9
}
}
@ -149,8 +149,11 @@ class TwentyFourGame
var leaves := new ArrayList();
tree.readLeaves:leaves;
ifnot (leaves.ascendant().sequenceEqual(theNumbers.ascendant()))
{ console.printLine:"Invalid input. Enter an equation using all of those four digits. Try again."; ^ self };
ifnot (leaves.ascendant().sequenceEqual(theNumbers.ascendant())) {
console
.printLine:"Invalid input. Enter an equation using all of those four digits. Try again.";
^ self
};
var result := tree.Value;
if (result == 24)
@ -188,7 +191,8 @@ extension gameOp
}
catch(Exception e)
{
console.printLine:"An error occurred. Check your input and try again."
console.printLine:e
//console.printLine:"An error occurred. Check your input and try again."
}
};
@ -197,6 +201,8 @@ extension gameOp
}
}
// --- program ---
public program()
{
var game := new TwentyFourGame().help();

View file

@ -14,7 +14,7 @@ extension bottleOp
{
bool next() = n > 0;
get() = new StringWriter()
get Value() = new StringWriter()
.printLine(n.bottleDescription()," of beer on the wall")
.printLine(n.bottleDescription()," of beer")
.printLine("Take one down, pass it around")
@ -22,7 +22,7 @@ extension bottleOp
reset() {}
enumerable() = __target;
enumerable() = weak self;
}
};
}

View file

@ -5,6 +5,6 @@ public program()
{
console.printLine(console.readLine()
.split()
.selectBy(mssgconst toInt<convertorOp>[1])
.selectBy(mssgconst toInt<intConvertOp>[1])
.summarize())
}

View file

@ -0,0 +1,59 @@
Header := "
(LTrim
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ID |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|QR| Opcode |AA|TC|RD|RA| Z | RCODE |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| QDCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ANCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| NSCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ARCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
)"
Data := "78477BBF5496E12E1BF169A4"
MsgBox % result := ASCII_art_diagram_converter(Header, Data)
return
ASCII_art_diagram_converter(Header, Data){
oDataBin := []
for i, h in StrSplit(Data)
for i, v in StrSplit(SubStr("0000" . ConvertBase(16, 2, h), -3))
oDataBin.Push(v)
bitWidth := StrLen(StrSplit(Header, "+").2) + 1
prevW := 0
result := "Name`t`tSize`tBinary"
for i, line in StrSplit(Header, "`n", "`r")
{
if Mod(A_Index, 2)
continue
strtPos := 0
loop
{
if w := (strtPos := InStr(line, "|",, ++strtPos)) // bitWidth
{
b := ""
loop % width := w - prevW
b .= oDataBin.RemoveAt(1)
result .= "`n" Trim(StrSplit(line, "|")[A_Index]) "`t`t" width . "`t" b
}
prevW := w
}
until !strtPos
}
return result
}
ConvertBase(InputBase, OutputBase, nptr){ ; Base 2 - 36 ; https://www.autohotkey.com/boards/viewtopic.php?t=3925#p21143
static u := A_IsUnicode ? "_wcstoui64" : "_strtoui64"
static v := A_IsUnicode ? "_i64tow" : "_i64toa"
VarSetCapacity(s, 66, 0)
value := DllCall("msvcrt.dll\" u, "Str", nptr, "UInt", 0, "UInt", InputBase, "CDECL Int64")
DllCall("msvcrt.dll\" v, "Int64", value, "Str", s, "UInt", OutputBase, "CDECL")
return s
}

View file

@ -0,0 +1,49 @@
program KindOfN; //[deficient,perfect,abundant]
{$IFDEF FPC}
{$MODE DELPHI}{$OPTIMIZATION ON,ALL}{$COPERATORS ON}{$CODEALIGN proc=16}
{$ENDIF}
{$IFDEF WINDOWS} {$APPTYPE CONSOLE}{$ENDIF}
uses
sysutils,PrimeDecomp // limited to 1.2e11
{$IFDEF WINDOWS},Windows{$ENDIF}
;
//alternative copy and paste PrimeDecomp.inc for TIO.RUN
{$I PrimeDecomp.inc}
type
tKindIdx = 0..2;//[deficient,perfect,abundant];
tKind = array[tKindIdx] of Uint64;
procedure GetKind(Limit:Uint64);
var
pPrimeDecomp :tpPrimeFac;
SumOfKind : tKind;
n: NativeUInt;
c: NativeInt;
T0:Int64;
Begin
writeln('Limit: ',LIMIT);
T0 := GetTickCount64;
fillchar(SumOfKind,SizeOf(SumOfKind),#0);
n := 1;
Init_Sieve(n);
repeat
pPrimeDecomp:= GetNextPrimeDecomp;
c := pPrimeDecomp^.pfSumOfDivs-2*n;
c := ORD(c>0)-ORD(c<0)+1;//sgn(c)+1
inc(SumOfKind[c]);
inc(n);
until n > LIMIT;
T0 := GetTickCount64-T0;
writeln('deficient: ',SumOfKind[0]);
writeln('abundant: ',SumOfKind[2]);
writeln('perfect: ',SumOfKind[1]);
writeln('runtime ',T0/1000:0:3,' s');
writeln;
end;
Begin
InitSmallPrimes; //using PrimeDecomp.inc
GetKind(20000);
GetKind(10*1000*1000);
GetKind(524*1000*1000);
end.

View file

@ -1,214 +0,0 @@
program AmicablePairs;
{find amicable pairs in a limited region 2..MAX
beware that >both< numbers must be smaller than MAX
there are 455 amicable pairs up to 524*1000*1000
correct up to
#437 460122410
}
//optimized for freepascal 2.6.4 32-Bit
{$IFDEF FPC}
{$MODE DELPHI}
{$OPTIMIZATION ON,peephole,cse,asmcse,regvar}
{$CODEALIGN loop=1,proc=8}
{$ELSE}
{$APPTYPE CONSOLE}
{$ENDIF}
uses
sysutils;
const
MAX = 20000;
//{$IFDEF UNIX} MAX = 524*1000*1000;{$ELSE}MAX = 499*1000*1000;{$ENDIF}
type
tValue = LongWord;
tpValue = ^tValue;
tPower = array[0..31] of tValue;
tIndex = record
idxI,
idxS : tValue;
end;
tdpa = array[0..2] of LongWord;
var
power : tPower;
PowerFac : tPower;
DivSumField : array[0..MAX] of tValue;
Indices : array[0..511] of tIndex;
DpaCnt : tdpa;
procedure Init;
var
i : LongInt;
begin
DivSumField[0]:= 0;
For i := 1 to MAX do
DivSumField[i]:= 1;
end;
procedure ProperDivs(n: tValue);
//Only for output, normally a factorication would do
var
su,so : string;
i,q : tValue;
begin
su:= '1';
so:= '';
i := 2;
while i*i <= n do
begin
q := n div i;
IF q*i -n = 0 then
begin
su:= su+','+IntToStr(i);
IF q <> i then
so:= ','+IntToStr(q)+so;
end;
inc(i);
end;
writeln(' [',su+so,']');
end;
procedure AmPairOutput(cnt:tValue);
var
i : tValue;
r : double;
begin
r := 1.0;
For i := 0 to cnt-1 do
with Indices[i] do
begin
writeln(i+1:4,IdxI:12,IDxS:12,' ratio ',IdxS/IDxI:10:7);
if r < IdxS/IDxI then
r := IdxS/IDxI;
IF cnt < 20 then
begin
ProperDivs(IdxI);
ProperDivs(IdxS);
end;
end;
writeln(' max ratio ',r:10:4);
end;
function Check:tValue;
var
i,s,n : tValue;
begin
fillchar(DpaCnt,SizeOf(dpaCnt),#0);
n := 0;
For i := 1 to MAX do
begin
//s = sum of proper divs (I) == sum of divs (I) - I
s := DivSumField[i]-i;
IF (s <=MAX) AND (s>i) then
begin
IF DivSumField[s]-s = i then
begin
With indices[n] do
begin
idxI := i;
idxS := s;
end;
inc(n);
end;
end;
inc(DpaCnt[Ord(s>=i)-Ord(s<=i)+1]);
end;
result := n;
end;
Procedure CalcPotfactor(prim:tValue);
//PowerFac[k] = (prim^(k+1)-1)/(prim-1) == Sum (i=1..k) prim^i
var
k: tValue;
Pot, //== prim^k
PFac : Int64;
begin
Pot := prim;
PFac := 1;
For k := 0 to High(PowerFac) do
begin
PFac := PFac+Pot;
IF (POT > MAX) then
BREAK;
PowerFac[k] := PFac;
Pot := Pot*prim;
end;
end;
procedure InitPW(prim:tValue);
begin
fillchar(power,SizeOf(power),#0);
CalcPotfactor(prim);
end;
function NextPotCnt(p: tValue):tValue;inline;
//return the first power <> 0
//power == n to base prim
var
i : tValue;
begin
result := 0;
repeat
i := power[result];
Inc(i);
IF i < p then
BREAK
else
begin
i := 0;
power[result] := 0;
inc(result);
end;
until false;
power[result] := i;
end;
function Sieve(prim: tValue):tValue;
//simple version
var
actNumber : tValue;
begin
while prim <= MAX do
begin
InitPW(prim);
//actNumber = actual number = n*prim
//power == n to base prim
actNumber := prim;
while actNumber < MAX do
begin
DivSumField[actNumber] := DivSumField[actNumber] *PowerFac[NextPotCnt(prim)];
inc(actNumber,prim);
end;
//next prime
repeat
inc(prim);
until (DivSumField[prim] = 1);
end;
result := prim;
end;
var
T2,T1,T0: TDatetime;
APcnt: tValue;
begin
T0:= time;
Init;
Sieve(2);
T1:= time;
APCnt := Check;
T2:= time;
//AmPairOutput(APCnt);
writeln(Max:10,' upper limit');
writeln(DpaCnt[0]:10,' deficient');
writeln(DpaCnt[1]:10,' perfect');
writeln(DpaCnt[2]:10,' abundant');
writeln(DpaCnt[2]/Max:14:10,' ratio abundant/upper Limit ');
writeln(DpaCnt[0]/Max:14:10,' ratio abundant/upper Limit ');
writeln(DpaCnt[2]/DpaCnt[0]:14:10,' ratio abundant/deficient ');
writeln('Time to calc sum of divs ',FormatDateTime('HH:NN:SS.ZZZ' ,T1-T0));
writeln('Time to find amicable pairs ',FormatDateTime('HH:NN:SS.ZZZ' ,T2-T1));
{$IFNDEF UNIX}
readln;
{$ENDIF}
end.

View file

@ -1,19 +1,20 @@
BEGIN # find some anti-primes: numbers with more divisors than the #
# previous numbers #
INT max number := 10 000;
REF[]INT ndc := HEAP[ 1 : 0 ]INT; # table of divisor counts #
INT max divisors := 0;
# construct a table of the divisor counts #
[ 1 : max number ]INT ndc; FOR i FROM 1 TO UPB ndc DO ndc[ i ] := 1 OD;
FOR i FROM 2 TO UPB ndc DO
FOR j FROM i BY i TO UPB ndc DO ndc[ j ] +:= 1 OD
OD;
# show the numbers with more divisors than their predecessors #
INT a count := 0;
FOR i TO UPB ndc WHILE a count < 20 DO
INT divisor count = ndc[ i ];
IF divisor count > max divisors THEN
print( ( " ", whole( i, 0 ) ) );
max divisors := divisor count;
INT a count := 0;
FOR n WHILE a count < 20 DO
IF n > UPB ndc THEN
# need a bigger table of divisor counts #
ndc := HEAP[ 1 : UPB ndc + 5 000 ]INT;
FOR i FROM 1 TO UPB ndc DO ndc[ i ] := 1 OD;
FOR i FROM 2 TO UPB ndc DO
FOR j FROM i BY i TO UPB ndc DO ndc[ j ] +:= 1 OD
OD
FI;
IF ndc[ n ] > max divisors THEN
print( ( " ", whole( n, 0 ) ) );
max divisors := ndc[ n ];
a count +:= 1
FI
OD;

View file

@ -0,0 +1,29 @@
-- Find the first 20 antiprimes.
-- returns a table of the first goal antiprimes
function antiprimes(goal)
local maxNumber = 0
local ndc = {} -- table of divisor counts - initially empty
local list, number, mostFactors = {}, 1, 0
while #list < goal do
if number > #ndc then
-- need a bigger table of divisor counts
maxNumber = maxNumber + 5000
ndc = {}
for i = 1, maxNumber do ndc[ i ] = 1 end
for i = 2, maxNumber do
for j = i, maxNumber, i do ndc[ j ] = ndc[ j ] + 1 end
end
end
local factors = ndc[ number ]
if factors > mostFactors then
table.insert( list, number )
mostFactors = factors
end
number = number + 1
end
return list
end
-- display the antiprimes
oo.write( table.concat( antiprimes( 20 ), " " ) )

View file

@ -0,0 +1,33 @@
// Find the first 20 antiprimes.
// returns a table of the first goal antiprimes
antiprimes = function(goal)
maxNumber = 0
ndc = [] // table of divisor counts - initially empty
list = [0] * goal; number = 1; mostFactors = 0
aCount = 0
while aCount < goal
if number > maxNumber then
// need a bigger table of divisor counts
maxNumber = maxNumber + 5000
ndc = [1] * ( maxNumber + 1 )
ndc[ 0 ] = 0
for i in range( 2, maxNumber )
for j in range( i, maxNumber, i )
ndc[ j ] = ndc[ j ] + 1
end for
end for
end if
factors = ndc[ number ]
if factors > mostFactors then
list[ aCount ] = number
mostFactors = factors
aCount = aCount + 1
end if
number = number + 1
end while
return list
end function
// display the antiprimes
print antiprimes( 20 ).join( " " )

View file

@ -0,0 +1,42 @@
package antiprimes
import "core:fmt"
main :: proc() {
AntiPrimeCount, MaxDivisors, Divisors, n: u64
MaxAntiPrime: u64 = 20
fmt.print("\nFirst 20 anti-primes\n")
fmt.println("--------------------")
for (AntiPrimeCount < MaxAntiPrime) {
n += 1
Divisors = DivisorCount(n)
if Divisors > MaxDivisors {
fmt.print(n, " ")
MaxDivisors = Divisors
AntiPrimeCount += 1
}
}
}
DivisorCount :: proc(v: u64) -> u64 {
total: u64 = 1
a := v
if a == 0 {
return 0
}
for a % 2 == 0 {
total += 1
a /= 2
}
for p: u64 = 3; p * p <= a; p += 2 {
count: u64 = 1
for a % p == 0 {
count += 1
a /= p
}
total *= count
}
if a > 1 {
total *= 2
}
return total
}

View file

@ -0,0 +1,36 @@
# find the first 20 antiprimes
# - numbers woth more divisors than the previous numbers
numberOfDivisorCounts = 0
maxDivisor = 0
num = 0
n = 0
result = list(20)
while num < 20
n += 1
if n > numberOfDivisorCounts
# need a bigger table of divisor counts
numberOfDivisorCounts += 5000
ndc = list(numberOfDivisorCounts)
for i = 1 to numberOfDivisorCounts
ndc[ i ] = 1
next
for i = 2 to numberOfDivisorCounts
j = i
while j <= numberOfDivisorCounts
ndc[ j ] = ndc[ j ] + 1
j += i
end
next
ok
div = ndc[ n ]
if (div > maxDivisor)
maxDivisor = div
num += 1
result[num] = n
ok
end
see result[1]
for n = 2 to len(result)
see " " + string(result[n])
next

View file

@ -1,6 +1,6 @@
require 'prime'
def num_divisors(n)
n.prime_division.inject(1){|prod, (_p,n)| prod *= (n + 1) }
n.prime_division.inject(1){|prod, (_p,n)| prod * (n + 1) }
end
anti_primes = Enumerator.new do |y| # y is the yielder

View file

@ -1,3 +1,3 @@
var x = 5**(4**(3**2));
var y = x.to_s;
printf("5**4**3**2 = %s...%s and has %i digits\n", y.ft(0,19), y.ft(-20), y.len);
var x = 5**(4**(3**2))
var y = x.to_s
printf("5**4**3**2 = %s...%s and has %i digits\n", y.first(20), y.last(20), y.len)

View file

@ -0,0 +1,25 @@
use prime_factorization::Factorization;
fn d(n: i128) -> i128 {
if n < 0 {
return -(d(-n));
} else if n < 2 {
return 0;
} else {
let fpairs = Factorization::run(n as u128).prime_factor_repr();
if fpairs.len() == 1 && fpairs[0].1 == 1 {
return 1;
}
return fpairs.iter().fold(0_i128, |p, q| p + n * (q.1 as i128) / (q.0 as i128));
}
}
fn main() {
for n in -99..101 {
print!("{:5}{}", d(n), { if n % 10 == 0 { "\n" } else {""} });
}
println!();
for m in 1..21 {
println!("(D for 10 ^ {}) divided by 7 is {}", m, d(10_i128.pow(m)) / 7)
}
}

View file

@ -0,0 +1,13 @@
dim string animals(2) rem here is our array
var array_struct_address = integer
based array_size = integer
animals(1) = "ardvark"
animals(2) = "bison"
location spec array_struct_address = animals
base array_size at array_struct_address + 5
print "Size of array ="; array_size
end

View file

@ -14,5 +14,6 @@ at least one significantly better and much faster way, needing a mere 511 odd/pr
;Related:
*[[Primes with digits in nondecreasing order]] (infinite series allowing duplicate digits, whereas this isn't and doesn't)
*[[Pandigital prime]] (whereas this is the smallest, with gaps in the used digits being permitted)
*[[Descending primes]]

View file

@ -0,0 +1,7 @@
AttractiveNumber(N):=block([Q:0],
if not primep(N) then (
if primep(apply("+", map(lambda([Z], Z[2]), ifactors(N)))) then Q: N
), Q
)$
delete(0, makelist(AttractiveNumber(K), K, 1, 120));

View file

@ -0,0 +1,493 @@
/* ARM assembly Raspberry PI */
/* program averageMed.s */
/* use quickselect look pseudo code in wikipedia quickselect */
/************************************/
/* Constantes */
/************************************/
/* for constantes see task include a file in arm assembly */
.include "../constantes.inc"
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessResultValue: .asciz "Result : "
szCarriageReturn: .asciz "\n"
.align 4
TableNumber: .float 4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2
.equ NBELEMENTS, (. - TableNumber) / 4
TableNumber2: .float 4.1, 7.2, 1.7, 9.3, 4.4, 3.2
.equ NBELEMENTS2, (. - TableNumber2) / 4
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
sZoneConv1: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r0,iAdrTableNumber @ address number table
mov r1,#0 @ index first item
mov r2,#NBELEMENTS -1 @ index last item
bl searchMedian
ldr r0,iAdrTableNumber2 @ address number table 2
mov r1,#0 @ index first item
mov r2,#NBELEMENTS2 -1 @ index last item
bl searchMedian
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
iAdrTableNumber: .int TableNumber
iAdrTableNumber2: .int TableNumber2
iAdrsZoneConv: .int sZoneConv
iAdrszMessResultValue: .int szMessResultValue
/***************************************************/
/* search median term in float array */
/***************************************************/
/* r0 contains the address of table */
/* r1 contains index of first item */
/* r2 contains index of last item */
searchMedian:
push {r1-r5,lr} @ save registers
mov r5,r0 @ save array address
add r4,r1,r2
add r4,r4,#1 @ sum numbers terms
tst r4,#1 @ odd ?
bne 1f
lsr r3,r4,#1 @ compute median index
bl select @ call selection
vmov s0,r0 @ save first result
sub r3,r3,#1 @ second term
mov r0,r5
bl select @ call selection
vmov s1,r0 @ save 2ieme résult
vadd.f32 s0,s1 @ compute average two résults
mov r0,#2
vmov s1,r0
vcvt.f32.u32 s1,s1 @ conversion integer -> float
vdiv.f32 s0,s0,s1
b 2f
1: @ even
lsr r3,r4,#1
bl select @ call selection
vmov s0,r0
2:
ldr r0,iAdrsZoneConv @ conversion float in decimal string
bl convertirFloat
mov r0,#3 @ and display result
ldr r1,iAdrszMessResultValue
ldr r2,iAdrsZoneConv
ldr r3,iAdrszCarriageReturn
bl displayStrings
100: @ end function
pop {r1-r5,pc} @ restaur register
/***************************************************/
/* Appel récursif selection */
/***************************************************/
/* r0 contains the address of table */
/* r1 contains index of first item */
/* r2 contains index of last item */
/* r3 contains search index */
/* r0 return final value in float */
/* remark : the final result is a float returned in r0 register */
select:
push {r1-r6,lr} @ save registers
mov r6,r3 @ save search index
cmp r1,r2 @ first = last ?
ldreq r0,[r0,r1,lsl #2] @ return value of first index
beq 100f @ yes -> end
add r3,r1,r2
lsr r3,r3,#1 @ compute median pivot
mov r4,r0 @ save r0
mov r5,r2 @ save r2
bl partition @ cutting into 2 parts
cmp r6,r0 @ pivot is ok ?
ldreq r0,[r4,r0,lsl #2] @ return value
beq 100f
bgt 1f
sub r2,r0,#1 @ index partition - 1
mov r0,r4 @ array address
mov r3,r6 @ search index
bl select @ select lower part
b 100f
1:
add r1,r0,#1 @ index begin = index partition + 1
mov r0,r4 @ array address
mov r2,r5 @ last item
mov r3,r6 @ search index
bl select @ select higter part
100: @ end function
pop {r1-r6,pc} @ restaur register
/******************************************************************/
/* Partition table elements */
/******************************************************************/
/* r0 contains the address of table */
/* r1 contains index of first item */
/* r2 contains index of last item */
/* r3 contains index of pivot */
partition:
push {r1-r6,lr} @ save registers
ldr r4,[r0,r3,lsl #2] @ load value of pivot
ldr r5,[r0,r2,lsl #2] @ load value last index
str r5,[r0,r3,lsl #2] @ swap value of pivot
str r4,[r0,r2,lsl #2] @ and value last index
mov r3,r1 @ init with first index
1: @ begin loop
ldr r6,[r0,r3,lsl #2] @ load value
cmp r6,r4 @ compare loop value and pivot value
ldrlt r5,[r0,r1,lsl #2] @ if < swap value table
strlt r6,[r0,r1,lsl #2]
strlt r5,[r0,r3,lsl #2]
addlt r1,#1 @ and increment index 1
add r3,#1 @ increment index 2
cmp r3,r2 @ end ?
blt 1b @ no loop
ldr r5,[r0,r1,lsl #2] @ swap value
str r4,[r0,r1,lsl #2]
str r5,[r0,r2,lsl #2]
mov r0,r1 @ return index partition
100:
pop {r1-r6,pc}
/***************************************************/
/* display multi strings */
/***************************************************/
/* r0 contains number strings address */
/* r1 address string1 */
/* r2 address string2 */
/* r3 address string3 */
/* other address on the stack */
/* thinck to add number other address * 4 to add to the stack */
displayStrings: @ INFO: displayStrings
push {r1-r4,fp,lr} @ save des registres
add fp,sp,#24 @ save paraméters address (6 registers saved * 4 bytes)
mov r4,r0 @ save strings number
cmp r4,#0 @ 0 string -> end
ble 100f
mov r0,r1 @ string 1
bl affichageMess
cmp r4,#1 @ number > 1
ble 100f
mov r0,r2
bl affichageMess
cmp r4,#2
ble 100f
mov r0,r3
bl affichageMess
cmp r4,#3
ble 100f
mov r3,#3
sub r2,r4,#4
1: @ loop extract address string on stack
ldr r0,[fp,r2,lsl #2]
bl affichageMess
subs r2,#1
bge 1b
100:
pop {r1-r4,fp,pc}
/******************************************************************/
/* Conversion Float */
/******************************************************************/
/* s0 contains Float */
/* r0 contains address conversion area mini 20 charactèrs*/
/* r0 return result length */
convertirFloat:
push {r1-r7,lr}
vpush {s0-s2}
mov r6,r0 @ save area address
vmov r0,s0
mov r1,#0
vmov s1,r1
movs r7,#0 @ result length
movs r3,#'+'
strb r3,[r6] @ sign + forcing
mov r2,r0
lsls r2,#1 @ extraction bit 31
bcc 1f @ positive ?
lsrs r0,r2,#1 @ raz sign if negative
movs r3,#'-' @ sign -
strb r3,[r6]
1:
adds r7,#1 @ next position
cmp r0,#0 @ case of positive or negative 0
bne 2f
movs r3,#'0'
strb r3,[r6,r7] @ store character 0
adds r7,#1 @ next position
movs r3,#0
strb r3,[r6,r7] @ store 0 final
mov r0,r7 @ return length
b 100f @ and end
2:
ldr r2,iMaskExposant
mov r1,r0
ands r1,r2 @ exposant = 255 ?
cmp r1,r2
bne 4f
lsls r0,#10 @ bit 22 à 0 ?
bcc 3f @ yes
movs r2,#'N' @ case of Nan. store byte, if not possible store int
strb r2,[r6] @ area no aligned
movs r2,#'a'
strb r2,[r6,#1]
movs r2,#'n'
strb r2,[r6,#2]
movs r2,#0 @ 0 final
strb r2,[r6,#3]
movs r0,#3 @ return length 3
b 100f
3: @ case infini positive or négative
movs r2,#'I'
strb r2,[r6,r7]
adds r7,#1
movs r2,#'n'
strb r2,[r6,r7]
adds r7,#1
movs r2,#'f'
strb r2,[r6,r7]
adds r7,#1
movs r2,#0
strb r2,[r6,r7]
mov r0,r7
b 100f
4:
bl normaliserFloat
mov r5,r0 @ save exposant
VCVT.U32.f32 s2,s0 @ integer value of integer part
vmov r0,s2 @ integer part
VCVT.F32.U32 s1,s2 @ conversion float
vsub.f32 s1,s0,s1 @ extraction fract part
vldr s2,iConst1
vmul.f32 s1,s2,s1 @ to crop it in full
VCVT.U32.f32 s1,s1 @ integer conversion
vmov r4,s1 @ fract value
@ integer conversion in r0
mov r2,r6 @ save address area begin
adds r6,r7
mov r1,r6
bl conversion10
add r6,r0
movs r3,#','
strb r3,[r6]
adds r6,#1
mov r0,r4 @ conversion fractional part
mov r1,r6
bl conversion10SP @ spécial routine with conservation begin 0
add r6,r0
subs r6,#1
@ remove trailing zeros
5:
ldrb r0,[r6]
cmp r0,#'0'
bne 6f
subs r6,#1
b 5b
6:
cmp r0,#','
bne 7f
subs r6,#1
7:
adds r6,#1
movs r3,#'E'
strb r3,[r6]
adds r6,#1
mov r0,r5 @ conversion exposant
mov r3,r0
lsls r3,#1
bcc 4f
rsbs r0,r0,#0
movs r3,#'-'
strb r3,[r6]
adds r6,#1
4:
mov r1,r6
bl conversion10
add r6,r0
movs r3,#0
strb r3,[r6]
adds r6,#1
mov r0,r6
subs r0,r2 @ return length result
subs r0,#1 @ - 0 final
100:
vpop {s0-s2}
pop {r1-r7,pc}
iMaskExposant: .int 0xFF<<23
iConst1: .float 0f1E9
/***************************************************/
/* normaliser float */
/***************************************************/
/* r0 contain float value (always positive value and <> Nan) */
/* s0 return new value */
/* r0 return exposant */
normaliserFloat:
push {lr} @ save registre
vmov s0,r0 @ value float
movs r0,#0 @ exposant
vldr s1,iConstE7 @ no normalisation for value < 1E7
vcmp.f32 s0,s1
vmrs APSR_nzcv,FPSCR
blo 10f @ if s0 < iConstE7
vldr s1,iConstE32
vcmp.f32 s0,s1
vmrs APSR_nzcv,FPSCR
blo 1f
vldr s1,iConstE32
vdiv.f32 s0,s0,s1
adds r0,#32
1:
vldr s1,iConstE16
vcmp.f32 s0,s1
vmrs APSR_nzcv,FPSCR
blo 2f
vldr s1,iConstE16
vdiv.f32 s0,s0,s1
adds r0,#16
2:
vldr s1,iConstE8
vcmp.f32 s0,s1
vmrs APSR_nzcv,FPSCR
blo 3f
vldr s1,iConstE8
vdiv.f32 s0,s0,s1
adds r0,#8
3:
vldr s1,iConstE4
vcmp.f32 s0,s1
vmrs APSR_nzcv,FPSCR
blo 4f
vldr s1,iConstE4
vdiv.f32 s0,s0,s1
adds r0,#4
4:
vldr s1,iConstE2
vcmp.f32 s0,s1
vmrs APSR_nzcv,FPSCR
blo 5f
vldr s1,iConstE2
vdiv.f32 s0,s0,s1
adds r0,#2
5:
vldr s1,iConstE1
vcmp.f32 s0,s1
vmrs APSR_nzcv,FPSCR
blo 10f
vldr s1,iConstE1
vdiv.f32 s0,s0,s1
adds r0,#1
10:
vldr s1,iConstME5 @ pas de normalisation pour les valeurs > 1E-5
vcmp.f32 s0,s1
vmrs APSR_nzcv,FPSCR
bhi 100f
vldr s1,iConstME31
vcmp.f32 s0,s1
vmrs APSR_nzcv,FPSCR
bhi 11f
vldr s1,iConstE32
vmul.f32 s0,s0,s1
subs r0,#32
11:
vldr s1,iConstME15
vcmp.f32 s0,s1
vmrs APSR_nzcv,FPSCR
bhi 12f
vldr s1,iConstE16
vmul.f32 s0,s0,s1
subs r0,#16
12:
vldr s1,iConstME7
vcmp.f32 s0,s1
vmrs APSR_nzcv,FPSCR
bhi 13f
vldr s1,iConstE8
vmul.f32 s0,s0,s1
subs r0,#8
13:
vldr s1,iConstME3
vcmp.f32 s0,s1
vmrs APSR_nzcv,FPSCR
bhi 14f
vldr s1,iConstE4
vmul.f32 s0,s0,s1
subs r0,#4
14:
vldr s1,iConstME1
vcmp.f32 s0,s1
vmrs APSR_nzcv,FPSCR
bhi 15f
vldr s1,iConstE2
vmul.f32 s0,s0,s1
subs r0,#2
15:
vldr s1,iConstE0
vcmp.f32 s0,s1
vmrs APSR_nzcv,FPSCR
bhi 100f
vldr s1,iConstE1
vmul.f32 s0,s0,s1
subs r0,#1
100: @ fin standard de la fonction
pop {pc} @ restaur des registres
.align 2
iConstE7: .float 0f1E7
iConstE32: .float 0f1E32
iConstE16: .float 0f1E16
iConstE8: .float 0f1E8
iConstE4: .float 0f1E4
iConstE2: .float 0f1E2
iConstE1: .float 0f1E1
iConstME5: .float 0f1E-5
iConstME31: .float 0f1E-31
iConstME15: .float 0f1E-15
iConstME7: .float 0f1E-7
iConstME3: .float 0f1E-3
iConstME1: .float 0f1E-1
iConstE0: .float 0f1E0
/******************************************************************/
/* Décimal Conversion */
/******************************************************************/
/* r0 contain value et r1 address conversion area */
conversion10SP:
push {r1-r6,lr} @ save registers
mov r5,r1
mov r4,#8
mov r2,r0
mov r1,#10 @ conversion decimale
1: @ begin loop
mov r0,r2 @ copy number or quotients
bl division @ r0 dividende r1 divisor r2 quotient r3 remainder
add r3,#48 @ compute digit
strb r3,[r5,r4] @ store byte area address (r5) + offset (r4)
subs r4,r4,#1 @ position précedente
bge 1b @ and loop if not < zero
mov r0,#8
mov r3,#0
strb r3,[r5,r0] @ store 0 final
100:
pop {r1-r6,pc} @ restaur registers
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
/* for this file see task include a file in language ARM assembly */
.include "../affichage.inc"

View file

@ -0,0 +1,133 @@
#include <cmath>
#include <iomanip>
#include <iostream>
#include <stack>
#include <tuple>
#include <vector>
const double TOLERANCE = 0.000'000'1;
const double SPACING = 10 * TOLERANCE;
typedef std::pair<double, double> point;
class quad_spline {
public:
quad_spline(double c0, double c1, double c2) : c0(c0), c1(c1), c2(c2) {};
quad_spline() : c0(0.0), c1(0.0), c2(0.0) {};
double c0, c1, c2;
};
class quad_curve {
public:
quad_curve(quad_spline x, quad_spline y) : x(x), y(y) {};
quad_curve() : x(quad_spline()), y(quad_spline()) {};
quad_spline x, y;
};
// de Casteljau's algorithm
void subdivide_quad_spline(const quad_spline& q, const double& t, quad_spline& u, quad_spline& v) {
const double s = 1.0 - t;
u.c0 = q.c0;
v.c2 = q.c2;
u.c1 = s * q.c0 + t * q.c1;
v.c1 = s * q.c1 + t * q.c2;
u.c2 = s * u.c1 + t * v.c1;
v.c0 = u.c2;
}
void subdivide_quad_curve(const quad_curve& q, const double t, quad_curve& u, quad_curve& v) {
subdivide_quad_spline(q.x, t, u.x, v.x);
subdivide_quad_spline(q.y, t, u.y, v.y);
}
bool rectangles_overlap(const double& xa0, const double& ya0, const double& xa1, const double& ya1,
const double& xb0, const double& yb0, const double& xb1, const double& yb1) {
return xb0 <= xa1 && xa0 <= xb1 && yb0 <= ya1 && ya0 <= yb1;
}
std::tuple<bool, bool, point> test_intersection(const quad_curve& p, const quad_curve& q) {
const double px_min = std::min(std::min(p.x.c0, p.x.c1), p.x.c2);
const double py_min = std::min(std::min(p.y.c0, p.y.c1), p.y.c2);
const double px_max = std::max(std::max(p.x.c0, p.x.c1), p.x.c2);
const double py_max = std::max(std::max(p.y.c0, p.y.c1), p.y.c2);
const double qx_min = std::min(std::min(q.x.c0, q.x.c1), q.x.c2);
const double qy_min = std::min(std::min(q.y.c0, q.y.c1), q.y.c2);
const double qx_max = std::max(std::max(q.x.c0, q.x.c1), q.x.c2);
const double qy_max = std::max(std::max(q.y.c0, q.y.c1), q.y.c2);
bool accepted = false;
bool excluded = true;
point intersect = std::make_pair(0.0, 0.0);
if ( rectangles_overlap(px_min, py_min, px_max, py_max, qx_min, qy_min, qx_max, qy_max) ) {
excluded = false;
const double x_min = std::max(px_min, qx_min);
const double x_max = std::min(px_max, px_max);
if ( x_max - x_min <= TOLERANCE ) {
const double y_min = std::max(py_min, qy_min);
const double y_max = std::min(py_max, qy_max);
if ( y_max - y_min <= TOLERANCE ) {
accepted = true;
intersect = std::make_pair(0.5 * ( x_min + x_max ), 0.5 * ( y_min + y_max));
}
}
}
return std::make_tuple(accepted, excluded, intersect);
}
bool seems_to_be_duplicate(const std::vector<point>& intersects, const point& pt) {
for ( point intersect : intersects ) {
if ( fabs(intersect.first - pt.first) < SPACING && fabs(intersect.second - pt.second) < SPACING ) {
return true;
}
}
return false;
}
std::vector<point> find_intersects(const quad_curve& p, const quad_curve& q) {
std::vector<point> result;
std::stack<quad_curve> stack;
stack.push(p);
stack.push(q);
while ( ! stack.empty() ) {
quad_curve pp = stack.top();
stack.pop();
quad_curve qq = stack.top();
stack.pop();
std::tuple<bool, bool, point> objects = test_intersection(pp, qq);
bool accepted, excluded;
point intersect;
std::tie(accepted, excluded, intersect) = objects;
if ( accepted ) {
if ( ! seems_to_be_duplicate(result, intersect) ) {
result.push_back(intersect);
}
} else if ( ! excluded ) {
quad_curve p0{}, q0{}, p1{}, q1{};
subdivide_quad_curve(pp, 0.5, p0, p1);
subdivide_quad_curve(qq, 0.5, q0, q1);
for ( quad_curve item : { p0, q0, p0, q1, p1, q0, p1, q1 } ) {
stack.push(item);
}
}
}
return result;
}
int main() {
quad_curve vertical(quad_spline(-1.0, 0.0, 1.0), quad_spline(0.0, 10.0, 0.0));
// QuadCurve vertical represents the Bezier curve having control points (-1, 0), (0, 10) and (1, 0)
quad_curve horizontal(quad_spline(2.0, -8.0, 2.0), quad_spline(1.0, 2.0, 3.0));
// QuadCurve horizontal represents the Bezier curve having control points (2, 1), (-8, 2) and (2, 3)
std::cout << "The points of intersection are:" << std::endl;
std::vector<point> intersects = find_intersects(vertical, horizontal);
for ( const point& intersect : intersects ) {
std::cout << "( " << std::setw(9) << std::setprecision(6) << intersect.first
<< ", " << intersect.second << " )" << std::endl;
}
}

View file

@ -0,0 +1,145 @@
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public final class BezierCurveIntersection {
public static void main(String[] aArgs) {
QuadCurve vertical = new QuadCurve( new QuadSpline(-1.0, 0.0, 1.0), new QuadSpline(0.0, 10.0, 0.0) );
// QuadCurve vertical represents the Bezier curve having control points (-1, 0), (0, 10) and (1, 0)
QuadCurve horizontal = new QuadCurve( new QuadSpline(2.0, -8.0, 2.0), new QuadSpline(1.0, 2.0, 3.0) );
// QuadCurve horizontal represents the Bezier curve having control points (2, 1), (-8, 2) and (2, 3)
System.out.println("The points of intersection are:");
List<Point> intersects = findIntersects(vertical, horizontal);
for ( Point intersect : intersects ) {
System.out.println(String.format("%s%9.6f%s%9.6f%s", "( ", intersect.aX, ", ", intersect.aY, " )"));
}
}
private static List<Point> findIntersects(QuadCurve aP, QuadCurve aQ) {
List<Point> result = new ArrayList<Point>();
Stack<QuadCurve> stack = new Stack<QuadCurve>();
stack.push(aP);
stack.push(aQ);
while ( ! stack.isEmpty() ) {
QuadCurve pp = stack.pop();
QuadCurve qq = stack.pop();
List<Object> objects = testIntersection(pp, qq);
final boolean accepted = (boolean) objects.get(0);
final boolean excluded = (boolean) objects.get(1);
Point intersect = (Point) objects.get(2);
if ( accepted ) {
if ( ! seemsToBeDuplicate(result, intersect) ) {
result.add(intersect);
}
} else if ( ! excluded ) {
QuadCurve p0 = new QuadCurve();
QuadCurve q0 = new QuadCurve();
QuadCurve p1 = new QuadCurve();
QuadCurve q1 = new QuadCurve();
subdivideQuadCurve(pp, 0.5, p0, p1);
subdivideQuadCurve(qq, 0.5, q0, q1);
stack.addAll(List.of( p0, q0, p0, q1, p1, q0, p1, q1 ));
}
}
return result;
}
private static boolean seemsToBeDuplicate(List<Point> aIntersects, Point aPoint) {
for ( Point intersect : aIntersects ) {
if ( Math.abs(intersect.aX - aPoint.aX) < SPACING && Math.abs(intersect.aY - aPoint.aY) < SPACING ) {
return true;
}
}
return false;
}
private static List<Object> testIntersection(QuadCurve aP, QuadCurve aQ) {
final double pxMin = Math.min(Math.min(aP.x.c0, aP.x.c1), aP.x.c2);
final double pyMin = Math.min(Math.min(aP.y.c0, aP.y.c1), aP.y.c2);
final double pxMax = Math.max(Math.max(aP.x.c0, aP.x.c1), aP.x.c2);
final double pyMax = Math.max(Math.max(aP.y.c0, aP.y.c1), aP.y.c2);
final double qxMin = Math.min(Math.min(aQ.x.c0, aQ.x.c1), aQ.x.c2);
final double qyMin = Math.min(Math.min(aQ.y.c0, aQ.y.c1), aQ.y.c2);
final double qxMax = Math.max(Math.max(aQ.x.c0, aQ.x.c1), aQ.x.c2);
final double qyMax = Math.max(Math.max(aQ.y.c0, aQ.y.c1), aQ.y.c2);
boolean accepted = false;
boolean excluded = true;
Point intersect = new Point(0.0, 0.0);
if ( rectanglesOverlap(pxMin, pyMin, pxMax, pyMax, qxMin, qyMin, qxMax, qyMax) ) {
excluded = false;
final double xMin = Math.max(pxMin, qxMin);
final double xMax = Math.min(pxMax, pxMax);
if ( xMax - xMin <= TOLERANCE ) {
final double yMin = Math.max(pyMin, qyMin);
final double yMax = Math.min(pyMax, qyMax);
if ( yMax - yMin <= TOLERANCE ) {
accepted = true;
intersect = new Point(0.5 * ( xMin + xMax), 0.5 * ( yMin + yMax));
}
}
}
return List.of( accepted, excluded, intersect );
}
private static boolean rectanglesOverlap(double aXa0, double aYa0, double aXa1, double aYa1,
double aXb0, double aYb0, double aXb1, double aYb1) {
return aXb0 <= aXa1 && aXa0 <= aXb1 && aYb0 <= aYa1 && aYa0 <= aYb1;
}
private static void subdivideQuadCurve(QuadCurve aQ, double aT, QuadCurve aU, QuadCurve aV) {
subdivideQuadSpline(aQ.x, aT, aU.x, aV.x);
subdivideQuadSpline(aQ.y, aT, aU.y, aV.y);
}
// de Casteljau's algorithm
private static void subdivideQuadSpline(QuadSpline aQ, double aT, QuadSpline aU, QuadSpline aV) {
final double s = 1.0 - aT;
aU.c0 = aQ.c0;
aV.c2 = aQ.c2;
aU.c1 = s * aQ.c0 + aT * aQ.c1;
aV.c1 = s * aQ.c1 + aT * aQ.c2;
aU.c2 = s * aU.c1 + aT * aV.c1;
aV.c0 = aU.c2;
}
private static record Point(double aX, double aY) {}
private static class QuadSpline {
public QuadSpline(double aC0, double aC1, double aC2) {
c0 = aC0; c1 = aC1; c2 = aC2;
}
public QuadSpline() {
this(0.0, 0.0, 0.0);
}
private double c0, c1, c2;
}
private static class QuadCurve {
public QuadCurve(QuadSpline aX, QuadSpline aY) {
x = aX; y = aY;
}
public QuadCurve() {
this( new QuadSpline(), new QuadSpline() );
}
private QuadSpline x, y;
}
private static final double TOLERANCE = 0.000_000_1;
private static final double SPACING = 10 * TOLERANCE;
}

View file

@ -1,22 +1,35 @@
/*REXX program supports the Caesar cypher for the Latin alphabet only, no punctuation */
/*──────────── or blanks allowed, all lowercase Latin letters are treated as uppercase.*/
parse arg key .; arg . p /*get key & uppercased text to be used.*/
p= space(p, 0) /*elide any and all spaces (blanks). */
say 'Caesar cypher key:' key /*echo the Caesar cypher key to console*/
say ' plain text:' p /* " " plain text " " */
y= Caesar(p, key); say ' cyphered:' y /* " " cyphered text " " */
z= Caesar(y,-key); say ' uncyphered:' z /* " " uncyphered text " " */
if z\==p then say "plain text doesn't match uncyphered cyphered text."
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
Caesar: procedure; arg s,k; @= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
ak= abs(k) /*obtain the absolute value of the key.*/
L= length(@) /*obtain the length of the @ string. */
if ak>length(@)-1 | k==0 then call err k 'key is invalid.'
_= verify(s, @) /*any illegal characters specified ? */
if _\==0 then call err 'unsupported character:' substr(s, _, 1)
if k>0 then ky= k + 1 /*either cypher it, or ··· */
else ky= L + 1 - ak /* decypher it. */
return translate(s, substr(@ || @, ky, L), @) /*return the processed text.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
err: say; say '***error***'; say; say arg(1); say; exit 13
/*REXX program supports the Caesar cipher for the Latin alphabet only, */
/* no punctuation or blanks allowed, lowercase is treated as uppercase. */
Parse Upper Arg key text /* get key & uppercased text to be ciphered*/
text=space(text,0) /* elide any and blanks */
Say 'Caesar cipher key:' key /* echo the Caesar cipher key */
Say ' plain text:' text /* " " plain text */
code=caesar(text,key)
Say ' ciphered:' code /* " " ciphered text */
back=caesar(code,-key)
Say ' unciphered:' back /* " " unciphered text */
If back\==text Then
Say "unciphered text doesn't match plain text."
Exit /* stick a fork in it, we're all done*/
/*----------------------------------------------------------------------*/
caesar: Procedure
Parse Arg text,key
abc='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
If abs(key)>length(abc)-1|key==0 Then
Call err 'key ('key') is invalid.'
badpos=verify(text,abc) /* any illegal character in the text */
If badpos\==0 Then
Call err 'unsupported character:' substr(text,badpos,1)
If key>0 Then /* cipher */
key2=key+1
Else /* decipher */
key2=length(abc)+key+1
Return translate(text,substr(abc||abc,key2,length(abc)),abc)
/*----------------------------------------------------------------------*/
err:
Say
Say '***error***'
Say
Say arg(1)
Say
Exit 13

View file

@ -1,22 +1,39 @@
/*REXX program supports the Caesar cypher for most keyboard characters including blanks.*/
parse arg key p /*get key and the text to be cyphered. */
say 'Caesar cypher key:' key /*echo the Caesar cypher key to console*/
say ' plain text:' p /* " " plain text " " */
y= Caesar(p, key); say ' cyphered:' y /* " " cyphered text " " */
z= Caesar(y,-key); say ' uncyphered:' z /* " " uncyphered text " " */
if z\==p then say "plain text doesn't match uncyphered cyphered text."
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
Caesar: procedure; parse arg s,k; @= 'abcdefghijklmnopqrstuvwxyz'
@= translate(@)@"0123456789(){}[]<>'" /*add uppercase, digits, group symbols.*/
@= @'~!@#$%^&*_+:";?,./`-= ' /*also add other characters to the list*/
L= length(@) /*obtain the length of the @ string. */
ak= abs(k) /*obtain the absolute value of the key.*/
if ak>length(@)-1 | k==0 then call err k 'key is invalid.'
_= verify(s,@) /*any illegal characters specified ? */
if _\==0 then call err 'unsupported character:' substr(s, _, 1)
if k>0 then ky= k + 1 /*either cypher it, or ··· */
else ky= L + 1 - ak /* decypher it. */
return translate(s, substr(@ || @, ky, L), @) /*return the processed text.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
err: say; say '***error***'; say; say arg(1); say; exit 13
/*REXX program supports the Caesar cipher for most keyboard characters */
/* including blanks.*/
Parse Arg key text /* get key and the text to be ciph */
Say 'Caesar cipher key:' key /* echo the Caesar cipher key */
Say ' plain text:' text /* " " plain text */
code=caesar(text,key)
Say ' ciphered:' code /* " " ciphered text */
back=caesar(code,-key)
Say ' unciphered:' back /* " " unciphered text */
If back\==text Then
Say "plain text doesn't match unciphered ciphered text."
Exit /* stick a fork in it, we're all done */
/*----------------------------------------------------------------------*/
caesar: Procedure
Parse Arg txt,ky
abcx='abcdefghijklmnopqrstuvwxyz'
abcx=translate(abcx)abcx"0123456789(){}[]<>'" /*add uppercase, digits */
abcx=abcx'~!@#$%^&*_+:";?,./`-= ' /* also add other characters */
l=length(abcx) /* obtain the length of abcx */
aky=abs(ky) /* absolute value of the key */
If aky>length(abcx)-1|ky==0 Then
Call err ky 'key is invalid.'
badpos=verify(txt,abcx) /* any illegal character in txt */
If badpos\==0 Then
Call err 'unsupported character:' substr(txt,badpos,1)
If ky>0 Then /* cipher */
ky=ky+1
Else /* decipher */
ky=l+1-aky
/* return translated input */
Return translate(txt,substr(abcx||abcx,ky,l),abcx)
/*----------------------------------------------------------------------*/
err:
Say
Say '***error***'
Say
Say arg(1)
Say
Exit 13

View file

@ -0,0 +1,54 @@
#lang "qb"
REM THE Binary OPS ONLY WORK On SIGNED 16-Bit NUMBERS
REM SO WE STORE THE IP ADDRESS As AN ARRAY OF FOUR OCTETS
Cls
Dim IP(3)
Do
REM Read DEMO Data
140 Read CI$
If CI$ = "" Then Exit Do 'Sleep: End
REM FIND /
SL = 0
For I = Len(CI$) To 1 Step -1
If Mid$(CI$,I,1) = "/" Then SL = I : I = 1
Next I
If SL = 0 Then Print "INVALID CIDR STRING: '"; CI$; "'": Goto 140
NW = Val(Mid$(CI$,SL+1))
If NW < 1 Or NW > 32 Then Print "INVALID NETWORK WIDTH:"; NW: Goto 140
REM PARSE OCTETS INTO IP ARRAY
BY = 0 : N = 0
For I = 1 To SL-1
C$ = Mid$(CI$,I,1)
If Not (C$ <> ".") Then
IP(N) = BY : N = N + 1
BY = 0
If IP(N-1) < 256 Then 310
Print "INVALID OCTET VALUE:"; IP(N-1): Goto 140
Else C = Val(C$):If C Or (C$="0") Then BY = BY*10+C
End If
310 '
Next I
IP(N) = BY : N = N + 1
If IP(N-1) > 255 Then Print "INVALID OCTET VALUE:"; IP(N-1): Goto 140
REM NUMBER OF COMPLETE OCTETS IN NETWORK PART
NB = Int(NW/8)
REM NUMBER OF NETWORK BITS IN PARTIAL OCTET
XB = NW And 7
REM ZERO Out HOST BITS IN PARTIAL OCTET
IP(NB) = IP(NB) And (255 - 2^(8-XB) + 1)
REM And SET Any ALL-HOST OCTETS To 0
If NB < 3 Then For I = NB +1 To 3 : IP(I) = 0 : Next I
REM Print Out THE RESULT
Print Mid$(Str$(IP(0)),2);
For I = 1 To 3
Print "."; Mid$(Str$(IP( I)),2);
Next I
Print Mid$(CI$,SL)
Loop
Data "87.70.141.1/22", "36.18.154.103/12", "62.62.197.11/29"
Data "67.137.119.181/4", "161.214.74.21/24", "184.232.176.184/18"
REM SOME INVALID INPUTS
Data "127.0.0.1", "123.45.67.89/0", "98.76.54.32/100", "123.456.789.0/12"
Sleep

View file

@ -0,0 +1,44 @@
CLS
DIM IP(3)
DO
REM Read DEMO Data
140 READ CI$
IF CI$ = "" THEN EXIT DO 'Sleep: End
REM FIND /
SL = 0
FOR I = LEN(CI$) TO 1 STEP -1
IF MID$(CI$, I, 1) = "/" THEN SL = I: I = 1
NEXT I
IF SL = 0 THEN PRINT "INVALID CIDR STRING: '"; CI$; "'": GOTO 140
NW = VAL(MID$(CI$, SL + 1))
IF NW < 1 OR NW > 32 THEN PRINT "INVALID NETWORK WIDTH:"; NW: GOTO 140
REM PARSE OCTETS INTO IP ARRAY
BY = 0: N = 0
FOR I = 1 TO SL - 1
C$ = MID$(CI$, I, 1): IF C$ <> "." THEN 300
IP(N) = BY: N = N + 1: BY = 0: IF IP(N - 1) < 256 THEN 310
290 PRINT "INVALID OCTET VALUE:"; IP(N - 1): GOTO 140
300 C = VAL(C$): IF C OR (C$ = "0") THEN BY = BY * 10 + C
310 '
NEXT I
IP(N) = BY: N = N + 1: IF IP(N - 1) > 255 THEN 290
REM NUMBER OF COMPLETE OCTETS IN NETWORK PART
NB = INT(NW / 8)
REM NUMBER OF NETWORK BITS IN PARTIAL OCTET
XB = NW AND 7
REM ZERO Out HOST BITS IN PARTIAL OCTET
IP(NB) = IP(NB) AND (255 - 2 ^ (8 - XB) + 1)
REM And SET Any ALL-HOST OCTETS To 0
IF NB < 3 THEN FOR I = NB + 1 TO 3: IP(I) = 0: NEXT I
REM Print Out THE RESULT
PRINT MID$(STR$(IP(0)), 2);
FOR I = 1 TO 3
PRINT "."; MID$(STR$(IP(I)), 2);
NEXT I
PRINT MID$(CI$, SL)
LOOP
DATA 87.70.141.1/22, 36.18.154.103/12, 62.62.197.11/29
DATA 67.137.119.181/4, 161.214.74.21/24, 184.232.176.184/18
REM SOME INVALID INPUTS
DATA 127.0.0.1, 123.45.67.89/0, 98.76.54.32/100, 123.456.789.0/12
DATA

View file

@ -0,0 +1,150 @@
use once_cell::sync::Lazy;
const GRID_SIZE: usize = 15;
static mut CANVAS: Lazy<Vec<[char; GRID_SIZE]>> = Lazy::new(|| vec![[' '; GRID_SIZE]; GRID_SIZE],);
/// initialize CANVAS
fn init_n() {
for i in 0..GRID_SIZE {
for j in 0..GRID_SIZE {
unsafe { CANVAS[i][j] = ' '; }
}
unsafe { CANVAS[i][5] = '#'; }
}
}
/// draw horizontal
fn horizontal(c1: usize, c2: usize, r: usize) {
for c in c1..=c2 {
unsafe { CANVAS[r][c] = '#'; }
}
}
/// draw vertical
fn vertical(r1: usize, r2: usize, c: usize) {
for r in r1..=r2 {
unsafe { CANVAS[r][c] = '#'; }
}
}
/// draw diagonal NE to SW
fn diag_d(c1 : usize, c2: usize, r: usize) {
for c in c1..=c2 {
unsafe { CANVAS[r + c - c1][c] = '#'; }
}
}
/// draw diagonal SE to NW
fn diag_u(c1: usize, c2: usize, r: usize) {
for c in c1..=c2 {
unsafe { CANVAS[r + c1 - c][c] = '#'; }
}
}
/// Mark the portions of the ones place.
fn draw_ones(v: i32) {
match v {
1 => horizontal(6, 10, 0),
2 => horizontal(6, 10, 4),
3 => diag_d(6, 10, 0),
4 => diag_u(6, 10, 4),
5 => { draw_ones(1); draw_ones(4); },
6 => vertical(0, 4, 10),
7 => { draw_ones(1); draw_ones(6); },
8 => { draw_ones(2); draw_ones(6); },
9 => { draw_ones(1); draw_ones(8); },
_ => {},
}
}
/// Mark the portions of the tens place.
fn draw_tens(v: i32) {
match v {
1 => horizontal(0, 4, 0),
2 => horizontal(0, 4, 4),
3 => diag_u(0, 4, 4),
4 => diag_d(0, 4, 0),
5 => { draw_tens(1); draw_tens(4); },
6 => vertical(0, 4, 0),
7 => { draw_tens(1); draw_tens(6); },
8 => { draw_tens(2); draw_tens(6); },
9 => { draw_tens(1); draw_tens(8); },
_ => {},
}
}
/// Mark the portions of the hundreds place.
fn draw_hundreds(hundreds: i32) {
match hundreds {
1 => horizontal(6, 10, 14),
2 => horizontal(6, 10, 10),
3 => diag_u(6, 10, 14),
4 => diag_d(6, 10, 10),
5 => { draw_hundreds(1); draw_hundreds(4) },
6 => vertical(10, 14, 10),
7 => { draw_hundreds(1); draw_hundreds(6); },
8 => { draw_hundreds(2); draw_hundreds(6); },
9 => { draw_hundreds(1); draw_hundreds(8); },
_ => {},
}
}
/// Mark the portions of the thousands place.
fn draw_thousands(thousands: i32) {
match thousands {
1 => horizontal(0, 4, 14),
2 => horizontal(0, 4, 10),
3 => diag_d(0, 4, 10),
4 => diag_u(0, 4, 14),
5 => { draw_thousands(1); draw_thousands(4); },
6 => vertical(10, 14, 0),
7 => { draw_thousands(1); draw_thousands(6); },
8 => { draw_thousands(2); draw_thousands(6); },
9 => { draw_thousands(1); draw_thousands(8); },
_ => {},
}
}
/// Mark the char matrix for the numeral drawing.
fn draw(mut v: i32) {
let thousands: i32 = v / 1000;
v %= 1000;
let hundreds: i32 = v / 100;
v %= 100;
let tens: i32 = v / 10;
let ones: i32 = v % 10;
if thousands > 0 {
draw_thousands(thousands);
}
if hundreds > 0 {
draw_hundreds(hundreds);
}
if tens > 0 {
draw_tens(tens);
}
if ones > 0 {
draw_ones(ones);
}
}
/// Test the drawings as outout to stdout.
fn test_output(n: i32) {
println!("{n}");
init_n();
draw(n);
unsafe {
for line in CANVAS.iter() {
for c in line.iter() {
print!("{}", *c);
}
println!();
}
}
println!("\n");
}
fn main() {
for n in [0, 1, 20, 300, 2022, 4000, 5555, 6789, 9999] {
test_output(n);
}
}

View file

@ -0,0 +1,127 @@
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.imageio.ImageIO;
public final class ColorQuantization {
public static void main(String[] aArgs) throws IOException {
BufferedImage original = ImageIO.read( new File("quantum_frog.png") );
final int width = original.getWidth();
final int height = original.getHeight();
int[] originalPixels = original.getRGB(0, 0, width, height, null, 0, width);
List<Item> bucket = new ArrayList<Item>();
for ( int i = 0; i < originalPixels.length; i++ ) {
bucket.add( new Item(new Color(originalPixels[i]), i) );
}
int[] resultPixels = new int[originalPixels.length];
medianCut(bucket, 4, resultPixels);
BufferedImage result = new BufferedImage(width, height, original.getType());
result.setRGB(0, 0, width, height, resultPixels, 0, width);
ImageIO.write(result, "png", new File("Quantum_frog16Java.png"));
System.out.println("The 16 colors used in Red, Green, Blue format are:");
for ( Color color : colorsUsed ) {
System.out.println("(" + color.getRed() + ", " + color.getGreen() + ", " + color.getBlue() + ")");
}
}
private static void medianCut(List<Item> aBucket, int aDepth, int[] aResultPixels) {
if ( aDepth == 0 ) {
quantize(aBucket, aResultPixels);
return;
}
int[] minimumValue = new int[] { 256, 256, 256 };
int[] maximumValue = new int[] { 0, 0, 0 };
for ( Item item : aBucket ) {
for ( Channel channel : Channel.values() ) {
int value = item.getPrimary(channel);
if ( value < minimumValue[channel.index] ) {
minimumValue[channel.index] = value;
}
if ( value > maximumValue[channel.index] ) {
maximumValue[channel.index] = value;
}
}
}
int[] valueRange = new int[] { maximumValue[Channel.RED.index] - minimumValue[Channel.RED.index],
maximumValue[Channel.GREEN.index] - minimumValue[Channel.GREEN.index],
maximumValue[Channel.BLUE.index] - minimumValue[Channel.BLUE.index] };
Channel selectedChannel = ( valueRange[Channel.RED.index] >= valueRange[Channel.GREEN.index] )
? ( valueRange[Channel.RED.index] >= valueRange[Channel.BLUE.index] ) ? Channel.RED : Channel.BLUE
: ( valueRange[Channel.GREEN.index] >= valueRange[Channel.BLUE.index] ) ? Channel.GREEN : Channel.BLUE;
Collections.sort(aBucket, switch(selectedChannel) {
case RED -> redComparator;
case GREEN -> greenComparator;
case BLUE -> blueComparator; });
final int medianIndex = aBucket.size() / 2;
medianCut(new ArrayList<Item>(aBucket.subList(0, medianIndex)), aDepth - 1, aResultPixels);
medianCut(new ArrayList<Item>(aBucket.subList(medianIndex, aBucket.size())), aDepth - 1, aResultPixels);
}
private static void quantize(List<Item> aBucket, int[] aResultPixels) {
int[] means = new int[Channel.values().length];
for ( Item item : aBucket ) {
for ( Channel channel : Channel.values() ) {
means[channel.index] += item.getPrimary(channel);
}
}
for ( Channel channel : Channel.values() ) {
means[channel.index] /= aBucket.size();
}
Color color = new Color(means[Channel.RED.index], means[Channel.GREEN.index], means[Channel.BLUE.index]);
colorsUsed.add(color);
for ( Item item : aBucket ) {
aResultPixels[item.aIndex] = color.getRGB();
}
}
private enum Channel {
RED(0), GREEN(1), BLUE(2);
private Channel(int aIndex) {
index = aIndex;
}
private final int index;
}
private record Item(Color aColor, Integer aIndex) {
public int getPrimary(Channel aChannel) {
return switch(aChannel) {
case RED -> aColor.getRed();
case GREEN -> aColor.getGreen();
case BLUE -> aColor.getBlue();
};
}
}
private static Comparator<Item> redComparator =
(one, two) -> Integer.compare(one.aColor.getRed(), two.aColor.getRed());
private static Comparator<Item> greenComparator =
(one, two) -> Integer.compare(one.aColor.getGreen(), two.aColor.getGreen());
private static Comparator<Item> blueComparator =
(one, two) -> Integer.compare(one.aColor.getBlue(), two.aColor.getBlue());
private static List<Color> colorsUsed = new ArrayList<Color>();
}

View file

@ -7,7 +7,7 @@ std::vector<uint32_t> count(8, 0);
std::vector<bool> used(10, false);
uint32_t largest = 0;
bool is_colorful(uint32_t number) {
bool is_colorful(const uint32_t& number) {
if ( number > 98'765'432 ) {
return false;
}
@ -42,7 +42,7 @@ bool is_colorful(uint32_t number) {
return true;
}
void count_colorful(uint32_t taken, uint32_t number, uint32_t digits) {
void count_colorful(const uint32_t& taken, const uint32_t& number, const uint32_t& digits) {
if ( taken == 0 ) {
for ( uint32_t digit = 0; digit < 10; ++digit ) {
used[digit] = true;

View file

@ -0,0 +1,73 @@
use core::cmp::max;
use std::collections::HashSet;
fn to_digits(mut n: u64, base: u64) -> Vec<u64> {
if n == 0 {
return [0].to_vec();
}
let mut v: Vec<u64> = Vec::new();
while n > 0 {
let d = n % base;
n /= base;
v.push(d);
}
return v;
}
fn is_colorful(n: u64) -> bool {
if &n > &9 {
let dig: Vec<u64> = to_digits(n, 10);
if dig.contains(&1) || dig.contains(&0) {
return false;
}
let mut products: HashSet<u64> = HashSet::new();
for i in 0..dig.len() {
if products.contains(&dig[i]) {
return false;
}
products.insert(dig[i]);
}
for i in 0..dig.len() {
for j in i+2..dig.len()+1 {
let p: u64 = (dig[i..j]).iter().product();
if products.contains(&p) {
return false;
}
products.insert(p);
}
}
}
return true;
}
fn main() {
println!("Colorful numbers for 1:25, 26:50, 51:75, and 76:100:");
for i in (1..101).step_by(25) {
for j in 0..25 {
if is_colorful(i + j) {
print!("{:5}", i + j);
}
}
println!();
}
println!();
let mut csum: u64 = 0;
let mut largest: u64 = 0;
let mut n: u64;
for i in 0..8 {
let j: u64 = { if i == 0 { 0 } else { 10_u64.pow(i) } };
let k: u64 = 10_u64.pow(i + 1) - 1;
n = 0;
for x in j..k+1 {
if is_colorful(x) {
largest = max(largest, x);
n += 1;
}
}
println!("The count of colorful numbers within the interval [{j}, {k}] is {n}.");
csum += n;
}
println!("The largest possible colorful number is {largest}.");
println!("The total number of colorful numbers is {csum}.")
}

View file

@ -1,7 +1,7 @@
func comma_quibbling(words) {
'{' + ([words.ft(0, -2).join(', ')]-[''] + [words.last] -> join(' and ')) + '}';
'{' + ([words.first(-1).join(', ')]-[''] + [words.last] -> join(' and ')) + '}'
}
[<>, <ABC>, <ABC DEF>, <ABC DEF G H>].each { |w|
say comma_quibbling(w);
say comma_quibbling(w)
}

View file

@ -0,0 +1,9 @@
# This is a line comment.
^|This is a single line block comment.|^
^| This is
| a multi-line
| block comment.
|^
^|This is a ^|nested|^ block comment.|^

View file

@ -0,0 +1,9 @@
public final class CompileTimeCalculation {
public static void main(String[] aArgs) {
System.out.println(tenFactorial);
}
private static int tenFactorial = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1;
}

View file

@ -1 +1 @@
say(BEGIN [*] 2..10);
say BEGIN [*] 2..10;

View file

@ -0,0 +1,44 @@
#include <stdio.h>
#include <stdbool.h>
bool is_substring(unsigned n, unsigned k) {
unsigned startMatch = 0;
for (unsigned pfx = k; n > 0; n /= 10) {
if (pfx % 10 == n % 10) {
pfx /= 10;
if (startMatch == 0) startMatch = n;
} else {
pfx = k;
if (startMatch != 0) n = startMatch;
startMatch = 0;
}
if (pfx == 0) return true;
}
return false;
}
bool factors_are_substrings(unsigned n) {
if (n%2==0 || n%3==0 || n%5==0 || n%7==0) return false;
unsigned factor_count = 0;
for (unsigned factor = 11, n_rest = n; factor <= n_rest; factor += 2) {
if (n_rest % factor != 0) continue;
while (n_rest % factor == 0) n_rest /= factor;
if (!is_substring(n, factor)) return false;
factor_count++;
}
return factor_count > 1;
}
int main(void) {
unsigned amount = 10;
for (unsigned n = 11; amount > 0; n += 2) {
if (factors_are_substrings(n)) {
printf("%u\n", n);
amount--;
}
}
return 0;
}

View file

@ -0,0 +1,74 @@
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
public final class CompositeNumbersK {
public static void main(String[] aArgs) {
int k = 11 * 11;
List<Integer> result = new ArrayList<Integer>();
while ( result.size() < 20 ) {
while ( k % 3 == 0 || k % 5 == 0 || k % 7 == 0 ) {
k += 2;
}
List<Integer> factors = primeFactors(k);
if ( factors.size() > 1 ) {
String stringK = String.valueOf(k);
if ( factors.stream().allMatch( factor -> stringK.indexOf(String.valueOf(factor)) >= 0 ) ) {
result.add(k);
}
}
k += 2;
}
for ( int i = 0; i < result.size(); i++ ) {
System.out.print(String.format("%10d%s", result.get(i), ( i == 9 || i == 19 ? "\n" : "" )));
}
}
private static List<Integer> primeFactors(int aK) {
ArrayList<Integer> result = new ArrayList<Integer>();
if ( aK <= 1 ) {
return result;
}
BigInteger bigK = BigInteger.valueOf(aK);
if ( bigK.isProbablePrime(CERTAINTY_LEVEL) ) {
result.add(aK);
return result;
}
int divisor = pollardsRho(bigK).intValueExact();
result.addAll(primeFactors(divisor));
result.addAll(primeFactors(aK / divisor));
Collections.sort(result);
return result;
}
private static BigInteger pollardsRho(BigInteger aN) {
final BigInteger constant = new BigInteger(aN.bitLength(), RANDOM);
BigInteger x = new BigInteger(aN.bitLength(), RANDOM);
BigInteger xx = x;
BigInteger divisor = null;
if ( aN.mod(BigInteger.TWO).signum() == 0 ) {
return BigInteger.TWO;
}
do {
x = x.multiply(x).mod(aN).add(constant).mod(aN);
xx = xx.multiply(xx).mod(aN).add(constant).mod(aN);
xx = xx.multiply(xx).mod(aN).add(constant).mod(aN);
divisor = x.subtract(xx).gcd(aN);
} while ( divisor.compareTo(BigInteger.ONE) == 0 );
return divisor;
}
private static final ThreadLocalRandom RANDOM = ThreadLocalRandom.current();
private static final int CERTAINTY_LEVEL = 10;
}

View file

@ -0,0 +1,25 @@
use primes::{is_prime,factors_uniq};
/// True if non-prime n's factors, all > 9, are all substrings of its representation in base 10
fn contains_its_prime_factors_all_over_7(n: u64) -> bool {
if n < 10 || is_prime(n) {
return false;
}
let strn = &n.to_string();
let pfacs = factors_uniq(n);
return pfacs.iter().all(|f| f > &9 && strn.contains(&f.to_string()));
}
fn main() {
let mut found = 0;
// 20 of these < 30 million
for n in 0..30_000_000 {
if contains_its_prime_factors_all_over_7(n) {
found += 1;
print!("{:12}{}", n, {if found % 10 == 0 {"\n"} else {""}});
if found == 20 {
break;
}
}
}
}

View file

@ -1,3 +1,5 @@
(if (= (* 2 2) 4) (print "if-then: equal"))
(if (= (* 2 2) 6) (print "if-then: non equal"))
(if (= (* 2 2) 4)
(print "if-then: equal"))
(if (= (* 2 2) 6)
(print "if-then: should not be printed"))
; ==> if-then: equal

View file

@ -1,4 +1,9 @@
(if (= (* 2 2) 4) (print "if-then-else: equal") (print "if-then-else: non equal"))
(if (= (* 2 2) 6) (print "if-then-else: non equal") (print "if-then-else: i don't know"))
(if (= (* 2 2) 4)
(print "if-then-else: equal")
(print "if-then-else: non equal"))
; ==> if-then-else: equal
; ==> if-then-else: i don't know
(if (= (* 2 2) 6)
(print "if-then-else: equal")
(print "if-then-else: non equal"))
; ==> if-then-else: non equal

View file

@ -1,7 +1,11 @@
(unless (= (* 2 2) 4) (print "unless: non equal"))
(unless (= (* 2 2) 6) (print "unless: i don't know"))
(unless (= (* 2 2) 4) (print "unless: non equal") (print "unless: equal"))
(unless (= (* 2 2) 6) (print "unless: i don't know") (print "unless: non equal"))
; ==> unless: i don't know
; ==> unless: equal
; ==> unless: i don't know
(when (= (* 2 2) 4)
(print "when: ..just do something..")
(print "when: equal"))
; ==> when: ..just do something..
; ==> when: equal
(unless (= (* 2 2) 6)
(print "unless: ..just do something..")
(print "unless: not equal"))
; ==> unless: ..just do something..
; ==> unless: not equal

View file

@ -1,10 +1,23 @@
(case (* 2 2)
(3
(print "case: 3"))
(4
(print "case: 4"))
((5 6 7)
(print "case: 5 or 6 or 7"))
(else
(print "case: i don't know")))
; ==> case: 4
(if (= (* 2 2) 4)
(print "if-then-else*: equal")
else
(print "if-then-else*: ..just do something..")
(print "if-then-else*: non equal"))
; ==> if-then-else*: equal
(if (= (* 2 2) 4)
then
(print "if-then-else*: ..just do something..")
(print "if-then-else*: equal")
else
(print "if-then-else*: ..just do something..")
(print "if-then-else*: non equal"))
; ==> if-then-else*: ..just do something..
; ==> if-then-else*: equal
(if (= (* 2 2) 4) ; same as `when`
then
(print "if-then-else*: ..just do something..")
(print "if-then-else*: equal"))
; ==> if-then-else*: ..just do something..
; ==> if-then-else*: equal

View file

@ -1,8 +1,35 @@
(case (vector 'selector 1 2 3)
(case (* 2 2)
(3 ; exact number
(print "case: 3"))
(4 ; exact number
(print "case: 4"))
((5 6 7) ; list of numbers
(print "case: 5 or 6 or 7"))
(else
(print "case: i don't know")))
; ==> case: 4
; extended case with usable else
(case (* 2 2)
(3 ; exact number
(print "case: 3"))
(else => (lambda (num)
(print "case: real value is " num))))
; ==> case: real value is 4
(case (* 2 2)
(3 ; exact number
(print "case: 3"))
(else is num
(print "case: real value is " num)))
; ==> case: real value is 4
; extended case with vectors
(case ['selector 1 2 3]
(['case1 x y]
(print "case: case1 " x ", " y))
(['selector x y z]
(print "case: selector " x ", " y ", " z))
(else
(print "case: i don't know")))
; ==> tuple-case: selector 1, 2, 3
; ==> case: selector 1, 2, 3

View file

@ -0,0 +1,86 @@
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
public final class ConsecutivePrimes {
public static void main(String[] aArgs) {
final int limit = 1_000_000;
List<Integer> primes = listPrimeNumbers(limit);
List<Integer> asc = new ArrayList<Integer>();
List<Integer> desc = new ArrayList<Integer>();
List<List<Integer>> maxAsc = new ArrayList<List<Integer>>();
List<List<Integer>> maxDesc = new ArrayList<List<Integer>>();
int maxAscSize = 0;
int maxDescSize = 0;
for ( int prime : primes ) {
final int ascSize = asc.size();
if ( ascSize > 1 && prime - asc.get(ascSize - 1) <= asc.get(ascSize - 1) - asc.get(ascSize - 2) ) {
asc = new ArrayList<Integer>(asc.subList(ascSize - 1, asc.size()));
}
asc.add(prime);
if ( asc.size() >= maxAscSize ) {
if ( asc.size() > maxAscSize ) {
maxAscSize = asc.size();
maxAsc.clear();
}
maxAsc.add( new ArrayList<Integer>(asc) );
}
final int descSize = desc.size();
if ( descSize > 1 && prime - desc.get(descSize - 1) >= desc.get(descSize - 1) - desc.get(descSize - 2) ) {
desc = new ArrayList<Integer>(desc.subList(descSize - 1, desc.size()));
}
desc.add(prime);
if ( desc.size() >= maxDescSize ) {
if ( desc.size() > maxDescSize ) {
maxDescSize = desc.size();
maxDesc.clear();
}
maxDesc.add( new ArrayList<Integer>(desc) );
}
}
System.out.println("Longest run(s) of ascending prime gaps up to " + limit + ":");
for ( List<Integer> list : maxAsc ) {
displayResult(list);
}
System.out.println();
System.out.println("Longest run(s) of descending prime gaps up to " + limit + ":");
for( List<Integer> list : maxDesc ) {
displayResult(list);
}
}
private static List<Integer> listPrimeNumbers(int aLimit) {
BitSet sieve = new BitSet(aLimit + 1);
sieve.set(2, aLimit + 1);
for ( int i = 2; i <= Math.sqrt(aLimit); i = sieve.nextSetBit(i + 1) ) {
for ( int j = i * i; j <= aLimit; j = j + i ) {
sieve.clear(j);
}
}
List<Integer> result = new ArrayList<Integer>(sieve.cardinality());
for ( int i = 2; i >= 0; i = sieve.nextSetBit(i + 1) ) {
result.add(i);
}
return result;
}
private static void displayResult(List<Integer> aList) {
for ( int i = 0; i < aList.size(); i++ ) {
if ( i > 0 ) {
System.out.print(" (" + ( aList.get(i) - aList.get(i - 1) ) + ") ");
}
System.out.print(aList.get(i));
}
System.out.println();
}
}

View file

@ -0,0 +1,48 @@
public final class CurzonNumbers {
public static void main(String[] aArgs) {
for ( int k = 2; k <= 10; k += 2 ) {
System.out.println("Generalised Curzon numbers with base " + k + ":");
int n = 1;
int count = 0;
while ( count < 50 ) {
if ( isGeneralisedCurzonNumber(k, n) ) {
System.out.print(String.format("%4d%s", n, ( ++count % 10 == 0 ? "\n" : " " )));
}
n += 1;
}
while ( count < 1_000 ) {
if ( isGeneralisedCurzonNumber(k, n) ) {
count += 1;
}
n += 1;
}
System.out.println("1,000th Generalised Curzon number with base " + k + ": " + ( n - 1 ));
System.out.println();
}
}
private static boolean isGeneralisedCurzonNumber(int aK, int aN) {
final long r = aK * aN;
return modulusPower(aK, aN, r + 1) == r;
}
private static long modulusPower(long aBase, long aExponent, long aModulus) {
if ( aModulus == 1 ) {
return 0;
}
aBase %= aModulus;
long result = 1;
while ( aExponent > 0 ) {
if ( ( aExponent & 1 ) == 1 ) {
result = ( result * aBase ) % aModulus;
}
aBase = ( aBase * aBase ) % aModulus;
aExponent >>= 1;
}
return result;
}
}

View file

@ -0,0 +1,125 @@
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 DeathStar {
public static void main(String[] aArgs) throws IOException {
Vector direction = new Vector(20.0, -40.0, -10.0);
direction.normalise();
Sphere positive = new Sphere(0, 0, 0, 120);
Sphere negative = new Sphere(-90, -90, -30, 100);
BufferedImage image = deathStar(positive, negative, direction, 1.5, 0.5);
ImageIO.write(image, "png", new File("DeathStarJava.png"));
}
private static BufferedImage deathStar(
Sphere aPositive, Sphere aNegative, Vector aDirection, double aShadow, double aBrightness) {
final int width = aPositive.radius * 4;
final int height = aPositive.radius * 3;
BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics graphics = result.getGraphics();
graphics.setColor(Color.CYAN);
graphics.fillRect(0, 0, width, height);
Vector ray = new Vector(0.0, 0.0, 0.0);
final int deltaX = aPositive.x - width / 2;
final int deltaY = aPositive.y - height / 2;
double xMax = aPositive.x + aPositive.radius;
double yMax = aPositive.y + aPositive.radius;
for ( int y = aPositive.y - aPositive.radius; y < yMax; y++ ) {
for ( int x = aPositive.x - aPositive.radius; x < xMax; x++ ) {
List<Object> contacts = aPositive.contact(x, y);
final double zb1 = (double) contacts.get(0);
final int zb2 = (int) contacts.get(1);
final boolean positiveHit = (boolean) contacts.get(2);
if ( ! positiveHit ) {
continue;
}
contacts = aNegative.contact(x, y);
final double zs1 = (double) contacts.get(0);
final int zs2 = (int) contacts.get(1);
boolean negativeHit = (boolean) contacts.get(2);
if ( negativeHit ) {
if ( zs1 > zb1 ) {
negativeHit = false;
} else if ( zs2 > zb2 ) {
continue;
}
}
if ( negativeHit ) {
ray.x = aNegative.x - x;
ray.y = aNegative.y - y;
ray.z = aNegative.z - zs2;
} else {
ray.x = x - aPositive.x;
ray.y = y - aPositive.y;
ray.z = zb1 - aPositive.z;
}
ray.normalise();
double rayComponent = ray.scalarProduct(aDirection);
if ( rayComponent < 0 ) {
rayComponent = 0;
}
int color = (int) ( 255 * ( Math.pow(rayComponent, aShadow) + aBrightness) / ( 1 + aBrightness ) );
if ( color < 0 ) {
color = 0;
} else if ( color > 255 ) {
color = 255;
}
result.setRGB(x - deltaX, y - deltaY, color);
}
}
return result;
}
private static class Vector {
public Vector(double aX, double aY, double aZ) {
x = aX; y = aY; z = aZ;
}
public double scalarProduct(Vector aOther) {
return x * aOther.x + y * aOther.y + z * aOther.z;
}
public Vector normalise() {
final double magnitude = Math.sqrt(this.scalarProduct(this));
return new Vector(x /= magnitude, y /= magnitude, z /= magnitude);
}
private double x, y, z;
}
private static class Sphere {
public Sphere(int aX, int aY, int aZ, int aRadius) {
x = aX; y = aY; z = aZ; radius = aRadius;
}
public List<Object> contact(int aX, int aY) {
final int xx = aX - x;
final int yy = aY - y;
final int zSquared = radius * radius - ( xx * xx + yy * yy );
if ( zSquared >= 0 ) {
final double zz = Math.sqrt(zSquared);
return List.of(z - zz, z, true);
}
return List.of( 0.0, 0, false );
}
private int x, y, z, radius;
}
}

View file

@ -0,0 +1,42 @@
public final class DeceptiveNumbers {
public static void main(String[] aArgs) {
int n = 7;
int count = 0;
while ( count < 100 ) {
if ( isDeceptive(n) ) {
System.out.print(String.format("%6d%s", n, ( ++count % 10 == 0 ? "\n" : " " )));
}
n += 1;
}
}
private static boolean isDeceptive(int aN) {
if ( aN % 2 != 0 && aN % 3 != 0 && aN % 5 != 0 && modulusPower(10, aN - 1, aN) == 1 ) {
for ( int divisor = 7; divisor < Math.sqrt(aN); divisor += 6 ) {
if ( aN % divisor == 0 || aN % ( divisor + 4 ) == 0 ) {
return true;
}
}
}
return false;
}
private static long modulusPower(long aBase, long aExponent, long aModulus) {
if ( aModulus == 1 ) {
return 0;
}
aBase %= aModulus;
long result = 1;
while ( aExponent > 0 ) {
if ( ( aExponent & 1 ) == 1 ) {
result = ( result * aBase ) % aModulus;
}
aBase = ( aBase * aBase ) % aModulus;
aExponent >>= 1;
}
return result;
}
}

View file

@ -0,0 +1,37 @@
#include <algorithm>
#include <cstdint>
#include <iostream>
#include <vector>
void print_vector(const std::vector<int32_t>& list) {
std::cout << "[";
for ( uint64_t i = 0; i < list.size() - 1; ++i ) {
std::cout << list[i] << ", ";
}
std::cout << list.back() << "]" << std::endl;
}
std::vector<int32_t> deconvolution(const std::vector<int32_t>& a, const std::vector<int32_t>& b) {
std::vector<int32_t> result(a.size() - b.size() + 1, 0);
for ( uint64_t n = 0; n < result.size(); n++ ) {
result[n] = a[n];
uint64_t start = std::max((int) (n - b.size() + 1), 0);
for ( uint64_t i = start; i < n; i++ ) {
result[n] -= result[i] * b[n - i];
}
result[n] /= b[0];
}
return result;
}
int main() {
const std::vector<int32_t> h = { -8, -9, -3, -1, -6, 7 };
const std::vector<int32_t> f = { -3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1 };
const std::vector<int32_t> g = { 24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52,
25, -67, -96, 96, 31, 55, 36, 29, -43, -7 };
std::cout << "h = "; print_vector(h);
std::cout << "deconvolution(g, f) = "; print_vector(deconvolution(g, f));
std::cout << "f = "; print_vector(f);
std::cout << "deconvolution(g, h) = "; print_vector(deconvolution(g, h));
}

View file

@ -0,0 +1,76 @@
#include <cmath>
#include <functional>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
double mean(const std::vector<double>& pseudo_random) {
double sum = 0.0;
for ( double item : pseudo_random ) {
sum += item;
}
return sum / pseudo_random.size();
}
double standard_deviation(const std::vector<double>& pseudo_random) {
const double average = mean(pseudo_random);
double sum_squares = 0.0;
for ( double item : pseudo_random ) {
sum_squares += item * item;
}
return sqrt(sum_squares / pseudo_random.size() - average * average);
}
std::vector<double> funnel(const std::vector<double>& pseudo_random,
const std::function<double(double, double)>& rule) {
double value = 0.0;
std::vector<double> result(pseudo_random.size(), 0);
for ( size_t i = 0; i < pseudo_random.size(); i++ ) {
const double result_value = value + pseudo_random[i];
value = rule(value, pseudo_random[i]);
result[i] = result_value;
}
return result;
}
void experiment(const std::string& label, const std::vector<double>& pseudo_random_xs,
const std::vector<double>& pseudo_random_ys, const std::function<double(double, double)>& rule) {
std::vector<double> result_x = funnel(pseudo_random_xs, rule);
std::vector<double> result_y = funnel(pseudo_random_ys, rule);
std::cout << label << std::endl;
std::cout << "-----------------------------------------" << std::endl;
std::cout << "Mean x, y" << std::setw(16) << ": " << std::fixed << std::setprecision(4)
<< mean(result_x) << ", " << mean(result_y) << std::endl;
std::cout << "Standard deviation x, y: " << standard_deviation(result_x) << ", "
<< standard_deviation(result_y) << std::endl;
std::cout << std::endl;
}
int main() {
const std::vector<double> pseudo_random_xs = { -0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071,
0.275, 1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001, -0.382, 0.161, 0.915, 2.080, -2.337,
0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047, -0.095, 0.695, 0.340,
-0.182, 0.287, 0.213, -0.423, -0.021, -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315,
0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181, -0.700, -0.361, -0.789, 0.279, -0.174,
-0.009, -0.323, -0.658, 0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774, -1.043, 0.051,
0.021, 0.247, -0.310, 0.171, 0.000, 0.106, 0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521,
0.017, 0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598, 0.443, -0.521, -0.799, 0.087 };
const std::vector<double> pseudo_random_ys = { 0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395,
0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000, 0.426, 0.205, -0.765, -2.188, -0.742,
-0.010, 0.089, 0.208, 0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096, -0.025, -0.868, 1.051,
0.157, 0.216, 0.162, 0.249, -0.007, 0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226, 0.710,
0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295, 1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074,
0.217, -0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219, 0.698, 0.275, 0.056, 0.031, 0.421, 0.064,
0.721, 0.104, -0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477, 1.537, -0.901, 0.939, -0.411,
0.341, -0.411, 0.106, 0.224, -0.947, -1.424, -0.542, -1.032 };
experiment("Rule 1:", pseudo_random_xs, pseudo_random_ys, [](double z, double dz) -> double { return 0.0; });
experiment("Rule 2:", pseudo_random_xs, pseudo_random_ys, [](double z, double dz) -> double { return -dz; });
experiment("Rule 3:", pseudo_random_xs, pseudo_random_ys, [](double z, double dz) -> double { return -( z + dz ); });
experiment("Rule 4:", pseudo_random_xs, pseudo_random_ys, [](double z, double dz) -> double { return z + dz; });
}

View file

@ -0,0 +1,48 @@
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public final class DescendingPrimes {
public static void main(String[] aArgs) {
List<Integer> allNumbersStrictlyDescendingDigits = new ArrayList<Integer>(512);
for ( int i = 0; i < 512; i++ ) {
int number = 0;
int temp = i;
int digit = 9;
while ( temp > 0 ) {
if ( temp % 2 == 1 ) {
number = number * 10 + digit;
}
temp >>= 1;
digit -= 1;
}
allNumbersStrictlyDescendingDigits.add(number);
}
Collections.sort(allNumbersStrictlyDescendingDigits);
int count = 0;
for ( int number : allNumbersStrictlyDescendingDigits ) {
if ( isPrime(number) ) {
System.out.print(String.format("%9d%s", number, ( ++count % 10 == 0 ? "\n" : " " )));
}
}
System.out.println(System.lineSeparator());
System.out.println("There are " + count + " descending primes.");
}
private static boolean isPrime(int aNumber) {
if ( aNumber < 2 || ( aNumber % 2 ) == 0 ) {
return aNumber == 2;
}
for ( int divisor = 3; divisor * divisor <= aNumber; divisor += 2 ) {
if ( aNumber % divisor == 0 ) {
return false;
}
}
return true;
}
}

View file

@ -0,0 +1,341 @@
(* Given that the context is collision detection, we will consider
containment of one triangle entirely inside the other as overlap
and test for that, as well as for overlap of the triangle sides
themselves. One must agree that, if one triangle has become buried
entirely inside another, then the two have collided. There are
consequences for the conservation of momentum.
Besides, the full set of overlap tests, INCLUDING containment of
one polygonal hull inside another, is relevant to the problem of
finding intersections of Bézier curves. See
https://rosettacode.org/wiki/B%C3%A9zier_curves/Intersections
This code specifically tests for overlapping vertices, in case the
main tests fail to catch such overlaps. Approximate equality is
employed rather than exact floating-point equality. *)
#include "share/atspre_staload.hats"
%{^
#include <math.h>
#include <float.h>
%}
macdef dbl_epsilon = $extval (double, "DBL_EPSILON")
(* We will use some simple homogeneous geometric algebra. *)
typedef point =
@{e1 = double,
e2 = double,
e0 = double}
macdef Pt (x, y) = (* Shorthand for creating a normalized point. *)
@{e1 = ,(x),
e2 = ,(y),
e0 = 1.0} : point
typedef line =
@{e0_e1 = double,
e0_e2 = double,
e1_e2 = double}
typedef triangle = @(point, point, point)
fn
outer_product_point_point (a : point, b : point) : line =
@{e0_e1 = ~(~a.e0 * b.e1 + a.e1 * b.e0),
e0_e2 = ~(~a.e0 * b.e2 + a.e2 * b.e0),
e1_e2 = (a.e1 * b.e2 - a.e2 * b.e1)}
fn
left_contraction_point_line (a : point, b : line) : point =
@{e1 = (a.e0 * b.e0_e1 - a.e2 * b.e1_e2),
e2 = (a.e0 * b.e0_e2 + a.e1 * b.e1_e2),
e0 = (~a.e1 * b.e0_e1 - a.e2 * b.e0_e2)}
fn
left_contraction_point_point (a : point, b : point) : double =
(* This is the same as the scalar product but saves us having to add
an operator for which I cannot think of a good symbol. *)
(a.e1 * b.e1) + (a.e2 * b.e2) + (a.e0 * b.e0)
fn
dual_line (a : line) : point =
@{e1 = ~a.e0_e2,
e2 = a.e0_e1,
e0 = a.e1_e2}
overload outer_product with outer_product_point_point
overload left_contraction with left_contraction_point_line
overload left_contraction with left_contraction_point_point
overload dual with dual_line (* Orthogonal complement. *)
infixl ( * ) ^ .|
overload ^ with outer_product
overload .| with left_contraction
fn
intersection_line_line (a : line, b : line) : point =
let
val p = dual a .| b
in
if p.e0 = 0.0 then
(* The lines are parallel (or coincident, if p is all zeros). *)
p
else
(* Normalize the intersection point. *)
@{e1 = p.e1 / p.e0,
e2 = p.e2 / p.e0,
e0 = 1.0}
end
fn
which_side_point_line (a : point, b : line) : Sgn =
(* 1 = left, 0 = lies on the line, ~1 = right *)
let
val x = dual b .| a
in
if x < 0.0 then
~1
else if x > 0.0 then
1
else
0
end
overload intersection with intersection_line_line
overload which_side with which_side_point_line
fn
orientation_triangle (t : triangle) : Sgn =
(* 1 = counterclockwise, 0 = collinear, ~1 = clockwise *)
which_side (t.2, t.0 ^ t.1)
overload orientation with orientation_triangle
fn
set_orientation_triangle {s : int | abs s == 1}
(t : triangle, s : int s) : triangle =
(* 1 = counterclockwise, ~1 = clockwise. If the triangle is
collinear, leave it unchanged. If the triangle does need
rearrangement, do so by swapping vertices t.1 and t.2. *)
let
val s0 = orientation t
in
if (s = 0) + (s = s0) then
t
else
@(t.0, t.2, t.1)
end
overload set_orientation with set_orientation_triangle
fn
overlap_triangle_triangle (t1 : triangle, t2 : triangle) : bool =
let
val t1 = set_orientation (t1, 1)
and t2 = set_orientation (t2, 1)
(* The lines that form the sides of the triangles. *)
val s1 = @(t1.0 ^ t1.1, t1.1 ^ t1.2, t1.2 ^ t1.0)
val s2 = @(t2.0 ^ t2.1, t2.1 ^ t2.2, t2.2 ^ t2.0)
fn
sides_intersect (pa : point, pb : point, ln_p : line,
qa : point, qb : point, ln_q : line) : bool =
let
val x = intersection (ln_p, ln_q)
in
if x.e0 <> 0.0 then
let
val px_min = min (pa.e1, pb.e1)
and px_max = max (pa.e1, pb.e1)
and py_min = min (pa.e2, pb.e1)
and py_max = max (pa.e2, pb.e1)
val px_min2 = px_min + px_min
and px_max2 = px_max + px_max
and py_min2 = py_min + py_min
and py_max2 = py_max + py_max
val px_min_eps = abs (px_min) * dbl_epsilon
and px_max_eps = abs (px_max) * dbl_epsilon
val py_min_eps = abs (py_min) * dbl_epsilon
and py_max_eps = abs (py_max) * dbl_epsilon
in
if px_min2 - px_min_eps <= x.e1 + x.e1
&& x.e1 + x.e1 <= px_max2 + px_max_eps
&& py_min2 - py_min_eps <= x.e2 + x.e2
&& x.e2 + x.e2 <= py_max2 + py_max_eps then
let
val qx_min = min (qa.e1, qb.e1)
and qx_max = max (qa.e1, qb.e1)
and qy_min = min (qa.e2, qb.e1)
and qy_max = max (qa.e2, qb.e1)
val qx_min2 = qx_min + qx_min
and qx_max2 = qx_max + qx_max
and qy_min2 = qy_min + qy_min
and qy_max2 = qy_max + qy_max
val qx_min_eps = abs (qx_min) * dbl_epsilon
and qx_max_eps = abs (qx_max) * dbl_epsilon
val qy_min_eps = abs (qy_min) * dbl_epsilon
and qy_max_eps = abs (qy_max) * dbl_epsilon
in
qx_min2 - qx_min_eps <= x.e1 + x.e1
&& x.e1 + x.e1 <= qx_max2 + qx_max_eps
&& qy_min2 - qy_min_eps <= x.e2 + x.e2
&& x.e2 + x.e2 <= qy_max2 + qy_max_eps
end
else
false
end
else if x.e1 = 0.0 && x.e2 = 0.0 then
(* The lines are coincident *)
~(max (qa.e1, qb.e1) < min (pa.e1, pb.e1)
|| max (pa.e1, pb.e1) < min (qa.e1, qb.e1))
&& ~(max (qa.e2, qb.e2) < min (pa.e2, pb.e2)
|| max (pa.e2, pb.e2) < min (qa.e2, qb.e2))
else
(* The lines are parallel. *)
false
end
fn
sides_intersection_tests () : bool =
sides_intersect (t1.0, t1.1, s1.0, t2.0, t2.1, s2.0)
|| sides_intersect (t1.0, t1.1, s1.0, t2.1, t2.2, s2.1)
|| sides_intersect (t1.0, t1.1, s1.0, t2.2, t2.0, s2.2)
|| sides_intersect (t1.1, t1.2, s1.1, t2.0, t2.1, s2.0)
|| sides_intersect (t1.1, t1.2, s1.1, t2.1, t2.2, s2.1)
|| sides_intersect (t1.1, t1.2, s1.1, t2.2, t2.0, s2.2)
|| sides_intersect (t1.2, t1.0, s1.2, t2.0, t2.1, s2.0)
|| sides_intersect (t1.2, t1.0, s1.2, t2.1, t2.2, s2.1)
|| sides_intersect (t1.2, t1.0, s1.2, t2.2, t2.0, s2.2)
fn
points_approx_equal (p : point, q : point) : bool =
let
val @{e1 = px, e2 = py, e0 = _} = p
and @{e1 = qx, e2 = qy, e0 = _} = q
val x_max_eps = max (abs px, abs qx) * dbl_epsilon
and y_max_eps = max (abs py, abs py) * dbl_epsilon
in
abs ((px + px) - (qx + qx)) <= x_max_eps
&& abs ((py + py) - (qy + qy)) <= y_max_eps
end
fn
vertex_vertex_tests () : bool =
points_approx_equal (t1.0, t2.0)
|| points_approx_equal (t1.0, t2.1)
|| points_approx_equal (t1.0, t2.2)
|| points_approx_equal (t1.1, t2.0)
|| points_approx_equal (t1.1, t2.1)
|| points_approx_equal (t1.1, t2.2)
|| points_approx_equal (t1.2, t2.0)
|| points_approx_equal (t1.2, t2.1)
|| points_approx_equal (t1.2, t2.2)
fn
is_inside (a : point, b : @(line, line, line)) : bool =
which_side (a, b.0) = 1
&& which_side (a, b.1) = 1
&& which_side (a, b.2) = 1
fn
vertex_insideness_tests () : bool =
is_inside (t1.0, s2)
|| is_inside (t1.1, s2)
|| is_inside (t1.2, s2)
|| is_inside (t2.0, s1)
|| is_inside (t2.1, s1)
|| is_inside (t2.2, s1)
in
sides_intersection_tests ()
|| vertex_vertex_tests ()
|| vertex_insideness_tests ()
end
overload overlap with overlap_triangle_triangle
fn
println_triangle (t : triangle) : void =
println! ("(", t.0.e1, ",", t.0.e2, ")--(",
t.1.e1, ",", t.1.e2, ")--(",
t.2.e1, ",", t.2.e2, ")--cycle")
fn
test_triangles (t1 : triangle, t2 : triangle) : void =
begin
println_triangle t1;
println_triangle t2;
println! (" overlap: ", overlap (t1, t2))
end
implement
main () =
begin
println! ();
test_triangles (@(Pt (0.0, 0.0),
Pt (5.0, 0.0),
Pt (0.0, 5.0)),
@(Pt (0.0, 0.0),
Pt (5.0, 0.0),
Pt (0.0, 6.0)));
test_triangles (@(Pt (0.0, 0.0),
Pt (0.0, 5.0),
Pt (5.0, 0.0)),
@(Pt (0.0, 0.0),
Pt (0.0, 5.0),
Pt (5.0, 0.0)));
test_triangles (@(Pt (0.0, 0.0),
Pt (5.0, 0.0),
Pt (0.0, 5.0)),
@(Pt (~10.0, 0.0),
Pt ( ~5.0, 0.0),
Pt ( ~1.0, 6.0)));
test_triangles (@(Pt (0.0, 0.0),
Pt (5.0, 0.0),
Pt (2.5, 5.0)),
@(Pt (0.0, 4.0),
Pt (2.5, ~1.0),
Pt (5.0, 4.0)));
test_triangles (@(Pt (0.0, 0.0),
Pt (1.0, 1.0),
Pt (0.0, 2.0)),
@(Pt (2.0, 1.0),
Pt (3.0, 0.0),
Pt (3.0, 2.0)));
test_triangles (@(Pt (0.0, 0.0),
Pt (1.0, 1.0),
Pt (0.0, 2.0)),
@(Pt (2.0, 1.0),
Pt (3.0, ~2.0),
Pt (3.0, 4.0)));
test_triangles (@(Pt (0.0, 0.0),
Pt (1.0, 0.0),
Pt (0.0, 1.0)),
@(Pt (1.0, 0.0),
Pt (2.0, 0.0),
Pt (1.0, 1.0)));
println! ();
println! ("What follows is a test where one triangle is ",
"contained entirely");
println! ("inside the other. Without such a test, our ",
"algorithm would have");
println! ("one of its features undemonstrated.");
println! ();
test_triangles (@(Pt ( 0.0, 0.0),
Pt (10.0, 0.0),
Pt ( 5.0, 10.0)),
@(Pt ( 4.0, 1.0),
Pt ( 5.0, 2.0),
Pt ( 6.0, 1.0)));
println! ();
0
end

View file

@ -3,9 +3,9 @@
* Fully (?) tested with integer coordinates of the 6 corners
* This was/is an exercise with ooRexx
* Removed the fraction arithmetic
* add test for triangles' validity
*-------------------------------------------------------------------*/
Parse Version v
oid='trioo.txt'; 'erase' oid
Call o v
case=0
@ -21,6 +21,8 @@ Call trio_test '0 0 5 0 2.5 5 0 4 2.5 -1 5 4'
Call trio_test '0 0 1 1 0 2 2 1 3 0 3 2'
Call trio_test '0 0 1 1 0 2 2 1 3 -2 3 4'
Call trio_test '0 0 1 0 0 1 1 0 2 0 1 1'
Call trio_test '0 0 0 0 2 2 1 1 2 1 1 2' -- two points are identical
Call trio_test '0 0 0 3 2 2 1 1 2 2 3 3' -- three points on a line
Exit
/* Other test cases */
Call trio_test '0 0 0 4 4 0 0 2 2 2 2 0'
@ -54,6 +56,7 @@ Parse Arg tlist
cc+=1
tlist=space(tlist)
tl1=tlist ; Call trio_t tl1
If result=-1 Then Return
tl2=reversex(tlist) ; Call trio_t tl2
tl3=''
tl=tlist
@ -64,13 +67,19 @@ Do While tl<>''
Call trio_t tl3
tl4=reversex(tl3) ; Call trio_t tl4
tl5=subword(tl4,7) subword(tl4,1,6) ; Call trio_t tl5
tl6=subword(tl5,7) subword(tl5,1,6) ; Call trio_t tl6
tl6=''
tl=tlist
Do While tl<>''
Parse Var tl x y tl
tl6=tl6 y x
End
Call trio_t tl6
Return
trio_t:
Parse Arg tlist
tlist=space(tlist)
Say tlist
Say '>' tlist
case+=1
Parse Arg ax ay bx by cx cy dx dy ex ey fx fy
/*---------------------------------------------------------------------
@ -78,6 +87,14 @@ Parse Arg ax ay bx by cx cy dx dy ex ey fx fy
*--------------------------------------------------------------------*/
a=.point~new(ax,ay); b=.point~new(bx,by); c=.point~new(cx,cy)
d=.point~new(dx,dy); e=.point~new(ex,ey); f=.point~new(fx,fy)
If area(a,b,c)=0 Then Do
Say a b c 'is not a valid triangle'
Return -1
End
If area(d,e,f)=0 Then Do
Say d e f 'is not a valid triangle'
Return -1
End
abc=.triangle~new(a,b,c)
def=.triangle~new(d,e,f)
Call o 'Triangle: ABC:' abc ,1
@ -282,6 +299,10 @@ Return
::method init
expose point edge
use arg p1,p2,p3
If area(p1,p2,p3)=0 Then Do
Say p1 p2 p3 'is not a valid triangle!'
Return .nil
End
point=.array~new
point[1]=p1
point[2]=p2
@ -545,3 +566,26 @@ Return
res=res word(list,i)
End
Return res
::ROUTINE distpp PUBLIC --Compute the distance between the points A and B
/***********************************************************************
* Compute the distance between the points A and B
***********************************************************************/
Use Arg A,B
ax=A~x; ay=A~y; bx=B~x; by=B~y
res=rxCalcsqrt((bx-ax)**2+(by-ay)**2)
Return res
::ROUTINE area PUBLIC --Compute the area of the triangla A B C
/***********************************************************************
* Compute the area of the triangla A B C
***********************************************************************/
Use Arg A,B,C
ax=A~x; ay=A~y; bx=B~x; by=B~y; cx=C~x; cy=C~y
ab=distpp(A,B)
bc=distpp(B,C)
ca=distpp(C,A)
s=(ab+bc+ca)/2
area=rxCalcsqrt(s*(s-ab)*(s-bc)*(s-ca))
Return area
::REQUIRES rxMath Library

View file

@ -0,0 +1,31 @@
#include <exception>
#include <iostream>
#include <string>
#include <vector>
char sentence_type(const std::string& sentence) {
if ( sentence.empty() ) {
throw std::invalid_argument("Cannot classify an empty sentence");
}
char result;
const char last_character = sentence.back();
switch (last_character) {
case '?': result = 'Q'; break;
case '.': result = 'S'; break;
case '!': result = 'E'; break;
default: result = 'N'; break;
};
return result;
}
int main() {
const std::vector<std::string> sentences = { "hi there, how are you today?",
"I'd like to present to you the washing machine 9001.",
"You have been nominated to win one of these!",
"Just make sure you don't break it" };
for ( const std::string& sentence : sentences ) {
std::cout << sentence << " -> " << sentence_type(sentence) << std::endl;
}
}

View file

@ -0,0 +1,30 @@
import java.util.List;
public final class DetermineSentenceType {
public static void main(String[] aArgs) {
List<String> sentences = List.of( "hi there, how are you today?",
"I'd like to present to you the washing machine 9001.",
"You have been nominated to win one of these!",
"Just make sure you don't break it" );
for ( String sentence : sentences ) {
System.out.println(sentence + " -> " + sentenceType(sentence));
}
}
private static char sentenceType(String aSentence) {
if ( aSentence.isEmpty() ) {
throw new IllegalArgumentException("Cannot classify an empty sentence");
}
final char lastCharacter = aSentence.charAt(aSentence.length() - 1);
return switch (lastCharacter) {
case '?' -> 'Q';
case '.' -> 'S';
case '!' -> 'E';
default -> 'N';
};
}
}

View file

@ -11,9 +11,9 @@ func winning(sides1, n1, sides2, n2) {
var (p1, p2) = (combos(sides1, n1), combos(sides2, n2))
var (win,loss,tie) = (0,0,0)
p1.each_kv { |i, x|
win += x*p2.ft(0,i-1).sum
tie += x*p2.ft(i, i).sum
loss += x*p2.ft(i+1).sum
win += x*p2.first(i).sum
tie += x*p2.slice(i).first(1).sum
loss += x*p2.slice(i+1).sum
}
[win, tie, loss] »/» p1.sum*p2.sum
}

View file

@ -0,0 +1,18 @@
use itertools::Itertools;
fn main() {
for p in (1..6).permutations(5) {
let baker: i32 = p[0];
let cooper: i32 = p[1];
let fletcher: i32 = p[2];
let miller: i32 = p[3];
let smith: i32 = p[4];
if baker != 5 && cooper != 1 && fletcher != 1 && fletcher != 5 && cooper < miller &&
(smith - fletcher).abs() > 1 && (cooper - fletcher).abs() > 1 {
print!("Baker on {baker}, Cooper on {cooper}, ");
println!("Fletcher on {fletcher}, Miller on {miller}, Smith on {smith}.");
break;
}
}
}

View file

@ -9,7 +9,7 @@ func dinesman(problem) {
var re_keywords = Regex(words.join('|'))
 
# Build an array of lambda's
var predicates = lines.ft(1, lines.end-1).map{ |line|
var predicates = lines.first(-1).last(-1).map{ |line|
var keywords = line.scan(re_keywords)
var (name1, name2) = line.scan(re_names)...
 

View file

@ -0,0 +1,109 @@
#include <cmath>
#include <cstdint>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <numbers>
#include <regex>
#include <sstream>
#include <string>
#include <vector>
constexpr double RADIUS = 6'371 / 1.852; // Mean radius of the Earth in nautical miles
constexpr double RADIAN_TO_DEGREE = 180.0 / std::numbers::pi;
class airport {
public:
airport(std::string aName, std::string aCountry, std::string aIcao, double aLatitude, double aLongitude)
: name(aName), country(aCountry), icao(aIcao), latitude(aLatitude), longitude(aLongitude) {}
std::string name;
std::string country;
std::string icao;
double latitude;
double longitude;
};
// Convert the given string to a double, which represents an angle,
// and then convert the angle from degrees to radians
double to_double_radians(const std::string& text) {
std::istringstream stream(text);
double decimal = 0.0;
stream >> decimal;
return decimal / RADIAN_TO_DEGREE;
}
std::string do_replace(const std::string& text, const std::string& original, const std::string& replacement) {
return std::regex_replace(text, std::regex(original), replacement);
}
std::vector<std::string> split(const std::string& line, const char& delimiter) {
std::stringstream stream(line);
std::string item;
std::vector<std::string> items;
while ( std::getline(stream, item, delimiter) ) {
items.push_back(std::move(item));
}
return items;
}
void read_file(const std::string& file_name, std::vector<airport>& airports) {
std::ifstream airports_file(file_name);
std::string line;
while ( std::getline(airports_file, line) ) {
std::vector<std::string> sections = split(line, ',');
airport air_port(do_replace(sections[1], "\"", ""), // Remove the double quotes from the string
do_replace(sections[3], "\"", ""),
do_replace(sections[5], "\"", ""),
to_double_radians(sections[6]),
to_double_radians(sections[7]));
airports.push_back(std::move(air_port));
}
airports_file.close();
}
// The given angles are in radians, and the result is in nautical miles.
double distance(double phi1, double lambda1, double phi2, double lambda2) {
double a = pow(sin((phi2 - phi1) * 0.5), 2) + cos(phi1) * cos(phi2) * pow(sin((lambda2 - lambda1) * 0.5), 2);
double c = 2 * atan2(sqrt(a), sqrt(1 - a));
return RADIUS * c;
}
// The given angles are in radians, and the result is in degrees in the range [0, 360).
double bearing(double phi1, double lambda1, double phi2, double lambda2) {
double delta = lambda2 - lambda1;
double result = atan2(sin(delta) * cos(phi2), cos(phi1) * sin(phi2) - sin(phi1) * cos(phi2) * cos(delta));
return std::fmod(result * RADIAN_TO_DEGREE + 360.0, 360.0);
}
int main() {
std::vector<airport> airports;
read_file("airports.dat", airports);
const double plane_latitude = 51.514669 / RADIAN_TO_DEGREE;
const double plane_longitude = 2.198581 / RADIAN_TO_DEGREE;
std::vector<std::pair<double, uint64_t>> distances;
for ( uint64_t i = 0; i < airports.size(); ++i ) {
double dist = distance(plane_latitude, plane_longitude, airports[i].latitude, airports[i].longitude);
distances.push_back(std::make_pair(dist, i));
}
std::sort(distances.begin(), distances.end(),
[](auto& left, auto& right) { return left.first < right.first; });
std::cout << "Distance" << std::setw(9) << "Bearing" << std::setw(11) << "ICAO"
<< std::setw(20) << "Country" << std::setw(40) << "Airport" << std::endl;
std::cout << std::string(88, '-') << std::endl;
for ( uint32_t i = 0; i < 20; ++i ) {
auto[distance, index] = distances[i];
airport air_port = airports[index];
double bear = bearing(plane_latitude, plane_longitude, air_port.latitude, air_port.longitude);
std::cout << std::setw(8) << std::fixed << std::setprecision(1) << distance
<< std::setw(9) << std::setprecision(0) << std::round(bear)
<< std::setw(11) << air_port.icao << std::setw(20) << air_port.country
<< std::setw(40) << air_port.name << std::endl;
}
}

View file

@ -0,0 +1,61 @@
import java.util.Arrays;
public final class DuffianNumbers {
public static void main(String[] aArgs) {
int[] duffians = createDuffians(11_000);
System.out.println("The first 50 Duffinian numbers:");
int count = 0;
int n = 1;
while ( count < 50 ) {
if ( duffians[n] > 0 ) {
System.out.print(String.format("%4d%s", n, ( ++count % 25 == 0 ? "\n" : "" )));
}
n += 1;
}
System.out.println();
System.out.println("The first 16 Duffinian triplets:");
count = 0;
n = 3;
while( count < 16 ) {
if ( duffians[n - 2] > 0 && duffians[n - 1] > 0 && duffians[n] > 0 ) {
System.out.print(String.format("%22s%s",
"(" + ( n - 2 ) + ", " + ( n - 1 ) + ", " + n + ")", ( ++count % 4 == 0 ? "\n" : "" )));
}
n += 1;
}
System.out.println();
}
private static int[] createDuffians(int aLimit) {
// Create a list where list[i] is the divisor sum of i.
int[] result = new int[aLimit];
Arrays.fill(result, 1);
for ( int i = 2; i < aLimit; i++ ) {
for ( int j = i; j < aLimit; j += i ) {
result[j] += i;
}
}
// Set the divisor sum of non-Duffinian numbers to 0.
result[1] = 0; // 1 is not a Duffinian number.
for ( int n = 2; n < aLimit; n++ ) {
int resultN = result[n];
if ( resultN == n + 1 || gcd(n, resultN) != 1 ) {
// n is prime, or it is not relatively prime to its divisor sum.
result[n] = 0;
}
}
return result;
}
private static int gcd(int aOne, int aTwo) {
if ( aTwo == 0 ) {
return aOne;
}
return gcd(aTwo, aOne % aTwo);
}
}

View file

@ -0,0 +1,59 @@
#include <algorithm>
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <vector>
void print_vector(const std::vector<int32_t>& list) {
std::cout << "[";
for ( uint64_t i = 0; i < list.size() - 1; ++i ) {
std::cout << list[i] << ", ";
}
std::cout << list.back() << "]" << std::endl;
}
bool contains(const std::vector<int32_t>& list, const int32_t& n) {
return std::find(list.begin(), list.end(), n) != list.end();
}
bool same_sequence(const std::vector<int32_t>& seq1, const std::vector<int32_t>& seq2, const int32_t& n) {
for ( uint64_t i = n ; i < seq1.size() ; ++i ) {
if ( seq1[i] != seq2[i] ) {
return false;
}
}
return true;
}
std::vector<int32_t> ekg(const int32_t& second_term, const uint64_t& term_count) {
std::vector<int32_t> result = { 1, second_term };
int32_t candidate = 2;
while ( result.size() < term_count ) {
if ( ! contains(result, candidate) && std::gcd(result.back(), candidate) > 1 ) {
result.push_back(candidate);
candidate = 2;
} else {
candidate++;
}
}
return result;
}
int main() {
std::cout << "The first 10 members of EKG[2], EKG[5], EKG[7], EKG[9] and EKG[10] are:" << std::endl;
for ( int32_t i : { 2, 5, 7, 9, 10 } ) {
std::cout << "EKG[" << std::setw(2) << i << "] = "; print_vector(ekg(i, 10));
}
std::cout << std::endl;
std::vector<int32_t> ekg5 = ekg(5, 100);
std::vector<int32_t> ekg7 = ekg(7, 100);
int32_t i = 1;
while ( ! ( ekg5[i] == ekg7[i] && same_sequence(ekg5, ekg7, i) ) ) {
i++;
}
// Converting from 0-based to 1-based index
std::cout << "EKG[5] and EKG[7] converge at index " << i + 1
<< " with a common value of " << ekg5[i] << "." << std::endl;
}

View file

@ -0,0 +1,22 @@
in Org:RosettaCode
type Fruits
enum
int APPLE, BANANA, CHERRY
end
type ExplicitFruits
enum
int APPLE = 10
int BANANA = 20
int CHERRY = 1
end
type Main
for each generic enumeration in generic[Fruits, ExplicitFruits]
writeLine("[" + Generic.name(enumeration) + "]")
writeLine("getting an object with value = 1:")
writeLine(:enumeration.byValue(1))
writeLine("iterating over the items:")
for each var fruit in :enumeration
writeLine(fruit)
end
writeLine()
end

View file

@ -2,16 +2,16 @@ func hailstone(n) {
gather {
while (n > 1) {
take(n)
n = (n.is_even ? n/2 : (3*n + 1))
n = (n.is_even ? (n/2) : (take(3*n + 1)/2))
}
take(1)
}
}
 
if (__FILE__ == __MAIN__) { # true when not imported
var seq = hailstone(27)
say "hailstone(27) - #{seq.len} elements: #{seq.ft(0, 3)} [...] #{seq.ft(-4)}"
 
say "hailstone(27) - #{seq.len} elements: #{seq.first(4)} [...] #{seq.last(4)}"
var n = 0
var max = 0
100_000.times { |i|
@ -21,6 +21,6 @@ if (__FILE__ == __MAIN__) { # true when not imported
n = i
}
}
 
say "Longest sequence is for #{n}: #{max}"
}

View file

@ -0,0 +1,22 @@
BEGIN # read FASTA format data from standard input and write the results to #
# standard output - only the ">" line start is handled #
BOOL at eof := FALSE;
on logical file end( stand in, ( REF FILE f )BOOL: at eof := TRUE );
WHILE STRING line;
read( ( line, newline ) );
NOT at eof
DO
IF line /= "" THEN # non-empty line #
INT start := LWB line;
BOOL is heading = line[ start ] = ">"; # check for heading line #
IF is heading THEN
print( ( newline ) );
start +:= 1
FI;
print( ( line[ start : ] ) );
IF is heading THEN print( ( ": " ) ) FI
FI
OD
END

View file

@ -0,0 +1,97 @@
100H: /* DISPLAY THE CONTENTS OF A FASTA FORMT FILE */
DECLARE FALSE LITERALLY '0', TRUE LITERALLY '0FFH';
DECLARE NL$CHAR LITERALLY '0AH'; /* NEWLINE: CHAR 10 */
DECLARE CR$CHAR LITERALLY '0DH'; /* CARRIAGE RETURN, CHAR 13 */
DECLARE EOF$CHAR LITERALLY '26'; /* EOF: CTRL-Z */
/* CP/M BDOS SYSTEM CALL, RETURNS A VALUE */
BDOS: PROCEDURE( FN, ARG )BYTE; DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;
/* CP/M BDOS SYSTEM CALL, NO RETURN VALUE */
BDOS$P: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;
EXIT: PROCEDURE; CALL BDOS$P( 0, 0 ); END; /* CP/M SYSTEM RESET */
PR$CHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS$P( 2, C ); END;
PR$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS$P( 9, S ); END;
PR$NL: PROCEDURE; CALL PR$STRING( .( 0DH, NL$CHAR, '$' ) ); END;
FL$EXISTS: PROCEDURE( FCB )BYTE; /* RETURNS TRUE IF THE FILE NAMED IN THE */
DECLARE FCB ADDRESS; /* FCB EXISTS */
RETURN ( BDOS( 17, FCB ) < 4 );
END FL$EXISTS ;
FL$OPEN: PROCEDURE( FCB )BYTE; /* OPEN THE FILE WITH THE SPECIFIED FCB */
DECLARE FCB ADDRESS;
RETURN ( BDOS( 15, FCB ) < 4 );
END FL$OPEN;
FL$READ: PROCEDURE( FCB )BYTE; /* READ THE NEXT RECORD FROM FCB */
DECLARE FCB ADDRESS;
RETURN ( BDOS( 20, FCB ) = 0 );
END FL$READ;
FL$CLOSE: PROCEDURE( FCB )BYTE; /* CLOSE THE FILE WITH THE SPECIFIED FCB */
DECLARE FCB ADDRESS;
RETURN ( BDOS( 16, FCB ) < 4 );
END FL$CLOSE;
/* I/O USES FILE CONTROL BLOCKS CONTAINING THE FILE-NAME, POSITION, ETC. */
/* WHEN THE PROGRAM IS RUN, THE CCP WILL FIRST PARSE THE COMMAND LINE AND */
/* PUT THE FIRST PARAMETER IN FCB1, THE SECOND PARAMETER IN FCB2 */
/* BUT FCB2 OVERLAYS THE END OF FCB1 AND THE DMA BUFFER OVERLAYS THE END */
/* OF FCB2 */
DECLARE FCB$SIZE LITERALLY '36'; /* SIZE OF A FCB */
DECLARE FCB1 LITERALLY '5CH'; /* ADDRESS OF FIRST FCB */
DECLARE FCB2 LITERALLY '6CH'; /* ADDRESS OF SECOND FCB */
DECLARE DMA$BUFFER LITERALLY '80H'; /* DEFAULT DMA BUFFER ADDRESS */
DECLARE DMA$SIZE LITERALLY '128'; /* SIZE OF THE DMA BUFFER */
DECLARE F$PTR ADDRESS, F$CHAR BASED F$PTR BYTE;
/* CLEAR THE PARTS OF FCB1 OVERLAYED BY FCB2 */
DO F$PTR = FCB1 + 12 TO FCB1 + ( FCB$SIZE - 1 );
F$CHAR = 0;
END;
/* SHOW THE FASTA DATA, IF THE FILE EXISTS */
IF NOT FL$EXISTS( FCB1 ) THEN DO; /* THE FILE DOES NOT EXIST */
CALL PR$STRING( .'FILE NOT FOUND$' );CALL PR$NL;
END;
ELSE IF NOT FL$OPEN( FCB1 ) THEN DO; /* UNABLE TO OPEN THE FILE */
CALL PR$STRING( .'UNABLE TO OPEN THE FILE$' );CALL PR$NL;
END;
ELSE DO; /* FILE EXISTS AND OPENED OK - ATTEMPT TO SHOW THE DATA */
DECLARE ( BOL, GOT$RCD, IS$HEADING ) BYTE, DMA$END ADDRESS;
DMA$END = DMA$BUFFER + ( DMA$SIZE - 1 );
GOT$RCD = FL$READ( FCB1 ); /* GET THE FIRST RECORD */
F$PTR = DMA$BUFFER;
BOL = TRUE;
IS$HEADING = FALSE;
DO WHILE GOT$RCD;
IF F$PTR > DMA$END THEN DO; /* END OF BUFFER */
GOT$RCD = FL$READ( FCB1 ); /* GET THE NEXT RECORDD */
F$PTR = DMA$BUFFER;
END;
ELSE IF F$CHAR = NL$CHAR THEN DO; /* END OF LINE */
IF IS$HEADING THEN DO;
CALL PR$STRING( .': $' );
IS$HEADING = FALSE;
END;
BOL = TRUE;
END;
ELSE IF F$CHAR = CR$CHAR THEN DO; END; /* IGNORE CARRIAGE RETURN */
ELSE IF F$CHAR = EOF$CHAR THEN GOT$RCD = FALSE; /* END OF FILE */
ELSE DO; /* HAVE ANOTHER CHARACTER */
IF NOT BOL THEN CALL PR$CHAR( F$CHAR ); /* NOT FIRST CHARACTER */
ELSE DO; /* FIRST CHARACTER - CHECK FOR A HEADING LINE */
BOL = FALSE;
IF IS$HEADING := F$CHAR = '>' THEN CALL PR$NL;
ELSE CALL PR$CHAR( F$CHAR );
END;
END;
F$PTR = F$PTR + 1;
END;
/* CLOSE THE FILE */
IF NOT FL$CLOSE( FCB1 ) THEN DO;
CALL PR$STRING( .'UNABLE TO CLOSE THE FILE$' ); CALL PR$NL;
END;
END;
CALL EXIT;
EOF

View file

@ -10,27 +10,24 @@ BEGIN # find some factorial primes - primes that are f - 1 or f + 1 #
FOR i FROM 3 BY 2 TO SHORTEN ENTIER long sqrt(p) WHILE prime := p MOD i /= 0 DO SKIP OD;
prime
FI;
# end of code based on the primality by trial divisio task #
# end of code based on the primality by trial division task #
PROC show factorial prime = ( INT fp number, INT n, CHAR fp op, LONG INT fp )VOID:
print( ( whole( fp number, -2 ), ":", whole( n, -4 )
, "! ", fp op, " 1 = ", whole( fp, 0 )
, newline
)
);
LONG INT f := 1;
INT fp count := 0;
FOR n WHILE fp count < 10 DO
f *:= n;
IF LONG INT fp = f - 1;
is prime( fp )
THEN
show factorial prime( fp count +:= 1, n, "-", fp )
FI;
IF LONG INT fp = f + 1;
is prime( fp )
THEN
show factorial prime( fp count +:= 1, n, "+", fp )
FI
CHAR fp op := "-";
FOR offset FROM -1 BY 2 TO 1 DO
IF LONG INT fp = f + offset;
is prime( fp )
THEN
print( ( whole( fp count +:= 1, -2 ), ":", whole( n, -4 )
, "! ", fp op, " 1 = ", whole( fp, 0 )
, newline
)
)
FI;
fp op := "+"
OD
OD
END

View file

@ -0,0 +1,39 @@
do -- find some factorial primes - primes that are f - 1 or f + 1
-- for some factorial f
function isPrime( p )
if p <= 1 or p % 2 == 0 then
return p == 2
else
local prime = true
local i = 3
local rootP = math.floor( math.sqrt( p ) )
while i <= rootP and prime do
prime = p % i ~= 0
i = i + 1
end
return prime
end
end
local f = 1
local fpCount = 0
local n = 0
local fpOp = ""
while fpCount < 10 do
n = n + 1
f = f * n
fpOp = "-"
for fp = f - 1, f + 1, 2 do
if isPrime( fp ) then
fpCount = fpCount + 1
io.write( string.format( "%2d", fpCount ), ":"
, string.format( "%4d", n ), "! "
, fpOp, " 1 = ", fp, "\n"
)
end
fpOp = "+"
end
end
end

View file

@ -0,0 +1,14 @@
var factorial_primes = Enumerator({|f|
for k in (1..Inf) {
if (k!-1 -> is_prime) { f([k, -1]) }
if (k!+1 -> is_prime) { f([k, +1]) }
}
})
func abr(v) {
v.len <= 40 ? v : (v.to_s.first(20) + '..' + v.to_s.last(20) + " (#{v.len} digits)")
}
factorial_primes.first(30).each_2d {|k,i|
printf("%3d! %s %d = %s\n", k, (i.sgn < 0 ? '-' : '+'), i.abs, abr(k! + i))
}

View file

@ -2,7 +2,7 @@ func fib(n, xs=[1], k=20) {
loop {
var len = xs.len
len >= k && break
xs << xs.ft(max(0, len - n)).sum
xs << xs.slice(max(0, len - n)).sum
}
return xs
}

View file

@ -0,0 +1,22 @@
package fib
import "core:fmt"
main :: proc() {
fmt.println("\nFibonacci Seq - starting n and n+1 from 0 and 1:")
fmt.println("------------------------------------------------")
for j: u128 = 0; j <= 20; j += 1 {
fmt.println("n:", j, "\tFib:", fibi(j))
}
}
fibi :: proc(n: u128) -> u128 {
if n < 2 {
return n
}
a, b: u128 = 0, 1
for _ in 2..=n {
a += b
a, b = b, a
}
return b
}

View file

@ -0,0 +1 @@
writeLine(range(1, 11).filter(<int i|i % 2 == 0))

View file

@ -1 +1 @@
{|i|say "#{<Fizz>[i%3]}#{<Buzz>[i%5]}"||i}*100
{>"#{<Fizz>[.%3]}#{<Buzz>[.%5]}"||_}<<1..100

View file

@ -0,0 +1,28 @@
import Foundation
let formats: [String] = [
"%d",
"%d",
"fizz",
"%d",
"buzz",
"fizz",
"%d",
"%d",
"fizz",
"buzz",
"%d",
"fizz",
"%d",
"%d",
"fizzbuzz",
]
var count = 0
var index = 0
while count < 100 {
count += 1
print(String(format: formats[index], count))
index += 1
index %= 15
}

View file

@ -1,32 +1,36 @@
# FRACTRAN interpreter implemented as an iterable struct
using .Iterators: filter, map, take
import Base: iterate, show
struct Fractran
rs::Vector{Rational{BigInt}}
i₀::BigInt
limit::Int
end
iterate(f::Fractran, i = f.i₀) =
Base.iterate(f::Fractran, i = f.i₀) =
for r in f.rs
if iszero(i % r.den) # faster than isinteger(i*r)
if iszero(i % r.den)
i = i ÷ r.den * r.num
return (i, i)
return i, i
end
end
run(f::Fractran) = map(trailing_zeros, filter(ispow2, f))
interpret(f::Fractran) =
take(
map(trailing_zeros,
filter(ispow2, f))
f.limit)
show(io::IO, f::Fractran) = join(io, take(run(f), 30), ' ')
Base.show(io::IO, f::Fractran) =
join(io, interpret(f), ' ')
macro code_str(s)
eval(Meta.parse("[" * replace(s, "/" => "//") * "]"))
[eval(Meta.parse(replace(t, "/" => "//"))) for t ∈ split(s)]
end
# Example FRACTRAN program generating primes
primes = Fractran(code"17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23,
77/19, 1/17, 11/13, 13/11, 15/14, 15/2, 55/1", 2)
primes = Fractran(code"17/91 78/85 19/51 23/38 29/33 77/29 95/23
77/19 1/17 11/13 13/11 15/14 15/2 55/1", 2, 30)
# Output
println("First 25 iterations of FRACTRAN program 'primes':\n2 ",

View file

@ -1,19 +1,19 @@
func maxsubseq(*a) {
var (start, end, sum, maxsum) = (-1, -1, 0, 0);
var (start, end, sum, maxsum) = (-1, -1, 0, 0)
a.each_kv { |i, x|
sum += x;
sum += x
if (maxsum < sum) {
maxsum = sum;
end = i;
maxsum = sum
end = i
}
elsif (sum < 0) {
sum = 0;
start = i;
sum = 0
start = i
}
};
a.ft(start+1, end);
}
a.slice(start+1).first(end-start)
}
say maxsubseq(-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1);
say maxsubseq(-2, -2, -1, 3, 5, 6, -1, 4, -4, 2, -1);
say maxsubseq(-2, -2, -1, -3, -5, -6, -1, -4, -4, -2, -1);
 
say maxsubseq(-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1)
say maxsubseq(-2, -2, -1, 3, 5, 6, -1, 4, -4, 2, -1)
say maxsubseq(-2, -2, -1, -3, -5, -6, -1, -4, -4, -2, -1)

View file

@ -0,0 +1,34 @@
precision 5
print "the first twenty harmonic numbers are:"
for n = 1 to 20
let h = h + 1 / n
print n, tab, h
next n
print newline, "the nth index of the first harmonic number that exceeds the nth integer:"
let h = 1
let n = 2
for i = 2 to 10
do
if h < i then
let h = h + 1 / n
let n = n + 1
endif
wait
loop h < i
print tab, n - 1,
next i

View file

@ -0,0 +1,30 @@
# Task 1
proc harmonic {n} {
if {$n < 1 || $n != [expr {floor($n)}]} {
error "Argument to harmonic function is not a natural number"
}
set Hn 1
for {set i 2} {$i <= $n} {incr i} {
set Hn [expr {$Hn + (1.0/$i)}]
}
return $Hn
}
# Task 2
for {set x 1} {$x <= 20} {incr x} {
set Hx [harmonic $x]
puts "$x: $Hx"
}
# Task 3 /stretch
set x 0
set lastInt 1
while {$lastInt <= 10} {
incr x
set Hx [harmonic $x]
if {$Hx > $lastInt} {
puts -nonewline "The first harmonic number above $lastInt"
puts " is $Hx at position $x"
incr lastInt
}
}

View file

@ -0,0 +1,4 @@
List keys = var["hal", 666, int[1,2,3]]
List vals = var["ibm", "devil", 123]
Map hash = keys.zip(vals)
writeLine(hash)

View file

@ -2,7 +2,7 @@ var Q = [0, 1, 1]
100_000.times {
Q << (Q[-Q[-1]] + Q[-Q[-2]])
}
 
say "First 10 terms: #{Q.ft(1, 10)}"
say "First 10 terms: #{Q.slice(1).first(10)}"
say "Term 1000: #{Q[1000]}"
say "Terms less than preceding in first 100k: #{2..100000->count{|i|Q[i]<Q[i-1]}}"

View file

@ -0,0 +1,18 @@
100 REM Horizontal sundial calculations
110 INPUT PROMPT "Enter latitude => ": Lat
120 INPUT PROMPT "Enter longitude => ": Lng
130 INPUT PROMPT "Enter legal meridian => ": Ref
140 PRINT
150 OPTION ANGLE DEGREES
160 LET Slat = SIN(Lat)
170 PRINT " sine of latitude: "; Slat
180 PRINT " diff longitude: "; Lng - Ref
190 PRINT
200 PRINT "Hour, sun hour angle, dial hour line angle from 6am to 6pm"
210 FOR Hour = -6 TO 6
220 LET HourAngle = 15 * Hour
230 LET HourAngle = HourAngle - (Lng - Ref) ! correct for longitude difference
240 LET HourLineAngle = ATN(Slat * TAN(HourAngle))
250 PRINT USING "HR=###; HRA=####.###; HLA=####.###": Hour, HourAngle, HourLineAngle
260 NEXT Hour
270 END

View file

@ -1,6 +1,7 @@
func horner(coeff, x) {
coeff.len > 0
&& (coeff[0] + x*horner(coeff.ft(1), x));
(coeff.len > 0) \
? (coeff[0] + x*horner(coeff.last(-1), x))
: 0
}
say horner([-19, 7, -4, 6], 3); # => 128
say horner([-19, 7, -4, 6], 3) # => 128

View file

@ -0,0 +1,16 @@
in Org:RosettaCode
type Animal
model do end
type Dog extends Animal
model do end
type Cat extends Animal
model do end
type Lab extends Dog
model do end
type Collie extends Dog
model do end
type Main
var fuffy = Collie()
for each generic kind in generic[Animal, Dog, Cat, Lab, Collie]
writeLine("Fuffy " + when(Generic.check(kind, fuffy), "is", "is not") + " a " + Generic.name(kind))
end

View file

@ -0,0 +1,113 @@
-- Juila Set
-- SQL Server 2017 and above
SET NOCOUNT ON
GO
-- Plot area 800 X 600
DECLARE @width INT = 800
DECLARE @height INT = 600
DECLARE @r_min DECIMAL (10, 8) = -1.5;
DECLARE @r_max DECIMAL (10, 8) = 1.5;
DECLARE @i_min DECIMAL (10, 8) = -1;
DECLARE @i_max DECIMAL (10, 8) = 1;
DECLARE @zoom INT = 1,
@moveX INT = 0,
@moveY INT = 0;
DECLARE @iter INT = 255; -- Iteration
DROP TABLE IF EXISTS dbo.Numbers
DROP TABLE IF EXISTS dbo.julia_set;
CREATE TABLE dbo.Numbers (n INT);
-- Generate a number table of 1000 rows
;WITH N1(n) AS
(
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
), -- 10
N2(n) AS (SELECT 1 FROM N1 CROSS JOIN N1 AS b), -- 10*10
N3(n) AS (SELECT 1 FROM N1 CROSS JOIN N2) -- 10*100
INSERT INTO dbo.Numbers (n)
SELECT n = ROW_NUMBER() OVER (ORDER BY n)
FROM N3 ORDER BY n;
/*
-- If the version is SQL Server 2022 and above
INSERT INTO dbo.Numbers (n)
SELECT value FROM GENERATE_SERIES(0, 1000);
*/
CREATE TABLE dbo.julia_set
(
a INT,
b INT,
c_re DECIMAL (10, 8),
c_im DECIMAL (10, 8),
z_re DECIMAL (10, 8) DEFAULT 0,
z_im DECIMAL (10, 8) DEFAULT 0,
znew_re DECIMAL (10, 8) DEFAULT 0,
znew_im DECIMAL (10, 8) DEFAULT 0,
steps INT DEFAULT 0,
active BIT DEFAULT 1,
)
-- Store all the z_re, z_im with constant c_re, c_im corresponding to each point in the plot area
-- Generate 480,000 rows (800 X 600)
INSERT INTO dbo.julia_set (a, b, c_re, c_im, z_re, z_im, steps)
SELECT a.n as a, b.n as b
,-0.7 AS c_re
,0.27015 AS c_im
,@r_max * (a.n - @width / 2) / (0.5 * @zoom * @width) + @moveX AS z_re
,@i_max * (b.n - @height / 2) / (0.5 * @zoom * @height) + @moveY AS z_im
,@iter as steps
FROM
(
SELECT n - 1 as n FROM dbo.Numbers WHERE n <= @width
) as a
CROSS JOIN
(
SELECT n - 1 as n FROM dbo.Numbers WHERE n <= @height
) as b;
-- Iteration
WHILE (@iter > 1)
BEGIN
UPDATE dbo.julia_set
SET
znew_re = POWER(z_re,2)-POWER(z_im,2)+c_re,
znew_im = 2*z_re*z_im+c_im,
steps = steps-1
WHERE active=1;
UPDATE dbo.julia_set
SET
z_re=znew_re,
z_im=znew_im,
active= CASE
WHEN POWER(znew_re,2)+POWER(znew_im,2)>4 THEN 0
ELSE 1
END
WHERE active=1;
SET @iter = @iter - 1;
END
-- Generating PPM File
-- Save the below query results to a file with extension .ppm
-- NOTE : All the unwanted info like 'rows affected', 'completed time' etc. needs to be
-- removed from the file. Most of the image editing softwares and online viewers can display the .ppm file
SELECT 'P3' UNION ALL
SELECT CAST(@width AS VARCHAR(5)) + ' ' + CAST(@height AS VARCHAR(5)) UNION ALL
SELECT '255' UNION ALL
SELECT
STRING_AGG(CAST(CASE WHEN active = 1 THEN 0 ELSE 55 + steps % 200 END AS VARCHAR(MAX)) + ' ' -- R
+ CAST(CASE WHEN active = 1 THEN 0 ELSE 55+POWER(steps,3) % 200 END AS VARCHAR(MAX)) + ' ' -- G
+ CAST(CASE WHEN active = 1 THEN 0 ELSE 55+ POWER(steps,2) % 200 END AS VARCHAR(MAX)) -- B
, ' ') WITHIN GROUP (ORDER BY a, b)
FROM dbo.julia_set
GROUP BY a, b

View file

@ -0,0 +1,14 @@
100 REM Largest proper divisor of n
110 PRINT "The largest proper divisor of n is:"
120 PRINT
130 PRINT USING " ## ##": 1, 1;
140 FOR I = 3 TO 100
150 FOR J = I - 1 TO 1 STEP -1
160 IF MOD(I, J) = 0 THEN
170 PRINT USING "###": J;
180 EXIT FOR
290 END IF
200 NEXT J
210 IF MOD(I, 10) = 0 THEN PRINT
220 NEXT I
230 END

View file

@ -0,0 +1,25 @@
print "Largest proper divisor of n is:"
print tab, "1", tab, "1",
for i = 3 to 100
for j = i - 1 to 1 step -1
if i mod j = 0 then
print tab, j,
break j
endif
wait
next j
if i mod 10 = 0 then
print
endif
next i

View file

@ -0,0 +1,24 @@
module lastfriday {
string year
integer y%
input "Year (e.g. 2023):", y%
year=str$(y%,"")
date a="1/1/"+year
date a1="31/12/"+year
double i, b=a, c=a1
for i=b to b+6
if val(date$(i, 1033, "d"))=6 then exit for
next
document result$="Last Friday per month for year " + year + {:
}
for i=i+7 to c step 7
if val(date$(i, 1033, "M")) <>val(date$(i+7, 1033, "M")) then
result$=date$(i, 1033, "M"+chr$(9)+"dd") + {
}
end if
next
report result$
clipboard result$
}
lastfriday

View file

@ -3,8 +3,8 @@ func align(s, t) {
t.chars!.prepend!('^')
var A = []
{|i| A[i][0]{@|<d s t>} = (i, s.ft(1, i).join, '~' * i) } << ^s
{|i| A[0][i]{@|<d s t>} = (i, '-' * i, t.ft(1, i).join) } << ^t
{|i| A[i][0]{@|<d s t>} = (i, s.slice(1).first(i).join, '~' * i) } << ^s
{|i| A[0][i]{@|<d s t>} = (i, '-' * i, t.slice(1).first(i).join) } << ^t
for i (1 .. s.end) {
for j (1 .. t.end) {

View file

@ -3,8 +3,8 @@ func lev(s, t) is cached {
s || return t.len
t || return s.len
 
var s1 = s.ft(1)
var t1 = t.ft(1)
var s1 = s.slice(1)
var t1 = t.slice(1)
 
s[0] == t[0] ? __FUNC__(s1, t1)
 : 1+Math.min(

View file

@ -1,16 +1,16 @@
func lcs(xstr, ystr) is cached {
xstr.is_empty && return xstr;
ystr.is_empty && return ystr;
xstr.is_empty && return xstr
ystr.is_empty && return ystr
var(x, xs, y, ys) = (xstr.ft(0,0), xstr.ft(1),
ystr.ft(0,0), ystr.ft(1));
var(x, xs, y, ys) = (xstr.first(1), xstr.slice(1),
ystr.first(1), ystr.slice(1))
if (x == y) {
x + lcs(xs, ys)
} else {
[lcs(xstr, ys), lcs(xs, ystr)].max_by { .len };
[lcs(xstr, ys), lcs(xs, ystr)].max_by { .len }
}
}
say lcs("thisisatest", "testing123testing");
say lcs("thisisatest", "testing123testing")

View file

@ -82,7 +82,7 @@ class MD5(String msg) {
var H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]
for i in (range(0, M.end, 16)) {
md5_block(H, M.ft(i, i+15))
md5_block(H, M.slice(i).first(16))
}
little_endian(8, 4, H)

View file

@ -5,7 +5,7 @@ d, h = 800, 500 # pixel density (= image width) and image height
n, r = 200, 500 # number of iterations and escape radius (r > 2)
direction, height = 45, 1.5 # direction and height of the incoming light
v = exp(direction / 180 * pi * im) # unit 2D vector in this direction
stripes, damping = 4, 2.0 # stripe density and damping parameter
x = range(0, 2, length=d+1)
y = range(0, 2 * h / d, length=h+1)
@ -14,31 +14,29 @@ A, B = collect(x) .- 1, collect(y) .- h / d
C = (2.0 + 1.0im) .* (A' .+ B .* im) .- 0.5
Z, dZ, ddZ = zero(C), zero(C), zero(C)
D, T = zeros(size(C)), zeros(size(C))
D, S, T = zeros(size(C)), zeros(size(C)), zeros(size(C))
for k in 1:n
M = abs2.(Z) .< abs2(r)
M = abs.(Z) .< r
S[M], T[M] = S[M] .+ cos.(stripes .* angle.(Z[M])), T[M] .+ 1
Z[M], dZ[M], ddZ[M] = Z[M] .^ 2 .+ C[M], 2 .* Z[M] .* dZ[M] .+ 1, 2 .* (dZ[M] .^ 2 .+ Z[M] .* ddZ[M])
end
N = abs.(Z) .> 2 # exterior distance estimation
D[N] = log.(abs.(Z[N])) .* abs.(Z[N]) ./ abs.(dZ[N])
N = abs.(Z) .>= r # normal map effect 1 (potential function)
P, Q = S[N] ./ T[N], (S[N] .+ cos.(stripes .* angle.(Z[N]))) ./ (T[N] .+ 1)
F = log2.(log.(abs.(Z[N])) ./ log(r)) # fraction between 0 and 1 (for interpolation)
R = Q .+ (P .- Q) .* F .* F .* (3 .- 2 .* F) # hermite interpolation (r is between q and p)
U, H = Z[N] ./ dZ[N], 1 .+ R ./ damping # normal vectors to the equipotential lines and height perturbation
U, v = U ./ abs.(U), exp(direction / 180 * pi * im) # unit normal vectors and vector in light direction
D[N] = max.((real.(U) .* real(v) .+ imag.(U) .* imag(v) .+ H .* height) ./ (1 + height), 0)
heatmap(D .^ 0.1, c=:balance)
savefig("Mandelbrot_distance_est.png")
N = abs.(Z) .> 2 # normal map effect 1 (potential function)
U = Z[N] ./ dZ[N] # normal vectors to the equipotential lines
U, S = U ./ abs.(U), 1 .+ sin.(100 .* angle.(U)) ./ 10 # unit normal vectors and stripes
T[N] = max.((real.(U) .* real(v) .+ imag.(U) .* imag(v) .+ S .* height) ./ (1 + height), 0)
heatmap(T .^ 1.0, c=:bone_1)
heatmap(D .^ 1.0, c=:bone_1)
savefig("Mandelbrot_normal_map_1.png")
N = abs.(Z) .> 2 # normal map effect 2 (distance estimation)
N = abs.(Z) .>= r # normal map effect 2 (distance estimation)
U = Z[N] .* dZ[N] .* ((1 .+ log.(abs.(Z[N]))) .* conj.(dZ[N] .^ 2) .- log.(abs.(Z[N])) .* conj.(Z[N] .* ddZ[N]))
U = U ./ abs.(U) # unit normal vectors to the equidistant lines
T[N] = max.((real.(U) .* real(v) .+ imag.(U) .* imag(v) .+ height) ./ (1 + height), 0)
U, v = U ./ abs.(U), exp(direction / 180 * pi * im) # unit normal vectors and vector in light direction
D[N] = max.((real.(U) .* real(v) .+ imag.(U) .* imag(v) .+ height) ./ (1 + height), 0)
heatmap(T .^ 1.0, c=:afmhot)
heatmap(D .^ 1.0, c=:afmhot)
savefig("Mandelbrot_normal_map_2.png")

View file

@ -5,7 +5,7 @@ d, h = 800, 500 # pixel density (= image width) and image height
n, r = 200, 500 # number of iterations and escape radius (r > 2)
direction, height = 45, 1.5 # direction and height of the incoming light
v = np.exp(direction / 180 * np.pi * 1j) # unit 2D vector in this direction
stripes, damping = 4, 2.0 # stripe density and damping parameter
x = np.linspace(0, 2, num=d+1)
y = np.linspace(0, 2 * h / d, num=h+1)
@ -14,30 +14,28 @@ A, B = np.meshgrid(x - 1, y - h / d)
C = (2.0 + 1.0j) * (A + B * 1j) - 0.5
Z, dZ, ddZ = np.zeros_like(C), np.zeros_like(C), np.zeros_like(C)
D, T = np.zeros(C.shape), np.zeros(C.shape)
D, S, T = np.zeros(C.shape), np.zeros(C.shape), np.zeros(C.shape)
for k in range(n):
M = Z.real ** 2 + Z.imag ** 2 < r ** 2
M = abs(Z) < r
S[M], T[M] = S[M] + np.cos(stripes * np.angle(Z[M])), T[M] + 1
Z[M], dZ[M], ddZ[M] = Z[M] ** 2 + C[M], 2 * Z[M] * dZ[M] + 1, 2 * (dZ[M] ** 2 + Z[M] * ddZ[M])
N = abs(Z) > 2 # exterior distance estimation
D[N] = np.log(abs(Z[N])) * abs(Z[N]) / abs(dZ[N])
N = abs(Z) >= r # normal map effect 1 (potential function)
P, Q = S[N] / T[N], (S[N] + np.cos(stripes * np.angle(Z[N]))) / (T[N] + 1)
F = np.log2(np.log(np.abs(Z[N])) / np.log(r)) # fraction between 0 and 1 (for interpolation)
R = Q + (P - Q) * F * F * (3 - 2 * F) # hermite interpolation (r is between q and p)
U, H = Z[N] / dZ[N], 1 + R / damping # normal vectors to the equipotential lines and height perturbation
U, v = U / abs(U), np.exp(direction / 180 * np.pi * 1j) # unit normal vectors and vector in light direction
D[N] = np.maximum((U.real * v.real + U.imag * v.imag + H * height) / (1 + height), 0)
plt.imshow(D ** 0.1, cmap=plt.cm.twilight_shifted, origin="lower")
plt.savefig("Mandelbrot_distance_est.png", dpi=200)
N = abs(Z) > 2 # normal map effect 1 (potential function)
U = Z[N] / dZ[N] # normal vectors to the equipotential lines
U, S = U / abs(U), 1 + np.sin(100 * np.angle(U)) / 10 # unit normal vectors and stripes
T[N] = np.maximum((U.real * v.real + U.imag * v.imag + S * height) / (1 + height), 0)
plt.imshow(T ** 1.0, cmap=plt.cm.bone, origin="lower")
plt.imshow(D ** 1.0, cmap=plt.cm.bone, origin="lower")
plt.savefig("Mandelbrot_normal_map_1.png", dpi=200)
N = abs(Z) > 2 # normal map effect 2 (distance estimation)
N = abs(Z) >= r # normal map effect 2 (distance estimation)
U = Z[N] * dZ[N] * ((1 + np.log(abs(Z[N]))) * np.conj(dZ[N] ** 2) - np.log(abs(Z[N])) * np.conj(Z[N] * ddZ[N]))
U = U / abs(U) # unit normal vectors to the equidistant lines
T[N] = np.maximum((U.real * v.real + U.imag * v.imag + height) / (1 + height), 0)
U, v = U / abs(U), np.exp(direction / 180 * np.pi * 1j) # unit normal vectors and vector in light direction
D[N] = np.maximum((U.real * v.real + U.imag * v.imag + height) / (1 + height), 0)
plt.imshow(T ** 1.0, cmap=plt.cm.afmhot, origin="lower")
plt.imshow(D ** 1.0, cmap=plt.cm.afmhot, origin="lower")
plt.savefig("Mandelbrot_normal_map_2.png", dpi=200)

View file

@ -1,24 +1,24 @@
var (n, sums, ts, mc) = (100, Set([2]), [], [1])
var st = Time.micro_sec
var (n, sums, ts, mc) = (100, Set(2), [], [1])
var st = Time.micro
for i in (1 ..^ n) {
for j in (mc[i-1]+1 .. Inf) {
mc[i] = j
for k in (0 .. i) {
var sum = mc[k]+j
if (sums.exists(sum)) {
if (sums.has(sum)) {
ts.clear
break
}
ts << sum
}
if (ts.len > 0) {
sums = (sums|Set(ts...))
sums |= Set(ts...)
break
}
}
}
var et = (Time.micro_sec - st)
var et = (Time.micro - st)
var s = " of the Mian-Chowla sequence are:\n"
say "The first 30 terms#{s}#{mc.ft(0, 29).join(' ')}\n"
say "Terms 91 to 100#{s}#{mc.ft(90, 99).join(' ')}\n"
say "The first 30 terms#{s}#{mc.first(30).join(' ')}\n"
say "Terms 91 to 100#{s}#{mc.slice(90).first(10).join(' ')}\n"
say "Computation time was #{et} seconds."

View file

@ -1,16 +1,16 @@
func middle_three(n) {
var l = n.len;
var l = n.len
if (l < 3) {
"#{n} is too short"
} elsif (l.is_even) {
"#{n} has an even number of digits"
} else {
"The three middle digits of #{n} are: " + n.digits.ft(l-3 / 2, l/2 + 1).join
"The three middle digits of #{n} are: " + n.digits.slice((l-3)/2).first(3).flip.join
}
}
var nums = %n(
123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345
1 2 -1 -10 2002 -2002 0
);
nums.each { say middle_three(_) };
)
nums.each { say middle_three(_) }

View file

@ -0,0 +1,13 @@
// Minkowski question-mark function. Nigel Galloway: July 14th., 2023
let fN g=let n=(int>>float)g in ((if g<0.0 then -1.0 else 1.0),abs n,abs (g-n))
let fI(n,_,(nl,nh))(g,_,(gl,gh))=let l,h=nl+gl,nh+gh in ((n+g)/2.0,(float l)/(float h),(l,h))
let fG n g=(max n g)-(min n g)
let fE(s,z,l)=Seq.unfold(fun(i,e)->let (n,g,_) as r=fI i e in Some((s*(z+n),s*(g+z)),if l<n then (i,r) else if l=n then (r,r) else (r,e)))((0.0,0.0,(0,1)),(1.0,1.0,(1,1)))
let fL(s,z,l)=Seq.unfold(fun(i,e)->let (n,g,_) as r=fI i e in Some((s*(z+n),s*(g+z)),if l<g then (i,r) else if l=g then (r,r) else (r,e)))((0.0,0.0,(0,1)),(1.0,1.0,(1,1)))
let f2M g=let _,(n,_)=fL(fN g)|>Seq.pairwise|>Seq.find(fun((n,_),(g,_))->(fG n g)<2.328306437e-11) in n
let m2F g=let _,(_,n)=fE(fN g)|>Seq.pairwise|>Seq.find(fun((_,n),(_,g))->(fG n g)<2.328306437e-11) in n
printfn $"?(φ) = 5/3 is %A{fG(f2M 1.61803398874989490253)(5.0/3.0)<2.328306437e-10}"
printfn $"?⁻¹(-5/9) = (√13-7)/6 is %A{fG(m2F(-5.0/9.0))((sqrt(13.0)-7.0)/6.0)<2.328306437e-10}"
let n=42.0/23.0 in printfn $"?⁻¹(?(n)) = n is %A{(fG(m2F(f2M n)) n)<2.328306437e-10}"
let n= -3.0/13.0 in printfn $"?(?⁻¹(n)) = n is %A{(fG(f2M(m2F n)) n)<2.328306437e-10}"

View file

@ -0,0 +1,29 @@
use ndhistogram::{Histogram, ndhistogram, axis::Uniform};
use rand::Rng;
/// change x in [0.0, 1.0) to a split with minimum probability at 0.5
fn modifier(x: f64) -> f64 {
if x < 0.5 {
return 2.0 * (0.5 - &x);
} else {
return 2.0 * (&x - 0.5);
}
}
const WANTED: usize = 20_000;
fn main() {
let mut hist = ndhistogram!(Uniform::new(19, -0.0, 1.0));
let mut rng = rand::thread_rng();
for _ in 0.. WANTED {
loop {
let x: f64 = rng.gen::<f64>();
let y: f64 = rng.gen::<f64>();
if y < modifier(x) {
hist.fill(&f64::from(x));
break;
}
}
}
println!("{}", hist);
}

View file

@ -32,7 +32,7 @@ F factor(BigInt n)
V e = 0
L
V (div, rem) = divmod(nn, d)
I bit_length(rem) > 0
I bits:length(rem) > 0
L.break
nn = div
e++
@ -61,7 +61,7 @@ F moBachShallit58(BigInt a, BigInt n; pf)
R mo
F moTest(a, n)
I bit_length(a) < 100
I bits:length(a) < 100
print(ord(a), end' )
E
print(ord([big]), end' )

View file

@ -1,11 +1,13 @@
/* Inspired by code from Python */
Queens(N):=block([K,C,P,V,A,S,L:[]],
Queens(N):=block([K,C,P,V,L:[]],
C: makelist(K,K,1,N),
P: permutations(C),
for V in P do (
A: length(unique(makelist(V[K]+K, K, C))),
S: length(unique(makelist(V[K]-K, K, C))),
if is(A=N) and is(S=N) then L: cons(V, L)
if is(N=length(unique(makelist(V[K]+K, K, C)))) then (
if is(N=length(unique(makelist(V[K]-K, K, C)))) then (
L: endcons(V, L)
)
)
), L
)$

View file

@ -23,15 +23,15 @@ armstrong(Exp, PSum):-
Min is 10^(Exp - 1)
; Min is 0
),
Max is 10^Exp,
Max is 10^Exp - 1,
combi(Exp, DigList, Comb),
powSum(Comb, Exp, 0, PSum),
between(Min, Max, PSum),
digits(PSum, DList),
sort(0, @=<, DList, DSort), % hold equal digits
( PSum =:= 0, Comb = [0] -> % special case because
true % DList in digits(0, DList) is [] and not [0]
; DSort = Comb
( DSort = Comb;
PSum =:= 0, % special case because
Comb = [0] % DList in digits(0, DList) is [] and not [0]
).
do:-between(1, 7, Exp),

View file

@ -0,0 +1,18 @@
Dim As Byte m = 0
For n As Byte = 0 To 23
If n = 23 Then
Print " 23" + ":30" + " = " + "7 bells"
Else
m += 1
Print ""; n Mod 23; ":30"; " ="; m; " bells"
End If
If n = 23 Then
Print " 00" + ":00" + " = " + "8 bells"
Else
m += 1
Print ""; (n Mod 23+1); ":00"; " ="; m; " bells"
If m = 8 Then m = 0
End If
Next n
Sleep

Some files were not shown because too many files have changed in this diff Show more