Data Update

This commit is contained in:
Ingy döt Net 2023-07-09 17:42:30 -04:00
parent 015c2add84
commit e50b5c3114
206 changed files with 6337 additions and 523 deletions

View file

@ -2,12 +2,11 @@ type NinetynineBottles
int DEFAULT_BOTTLES_COUNT = 99
model
int initialBottlesCount, bottlesCount
new by int bottlesCount
new by int =bottlesCount
me.initialBottlesCount = bottlesCount
me.bottlesCount = bottlesCount
end
fun subject = text by block do return when(me.bottlesCount == 1, "bottle", "bottles") end
fun bottles = text by block do return when(me.bottlesCount == 0, "no more", text!me.bottlesCount) end
fun subject = <|when(me.bottlesCount == 1, "bottle", "bottles")
fun bottles = <|when(me.bottlesCount == 0, "no more", text!me.bottlesCount)
fun goToWall = void by block
text line = me.bottles() + " " + me.subject() + " of beer on the wall, " +
me.bottles() + " " + me.subject() + " of beer."

View file

@ -1,18 +1,23 @@
main(number=99):
map:
- println
- map:
- paragraph
- range(number, 0, -1)
#!/usr/bin/env yamlscript
paragraph(num): |
# Print the verses to "99 Bottles of Beer"
#
# usage:
# yamlscript 99-bottles.ys [<count>]
defn main(number=99):
map(say):
map(paragraph):
(number .. 1)
defn paragraph(num): |
$(bottles num) of beer on the wall,
$(bottles num) of beer.
Take one down, pass it around.
$(bottles (num - 1)) of beer on the wall.
bottles(n):
cond: [
(n == 0), "No more bottles",
(n == 1), "1 bottle",
:else, "$n bottles" ]
defn bottles(n):
???:
(n == 0) : "No more bottles"
(n == 1) : "1 bottle"
:else : "$n bottles"

View file

@ -0,0 +1,124 @@
void local fn SandpilePrint( s(2,2) as ^long )
long r, c
for r = 0 to 2
for c = 0 to 2
printf @"%ld\t",s(r,c)
next
print
next
print
end fn
void local fn SandpileTopple( s(2,2) as ^long )
BOOL stable = NO
long r, c, value
while ( stable == NO )
stable = YES
for r = 0 to 2
for c = 0 to 2
value = s(r,c)
if ( value > 3 )
s(r,c) -= 4
if ( r > 0 ) then s(r-1,c)++
if ( r < 2 ) then s(r+1,c)++
if ( c > 0 ) then s(r,c-1)++
if ( c < 2 ) then s(r,c+1)++
print @"⇣ ⇣ ⇣ ⇣ ⇣"
print
fn SandpilePrint( s(0,0) )
stable = NO : break
end if
next
if ( stable == NO ) then break
next
wend
end fn
void local fn SandpileLoad( s(2,2) as ^long, values as CFStringRef )
long r, c, i = 0
for r = 0 to 2
for c = 0 to 2
s(r,c) = intval(mid(values,i,1))
i++
next
next
end fn
void local fn DoIt
long r, c, s(2,2), s1(2,2), s2(2,2), s3(2,2), s3_id(2,2)
// s
text @"Menlo-Bold" : print @"avalanche"
text @"Menlo" : print @"----------"
fn SandpileLoad( s(0,0), @"433312023" )
fn SandpilePrint( s(0,0) )
fn SandpileTopple( s(0,0) )
// s1
fn SandpileLoad( s1(0,0), @"120211013" )
// s2
fn SandpileLoad( s2(0,0), @"213101010" )
// s1 + s2
for r = 0 to 2
for c = 0 to 2
s(r,c) = s1(r,c) + s2(r,c)
next
next
text @"Menlo-Bold" : print @"s1 + s2"
text @"Menlo" : print @"----------"
fn SandpileTopple( s(0,0) )
fn SandpilePrint( s(0,0) )
// s2 + s1
for r = 0 to 2
for c = 0 to 2
s(r,c) = s2(r,c) + s1(r,c)
next
next
text @"Menlo-Bold" : print @"s2 + s1"
text @"Menlo" : print @"----------"
fn SandpileTopple( s(0,0) )
fn SandpilePrint( s(0,0) )
// s3
fn SandpileLoad( s3(0,0), @"333333333" )
text @"Menlo-Bold" : print @"s3"
text @"Menlo" : print @"----------"
fn SandpilePrint( s3(0,0) )
// s3_id
fn SandpileLoad( s3_id(0,0), @"212101212" )
text @"Menlo-Bold" : print @"s3_id"
text @"Menlo" : print @"----------"
fn SandpilePrint( s3_id(0,0) )
// s3 + s3_id
for r = 0 to 2
for c = 0 to 2
s(r,c) = s3(r,c) + s3_id(r,c)
next
next
text @"Menlo-Bold" : print @"s3+s3_id"
text @"Menlo" : print @"----------"
fn SandpilePrint( s(0,0) )
fn SandpileTopple( s(0,0) )
// s3_id + s3_id
for r = 0 to 2
for c = 0 to 2
s(r,c) = s3_id(r,c) + s3_id(r,c)
next
next
text @"Menlo-Bold" : print @"s3_id+s3_id"
text @"Menlo" : print @"-----------"
fn SandpilePrint( s(0,0) )
fn SandpileTopple( s(0,0) )
end fn
fn DoIt
HandleEvents

View file

@ -0,0 +1,151 @@
_mFile = 1
begin enum
_iClose
end enum
_window = 1
begin enum 1
_gridView
_gridSizeLabel
_gridSizeFld
_centerNumLabel
_centerNumFld
_colorRadio
_monoRadio
_avalancheBtn
end enum
void local fn BuildMenu
menu _mFile,,, @"File"
menu _mFile, _iClose,, @"Close", @"w"
MenuItemSetAction( _mFile, _iClose, @"performClose:" )
end fn
void local fn BuildWindow
window _window, @"Abelian Sandpile Model", (0,0,513,360), NSWindowStyleMaskTitled + NSWindowStyleMaskClosable + NSWindowStyleMaskMiniaturizable
subclass view _gridView, (20,20,320,320)
textlabel _gridSizeLabel, @"Grid size:", (385,322,61,16)
textfield _gridSizeFld,, @"5", (452,319,41,21)
ControlSetFormat( _gridSizeFld, @"0123456789", YES, 4, 0 )
textlabel _centerNumLabel, @"Center number:", (347,285,99,16)
textfield _centerNumFld,, @"32", (452,282,41,21)
ControlSetFormat( _centerNumFld, @"0123456789", YES, 4, 0 )
radiobutton _colorRadio,, NSControlStateValueOn, @"Color", (367,249,59,18)
radiobutton _monoRadio,, NSControlStateValueOff, @"Mono", (432,249,61,18)
button _avalancheBtn,,, @"Avalanche", (375,13,96,32)
WindowMakeFirstResponder( _window, _gridSizeFld )
end fn
void local fn ViewDrawRect
long gridSize = fn ControlIntegerValue(_gridSizeFld)
CGRect bounds = fn ViewBounds( _gridView )
CGFloat cellSize = bounds.size.width/gridSize
ColorRef col0 = fn ColorWhite, col1, col2, col3
long r, c, value
CGFloat x = 0, y = 0
ColorRef color
if ( fn ButtonState( _colorRadio ) == NSControlStateValueOn )
col1 = fn ColorRed
col2 = fn ColorGreen
col3 = fn ColorBlue
else
col1 = fn ColorWithRGB( 0.25, 0.25, 0.25, 1.0 )
col2 = fn ColorWithRGB( 0.5, 0.5, 0.5, 1.0 )
col3 = fn ColorWithRGB( 0.75, 0.75, 0.75, 1.0 )
end if
for r = 0 to gridSize-1
for c = 0 to gridSize-1
value = mda_integer(r,c)
select ( value )
case 1 : color = col1
case 2 : color = col2
case 3 : color = col3
case else : color = col0
end select
BezierPathFillRect( fn CGRectMake( x, y, cellSize, cellSize ), color )
x += cellSize
next
x = 0
y += cellSize
next
end fn
void local fn AvalancheAction
long r, c, gridSize = fn ControlIntegerValue(_gridSizeFld)
long centerNum = fn ControlIntegerValue(_centerNumFld)
long midNum = gridSize/2
long limit = gridSize-1
BOOL stable = NO
long value
// initialize array
mda_kill
for r = 0 to gridSize-1
for c = 0 to gridSize-1
mda(r,c) = 0
next
next
mda(midNum,midNum) = centerNum
// collapse
while ( stable == NO )
stable = YES
for r = 0 to gridSize-1
for c = 0 to gridSize-1
value = mda_integer(r,c)
if ( value > 3 )
mda(r,c) = @(mda_integer(r,c)-4)
if ( r > 0 ) then mda(r-1,c) = @(mda_integer(r-1,c) + 1)
if ( r < limit ) then mda(r+1,c) = @(mda_integer(r+1,c) + 1)
if ( c > 0 ) then mda(r,c-1) = @(mda_integer(r,c-1) + 1)
if ( c < limit ) then mda(r,c+1) = @(mda_integer(r,c+1) + 1)
stable = NO : break
end if
next
if ( stable == NO ) then break
next
wend
ViewSetNeedsDisplay( _gridView )
end fn
void local fn DoAppEvent( ev as long )
select ( ev )
case _appWillFinishLaunching
fn BuildMenu
fn BuildWindow
fn AvalancheAction
case _appShouldTerminateAfterLastWindowClosed : AppEventSetBool(YES)
end select
end fn
void local fn DoDialog( ev as long, tag as long, wnd as long, obj as CFTypeRef )
select ( ev )
case _btnClick
select ( tag )
case _avalancheBtn : fn AvalancheAction
case _gridSizeFld, _centerNumFld : fn AvalancheAction
case _colorRadio, _monoRadio : ViewSetNeedsDisplay( _gridView )
end select
case _viewDrawRect : fn ViewDrawRect
end select
end fn
on appevent fn DoAppEvent
on dialog fn DoDialog
HandleEvents

View file

@ -2,9 +2,6 @@ BEGIN # classify the numbers 1 : 20 000 as abudant, deficient or perfect #
INT abundant count := 0;
INT deficient count := 0;
INT perfect count := 0;
INT abundant example := 0;
INT deficient example := 0;
INT perfect example := 0;
INT max number = 20 000;
# construct a table of the proper divisor sums #
[ 1 : max number ]INT pds;
@ -15,39 +12,16 @@ BEGIN # classify the numbers 1 : 20 000 as abudant, deficient or perfect #
OD;
# classify the numbers #
FOR n TO max number DO
IF INT pd sum = pds[ n ];
pd sum < n
THEN
# have a deficient number #
deficient count +:= 1;
deficient example := n
ELIF pd sum = n
THEN
# have a perfect number #
perfect count +:= 1;
perfect example := n
INT pd sum = pds[ n ];
IF pd sum < n THEN
deficient count +:= 1
ELIF pd sum = n THEN
perfect count +:= 1
ELSE # pd sum > n #
# have an abundant number #
abundant count +:= 1;
abundant example := n
abundant count +:= 1
FI
OD;
# displays the classification, count and example #
PROC show result = ( STRING classification, INT count, example )VOID:
print( ( "There are "
, whole( count, -8 )
, " "
, classification
, " numbers up to "
, whole( max number, 0 )
, " e.g.: "
, whole( example, 0 )
, newline
)
);
# show how many of each type of number there are and an example #
show result( "abundant ", abundant count, abundant example );
show result( "deficient", deficient count, deficient example );
show result( "perfect ", perfect count, perfect example )
print( ( "abundant ", whole( abundant count, 0 ), newline ) );
print( ( "deficient ", whole( deficient count, 0 ), newline ) );
print( ( "perfect ", whole( perfect count, 0 ), newline ) )
END

View file

@ -0,0 +1,27 @@
do -- classify the numbers 1 : 20 000 as abudant, deficient or perfect
local abundantCount = 0
local deficientCount = 0
local perfectCount = 0
local maxNumber = 20000
-- construct a table of the proper divisor sums
local pds = {}
pds[ 1 ] = 0
for i = 2, maxNumber do pds[ i ] = 1 end
for i = 2, maxNumber do
for j = i + i, maxNumber, i do pds[ j ] = pds[ j ] + i end
end
-- classify the numbers
for n = 1, maxNumber do
local pdSum = pds[ n ]
if pdSum < n then
deficientCount = deficientCount + 1
elseif pdSum == n then
perfectCount = perfectCount + 1
else -- pdSum > n
abundantCount = abundantCount + 1
end
end
io.write( "abundant ", abundantCount, "\n" )
io.write( "deficient ", deficientCount, "\n" )
io.write( "perfect ", perfectCount, "\n" )
end

View file

@ -0,0 +1,30 @@
// classify the numbers 1 : 20 000 as abudant, deficient or perfect
abundantCount = 0
deficientCount = 0
perfectCount = 0
maxNumber = 20000
// construct a table of the proper divisor sums
pds = [0] * ( maxNumber + 1 )
pds[ 1 ] = 0
for i in range( 2, maxNumber )
pds[ i ] = 1
end for
for i in range( 2, maxNumber )
for j in range( i + i, maxNumber, i )
pds[ j ] = pds[ j ] + i
end for
end for
// classify the numbers
for n in range( 1, maxNumber )
pdSum = pds[ n ]
if pdSum < n then
deficientCount = deficientCount + 1
else if pdSum == n then
perfectCount = perfectCount + 1
else // pdSum > n
abundantCount = abundantCount + 1
end if
end for
print "abundant " + abundantCount
print "deficient " + deficientCount
print "perfect " + perfectCount

View file

@ -0,0 +1,26 @@
a = 0
d = 0
p = 0
for n = 1 to 20000
Pn = sumDivs(n)
if Pn > n a = a + 1 ok
if Pn < n d = d + 1 ok
if Pn = n p = p + 1 ok
next
see "Abundant : " + a + nl
see "Deficient: " + d + nl
see "Perfect : " + p + nl
func sumDivs (n)
if n < 2 return 0
else
sum = 1
sr = sqrt(n)
for d = 2 to sr
if n % d = 0
sum = sum + d
if d != sr sum = sum + n / d ok
ok
next
return sum
ok

View file

@ -0,0 +1,25 @@
maxNumber = 20000
abundantCount = 0
deficientCount = 0
perfectCount = 0
pds = list( maxNumber )
pds[ 1 ] = 0
for i = 2 to maxNumber pds[ i ] = 1 next
for i = 2 to maxNumber
for j = i + i to maxNumber step i pds[ j ] = pds[ j ] + i next
next
for n = 1 to maxNumber
pdSum = pds[ n ]
if pdSum < n
deficientCount = deficientCount + 1
but pdSum = n
perfectCount = perfectCount + 1
else # pdSum > n
abundantCount = abundantCount + 1
ok
next
see "Abundant : " + abundantCount + nl
see "Deficient: " + deficientCount + nl
see "Perfect : " + perfectCount + nl

View file

@ -0,0 +1,32 @@
var maxNumber = 20000
var abundantCount = 0
var deficientCount = 0
var perfectCount = 0
var pds = []
pds.add( 0 ) // element 0
pds.add( 0 ) // element 1
for( i in 2 .. maxNumber ){
pds.add( 1 )
}
for( i in 2 .. maxNumber ){
var j = i + i
while( j < maxNumber ){
pds[ j ] = pds[ j ] + i
j = j + i
}
}
for( n in 1 .. maxNumber ){
var pdSum = pds[ n ]
if ( pdSum < n ){
deficientCount = deficientCount + 1
} else if( pdSum == n ){
perfectCount = perfectCount + 1
} else { // pdSum > n
abundantCount = abundantCount + 1
}
}
System.print( "Abundant : %(abundantCount)" )
System.print( "Deficient: %(deficientCount)" )
System.print( "Perfect : %(perfectCount)" )

57
Task/Amb/C++/amb-2.cpp Normal file
View file

@ -0,0 +1,57 @@
#include <functional>
#include <iostream>
#include <numeric>
#include <string>
#include <vector>
std::string join(const std::string& delimiter, const std::vector<std::string>& list) {
return list.empty() ? "" : std::accumulate(++list.begin(), list.end(), list[0],
[delimiter](auto& a, auto& b) { return a + delimiter + b; });
}
std::vector<std::string> amb(std::function<bool(std::string&, std::string&)> func,
std::vector<std::vector<std::string>> options, std::string previous) {
if ( options.empty() ) {
return std::vector<std::string>();
}
for ( std::string& option : options.front() ) {
if ( ! previous.empty() && ! func(previous, option) ) {
continue;
}
if ( options.size() == 1 ) {
return std::vector<std::string>(1, option);
}
std::vector<std::vector<std::string>> next_options(options.begin() + 1, options.end());
std::vector<std::string> result = amb(func, next_options, option);
if ( ! result.empty() ) {
result.emplace(result.begin(), option);
return result;
}
}
return std::vector<std::string>();
}
std::string Amb(std::vector<std::vector<std::string>> options) {
std::function<bool(std::string, std::string)> continues =
[](std::string before, std::string after) { return before.back() == after.front(); };
std::vector<std::string> amb_result = amb(continues, options, "");
return ( amb_result.empty() ) ? "No match found" : join(" ", amb_result);
}
int main() {
std::vector<std::vector<std::string>> words = { { "the", "that", "a" },
{ "frog", "elephant", "thing" },
{ "walked", "treaded", "grows" },
{ "slowly", "quickly" } };
std::cout << Amb(words) << std::endl;
}

52
Task/Amb/Java/amb.java Normal file
View file

@ -0,0 +1,52 @@
import java.util.ArrayList;
import java.util.List;
import java.util.function.BiFunction;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public final class AmbTask {
public static void main(String[] aArgs) {
List<List<String>> words = List.of(
List.of( "the", "that", "a" ),
List.of( "frog", "elephant", "thing" ),
List.of( "walked", "treaded", "grows" ),
List.of( "slowly", "quickly" ) );
System.out.println(Amb(words));
}
private static String Amb(List<List<String>> aOptions) {
BiFunction<String, String, Boolean> continues = (before, after) -> before.endsWith(after.substring(0, 1));
List<String> ambResult = amb(continues, aOptions, "");
return ( ambResult.isEmpty() ) ? "No match found" : String.join(" ", ambResult);
}
private static List<String> amb(
BiFunction<String, String, Boolean> aBiFunction, List<List<String>> aOptions, String aPrevious) {
if ( aOptions.isEmpty() ) {
return new ArrayList<String>();
}
for ( String option : aOptions.get(0) ) {
if ( ! aPrevious.isEmpty() && ! aBiFunction.apply(aPrevious, option) ) {
continue;
}
if ( aOptions.size() == 1 ) {
return Stream.of(option).collect(Collectors.toList());
}
List<String> result = (ArrayList<String>) amb(aBiFunction, aOptions.subList(1, aOptions.size()), option);
if ( ! result.isEmpty() ) {
result.add(0, option);
return result;
}
}
return new ArrayList<String>();
}
}

View file

@ -0,0 +1,25 @@
double a, c, g, t, p
double apprpi
short i
// Initial values
a = 1
g = sqr(0.5)
p = 1
t = 0.25
//Iterate just 3 times
for i = 1 to 3
c = a
a = ( a + g ) / 2
g = sqr( c * g )
c -= a
t -= ( p * c^2 )
p *= 2
apprpi = (( a + g )^2) / ( t * 4 )
print "Iteration "i": ", apprpi
next
print "Actual value:",pi
handleevents

View file

@ -1,14 +1,16 @@
with Ada.Text_IO; use Ada.Text_IO;
with System;
procedure Array_Length is
Fruits : constant array (Positive range <>) of access constant String
:= (new String'("orange"),
new String'("apple"));
begin
for Fruit of Fruits loop
Ada.Text_IO.Put (Integer'Image (Fruit'Length));
end loop;
Memory_Size : constant Integer := Fruits'Size / System.Storage_Unit;
Ada.Text_IO.Put_Line (" Array Size : " & Integer'Image (Fruits'Length));
begin
Put_Line ("Number of elements : " & Fruits'Length'Image);
Put_Line ("Array memory Size : " & Memory_Size'Image & " bytes" );
Put_Line (" " & Integer'Image (Memory_Size * System.Storage_Unit / System.Word_Size) & " words" );
end Array_Length;

View file

@ -571,11 +571,6 @@ procedure bezier_intersections is
pt1 : dpoint;
pt2 : opoint;
begin
--
-- NOTE FOR THE FUTURE: This operation is a change of HOMOGENEOUS
-- coordinates. Here we are still using
-- regular euclidean coordinates, however.
--
pt0 := eval (gcurve, t0);
pt1 := ((t1 - t0 - t0) * t1 + (t0 * t0)) * gcurve.pt1;
pt2 := eval (gcurve, t1);

View file

@ -0,0 +1,74 @@
#include <cmath>
#include <iomanip>
#include <iostream>
#include <numbers>
#include <vector>
typedef std::pair<int32_t, int32_t> point;
std::vector<point> babylonian_spiral(int32_t step_count) {
const double tau = 2 * std::numbers::pi;
std::vector<int32_t> squares(step_count + 1);
for ( int32_t i = 0; i < step_count; ++i ) {
squares[i] = i * i;
}
std::vector<point> points { point(0, 0), point (0, 1) };
int32_t norm = 1;
for ( int32_t step = 0; step < step_count - 2; ++step ) {
point previousPoint = points.back();
const double theta = atan2(previousPoint.second, previousPoint.first);
std::vector<point> candidates;
while ( candidates.empty() ) {
norm += 1;
for ( int32_t i = 0; i < step_count; ++i ) {
int32_t a = squares[i];
if ( a > norm / 2 ) {
break;
}
for ( int32_t j = sqrt(norm) + 1; j >= 0; --j ) {
int32_t b = squares[j];
if ( a + b < norm ) {
break;
}
if ( a + b == norm ) {
std::vector<point> next_points = { point(i, j), point(-i, j), point(i, -j), point(-i, -j),
point(j, i), point(-j, i), point(j, -i), point(-j, -i) };
candidates.reserve(next_points.size());
std::move(next_points.begin(), next_points.end(), std::back_inserter(candidates));
}
}
}
}
point minimum;
double minimum_value = tau;
for ( point candidate : candidates ) {
double value = fmod(theta - atan2(candidate.second, candidate.first) + tau, tau);
if ( value < minimum_value ) {
minimum_value = value;
minimum = candidate;
}
}
points.push_back(minimum);
}
for ( uint64_t i = 0; i < points.size() - 1; ++i ) {
points[i + 1] = point(points[i].first + points[i + 1].first, points[i].second + points[i + 1].second);
}
return points;
}
int main() {
std::vector<point> points = babylonian_spiral(40);
std::cout << "The first 40 points of the Babylonian spiral are:" << std::endl;
for ( int32_t i = 0, column = 0; i < 40; ++i ) {
std::string point_str = "(" + std::to_string(points[i].first) + ", " + std::to_string(points[i].second) + ")";
std::cout << std::setw(10) << point_str;
if ( ++column % 10 == 0 ) {
std::cout << std::endl;
}
}
}

View file

@ -20,29 +20,30 @@ public final class BabylonianSpiral {
"(" + points.get(i).x + ", " + points.get(i).y + ")", ( ++column % 10 == 0 ) ? "\n" : " "));
}
System.out.println();
String text = svgText(points, 800);
Files.write(Paths.get("BabylonianSpiralJava.svg"), text.getBytes());
Files.write(Paths.get("C:/Users/psnow/Desktop/BabylonianSpiralJava.svg"), text.getBytes());
}
private static List<Point> babylonianSpiral(int aStepCount) {
final double tau = 2 * Math.PI;
List<Integer> squares = IntStream.rangeClosed(0, aStepCount).map( i -> i * i ).boxed().toList();
List<Point> deltas = Stream.of( new Point(0, 0), new Point(0, 1) ).collect(Collectors.toList());
long norm = 1;
List<Point> points = Stream.of( new Point(0, 0), new Point(0, 1) ).collect(Collectors.toList());
int norm = 1;
for ( int step = 0; step < aStepCount - 2; step++ ) {
Point previousPoint = deltas.get(deltas.size() - 1);
Point previousPoint = points.get(points.size() - 1);
final double theta = Math.atan2(previousPoint.y, previousPoint.x);
Set<Point> candidates = new HashSet<Point>();
while ( candidates.isEmpty() ) {
norm += 1;
for ( int i = 0; i < aStepCount; i++ ) {
long a = squares.get(i);
int a = squares.get(i);
if ( a > norm / 2 ) {
break;
}
for ( int j = (int) Math.sqrt(norm) + 1; j >= 0; j-- ) {
long b = squares.get(j);
int b = squares.get(j);
if ( a + b < norm ) {
break;
}
@ -56,16 +57,16 @@ public final class BabylonianSpiral {
}
Comparator<Point> comparatorPoint = (one, two) -> Double.compare(
( theta - Math.atan2(one.y, one.x) + TAU ) % TAU, ( theta - Math.atan2(two.y, two.x) + TAU ) % TAU);
( theta - Math.atan2(one.y, one.x) + tau ) % tau, ( theta - Math.atan2(two.y, two.x) + tau ) % tau);
Point minimum = candidates.stream().min(comparatorPoint).get();
deltas.add(minimum);
points.add(minimum);
}
for ( int i = 0; i < deltas.size() - 1; i++ ) {
deltas.set(i + 1, new Point(deltas.get(i).x + deltas.get(i + 1).x, deltas.get(i).y + deltas.get(i + 1).y));
}
return deltas;
for ( int i = 0; i < points.size() - 1; i++ ) {
points.set(i + 1, new Point(points.get(i).x + points.get(i + 1).x, points.get(i).y + points.get(i + 1).y));
}
return points;
}
private static String svgText(List<Point> aPoints, int aSize) {
@ -83,6 +84,4 @@ public final class BabylonianSpiral {
return text.toString();
}
private static final double TAU = 2 * Math.PI;
}

View file

@ -1,5 +1,4 @@
use Regexp::Common 'balanced';
my $re = qr/^$RE{balanced}{-parens=>'[]'}$/;
use Regexp::Common 'RE_balanced';
sub balanced {
return shift =~ $re;
return shift =~ RE_balanced(-parens=>'[]')
}

View file

@ -1,6 +1,7 @@
#include <cstdint>
#include <iostream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <unordered_map>
#include <vector>
@ -8,7 +9,7 @@ typedef std::pair<int32_t, int32_t> point;
class Bifid {
public:
Bifid(const int32_t& n, const std::string& text) {
Bifid(const int32_t n, std::string_view text) {
if ( text.length() != n * n ) {
throw new std::invalid_argument("Incorrect length of text");
}
@ -20,7 +21,7 @@ public:
int32_t row = 0;
int32_t col = 0;
for ( char ch : text ) {
for ( const char& ch : text ) {
grid[row][col] = ch;
coordinates[ch] = point(row, col);
col += 1;
@ -35,9 +36,9 @@ public:
}
}
std::string encrypt(const std::string& text) {
std::string encrypt(std::string_view text) {
std::vector<int32_t> row_one, row_two;
for ( char ch : text ) {
for ( const char& ch : text ) {
point coordinate = coordinates[ch];
row_one.push_back(coordinate.first);
row_two.push_back(coordinate.second);
@ -51,9 +52,9 @@ public:
return result;
}
std::string decrypt(const std::string& text) {
std::string decrypt(std::string_view text) {
std::vector<int32_t> row;
for ( char ch : text ) {
for ( const char& ch : text ) {
point coordinate = coordinates[ch];
row.push_back(coordinate.first);
row.push_back(coordinate.second);
@ -70,8 +71,8 @@ public:
}
void display() const {
for ( std::vector<char> row : grid ) {
for ( char ch : row ) {
for ( const std::vector<char>& row : grid ) {
for ( const char& ch : row ) {
std::cout << ch << " ";
}
std::cout << std::endl;
@ -82,7 +83,7 @@ private:
std::unordered_map<char, point> coordinates;
};
void runTest(Bifid bifid, std::string message) {
void runTest(Bifid& bifid, std::string_view message) {
std::cout << "Using Polybius square:" << std::endl;
bifid.display();
std::cout << "Message: " << message << std::endl;
@ -94,9 +95,9 @@ void runTest(Bifid bifid, std::string message) {
}
int main() {
const std::string message1 = "ATTACKATDAWN";
const std::string message2 = "FLEEATONCE";
const std::string message3 = "THEINVASIONWILLSTARTONTHEFIRSTOFJANUARY";
const std::string_view message1 = "ATTACKATDAWN";
const std::string_view message2 = "FLEEATONCE";
const std::string_view message3 = "THEINVASIONWILLSTARTONTHEFIRSTOFJANUARY";
Bifid bifid1(5, "ABCDEFGHIKLMNOPQRSTUVWXYZ");
Bifid bifid2(5, "BGWKZQPNDSIOAXEFCLUMTHYVR");

View file

@ -0,0 +1,8 @@
# _nwise is for gojq
def _nwise($n):
def n: if length <= $n then . else .[0:$n] , (.[$n:] | n) end;
n;
# Input: a string
# Output: a stream of strings
def chars: explode[] | [.] | implode;

View file

@ -0,0 +1,54 @@
# Input: the message to be encrypted
def encrypt($polybius):
(ascii_upcase | gsub("J"; "I") ) as $m
| {rows: [], cols : [] }
| reduce ($m|chars) as $c (.;
($polybius|index($c)) as $ix
| if $ix
then .rows += [($ix/5)|floor + 1]
| .cols += [($ix%5) + 1]
else .
end )
| reduce (.rows + .cols | _nwise(2)) as $pair ("";
(($pair[0] - 1) * 5 + $pair[1] - 1) as $ix
| . + $polybius[$ix:$ix+1] ) ;
# Input: the message to be decrypted
def decrypt($polybius):
reduce chars as $c ( {rows: [], cols : [] };
($polybius|index($c)) as $ix
| .rows += [($ix/5)|floor + 1]
| .cols += [($ix%5) + 1] )
| ([.rows, .cols] | transpose | flatten) as $lines
| ($lines|length/2) as $count
| $lines[:$count] as $rows
| $lines[$count:] as $cols
| [$rows, $cols] as $d
| reduce range(0; $count) as $i ("";
(($rows[$i] - 1) * 5 + $cols[$i] - 1) as $ix
| . + $polybius[$ix:$ix+1] ) ;
def polys:
def p1: "ABCDEFGHIKLMNOPQRSTUVWXYZ";
def p2: "BGWKZQPNDSIOAXEFCLUMTHYVR";
def p3: "PLAYFIREXMBCDGHKNOQSTUVWZ";
[p1, p2, p2, p3];
def messages: [
"ATTACKATDAWN",
"FLEEATONCE",
"ATTACKATDAWN",
"The invasion will start on the first of January"
];
def task:
range(0; messages|length) as $i
| messages[$i]
| encrypt(polys[$i]) as $encrypted
| ($encrypted | decrypt(polys[$i] )) as $decrypted
| "Message : \(.)",
"Encrypted : \($encrypted)",
"Decrypted : \($decrypted)"
"" ;
task

View file

@ -1,30 +0,0 @@
/*REXX program finds a value in a list of integers using an iterative binary search.*/
@= 3 7 13 19 23 31 43 47 61 73 83 89 103 109 113 131 139 151 167 181,
193 199 229 233 241 271 283 293 313 317 337 349 353 359 383 389 401 409 421 433,
443 449 463 467 491 503 509 523 547 571 577 601 619 643 647 661 677 683 691 709,
743 761 773 797 811 823 829 839 859 863 883 887 911 919 941 953 971 983 1013
/* [↑] a list of some low weak primes.*/
parse arg ? . /*get a # that's specified on the CL.*/
if ?=='' then do; say; say '***error*** no argument specified.'; say
exit /*stick a fork in it, we're all done. */
end
low= 1
high= words(@)
avg= (word(@, 1) + word(@, high)) / 2
loc= binarySearch(low, high)
if loc==-1 then do; say ? " wasn't found in the list."
exit /*stick a fork in it, we're all done. */
end
else say ? ' is in the list, its index is: ' loc
say
say 'arithmetic mean of the ' high " values is: " avg
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
binarySearch: procedure expose @ ?; parse arg low,high
if high<low then return -1 /*the item wasn't found in the @ list. */
mid= (low + high) % 2 /*calculate the midpoint in the list. */
y= word(@, mid) /*obtain the midpoint value in the list*/
if ?=y then return mid
if y>? then return binarySearch(low, mid-1)
return binarySearch(mid+1, high)

View file

@ -1,25 +1,27 @@
/*REXX program finds a value in a list of integers using an iterative binary search.*/
@= 3 7 13 19 23 31 43 47 61 73 83 89 103 109 113 131 139 151 167 181,
193 199 229 233 241 271 283 293 313 317 337 349 353 359 383 389 401 409 421 433,
443 449 463 467 491 503 509 523 547 571 577 601 619 643 647 661 677 683 691 709,
/* REXX program finds a value in a list of integers */
/* using an iterative binary search. */
list=3 7 13 19 23 31 43 47 61 73 83 89 103 109 113 131 139 151 167 181 193 199,
229 233 241 271 283 293 313 317 337 349 353 359 383 389 401 409 421 433 443,
449 463 467 491 503 509 523 547 571 577 601 619 643 647 661 677 683 691 709,
743 761 773 797 811 823 829 839 859 863 883 887 911 919 941 953 971 983 1013
/* [↑] a list of some low weak primes.*/
parse arg ? . /*get a # that's specified on the CL.*/
if ?=='' then do; say; say '***error*** no argument specified.'; say
exit 13
end
low= 1
high= words(@)
say 'arithmetic mean of the ' high " values is: " (word(@, 1) + word(@, high)) / 2
say
do while low<=high; mid= (low + high) % 2; y= word(@, mid)
/* list: a list of some low weak primes. */
Parse Arg needle /* get a number to be looked for */
If needle=="" Then
Call exit "***error*** no argument specified."
low=1
high=words(list)
Do While low<=high
mid=(low+high)%2
y=word(list,mid)
Select
When y=needle Then
Call exit needle "is in the list, its index is:" mid'.'
When y>needle Then /* too high */
high=mid-1 /* set upper nound */
Otherwise /* too low */
low=mid+1 /* set lower limit */
End
End
Call exit needle "wasn't found in the list."
if ?=y then do; say ? ' is in the list, its index is: ' mid
exit /*stick a fork in it, we're all done. */
end
if y>? then high= mid - 1 /*too high? */
else low= mid + 1 /*too low? */
end /*while*/
say ? " wasn't found in the list." /*stick a fork in it, we're all done. */
exit: Say arg(1)

View file

@ -0,0 +1,25 @@
/*REXX program finds a value in a list of integers using an iterative binary search.*/
@= 3 7 13 19 23 31 43 47 61 73 83 89 103 109 113 131 139 151 167 181,
193 199 229 233 241 271 283 293 313 317 337 349 353 359 383 389 401 409 421 433,
443 449 463 467 491 503 509 523 547 571 577 601 619 643 647 661 677 683 691 709,
743 761 773 797 811 823 829 839 859 863 883 887 911 919 941 953 971 983 1013
/* [↑] a list of some low weak primes.*/
parse arg ? . /*get a # that's specified on the CL.*/
if ?=='' then do; say; say '***error*** no argument specified.'; say
exit 13
end
low= 1
high= words(@)
say 'arithmetic mean of the ' high " values is: " (word(@, 1) + word(@, high)) / 2
say
do while low<=high; mid= (low + high) % 2; y= word(@, mid)
if ?=y then do; say ? ' is in the list, its index is: ' mid
exit /*stick a fork in it, we're all done. */
end
if y>? then high= mid - 1 /*too high? */
else low= mid + 1 /*too low? */
end /*while*/
say ? " wasn't found in the list." /*stick a fork in it, we're all done. */

View file

@ -14,6 +14,7 @@ otherB= other'$' /*same as above, but with less
new= changeStr('A' , other, "Z") /*change the upper letter A ──► Z. */
tt= changeStr('~~', other, ";") /*change two tildes ──► one semicolon.*/
joined= dingsta || dingsta2 /*join two strings together (concat). */
say joined c2b(joined)
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
c2b: return x2b( c2x( arg(1) ) ) /*return the string as a binary string.*/
c2b: Return x2b(c2x(arg(1))) /*return the string as a binary string.*/

View file

@ -0,0 +1,137 @@
#include <algorithm>
#include <cstdint>
#include <iostream>
#include <numeric>
#include <unordered_map>
#include <unordered_set>
#include <string>
#include <vector>
// Print a report of the given string to the standard output device.
void print_report(const std::string& text) {
std::unordered_map<char, int32_t> bases;
for ( const char& ch : text ) {
bases[ch]++;
}
const int32_t total = std::accumulate(bases.begin(), bases.end(), 0,
[&](int32_t previous_sum, std::pair<char, int32_t> entry) {
return previous_sum + entry.second;
});
std::cout << "Nucleotide counts for: " << ( ( text.length() > 50 ) ? "\n" : "" );
std::cout << text << std::endl;
std::cout << "Bases: A " << bases['A'] << ", C: " << bases['C'] << ", G: " << bases['G'] << ", T: " << bases['T']
<< ", total: " << total << "\n" << std::endl;
}
// Return all permutations of the given list of strings.
std::vector<std::vector<std::string>> permutations(std::vector<std::string>& list) {
int32_t indexes[list.size()] = {};
std::vector<std::vector<std::string>> result;
result.push_back(list);
int32_t i = 0;
while ( (uint64_t) i < list.size() ) {
if ( indexes[i] < i ) {
const int j = ( i % 2 == 0 ) ? 0 : indexes[i];
std::swap(list[i], list[j]);
result.push_back(list);
indexes[i]++;
i = 0;
} else {
indexes[i] = 0;
i++;
}
}
return result;
}
// Return 'before' concatenated with 'after', removing the longest suffix of 'before' that matches a prefix of 'after'.
std::string concatenate(const std::string& before, const std::string& after) {
for ( uint64_t i = 0; i < before.length(); ++i ) {
if ( after.starts_with(before.substr(i, before.length())) ) {
return before.substr(0, i) + after;
}
}
return before + after;
}
// Remove duplicate strings and strings which are substrings of other strings in the given list.
std::vector<std::string> deduplicate(const std::vector<std::string>& list) {
std::vector<std::string> singletons(list);
std::sort(singletons.begin(), singletons.end());
singletons.erase(std::unique(singletons.begin(), singletons.end()), singletons.end());
std::vector<std::string> result(singletons);
std::unordered_set<std::string> marked_for_removal;
for ( const std::string& test_word : result ) {
for ( const std::string& word : singletons ) {
if ( word != test_word && word.find(test_word) != std::string::npos ) {
marked_for_removal.emplace(test_word);
}
}
}
result.erase(std::remove_if(result.begin(), result.end(),
[&](std::string& word) {
return marked_for_removal.count(word) != 0;
}
), result.end());
return result;
}
// Return a set containing all of the shortest common superstrings of the given list of strings.
std::unordered_set<std::string> shortest_common_superstrings(const std::vector<std::string>& list) {
std::vector<std::string> deduplicated = deduplicate(list);
std::unordered_set<std::string> shortest;
shortest.emplace(std::reduce(list.begin(), list.end(), std::string("")));
uint64_t shortest_length;
for ( const std::string& word : list ) {
shortest_length += word.length();
}
for ( std::vector<std::string> permutation : permutations(deduplicated) ) {
std::string candidate;
for ( const std::string& word : permutation ) {
candidate = concatenate(candidate, word);
}
if ( candidate.length() < shortest_length ) {
shortest.clear();
shortest.emplace(candidate);
shortest_length = candidate.length();
} else if ( candidate.length() == shortest_length ) {
shortest.emplace(candidate);
}
}
return shortest;
}
int main() {
const std::vector<std::vector<std::string>> test_sequences = {
{ "TA", "AAG", "TA", "GAA", "TA" },
{ "CATTAGGG", "ATTAG", "GGG", "TA" },
{ "AAGAUGGA", "GGAGCGCAUC", "AUCGCAAUAAGGA" },
{ "ATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTAT",
"GGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGT",
"CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA",
"TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC",
"AACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT",
"GCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTC",
"CGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCT",
"TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC",
"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGC",
"GATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATT",
"TTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC",
"CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA",
"TCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGA" } };
for ( const std::vector<std::string>& test : test_sequences ) {
for ( const std::string& superstring : shortest_common_superstrings(test) ) {
print_report(superstring);
}
}
}

View file

@ -56,7 +56,7 @@ public final class BioinformaticsGlobalAlignment {
return shortest;
}
// Remove duplicate words and words which are substrings of other words in the given list.
// Remove duplicate strings and strings which are substrings of other strings in the given list.
private static List<String> deduplicate(List<String> aList) {
List<String> unique = aList.stream().distinct().collect(Collectors.toList());
List<String> result = new ArrayList<String>(unique);
@ -99,7 +99,7 @@ public final class BioinformaticsGlobalAlignment {
i = 0;
} else {
indexes[i] = 0;
i++;
i += 1;
}
}
return result;

View file

@ -1,13 +1,13 @@
fun printSequence(sequence: String, width: Int = 50) {
fun <K, V> printWithLabel(k: K, v: V) {
val label = k.toString().padStart(5)
println("$label: $v")
}
fun printWithLabel(label: Any, data: Any) =
label.toString().padStart(5).also { println("$it: $data") }
println("SEQUENCE:")
sequence.chunked(width).withIndex().forEach { (i, line) ->
printWithLabel(i*width + line.length, line)
sequence.chunked(width).forEachIndexed() { i, chunk ->
printWithLabel(i * width + chunk.length, chunk)
}
println("BASE:")
sequence.groupingBy { it }.eachCount().forEach { (k, v) ->
printWithLabel(k, v)
@ -17,6 +17,4 @@ fun printSequence(sequence: String, width: Int = 50) {
const val BASE_SEQUENCE = "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT"
fun main() {
printSequence(BASE_SEQUENCE)
}
fun main() = printSequence(BASE_SEQUENCE)

View file

@ -1,31 +1,36 @@
/*REXX program finds the number of each base in a DNA string (along with a total). */
parse arg dna .
if dna=='' | dna=="," then dna= 'cgtaaaaaattacaacgtcctttggctatctcttaaactcctgctaaatg' ,
'ctcgtgctttccaattatgtaagcgttccgagacggggtggtcgattctg' ,
'aggacaaaggtcaagatggagcgcatcgaacgcaataaggatcatttgat' ,
'gggacgtttcgtcgacaaagtcttgtttcgagagtaacggctaccgtctt' ,
'cgattctgcttataacactatgttcttatgaaatggatgttctgagttgg' ,
'tcagtcccaatgtgcggggtttcttttagtacgtcgggagtggtattata' ,
'tttaatttttctatatagcgatctgtatttaagcaattcatttaggttat' ,
'cgccgcgatgctcggttcggaccgccaagcatctggctccactgctagtg' ,
'tcctaaatttgaatggcaaacacaaataagatttagcaattcgtgtagac' ,
'gaccggggacttgcatgatgggagcagctttgttaaactacgaacgtaat'
dna= space(dna, 0); upper dna /*elide blanks from DNA; uppercase it. */
say 'length of the DNA string: ' length(dna)
@.= 0 /*initialize the count for all bases. */
w= 1 /*the maximum width of a base count. */
$= /*a placeholder for the names of bases.*/
do j=1 for length(dna) /*traipse through the DNA string. */
_= substr(dna, j, 1) /*obtain a base name from the DNA str. */
if pos(_, $)==0 then $= $ || _ /*if not found before, add it to list. */
@._= @._ + 1 /*bump the count of this base. */
w= max(w, length(@._) ) /*compute the maximum width number. */
end /*j*/
say
do k=0 for 255; z= d2c(k) /*traipse through all possibilities. */
if pos(z, $)==0 then iterate /*Was this base found? No, then skip. */
say ' base ' z " has a basecount of: " right(@.z, w)
@.tot= @.tot + @.z /*add to a grand total to verify count.*/
end /*k*/ /*stick a fork in it, we're all done. */
say
say 'total for all basecounts:' right(@.tot, w+1)
/*REXX program finds the number of each base in a DNA string */
/* (along with a total). */
Parse Arg dna .
If dna==''|dna==',' Then
dna='cgtaaaaaattacaacgtcctttggctatctcttaaactcctgctaaatg',
'ctcgtgctttccaattatgtaagcgttccgagacggggtggtcgattctg',
'aggacaaaggtcaagatggagcgcatcgaacgcaataaggatcatttgat',
'gggacgtttcgtcgacaaagtcttgtttcgagagtaacggctaccgtctt',
'cgattctgcttataacactatgttcttatgaaatggatgttctgagttgg',
'tcagtcccaatgtgcggggtttcttttagtacgtcgggagtggtattata',
'tttaatttttctatatagcgatctgtatttaagcaattcatttaggttat',
'cgccgcgatgctcggttcggaccgccaagcatctggctccactgctagtg',
'tcctaaatttgaatggcaaacacaaataagatttagcaattcgtgtagac',
'gaccggggacttgcatgatgggagcagctttgttaaactacgaacgtaat'
dna=translate(space(dna,0)) /* elide blanks from DNA; uppercas*/
Say '--------length of the DNA string: ' length(dna)
count.=0 /* initialize the count for all bases*/
w=1 /* the maximum width of a base count */
names='' /* list of all names */
Do j=1 To length(dna) /* traipse through the DNA string */
name=substr(dna,j,1) /* obtain a base name from the DNA */
If pos(name,names)==0 Then
names=names||name /* if not found, add it to the list */
count.name=count.name+1 /* bump the count of this base. */
w=max(w,length(count.name)) /* compute the maximum number width */
End
Say
Do k=0 To 255
z=d2c(k) /* traipse through all possibilities */
If pos(z,names)>0 Then Do
Say ' base ' z ' has a basecount of: ' right(count.z,w)
count.tot=count.tot+count.z /* add to a grand total to verify */
End
End
Say
Say '--------total for all basecounts:' right(count.tot,w+1)

View file

@ -0,0 +1,78 @@
#include <chrono>
#include <cmath>
#include <cstdint>
#include <iostream>
#include <numbers>
#include <sstream>
#include <string>
#include <vector>
const double tau = 2 * std::numbers::pi;
const std::vector<std::string> cycles { "PHYSICAL", "EMOTIONAL", "MENTAL" };
const std::vector<std::int32_t> cycle_lengths { 23, 28, 33 };
const std::vector<std::vector<std::string>> descriptions { { "up and rising", "peak" },
{ "up but falling", "transition" },
{ "down and falling", "valley" },
{ "down but rising", "transition" } };
std::string to_string(const std::chrono::sys_days& sys_date) {
std::stringstream stream;
stream << sys_date;
std::string iso_date;
stream >> iso_date;
return iso_date;
}
std::chrono::sys_days create_date(const std::string& iso_date) {
const int year = std::stoi(iso_date.substr(0, 4));
const unsigned int month = std::stoi(iso_date.substr(5, 7));
const unsigned int day = std::stoi(iso_date.substr(8, 10));
std::chrono::year_month_day date{std::chrono::year{year}, std::chrono::month{month}, std::chrono::day{day}};
return std::chrono::sys_days(date);
}
void biorhythms(const std::vector<std::string>& date_pair) {
std::chrono::sys_days birth_date = create_date(date_pair[0]);
std::chrono::sys_days target_date = create_date(date_pair[1]);
int32_t days_between = ( target_date - birth_date ).count();
std::cout << "Birth date " << birth_date << ", Target date " << target_date << std::endl;
std::cout << "Days between: " << days_between << std::endl;
for ( int32_t i = 0; i < 3; ++i ) {
const int32_t cycle_length = cycle_lengths[i];
const int32_t position_in_cycle = days_between % cycle_length;
const int32_t quadrant_index = 4 * position_in_cycle / cycle_length;
const int32_t percentage = round(100 * sin(tau * position_in_cycle / cycle_length));
std::string description;
if ( percentage > 95 ) {
description = "peak";
} else if ( percentage < -95 ) {
description = "valley";
} else if ( abs(percentage) < 5 ) {
description = "critical transition";
} else {
const int32_t days_to_transition = ( cycle_length * ( quadrant_index + 1 ) / 4 ) - position_in_cycle;
std::chrono::sys_days transition_date = target_date + std::chrono::days{days_to_transition};
std::string trend = descriptions[quadrant_index][0];
std::string next_transition = descriptions[quadrant_index][1];
description = std::to_string(percentage) + "% (" + trend + ", next " + next_transition
+ " " + to_string(transition_date) + ")";
}
std::cout << cycles[i] << " day " << position_in_cycle << ": " << description << std::endl;
}
std::cout << std::endl;
}
int main() {
const std::vector<std::vector<std::string>> date_pairs = {
{ "1943-03-09", "1972-07-11" },
{ "1809-01-12", "1863-11-19" },
{ "1809-02-12", "1863-11-19" } };
for ( const std::vector<std::string>& date_pair : date_pairs ) {
biorhythms(date_pair);
}
}

View file

@ -3,4 +3,3 @@ gcc -o cbio cbio.c -lm
Age: 10717 days
Physical cycle: -27%
Emotional cycle: -100%
Intellectual cycle: -100%

View file

@ -0,0 +1,76 @@
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.List;
public final class Biorythms {
public static void main(String[] aArgs) {
List<List<String>> datePairs = List.of(
List.of( "1943-03-09", "1972-07-11" ),
List.of( "1809-01-12", "1863-11-19" ),
List.of( "1809-02-12", "1863-11-19" ));
for ( List<String> datePair : datePairs ) {
biorhythms(datePair);
}
}
private static void biorhythms(List<String> aDatePair) {
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE;
LocalDate birthDate = LocalDate.parse(aDatePair.get(0), formatter);
LocalDate targetDate = LocalDate.parse(aDatePair.get(1), formatter);
final int daysBetween = (int) ChronoUnit.DAYS.between(birthDate, targetDate);
System.out.println("Birth date " + birthDate + ", Target date " + targetDate);
System.out.println("Days between: " + daysBetween);
for ( Cycle cycle : Cycle.values() ) {
final int cycleLength = cycle.length();
final int positionInCycle = daysBetween % cycleLength;
final int quadrantIndex = 4 * positionInCycle / cycleLength;
final int percentage = (int) Math.round(100 * Math.sin(2 * Math.PI * positionInCycle / cycleLength));
String description;
if ( percentage > 95 ) {
description = "peak";
} else if ( percentage < -95 ) {
description = "valley";
} else if ( Math.abs(percentage) < 5 ) {
description = "critical transition";
} else {
final int daysToTransition = ( cycleLength * ( quadrantIndex + 1 ) / 4 ) - positionInCycle;
LocalDate transitionDate = targetDate.plusDays(daysToTransition);
List<String> descriptions = cycle.descriptions(quadrantIndex);
String trend = descriptions.get(0);
String nextTransition = descriptions.get(1);
description = percentage + "% (" + trend + ", next " + nextTransition + " " + transitionDate + ")";
}
System.out.println(cycle + " day " + positionInCycle + ": " + description);
}
System.out.println();
}
private enum Cycle {
PHYSICAL(23), EMOTIONAL(28), MENTAL(33);
public int length() {
return length;
}
public List<String> descriptions(int aNumber) {
return DESCRIPTIONS.get(aNumber);
}
private Cycle(int aLength) {
length = aLength;
}
private final int length;
private static final List<List<String>> DESCRIPTIONS = List.of(
List.of( "up and rising", "peak" ), List.of( "up but falling", "transition" ),
List.of( "down and falling", "valley" ), List.of( "down but rising", "transition" ));
}
}

View file

@ -1,23 +1,67 @@
/*REXX pgm shows the states of a person's biorhythms (physical, emotional, intellectual)*/
parse arg birthdate targetDate . /*obtain one or two dates from the C.L.*/
days= daysbet2(birthdate targetDate) /*invoke the 2nd version of a REXX pgm.*/
if days==0 then do; say; say 'The two dates specified are exacty the same.'; exit 1
end
cycles= 'physical emotional intellectual' /*the names of each biorhythm cycle*/
cycle = 'negative neutral positive' /* " states of " " " */
@.1= 23; @.2= 28; @.3= 33 /* " # of days in " " " */
pid2= pi() * 2 * days /*calculate pi * t * number─of─days. */
/*REXX pgm shows the states of a person's biorhythms */
/* (physical, emotional, intellectual) */
Parse Arg birthdate targetdate . /* obtain one or two dates from CL */
If birthdate='?' Then Do
Say 'rexx bio birthdate (yyyymmdd) shows you today''s biorhythms'
Say 'or enter your birthday now'
Parse Pull birthdate
If birthdate='' Then Exit
End
If birthdate='' Then
Parse Value 19460906 20200906 With birthdate targetdate
If targetdate='' Then
targetdate=Date('S')
days=daysbet2(birthdate,targetdate)
If days==0 Then Do
Say
Say 'The two dates specified are exacty the same.'
Exit 1
End
cycles='physical emotional intellectual' /*the biorhythm cycle names */
cycle='negative neutral positive'
period.1=23
period.2=28
period.3=33
pid2=pi()*2*days
say 'Birthdate: ' birthdate '('translate('gh.ef.abcd',birthdate,'abcdefgh')')'
say 'Today: ' targetdate '('translate('gh.ef.abcd',targetdate,'abcdefgh')')'
Say 'Elapsed days:' days
Do j=1 To 3
state=2+sign(sin(pid2/period.j)) /* obtain state for each biorhythm */
Say 'biorhythm for the' right(word(cycles,j),12) 'cycle is',
word(cycle,state)
End
Exit
/*---------------------------------------------------------------------*/
pi:
pi=3.1415926535897932384626433832795028841971693993751058209749445923078
Return pi
r2r:
Return arg(1)//(pi()*2) /* normalize radians --? a unit ci*/
/*--------------------------------------------------------------------------------------*/
sin: Procedure
Parse Arg x
x=r2r(x)
_=x
Numeric Fuzz min(5,max(1,digits()-3))
If x=pi*.5 Then
Return 1
If x==pi*1.5 Then
Return-1
If abs(x)=pi|x=0 Then
Return 0
q=x*x
z=x
Do k=2 By 2 Until p=z
p=z
_=-_*q/(k*k+k)
z=z+_
End
Return z
do j=1 for 3
state= 2 + sign( sin( pid2 / @.j) ) /*obtain state for each biorhythm cycle*/
say 'biorhythm for the' right(word(cycles,j),12) "cycle is" word(cycle, state)
end /*j*/ /* [↑] get state for each biorhythm. */
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
pi: pi= 3.1415926535897932384626433832795028841971693993751058209749445923078; return pi
r2r: return arg(1) // (pi() * 2) /*normalize radians ──► a unit circle. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
sin: procedure; parse arg x; x= r2r(x); _= x; numeric fuzz min(5, max(1, digits() -3))
if x=pi * .5 then return 1; if x==pi*1.5 then return -1
if abs(x)=pi | x=0 then return 0; q= x*x; z= x
do k=2 by 2 until p=z; p= z; _= -_ *q/(k*k+k); z= z+_; end; return z
daysbet2: Procedure
/* compute the number of days between fromdate and todate */
Parse Arg fromdate,todate
fromday=date('B',fromdate,'S')
today=date('B',todate,'S')
Return today-fromday

View file

@ -1,38 +1,44 @@
/*REXX program demonstrates how to process/display a simple RGB raster graphics image.*/
red = 'ff 00 00'x /*a method to define a red value. */
blue = '00 00 ff'x /*" " " " " blue " */
@. = /*define entire @. array to nulls. */
outFN = 'image' /*the filename of the output image PPM */
sWidth = 500; sHeight= 500 /*the screen width and height in pixels*/
call RGBfill red /*set the entire image to red. */
x= 10; y= 40 /*set pixel's coördinates. */
call RGBset x, y, blue /*set a pixel (at 10,40) to blue. */
color = RGBget(x, y) /*get the color of a pixel. */
hexV = c2x(color) /*get hex value of pixel's color. */
binV = x2b(hexV) /* " binary " " " " */
bin3V = left(binV, 8) substr(binV, 9, 8) right(binV, 8)
hex3V = left(hexV, 2) substr(hexV, 3, 2) right(hexV, 2)
xy= '(' || x","y')' /*create a handy─dandy literal for SAY.*/
say xy ' pixel in binary: ' binV /*show the binary value of 20,50 */
say xy ' pixel in binary: ' bin3V /*show again, but with spaces. */
say /*show a blank between binary and hex. */
say xy ' pixel in hex: ' hexV /*show again, but in hexadecimal. */
say xy ' pixel in hex: ' hex3V /*show again, but with spaces. */
call PPMwrite outFN, sWidth, sHeight /*create a PPM (output) file of image. */ /* ◄■■■■■■■■ not part of this task.*/
say /*show a blank. */
say 'The file ' outFN".PPM was created." /*inform user that a file was created. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
RGBfill: @.=arg(1); return /*fill image with a color.*/
RGBget: parse arg px,py; return @.px.py /*get a pixel's color. */
RGBset: parse arg px,py,p$; @.px.py=p$; return /*set " " " */
/*──────────────────────────────────────────────────────────────────────────────────────*/
PPMwrite: parse arg oFN, width, height /*obtain output filename, width, height*/
oFID= oFN'.PPM'; $='9'x; #=255 /*fileID; separator; max color value.*/
call charout oFID, , 1 /*set the position of the file's output*/
call charout oFID,'P6'width || $ || height || $ || # || $ /*write hdr info.*/
do j=1 for width
do k=1 for height; call charout oFID, @.j.k
end /*k*/ /* ↑ write the PPM file, ··· */
end /*j*/ /* └───────── ··· one pixel at a time.*/
call charout oFID; return /*close the output file just to be safe*/
/*REXX program demonstrates how to process/display */
/* a simple RGB raster graphics image.*/
red = 'ff 00 00'x /*a method to define a red value. */
blue = '00 00 ff'x /*' ' ' ' ' blue ' */
pixel='' /*define entire pixel. array to nulls.*/
outFN = 'image' /*the filename of the output image PPM */
sWidth = 500; sHeight= 500 /*the screen width and height in pixels*/
Call RGBfill red /*set the entire image to red. */
x=10; y=40 /*set pixel's coördinates. */
Call RGBset x,y,blue /*set a pixel (at 10,40) to blue. */
color = RGBget(x,y) /*get the color of a pixel. */
hexV = c2x(color) /*get hex value of pixel's color. */
binV = x2b(hexV) /* " binary " " " " */
bin3V = left(binV,8) substr(binV,9,8) right(binV,8)
hex3V = left(hexV,2) substr(hexV,3,2) right(hexV,2)
xy= '('||x','y')' /*create a handy-dandy literal for SAY.*/
Say xy ' pixel in binary: ' binV /*show the binary value of 20,50 */
Say xy ' pixel in binary: ' bin3V /*show again,but with spaces. */
Say /*show a blank between bin & hex. */
Say xy ' pixel in hex: ' hexV /*show again,but in hexadecimal. */
Say xy ' pixel in hex: ' hex3V /*show again,but with spaces. */
Call PPMwrite outFN,sWidth,sHeight /*create a PPM (output) file */
/* ?¦¦¦¦¦¦¦¦ not part of this task.*/
Say /*show a blank. */
Say 'The file ' outFN'.PPM was created.' /*inform user */
Exit /*stick a fork in it, we're all done. */
/*---------------------------------------------------------------------*/
RGBfill: pixel.=arg(1); Return /*fill image with a color.*/
RGBget: Parse arg px,py; Return pixel.px.py /*get a pixel's color. */
RGBset: Parse arg px,py,psep; pixel.px.py=psep; Return /*set a pixel */
/*---------------------------------------------------------------------*/
PPMwrite: Parse arg oFN,width,height
oFID= oFN'.PPM' /* fileID */
sep='9'x; /* separator */
maxcol=255 /* max color value. */
Call charout oFID,,1 /*set the position of the file's output*/
Call charout oFID,'P6'width||sep||height||sep||maxcol||sep /* header */
Do i=1 To width
Do j=1 To height;
Call charout oFID,pixel.i.j
End
End
Call charout oFID /* close the output file just to be safe */
Return

View file

@ -0,0 +1,68 @@
#include <algorithm>
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <vector>
bool is_prime_type_3(const int32_t number) {
if ( number < 2 ) return false;
if ( number % 2 == 0 ) return false;
if ( number % 3 == 0 ) return number == 3;
for ( int divisor = 5; divisor * divisor <= number; divisor += 2 ) {
if ( number % divisor == 0 ) { return false; }
}
return number % 4 == 3;
}
int32_t least_prime_factor(const int32_t number) {
if ( number == 1 ) { return 1; }
if ( number % 3 == 0 ) { return 3; }
if ( number % 5 == 0 ) { return 5; }
for ( int divisor = 7; divisor * divisor <= number; divisor += 2 ) {
if ( number % divisor == 0 ) { return divisor; }
}
return number;
}
int main() {
int32_t blums[50];
int32_t blum_count = 0;
int32_t last_digit_counts[10] = {};
int32_t number = 1;
while ( blum_count < 400'000 ) {
const int32_t prime = least_prime_factor(number);
if ( prime % 4 == 3 ) {
const int32_t quotient = number / prime;
if ( quotient != prime && is_prime_type_3(quotient) ) {
if ( blum_count < 50 ) {
blums[blum_count] = number;
}
last_digit_counts[number % 10] += 1;
blum_count += 1;
if ( blum_count == 50 ) {
std::cout << "The first 50 Blum integers:" << std::endl;
for ( int32_t i = 0; i < 50; ++i ) {
std::cout << std::setw(3) << blums[i] << ( ( i % 10 == 9 ) ? "\n" : " " );
}
std::cout << std::endl;
} else if ( blum_count == 26'828 || blum_count % 100'000 == 0 ) {
std::cout << "The " << std::setw(6) << blum_count << "th Blum integer is: "
<< std::setw(7) << number << std::endl;
if ( blum_count == 400'000 ) {
std::cout << "\nPercent distribution of the first 400000 Blum integers:" << std::endl;
for ( const int32_t& i : { 1, 3, 7, 9 } ) {
std::cout << " " << std::setw(6) << std::setprecision(5)
<< (double) last_digit_counts[i] / 4'000 << "% end in " << i << std::endl;
}
}
}
}
}
number += ( number % 5 == 3 ) ? 4 : 2;
}
}

View file

@ -0,0 +1,69 @@
import java.util.HashMap;
import java.util.Map;
public final class BlumInteger {
public static void main(String[] aArgs) {
int[] blums = new int[50];
int blumCount = 0;
Map<Integer, Integer> lastDigitCounts = new HashMap<Integer, Integer>();
int number = 1;
while ( blumCount < 400_000 ) {
final int prime = leastPrimeFactor(number);
if ( prime % 4 == 3 ) {
final int quotient = number / prime;
if ( quotient != prime && isPrimeType3(quotient) ) {
if ( blumCount < 50 ) {
blums[blumCount] = number;
}
lastDigitCounts.merge(number % 10, 1, Integer::sum);
blumCount += 1;
if ( blumCount == 50 ) {
System.out.println("The first 50 Blum integers:");
for ( int i = 0; i < 50; i++ ) {
System.out.print(String.format("%3d", blums[i]));
System.out.print(( i % 10 == 9 ) ? System.lineSeparator() : " ");
}
System.out.println();
} else if ( blumCount == 26_828 || blumCount % 100_000 == 0 ) {
System.out.println(String.format("%s%6d%s%7d",
"The ", blumCount, "th Blum integer is: ", number));
if ( blumCount == 400_000 ) {
System.out.println();
System.out.println("Percent distribution of the first 400000 Blum integers:");
for ( int key : lastDigitCounts.keySet() ) {
System.out.println(String.format("%s%6.3f%s%d",
" ", (double) lastDigitCounts.get(key) / 4_000, "% end in ", key));
}
}
}
}
}
number += ( number % 5 == 3 ) ? 4 : 2;
}
}
private static boolean isPrimeType3(int aNumber) {
if ( aNumber < 2 ) { return false; }
if ( aNumber % 2 == 0 ) { return false; }
if ( aNumber % 3 == 0 ) { return aNumber == 3; }
for ( int divisor = 5; divisor * divisor <= aNumber; divisor += 2 ) {
if ( aNumber % divisor == 0 ) { return false; }
}
return aNumber % 4 == 3;
}
private static int leastPrimeFactor(int aNumber) {
if ( aNumber == 1 ) { return 1; }
if ( aNumber % 3 == 0 ) { return 3; }
if ( aNumber % 5 == 0 ) { return 5; }
for ( int divisor = 7; divisor * divisor <= aNumber; divisor += 2 ) {
if ( aNumber % divisor == 0 ) { return divisor; }
}
return aNumber;
}
}

View file

@ -0,0 +1,15 @@
require 'prime'
BLUM_EXP = [1, 1]
blums = (1..).step(2).lazy.select do |c|
next if c % 5 == 0
primes, exps = c.prime_division.transpose
exps == BLUM_EXP && primes.all?{|pr| (pr-3) % 4 == 0}
end
n, m = 50, 26828
res = blums.first(m)
puts "First #{n} Blum numbers:"
res.first(n).each_slice(10){|s| puts "%4d"*s.size % s}
puts "\n#{m}th Blum number: #{res.last}"

View file

@ -1,29 +1,38 @@
/*REXX program "boxes the compass" [from degree (º) headings ───► a 32 point set]. */
parse arg $ /*allow º headings to be specified.*/
if $='' then $= 0 16.87 16.88 33.75 50.62 50.63 67.5 84.37 84.38 101.25 118.12 118.13 ,
135 151.87 151.88 168.75 185.62 185.63 202.5 219.37 219.38 236.25 ,
253.12 253.13 270 286.87 286.88 303.75 320.62 320.63 337.5 354.37 354.38
/* [↑] use default, they're in degrees*/
@pts= 'n nbe n-ne nebn ne nebe e-ne ebn e ebs e-se sebe se sebs s-se sbe',
"s sbw s-sw swbs sw swbw w-sw wbs w wbn w-nw nwbw nw nwbn n-nw nbw"
/*REXX program "boxes the compass" */
/* [from degree (º) headings ---> a 32 point set]. */
Parse Arg degrees
If degrees='' Then
degrees=0 16.87 16.88 33.75 50.62 50.63 67.5 84.37 84.38 101.25,
118.12 118.13 135 151.87 151.88 168.75 185.62 185.63 202.5,
219.37 219.38 236.25 253.12 253.13 270 286.87 286.88 303.75,
320.62 320.63 337.5 354.37 354.38
names='n nbe n-ne nebn ne nebe e-ne ebn e ebs e-se sebe se sebs s-se sbe',
's sbw s-sw swbs sw swbw w-sw wbs w wbn w-nw nwbw nw nwbn n-nw nbw'
#= words(@pts) + 1 /*#: used for integer ÷ remainder (//)*/
dirs= 'north south east west' /*define cardinal compass directions. */
/* [↓] choose a glyph for degree (°).*/
if 4=='f4'x then degSym= "a1"x /*is this system an EBCDIC system? */
else degSym= "a7"x /*'f8'x is the degree symbol: ° vs º */
/*──────────────────────────── f8 vs a7*/
say right(degSym'heading', 30) center("compass heading", 20)
say right( '', 30) copies( "", 20)
pad= ' ' /*used to interject a blank for output.*/
do j=1 for words($); x= word($, j) /*obtain one of the degree headings. */
say right( format(x, , 2)degSym, 30-1) pad boxHeading(x)
end /*j*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
boxHeading: y= arg(1)//360; if y<0 then y=360-y /*normalize heading within unit circle.*/
z= word(@pts, trunc(max(1, (y/11.25 +1.5) // #))) /*convert degrees─►heading*/
do k=1 for words(dirs); d= word(dirs, k)
z= changestr( left(d, 1), z, d)
end /*k*/ /* [↑] old, haystack, new*/
return changestr('b', z, " by ") /*expand "b" ───► " by ".*/
nn=words(names)+1 /* nn: used for integer ÷ remainder */
dirs='north south east west' /* define cardinal compass directions*/
/* choose a glyph for degree (°).*/
If 4=='f4'x Then /* is this system an EBCDIC system*/
degsym='a1'x
Else
degsym='f8'x /* or degsym='a7'x */
Say right(degsym'heading',30) center('compass heading',20)
Say right('--------',30) copies('-',20)
pad=' ' /* used to interject a blank for o */
Do i=1 To words(degrees)
x=word(degrees,i) /* obtain one of the degree headings */
Say right(format(x,,2)degsym,30-1) pad boxheading(x)
End
Exit /* stick a fork in it, we're all done*/
/*---------------------------------------------------------------------*/
boxheading:
y=arg(1)//360
If y<0 Then
y=360-y /* normalize heading within unit circle */
z=word(names,trunc(max(1,(y/11.25+1.5)//nn))) /* degrees->heading */
/* n e s w are now replaced by north east south west, respectively */
Do k=1 To words(dirs)
d=word(dirs,k)
z=changestr(left(d,1),z,d)
End
Return changestr('b',z,' by ') /* expand 'b' ---? ' by '. */

View file

@ -0,0 +1,62 @@
#include <algorithm>
#include <cstdint>
#include <experimental/iterator>
#include <functional>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
void display(const std::vector<int32_t>& numbers) {
std::cout << "[";
std::copy(std::begin(numbers), std::end(numbers), std::experimental::make_ostream_joiner(std::cout, ", "));
std::cout << "]" << std::endl;
}
int32_t string_search_single(const std::string& haystack, const std::string& needle) {
auto it = std::search(haystack.begin(), haystack.end(), std::boyer_moore_searcher(needle.begin(), needle.end()));
if ( it != haystack.end() ) {
return std::distance(haystack.begin(), it);
}
return -1;
}
std::vector<int32_t> string_search(const std::string& haystack, const std::string& needle) {
std::vector<int32_t> result = {};
uint64_t start = 0;
int32_t index = 0;
while ( index >= 0 && start < haystack.length() ) {
std::string haystackReduced = haystack.substr(start);
index = string_search_single(haystackReduced, needle);
if ( index >= 0 ) {
result.push_back(start + index);
start += index + needle.length();
}
}
return result;
}
int main() {
const std::vector<std::string> texts = {
"GCTAGCTCTACGAGTCTA",
"GGCTATAATGCGTA",
"there would have been a time for such a word",
"needle need noodle needle",
"DKnuthusesandprogramsanimaginarycomputertheMIXanditsassociatedmachinecodeandassemblylanguages",
"Nearby farms grew an acre of alfalfa on the dairy's behalf, with bales of that alfalfa exchanged for milk."
};
const std::vector<std::string> patterns = { "TCTA", "TAATAAA", "word", "needle", "and", "alfalfa" };
for ( uint64_t i = 0; i < texts.size(); ++i ) {
std::cout << "text" << ( i + 1 ) << " = " << texts[i] << std::endl;
}
std::cout << std::endl;
for ( uint64_t i = 0; i < texts.size(); ++i ) {
std::vector<int32_t> indexes = string_search(texts[i], patterns[i]);
std::cout << "Found " << std::quoted(patterns[i]) << " in 'text" << ( i + 1 ) << "' at indexes ";
display(string_search(texts[i], patterns[i]));
}
}

View file

@ -0,0 +1,96 @@
#define max(a, b) iif((a) > (b), (a), (b))
Dim Shared As Integer suff(), bmBc(), bmGs()
Sub preBmBc(pat As String)
Dim As Integer m = Len(pat), i
Redim bmBc(m)
For i = 1 To m-1
bmBc(Cint(pat[i])) = m - i
Next
End Sub
Sub suffixes(pat As String)
Dim As Integer m = Len(pat), g = m, i, f
Redim suff(m)
suff(m) = m
For i = m-1 To 1 Step -1
If i > g And suff(i + m - f) < i - g Then
suff(i) = suff(i + m - f)
Else
If i < g Then g = i
f = i
While g >= 1 And pat[g] = pat[g + m - f]
g -= 1
Wend
suff(i) = f - g
End If
Next
End Sub
Sub preBmGs(pat As String)
Dim As Integer m = Len(pat), j = 1, i
Redim suff(m)
Redim bmGs(m)
For i = m To 1 Step -1
If suff(i) = i Then
While j < m - i
If bmGs(j) = m Then bmGs(j) = m - i
j += 1
Wend
End If
Next
For i = 1 To m-1
bmGs(m - suff(i)) = m - i
Next
End Sub
Sub BM(pat As String, s As String, case_insensitive As Boolean = False)
Dim As String pins = "'" & pat & "' in " & "'" & s & "'"
If case_insensitive Then
pat = Lcase(pat)
s = Lcase(s)
End If
' Preprocessing
preBmGs(pat)
preBmBc(pat)
' Searching
Dim As Integer j = 0, n = Len(s), m = Len(pat), i = m
While j <= n - m
i -= 1
If pat[i] <> s[i+j] Then Exit While
j += Iif(i < 1, bmGs(0), max(bmGs(i), bmBc(Len(s[i+j]) - m + i)))
Wend
Dim As Integer many = Instr(s, pat)
Dim As String tmp = ""
If Not many > 0 Then
Print "No "; pins
Else
Do While many > 0 'if not found loop will be skipped
tmp &= Str(many) & ","
many = Instr(many + 1, s, pat)
Loop
Print Using "Found & at indices [&]"; pins; tmp & Chr(8)
End If
End Sub
BM("GCAGAGAG","GCATCGCAGAGAGTATACAGTACG")
BM("TCTA","GCTAGCTCTACGAGTCTA")
BM("TAATAAA","GGCTATAATGCGTA")
BM("word","there would have been a time for such a word")
BM("needle","needle need noodle needle")
Const book = "InhisbookseriesTheArtofComputerProgrammingpublishedbyAddisonWesley" + _
"DKnuthusesanimaginarycomputertheMIXanditsassociatedmachinecodeand" + _
"assemblylanguagestoillustratetheconceptsandalgorithmsastheyarepresented"
BM("put",book)
BM("and",book)
Const farm = "Nearby farms grew a half acre of alfalfa on the dairy's behalf, with " + _
"bales of all that alfalfa exchanged for milk."
BM("alfalfa",farm)
Sleep

View file

@ -0,0 +1,238 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
/**
* An implementation of the Boyer-Moore string search algorithm.
* It finds all occurrences of a pattern in a text, performing a case-insensitive search on ASCII characters.
*
* For all full description of the algorithm visit:
* https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string-search_algorithm
*/
public final class BoyerMooreStringSearch {
public static void main(String[] aArgs) {
List<String> texts = List.of(
"GCTAGCTCTACGAGTCTA",
"GGCTATAATGCGTA",
"there would have been a time for such a word",
"needle need noodle needle",
"DKnuthusesandshowsanimaginarycomputertheMIXanditsassociatedmachinecodeandassemblylanguagestoillustrate",
"Farms grew an acre of alfalfa on the dairy's behalf, with bales of that alfalfa exchanged for milk.");
List<String> patterns = List.of( "TCTA", "TAATAAA", "word", "needle", "put", "and", "alfalfa" );
for ( int i = 0; i < texts.size(); i++ ) {
System.out.println("text" + ( i + 1 ) + " = " + texts.get(i));
}
System.out.println();
for ( int i = 0; i < patterns.size(); i++ ) {
final int j = ( i < 5 ) ? i : i - 1;
System.out.println("Found \"" + patterns.get(i) + "\" in 'text" + ( j + 1 ) + "' at indexes "
+ stringSearch(texts.get(j), patterns.get(i)));
}
}
/**
* Return a list of indexes at which the given pattern matches the given text.
*/
private static List<Integer> stringSearch(String aText, String aPattern) {
if ( aPattern.isEmpty() || aText.isEmpty() || aText.length() < aPattern.length() ) {
return Collections.emptyList();
}
List<Integer> matches = new ArrayList<Integer>();
// Preprocessing
List<List<Integer>> R = badCharacterTable(aPattern);
int[] L = goodSuffixTable(aPattern);
int[] F = fullShiftTable(aPattern);
int k = aPattern.length() - 1; // Represents the alignment of the end of aPattern relative to aText
int previousK = -1; // Represents the above alignment in the previous phase
while ( k < aText.length() ) {
int i = aPattern.length() - 1; // Index of the character to compare in aPattern
int h = k; // Index of the character to compare in aText
while ( i >= 0 && h > previousK && aPattern.charAt(i) == aText.charAt(h) ) {
i -= 1;
h -= 1;
}
if ( i == -1 || h == previousK ) { // Match has been found
matches.add(k - aPattern.length() + 1);
k += ( aPattern.length() > 1 ) ? aPattern.length() - F[1] : 1;
} else { // No match, shift by the maximum of the bad character and good suffix rules
int suffixShift;
int charShift = i - R.get(alphabetIndex(aText.charAt(h))).get(i);
if ( i + 1 == aPattern.length() ) { // Mismatch occurred on the first character
suffixShift = 1;
} else if ( L[i + 1] == -1 ) { // Matched suffix does not appear anywhere in aPattern
suffixShift = aPattern.length() - F[i + 1];
} else { // Matched suffix appears in aPattern
suffixShift = aPattern.length() - 1 - L[i + 1];
}
int shift = Math.max(charShift, suffixShift);
if ( shift >= i + 1 ) { // Galil's rule
previousK = k;
}
k += shift;
}
}
return matches;
}
/**
* Create the shift table, F, for the given text, which is an array such that
* F[i] is the length of the longest suffix of, aText.substring(i), which is also a prefix of the given text.
*
* Use case: If a mismatch occurs at character index i - 1 in the pattern,
* the magnitude of the shift of the pattern, P, relative to the text is: P.length() - F[i].
*/
private static int[] fullShiftTable(String aText) {
int[] F = new int[aText.length()];
int[] Z = fundamentalPreprocess(aText);
int longest = 0;
Collections.reverse(Arrays.asList(Z));
for ( int i = 0; i < Z.length; i++ ) {
int zv = Z[i];
if ( zv == i + 1 ) {
longest = Math.max(zv, longest);
}
F[F.length - i - 1] = longest;
}
return F;
}
/**
* Create the good suffix table, L, for the given text, which is an array such that
* L[i] = k, is the largest index in the given text, S,
* such that S.substring(i) matches a suffix of S.substring(0, k).
*
* Use case: If a mismatch of characters occurs at index i - 1 in the pattern, P,
* then a shift of magnitude, P.length() - L[i], is such that no instances of the pattern in the text are omitted.
* Furthermore, a suffix of P.substring(0, L[i]) matches the same substring of the text that was matched by a
* suffix in the pattern on the previous matching attempt.
* In the case that L[i] = -1, the full shift table must be used.
*/
private static int[] goodSuffixTable(String aText) {
int[] L = IntStream.generate( () -> -1 ).limit(aText.length()).toArray();
String reversed = new StringBuilder(aText).reverse().toString();
int[] N = fundamentalPreprocess(reversed);
Collections.reverse(Arrays.asList(N));
for ( int j = 0; j < aText.length() - 1; j++ ) {
int i = aText.length() - N[j];
if ( i != aText.length() ) {
L[i] = j;
}
}
return L;
}
/**
* Create the bad character table, R, for the given text,
* which is a list indexed by the ASCII value of a character, C, in the given text.
*
* Use case: The entry at index i of R is a list of size: 1 + length of the given text.
* This inner list gives at each index j the next position at which character C will be found
* while traversing the given text from right to left starting from index j.
*/
private static List<List<Integer>> badCharacterTable(String aText) {
if ( aText.isEmpty() ) {
return Collections.emptyList();
}
List<List<Integer>> R = IntStream.range(0, ALPHABET_SIZE).boxed()
.map( i -> new ArrayList<Integer>(Collections.nCopies(1,-1)) ).collect(Collectors.toList());
List<Integer> alpha = new ArrayList<Integer>(Collections.nCopies(ALPHABET_SIZE, -1));
for ( int i = 0; i < aText.length(); i++ ) {
alpha.set(alphabetIndex(aText.charAt(i)), i);
for ( int j = 0; j < alpha.size(); j++ ) {
R.get(j).add(alpha.get(j));
}
}
return R;
}
/**
* Create the fundamental preprocess, Z, of the given text, which is an array such that
* Z[i] is the length of the substring of the given text beginning at index i which is also a prefix of the text.
*/
private static int[] fundamentalPreprocess(String aText) {
if ( aText.isEmpty() ) {
return new int[0];
}
if ( aText.length() == 1 ) {
return new int[] { 1 };
}
int[] Z = new int[aText.length()];
Z[0] = aText.length();
Z[1] = matchLength(aText, 0, 1);
for ( int i = 2; i <= Z[1]; i++ ) {
Z[i] = Z[1] - i + 1;
}
// Define the left and right limits of the z-box
int left = 0;
int right = 0;
for ( int i = 2 + Z[1]; i < aText.length(); i++ ) {
if ( i <= right ) { // i falls within existing z-box
final int k = i - left;
final int b = Z[k];
final int a = right - i + 1;
if ( b < a ) { // b ends within existing z-box
Z[i] = b;
} else { // b ends at or after the end of the z-box,
// an explicit match to the right of the z-box is required
Z[i] = a + matchLength(aText, a, right + 1);
left = i;
right = i + Z[i] - 1;
}
} else { // i does not fall within existing z-box
Z[i] = matchLength(aText, 0, i);
if ( Z[i] > 0 ) {
left = i;
right = i + Z[i] - 1;
}
}
}
return Z;
}
/**
* Return the length of the match of the two substrings of the given text beginning at each of the given indexes.
*/
private static int matchLength(String aText, int aIndexOne, int aIndexTwo) {
if ( aIndexOne == aIndexTwo ) {
return aText.length() - aIndexOne;
}
int matchCount = 0;
while ( aIndexOne < aText.length() && aIndexTwo < aText.length()
&& aText.charAt(aIndexOne) == aText.charAt(aIndexTwo) ) {
matchCount += 1;
aIndexOne += 1;
aIndexTwo += 1;
}
return matchCount;
}
/**
* Return the ASCII index of the given character, if it is such, otherwise throw an illegal argument exception.
*/
private static int alphabetIndex(char aChar) {
final int result = (int) aChar;
if ( result >= ALPHABET_SIZE ) {
throw new IllegalArgumentException("Not an ASCII character:" + aChar);
}
return result;
}
/* The range of ASCII characters is 0..255, both inclusive. */
private static final int ALPHABET_SIZE = 256;
}

View file

@ -0,0 +1,188 @@
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program caresarcode64.s */
/************************************/
/* Constantes */
/************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ KEY, 23
.equ STRINGSIZE, 500
/************************************/
/* Initialized data */
/************************************/
.data
szMessString: .asciz "String :\n"
szMessEncrip: .asciz "\nEncrypted :\n"
szMessDecrip: .asciz "\nDecrypted :\n"
szString1: .asciz "The quick brown fox jumps over the lazy dog."
szCarriageReturn: .asciz "\n"
/************************************/
/* UnInitialized data */
/************************************/
.bss
szString2: .skip STRINGSIZE
szString3: .skip STRINGSIZE
/************************************/
/* code section */
/************************************/
.text
.global main
main:
ldr x0,qAdrszMessString // display message
bl affichageMess
ldr x0,qAdrszString1 // display string
bl affichageMess
ldr x0,qAdrszString1
ldr x1,qAdrszString2
mov x2,#KEY // key
bl encrypt
ldr x0,qAdrszMessEncrip
bl affichageMess
ldr x0,qAdrszString2 // display string
bl affichageMess
ldr x0,qAdrszString2
ldr x1,qAdrszString3
mov x2,#KEY // key
bl decrypt
ldr x0,qAdrszMessDecrip
bl affichageMess
ldr x0,qAdrszString3 // display string
bl affichageMess
ldr x0,qAdrszCarriageReturn
bl affichageMess
100: // standard end of the program
mov x0, #0 // return code
mov x8,EXIT
svc 0 // perform system call
qAdrszMessString: .quad szMessString
qAdrszMessDecrip: .quad szMessDecrip
qAdrszMessEncrip: .quad szMessEncrip
qAdrszString1: .quad szString1
qAdrszString2: .quad szString2
qAdrszString3: .quad szString3
qAdrszCarriageReturn: .quad szCarriageReturn
/******************************************************************/
/* encrypt strings */
/******************************************************************/
/* x0 contains the address of the string1 */
/* x1 contains the address of the encrypted string */
/* x2 contains the key (1-25) */
encrypt:
stp x3,lr,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
mov x3,#0 // counter byte string 1
1:
ldrb w4,[x0,x3] // load byte string 1
cmp w4,#0 // zero final ?
bne 2f
strb w4,[x1,x3]
mov x0,x3
b 100f
2:
cmp w4,#65 // < A ?
bge 3f
strb w4,[x1,x3]
add x3,x3,#1
b 1b // and loop
3:
cmp x4,#90 // > Z
bgt 4f
add x4,x4,x2 // add key
cmp x4,#90 // > Z
sub x5,x4,26
csel x4,x5,x4,gt
//subgt x4,#26
strb w4,[x1,x3]
add x3,x3,#1
b 1b
4:
cmp x4,#97 // < a ?
bge 5f
strb w4,[x1,x3]
add x3,x3,#1
b 1b
5:
cmp x4,#122 //> z
ble 6f
strb w4,[x1,x3]
add x3,x3,#1
b 1b
6:
add x4,x4,x2
cmp x4,#122
sub x5,x4,26
csel x4,x5,x4,gt
//subgt x4,#26
strb w4,[x1,x3]
add x3,x3,#1
b 1b
100:
ldp x4,x5,[sp],16 // restaur registers
ldp x3,lr,[sp],16 // restaur registers
ret
/******************************************************************/
/* decrypt strings */
/******************************************************************/
/* x0 contains the address of the encrypted string1 */
/* x1 contains the address of the decrypted string */
/* x2 contains the key (1-25) */
decrypt:
stp x3,lr,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
mov x3,#0 // counter byte string 1
1:
ldrb w4,[x0,x3] // load byte string 1
cmp x4,#0 // zero final ?
bne 2f
strb w4,[x1,x3]
mov x0,x3
b 100f
2:
cmp x4,#65 // < A ?
bge 3f
strb w4,[x1,x3]
add x3,x3,#1
b 1b // and loop
3:
cmp x4,#90 // > Z
bgt 4f
sub x4,x4,x2 // substract key
cmp x4,#65 // < A
add x5,x4,26
csel x4,x5,x4,lt
//addlt x4,#26
strb w4,[x1,x3]
add x3,x3,#1
b 1b
4:
cmp x4,#97 // < a ?
bge 5f
strb w4,[x1,x3]
add x3,x3,#1
b 1b
5:
cmp x4,#122 // > z
ble 6f
strb w4,[x1,x3]
add x3,x3,#1
b 1b
6:
sub x4,x4,x2 // substract key
cmp x4,#97 // < a
add x5,x4,26
csel x4,x5,x4,lt
//addlt x4,#26
strb w4,[x1,x3]
add x3,x3,#1
b 1b
100:
ldp x4,x5,[sp],16 // restaur registers
ldp x3,lr,[sp],16 // restaur registers
ret
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../includeARM64.inc"

View file

@ -57,7 +57,7 @@ iAdrszMessDecrip: .int szMessDecrip
iAdrszMessEncrip: .int szMessEncrip
iAdrszString1: .int szString1
iAdrszString2: .int szString2
iAdrszString3: .int szString2
iAdrszString3: .int szString3
iAdrszCarriageReturn: .int szCarriageReturn
/******************************************************************/
/* encrypt strings */

View file

@ -0,0 +1,85 @@
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
const char HYPHEN = '-';
const char SPACE = ' ';
const char UNDERSCORE = '_';
const std::string WHITESPACE = " \n\r\t\f\v";
std::string left_trim(const std::string& text) {
size_t start = text.find_first_not_of(WHITESPACE);
return ( start == std::string::npos ) ? "" : text.substr(start);
}
std::string right_trim(const std::string& text) {
size_t end = text.find_last_not_of(WHITESPACE);
return ( end == std::string::npos ) ? "" : text.substr(0, end + 1);
}
std::string trim(const std::string& text) {
return left_trim(right_trim(text));
}
void prepare_for_conversion(std::string& text) {
text = trim(text);
std::replace(text.begin(), text.end(), SPACE, UNDERSCORE);
std::replace(text.begin(), text.end(), HYPHEN, UNDERSCORE);
}
std::string to_snake_case(std::string& camel) {
prepare_for_conversion(camel);
std::string snake = "";
bool first = true;
for ( const char& ch : camel ) {
if ( first ) {
snake += ch;
first = false;
} else if ( ! first && ch >= 'A' && ch <= 'Z' ) {
if ( snake[snake.length() - 1] == UNDERSCORE ) {
snake += tolower(ch);
} else {
snake += UNDERSCORE;
snake += tolower(ch);
}
} else {
snake += ch;
}
}
return snake;
}
std::string to_camel_case(std::string& snake) {
prepare_for_conversion(snake);
std::string camel = "";
bool underscore = false;
for ( const char& ch : snake ) {
if ( ch == UNDERSCORE ) {
underscore = true;
} else if ( underscore ) {
camel += toupper(ch);
underscore = false;
} else {
camel += ch;
}
}
return camel;
}
int main() {
const std::vector<std::string> variable_names = { "snakeCase", "snake_case", "variable_10_case",
"variable10Case", "ergo rE tHis", "hurry-up-joe!", "c://my-docs/happy_Flag-Day/12.doc", " spaces " };
std::cout << std::setw(48) << "=== To snake_case ===" << std::endl;
for ( std::string text : variable_names ) {
std::cout << std::setw(34) << text << " --> " << to_snake_case(text) << std::endl;
}
std::cout << std::endl;
std::cout << std::setw(48) << "=== To camelCase ===" << std::endl;
for ( std::string text : variable_names ) {
std::cout << std::setw(34) << text << " --> " << to_camel_case(text) << std::endl;
}
}

View file

@ -0,0 +1,65 @@
Function isDigit(ch As String) As Boolean
Return ch >= "0" And ch <= "9"
End Function
Function to_snake_case(s As String) As String
Dim As Integer l = Len(s)
Dim As String snake = Trim(s), tmp = snake
For i As Integer = 1 To Len(snake)
If isDigit(Mid(snake, i, 1)) Then
Continue For
Elseif Instr(Mid(snake, i, 1), " ") Then
Mid(snake, i) = "_"
Continue For
Elseif Instr(Mid(snake, i, 1), Any "\:/-_!.") Then
Continue For
Elseif Mid(snake, i, 1) = Ucase(Mid(snake, i, 1)) Then
tmp = Lcase(Mid(snake, i,1))
Mid(snake, i) = "_"
snake = Left(snake, i) & tmp & Mid(snake, i+1)
End If
Next i
Return snake
End Function
Function toCamelCase(s As String) As String
Dim As Integer l = Len(s)
Dim As String camel = Trim(s), tmp = camel
For i As Integer = 1 To Len(camel)
If Instr(Mid(camel, i, 1), Any ":/!.") Then
Continue For
Elseif Instr(Mid(camel, i, 1), Any " _-") Then
camel = Left(camel, i-1) & Ucase(Mid(camel, i+1,1)) & Mid(camel, i+2)
End If
Next i
Return camel
End Function
Dim Shared tests(1 To ...) As String*33 => {_
"snakeCase", "snake_case", "variable_10_case", "variable10Case", _
"\u025brgo rE tHis", "ergo rE tHis", "hurry-up-joe!", _
"c://my-docs/happy_Flag-Day/12.doc", " spaces "}
Sub test0(title As String, fn As String)
Print title
For i As Integer = 1 To Ubound(tests)
Dim As String texto = tests(i) & " ===> " & to_snake_case(tests(i))
Locate i+1, 41 - Len(texto) / 2 : Print texto
Next i
End Sub
Sub test1(title As String, fn As String)
Print title
For i As Integer = 1 To Ubound(tests)
Dim As String texto = tests(i) & " ===> " & toCamelCase(tests(i))
Locate i+12, 41 - Len(texto) / 2 : Print texto
Next i
End Sub
test0 "to_snake_case:", "to_snake_case"
Print
test1 "toCamelCase:", "toCamelCase"
Sleep

View file

@ -0,0 +1,64 @@
import java.util.List;
public final class CamelCaseAndSnakeCase {
public static void main(String[] aArgs) {
List<String> variableNames = List.of( "snakeCase", "snake_case", "variable_10_case", "variable10Case",
"ergo rE tHis", "hurry-up-joe!", "c://my-docs/happy_Flag-Day/12.doc", " spaces ");
System.out.println(String.format("%48s", "=== To snake_case ==="));
for ( String text : variableNames ) {
System.out.println(String.format("%34s%s%s", text, " --> ", toSnakeCase(text)));
}
System.out.println();
System.out.println(String.format("%48s", "=== To camelCase ==="));
for ( String text : variableNames ) {
System.out.println(String.format("%34s%s%s", text, " --> ", toCamelCase(text)));
}
}
private static String toSnakeCase(String aCamel) {
aCamel = aCamel.trim().replace(SPACE, UNDERSCORE).replace(HYPHEN, UNDERSCORE);
StringBuilder snake = new StringBuilder();
boolean first = true;
for ( char ch : aCamel.toCharArray() ) {
if ( first ) {
snake.append(ch);
first = false;
} else if ( ! first && Character.isUpperCase(ch) ) {
if ( snake.toString().endsWith(UNDERSCORE) ) {
snake.append(Character.toLowerCase(ch));
} else {
snake.append(UNDERSCORE + Character.toLowerCase(ch));
}
} else {
snake.append(ch);
}
}
return snake.toString();
}
private static String toCamelCase(String aSnake) {
aSnake = aSnake.trim().replace(SPACE, UNDERSCORE).replace(HYPHEN, UNDERSCORE);
StringBuilder camel = new StringBuilder();
boolean underscore = false;
for ( char ch : aSnake.toCharArray() ) {
if ( Character.toString(ch).equals(UNDERSCORE) ) {
underscore = true;
} else if ( underscore ) {
camel.append(Character.toUpperCase(ch));
underscore = false;
} else {
camel.append(ch);
}
}
return camel.toString();
}
private static final String SPACE = " ";
private static final String UNDERSCORE = "_";
private static final String HYPHEN = "-";
}

View file

@ -0,0 +1,17 @@
^|ord and chr work with Unicode code points|^
writeLine(ord("a")) # prints "97"
writeLine(chr(97)) # prints "a"
writeLine(ord("π")) # prints "960"
writeLine(chr(960)) # prints "π"
writeLine()
var cps = int[]
for each var c in text["a", "π", "字", "🐘"]
var cp = ord(c)
cps.append(cp)
writeLine(c + " = " + cp)
end
writeLine()
for each int i in cps
var c = chr(i)
writeLine(i + " = " + c)
end

View file

@ -0,0 +1,125 @@
_window = 1
begin enum 1
_numView
_numFld
end enum
_numHeight = 54
_lineLength = _numHeight/3
void local fn BuildWindow
window _window, @"Cistercian Numerals",, NSWindowStyleMaskTitled + NSWindowStyleMaskClosable + NSWindowStyleMaskMiniaturizable
subclass view _numView, (237,153,76,94)
ViewSetFlipped( _numView, YES )
textfield _numFld,, @"0", (237,20,76,21)
ControlSetAlignment( _numFld, NSTextAlignmentCenter )
ControlSetFormat( _numFld, @"0123456789", YES, 4, 0 )
WindowMakeFirstResponder( _window, _numFld )
end fn
void local fn PathDraw( path as BezierPathRef, lines as CFStringRef, x as CGFloat, y as CGFloat )
CGPoint pt1, pt2
long i
for i = 0 to 4
if ( intval(mid(lines,i,1)) )
select ( i )
case 0
pt1 = fn CGPointMake( x + _lineLength, y )
pt2 = fn CGPointMake( x + _lineLength, y + _lineLength )
case 1
pt1 = fn CGPointMake( x, y + _lineLength )
pt2 = fn CGPointMake( x + _lineLength, y )
case 2
pt1 = fn CGPointMake( x, y )
pt2 = fn CGPointMake( x + _lineLength, y + _lineLength )
case 3
pt1 = fn CGPointMake( x, y + _lineLength )
pt2 = fn CGPointMake( x + _lineLength, y + _lineLength )
case 4
pt1 = fn CGPointMake( x, y )
pt2 = fn CGPointMake( x + _lineLength, y )
end select
BezierPathMoveToPoint( path, pt1 )
BezierPathLineToPoint( path, pt2 )
end if
next
end fn
void local fn ViewDrawRect
CFArrayRef lines = @[@"00001",@"00010",@"00100",@"01000",@"01001",@"10000",@"10001",@"10010",@"10011"]
CFStringRef numString = fn ViewProperty( _numView, @"num" )
if ( numString )
CGFloat x = 38, y = 20
long i
for i = 0 to 3
BezierPathRef path = fn BezierPathWithRect( fn ViewBounds(_numView) )
BezierPathMoveToPoint( path, fn CGPointMake( x, y ) )
BezierPathLineToPoint( path, fn CGPointMake( x, y + _numHeight ) )
long num = intval( mid( numString, i, 1 ) )
if ( num )
fn PathDraw( path, lines[num-1], x, y )
if ( i < 3 )
CGFloat xScale = 1.0, yScale = 1.0
select ( i )
case 0 : xScale = -1.0 : yScale = -1.0 // 1000
case 1 : yScale = -1.0 // 100
case 2 : xScale = -1.0 // 10
end select
CGRect bounds = fn BezierPathBounds( path )
AffineTransformRef tx = fn AffineTransformInit
AffineTransformScaleXY( tx, xScale, yScale )
if ( xScale < 0.0 ) then AffineTransformTranslate( tx, -bounds.origin.x-bounds.size.width, 0.0 )
if ( yScale < 0.0 ) then AffineTransformTranslate( tx, 0.0, -bounds.size.height )
BezierPathTransformUsingAffineTranform( path, tx )
end if
end if
BezierPathStroke( path )
next
end if
end fn
void local fn DrawAction
CFStringRef string = fn StringWithFormat( @"%.4ld", fn ControlIntegerValue( _numFld ) )
ViewSetProperty( _numView, @"num", string )
ViewSetNeedsDisplay( _numView )
end fn
void local fn DoAppEvent( ev as long )
select ( ev )
case _appDidFinishLaunching
fn BuildWindow
fn DrawAction
case _appShouldTerminateAfterLastWindowClosed : AppEventSetBool(YES)
end select
end fn
void local fn DoDialog( ev as long, tag as long, wnd as long )
select ( ev )
case _btnClick
select ( tag )
case _numFld : fn DrawAction
end select
case _viewDrawRect
select ( tag )
case _numView : fn ViewDrawRect
end select
end select
end fn
on appevent fn DoAppEvent
on dialog fn DoDialog
HandleEvents

View file

@ -0,0 +1,91 @@
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <vector>
std::vector<uint32_t> count(8, 0);
std::vector<bool> used(10, false);
uint32_t largest = 0;
bool is_colorful(uint32_t number) {
if ( number > 98'765'432 ) {
return false;
}
std::vector<uint32_t> digit_count(10, 0);
std::vector<uint32_t> digits(8, 0);
uint32_t number_digits = 0;
for ( uint32_t i = number; i > 0; i /= 10 ) {
uint32_t digit = i % 10;
if ( number > 9 && ( digit == 0 || digit == 1 ) ) {
return false;
}
if ( ++digit_count[digit] > 1 ) {
return false;
}
digits[number_digits++] = digit;
}
std::vector<uint32_t> products(36, 0);
for ( uint32_t i = 0, product_count = 0; i < number_digits; ++i ) {
for ( uint32_t j = i, product = 1; j < number_digits; ++j ) {
product *= digits[j];
for ( uint32_t k = 0; k < product_count; ++k ) {
if ( products[k] == product ) {
return false;
}
}
products[product_count++] = product;
}
}
return true;
}
void count_colorful(uint32_t taken, uint32_t number, uint32_t digits) {
if ( taken == 0 ) {
for ( uint32_t digit = 0; digit < 10; ++digit ) {
used[digit] = true;
count_colorful(digit < 2 ? 9 : 1, digit, 1);
used[digit] = false;
}
} else {
if ( is_colorful(number) ) {
++count[digits - 1];
if ( number > largest ) {
largest = number;
}
}
if ( taken < 9 ) {
for ( uint32_t digit = 2; digit < 10; ++digit ) {
if ( ! used[digit] ) {
used[digit] = true;
count_colorful(taken + 1, number * 10 + digit, digits + 1);
used[digit] = false;
}
}
}
}
}
int main() {
std::cout << "Colorful numbers less than 100:" << std::endl;
for ( uint32_t number = 0, count = 0; number < 100; ++number ) {
if ( is_colorful(number) ) {
std::cout << std::setw(2) << number << ( ++count % 10 == 0 ? "\n" : " ");
}
}
std::cout << "\n" << std::endl;
count_colorful(0, 0, 0);
std::cout << "Count of colorful numbers by number of digits:" << std::endl;
uint32_t total = 0;
for ( uint32_t digit = 0; digit < 8; ++digit ) {
std::cout << digit + 1 << ": " << count[digit] << std::endl;
total += count[digit];
}
std::cout << std::endl;
std::cout << "The largest possible colorful number is: " << largest << "\n" << std::endl;
std::cout << "The total number of colorful numbers is: " << total << std::endl;
}

View file

@ -0,0 +1,47 @@
/*REXX program displays combination sets for X things taken Y at a time. */
Parse Arg things size characters
If things='?' Then Do
Say 'rexx combi2 things size characters'
Say ' defaults: 5 3 123456789...'
Say 'example rexx combi2 , , xyzuvw'
Say 'size<0 shows only the number of possible combinations'
Exit
End
If things==''|things=="," Then things=5 /* No things specified? Then use default*/
If size=='' |size=="," Then size=3 /* No size specified? Then use default*/
Numeric Digits 20
show=sign(size)
size=abs(size)
If things<size Then
Call exit 'Not enough things ('things') for size ('size').' Say '----------' things 'things taken' size 'at a time:'
n=2**things-1
nc=0
Do u=1 to n
nc=nc+combinations(u)
End
Say '------------' nc 'combinations.'
Exit
combinations: Procedure Expose things size characters show
Parse Arg u
nc=0
bu=x2b(d2x(u))
bu1=space(translate(bu,' ',0),0)
If length(bu1)=size Then Do
ub=reverse(bu)
res=''
Do i=1 To things
If characters<>'' then
c=substr(characters,i,1)
Else
c=i
If substr(ub,i,1)=1 Then res=res c
End
If show=1 then
Say res
Return 1
End
Else
Return 0
exit:
Say '*****error*****' arg(1)
Exit 13

View file

@ -0,0 +1,20 @@
local fn CommaQuibbler( s as CFArrayRef ) as CFStringRef
CFStringRef result = NULL
select ( len(s) )
case 0: exit fn = @"{}"
case 1: exit fn = fn StringWithFormat( @"{%@}", s[0] )
case 2: exit fn = fn StringWithFormat( @"{%@ and %@}", s[0], s[1] )
case else
result = fn StringWithFormat( @"{%@}", fn ArrayComponentsJoinedByString( s, @", " ) )
CFRange lastComma = fn StringRangeOfStringWithOptions( result, @",", NSBackwardsSearch )
result = fn StringByReplacingCharactersInRange( result, lastComma, @" and" )
end select
end fn = result
print fn CommaQuibbler( @[] )
print fn CommaQuibbler( @[@"ABC"] )
print fn CommaQuibbler( @[@"ABC", @"DEF"] )
print fn CommaQuibbler( @[@"ABC", @"DEF", @"G", @"H"] )
HandleEvents

View file

@ -1,15 +1,25 @@
import Data.List (intercalate)
quibble :: [String] -> String
quibble ws
| length ws > 1 =
intercalate
" and "
([intercalate ", " . reverse . tail, head] <*> [reverse ws])
| otherwise = concat ws
--------------------- COMMA QUIBBLING --------------------
quibble :: [String] -> String
quibble ws@(_ : _ : _) =
intercalate
" and "
( [intercalate ", " . reverse . tail, head]
<*> [reverse ws]
)
quibble xs = concat xs
--------------------------- TEST -------------------------
main :: IO ()
main =
mapM_ (putStrLn . (`intercalate` ["{", "}"]) . quibble) $
[[], ["ABC"], ["ABC", "DEF"], ["ABC", "DEF", "G", "H"]] ++
(words <$> ["One two three four", "Me myself I", "Jack Jill", "Loner"])
[[], ["ABC"], ["ABC", "DEF"], ["ABC", "DEF", "G", "H"]]
<> ( words
<$> [ "One two three four",
"Me myself I",
"Jack Jill",
"Loner"
]
)

View file

@ -0,0 +1,49 @@
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program commandLine64.s */
/************************************/
/* Constantes */
/************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/************************************/
/* Initialized data */
/************************************/
.data
szCarriageReturn: .asciz "\n"
/************************************/
/* UnInitialized data */
/************************************/
.bss
.align 4
/************************************/
/* code section */
/************************************/
.text
.global main
main: // entry of program
mov fp,sp // fp <- start address
ldr x4,[fp] // number of Command line arguments
add x5,fp,#8 // first parameter address
mov x2,#0 // init loop counter
1:
ldr x0,[x5,x2,lsl #3] // string address parameter
bl affichageMess // display string
ldr x0,qAdrszCarriageReturn
bl affichageMess // display carriage return
add x2,x2,#1 // increment counter
cmp x2,x4 // number parameters ?
blt 1b // loop
100: // standard end of the program
mov x0, #0 // return code
mov x8,EXIT
svc 0 // perform the system call
qAdrszCarriageReturn: .quad szCarriageReturn
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeARM64.inc"

View file

@ -0,0 +1,27 @@
void local fn StringHasUniqueCharacters( string as CFStringRef )
long i, j, length = len( string )
if length == 0 then printf @"The string \"\" is empty and thus has no characters to compare.\n" : exit fn
printf @"The string: \"%@\" has %ld characters.", string, length
for i = 0 to length - 1
for j = i + 1 to length - 1
if ( fn StringIsEqual( mid( string, i, 1 ), mid( string, j, 1 ) ) )
CFStringRef duplicate = mid( string, i, 1 )
printf @"The first duplicate character, \"%@\", is found at positions %ld and %ld.", duplicate, i, j
printf @"The hex value of \"%@\" is: 0X%x\n", duplicate, fn StringCharacterAtIndex( duplicate, 0 )
exit fn
end if
next
next
printf @"All characters in string are unique.\n"
end fn
fn StringHasUniqueCharacters( @"" )
fn StringHasUniqueCharacters( @"." )
fn StringHasUniqueCharacters( @"abcABC" )
fn StringHasUniqueCharacters( @"XYZ ZYX" )
fn StringHasUniqueCharacters( @"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ" )
HandleEvents

View file

@ -1,93 +1,62 @@
;; Path format: (start-point end-point previous-point distance)
(setq path-list `(
(a b ,nil 7)
(a c ,nil 9)
(a f ,nil 14)
(b c ,nil 10)
(b d ,nil 15)
(c d ,nil 11)
(c f ,nil 2)
(d e ,nil 6)
(e f ,nil 9)
))
(defvar path-list '((a b 7)
(a c 9)
(a f 14)
(b c 10)
(b d 15)
(c d 11)
(c f 2)
(d e 6)
(e f 9)))
(defun calculate-shortest-path ()
(let ((shortest-path '())
(head-point (nth 0 (nth 0 path-list))))
(defun combine-new-path (path1 path2)
(list (nth 0 path1) (nth 1 path2) (nth 0 path2)
(+ (nth 3 path1) (nth 3 path2))) )
(defun find-shortest-path (start end)
(seq-find (lambda (item)
(and (eq (nth 0 item) start) (eq (nth 1 item) end)))
shortest-path)
)
(defun add-shortest-path (item)
(add-to-list 'shortest-path item) )
(defun process-path (path)
(if (eq head-point (nth 0 path))
(add-to-list 'shortest-path path)
(progn
(dolist (spath shortest-path)
(when (eq (nth 1 spath) (nth 0 path))
(let* ((new-path (combine-new-path spath path))
(spath-found (find-shortest-path (nth 0 new-path)
(nth 1 new-path))))
(if spath-found
(when (< (nth 3 new-path) (nth 3 spath-found))
(setcdr (nthcdr 1 spath-found) (list (nth 2 new-path) (nth 3 new-path)))
)
(add-shortest-path new-path)) ) ) ) ) ) )
(defun find-shortest-route (start end)
(let ((point-list '())
(end-point end)
path-found)
(add-to-list 'point-list end)
(catch 'no-more-path
(while 't
(setq path-found (find-shortest-path start end-point))
(if (or (not path-found) (not (nth 2 path-found)))
(throw 'no-more-path nil)
(progn
(add-to-list 'point-list (nth 2 path-found))
(setq end-point (nth 2 path-found)) )
)
)
)
(add-to-list 'point-list start)
)
)
(defun show-shortest-path (start end)
(let ((path-found (find-shortest-path start end))
(route-found (find-shortest-route start end)))
(if path-found
(progn
(message "shortest distance: %s" (nth 3 path-found))
(message "shortest route: %s" route-found) )
(message "shortest path not found") )
)
(message "--") )
;; Process each path
(defun calculate-shortest-path (path-list)
(let (shortest-path)
(dolist (path path-list)
(process-path path) )
(add-to-list 'shortest-path (list (nth 0 path)
(nth 1 path)
nil
(nth 2 path))
't))
(message "from %s to %s:" 'a 'e)
(show-shortest-path 'a 'e)
(message "from %s to %s:" 'a 'f)
(show-shortest-path 'a 'f)
(dolist (path path-list)
(dolist (short-path shortest-path)
)
)
(when (equal (nth 0 path) (nth 1 short-path))
(let ((test-path (list (nth 0 short-path)
(nth 1 path)
(nth 0 path)
(+ (nth 2 path) (nth 3 short-path))))
is-path-found)
(calculate-shortest-path)
(dolist (short-path1 shortest-path)
(when (equal (seq-take test-path 2)
(seq-take short-path1 2))
(setq is-path-found 't)
(when (> (nth 3 short-path1) (nth 3 test-path))
(setcdr (cdr short-path1) (cddr test-path)))))
(when (not is-path-found)
(add-to-list 'shortest-path test-path 't))))))
shortest-path))
(defun find-shortest-route (from to path-list)
(let ((shortest-path-list (calculate-shortest-path path-list))
point-list matched-path distance)
(add-to-list 'point-list to)
(setq matched-path
(seq-find (lambda (path) (equal (list from to) (seq-take path 2)))
shortest-path-list))
(setq distance (nth 3 matched-path))
(while (nth 2 matched-path)
(add-to-list 'point-list (nth 2 matched-path))
(setq to (nth 2 matched-path))
(setq matched-path
(seq-find (lambda (path) (equal (list from to) (seq-take path 2)))
shortest-path-list)))
(if matched-path
(progn
(add-to-list 'point-list from)
(list 'route point-list 'distance distance))
nil)))
(format "%S" (find-shortest-route 'a 'e path-list))

View file

@ -0,0 +1,73 @@
include "Tlbx SceneKit.incl"
_window = 1
begin enum output 1
_sceneView
end enum
local fn Cuboid as SCNSceneRef
SCNSceneRef scene = fn SCNSceneInit
SCNNodeRef rootNode = fn SCNSceneRootNode( scene )
SCNCameraRef camera = fn SCNCameraInit
SCNNodeRef cameraNode = fn SCNNodeInit
SCNNodeSetCamera( cameraNode, camera )
SCNNodeAddChildNode( rootNode, cameraNode )
SCNVector3 cameraPos = {0.0, 0.0, 10.0}
SCNNodeSetPosition( cameraNode, cameraPos )
SCNNodeRef lightNode = fn SCNNodeInit
SCNLightRef light = fn SCNLightInit
SCNLightSetType( light, SCNLightTypeOmni )
SCNNodeSetPosition( lightNode, fn SCNVector3Make( 0.0, 10.0, 10.0 ) )
SCNNodeAddChildNode( rootNode, lightNode )
SCNNodeRef ambientLightNode = fn SCNNodeInit
SCNLightRef ambientLight = fn SCNLightInit
SCNLightSetType( ambientLight, SCNLightTypeAmbient )
SCNLightSetColor( ambientLight, fn ColorGray )
SCNNodeSetLight( ambientLightNode, ambientLight )
SCNNodeAddChildNode( rootNode, ambientLightNode )
SCNBoxRef boxGeometry = fn SCNBoxInit( 2.0, 3.0, 4.0, 0.0 )
SCNNodeRef boxNode = fn SCNNodeWithGeometry( boxGeometry )
SCNMaterialRef side1 = fn SCNMaterialInit
SCNMaterialRef side2 = fn SCNMaterialInit
SCNMaterialRef side3 = fn SCNMaterialInit
SCNMaterialRef side4 = fn SCNMaterialInit
SCNMaterialRef side5 = fn SCNMaterialInit
SCNMaterialRef side6 = fn SCNMaterialInit
SCNMaterialPropertySetContents( fn SCNMaterialMultiply( side1 ), fn ColorBlue )
SCNMaterialPropertySetContents( fn SCNMaterialMultiply( side2 ), fn ColorOrange )
SCNMaterialPropertySetContents( fn SCNMaterialMultiply( side3 ), fn ColorRed )
SCNMaterialPropertySetContents( fn SCNMaterialMultiply( side4 ), fn ColorGreen )
SCNMaterialPropertySetContents( fn SCNMaterialMultiply( side5 ), fn ColorYellow )
SCNMaterialPropertySetContents( fn SCNMaterialMultiply( side6 ), fn ColorCyan )
SCNGeometrySetMaterials( boxGeometry, @[side1,side2,side3,side4,side5,side6] )
SCNNodeAddChildNode( rootNode, boxNode )
SCNActionableRunAction( boxNode, fn SCNActionRotateByAngle( M_PI, fn SCNVector3Make( 1.0, 1.0, 1.0 ), 0.0 ) )
end fn = scene
void local fn BuildWindow
CGRect r = fn CGRectMake( 0, 0, 400, 400 )
window _window, @"Rosetta Code 2-3-4 Cuboid", r
scnview _sceneView, fn Cuboid, r
SCNViewSetBackgroundColor( _sceneView, fn ColorBlack )
SCNViewSetAllowsCameraControl( _sceneView, YES )
end fn
void local fn DoDialog( ev as long, tag as long, wnd as long )
select (ev)
case _windowWillClose : end
end select
end fn
on dialog fn DoDialog
fn BuildWindow
HandleEvents

View file

@ -0,0 +1,2 @@
2x (, <./@(>:&.(*/)))@[&_~ 15
2 3 7 43 13 53 5 6221671 38709183810571 139 2801 11 17 5471 52662739 23003

View file

@ -0,0 +1,4 @@
defn factorial(x):
apply(*): (2 .. x)
say: factorial(10)

View file

@ -0,0 +1,96 @@
;-------------------------------------------------------
; useful equates
;-------------------------------------------------------
bdos equ 5 ; BDOS entry
cr equ 13 ; ASCII carriage return
lf equ 10 ; ASCII line feed
space equ 32 ; ASCII space char
conout equ 2 ; BDOS console output function
putstr equ 9 ; BDOS print string function
;-------------------------------------------------------
; program code begins here
;-------------------------------------------------------
org 100h ; load point under CP/M
lxi h,0 ; save command processor's stack
dad sp
shld oldstk
lxi sp,stack ; set our own stack
lxi d,signon ; print signon message
mvi c,putstr
call bdos
mvi a,1 ; test by displaying first 20
mloop: push a ; save our count (putdec will trash)
call fib
call putdec
mvi a,space ; separate the numbers
call putchr
pop a ; get our count back
inr a ; increase it by one
cpi 20+1 ; have we reached our limit?
jnz mloop ; not yet; do another
lhld oldstk ; we're done - get CP/M's stack back
sphl ; restore it
ret ; back to command processor
;-------------------------------------------------------
; calculate nth Fibonacci number
; entry: A = n
; exit: HL = Fib(n)
;-------------------------------------------------------
fib: mov c,a ; C holds n
lxi d,0 ; initial value for Fib(n-2)
lxi h,1 ; intiial value for Fib(n-1)
fib2: dcr c
jz fib3 ; we're done
push h ; save Fib(n-1)
dad d ; HL holds Fib(n)
pop d ; Former Fib(n-1) now Fib(n-2)
jmp fib2 ; loop until done
fib3: ret
;-------------------------------------------------------
; console output of char in A register
;-------------------------------------------------------
putchr:
push h
push d
push b
mov e,a
mvi c,conout
call bdos
pop b
pop d
pop h
ret
;---------------------------------------------------------
; Output decimal number to console
; HL holds 16-bit unsigned binary number to print
;---------------------------------------------------------
putdec: push b
push d
push h
lxi b,-10
lxi d,-1
putdec2:
dad b
inx d
jc putdec2
lxi b,10
dad b
xchg
mov a,h
ora l
cnz putdec ; recursive call
mov a,e
adi '0'
call putchr
pop h
pop d
pop b
ret
;-------------------------------------------------------
; message and data area
;-------------------------------------------------------
signon: db 'First 20 Fibonacci numbers:',cr,lf,'$'
oldstk: dw 0
stack equ $+128 ; 64-level stack
;
end

View file

@ -0,0 +1,4 @@
loop [a 0, b 1, i 1 ]:
say: a
(i < 10) ?:
^^^: b, (a + b), (i + 1)

View file

@ -0,0 +1,10 @@
local fn DoIt
CFURLRef desktopURL = fn FileManagerURLForDirectory( NSDesktopDirectory, NSUserDomainMask )
CFURLRef url = fn URLByAppendingPathComponent( desktopURL, @"test_file.txt" )
CFDictionaryRef attributes = fn FileManagerAttributesOfItemAtURL( url )
printf @"%@", fn DictionaryObjectForKey( attributes, NSFileSize )
end fn
fn DoIt
HandleEvents

View file

@ -0,0 +1,172 @@
(* The principle employed here is to treat the triangle as a convex
hull oriented counterclockwise. Then a point is inside the hull if
it is to the left of every side of the hull.
This will prove easy to determine. Because the sine is positive in
quadrants 1 and 2 and negative in quadrants 3 and 4, the sideness
of a point can be determined by the sign of an outer product of
vectors. Or you can use any such trigonometric method, including
those that employ an inner product.
Suppose one side of the triangle goes from point p0 to point p1,
and that the point we are testing for leftness is p2. Then we
compute the geometric outer product
(p1 - p0)∧(p2 - p0)
(or equivalently the cross product of Gibbs vector analysis) and
test the sign of its grade-2 component (or the sign of the
right-hand-rule Gibbs pseudovector along the z-axis). If the sign
is positive, then p2 is left of the side, because the sine of the
angle between the vectors is positive.
The algorithm considers the vertices and sides of the triangle as
as NOT inside the triangle.
Our algorithm is the same as that of the Common Lisp. We merely
have dressed it up in prêt-à-porter fashion and costume jewelry. *)
#include "share/atspre_staload.hats"
#define COUNTERCLOCKWISE 1
#define COLLINEAR 0
#define CLOCKWISE ~1
(* We will use some simple Euclidean geometric algebra. *)
typedef vector =
(* This type will represent either a point relative to the origin or
the difference between two points. The e1 component is the x-axis
and the e2 component is the y-axis. *)
@{e1 = double, e2 = double}
typedef rotor =
(* This type is analogous to a pseudovectors, complex numbers, and
so forth. It will be used to represent the outer product. *)
@{scalar = double, e1_e2 = double}
typedef triangle = @(vector, vector, vector)
fn
vector_sub (a : vector, b : vector) : vector =
@{e1 = a.e1 - b.e1, e2 = a.e2 - b.e2}
overload - with vector_sub
fn
outer_product (a : vector, b : vector) : rotor =
@{scalar = 0.0, (* The scalar term vanishes. *)
e1_e2 = a.e1 * b.e2 - a.e2 * b.e1}
fn
is_left_of (pt : vector,
side : @(vector, vector)) =
let
val r = outer_product (side.1 - side.0, pt - side.0)
in
r.e1_e2 > 0.0
end
fn
orient_triangle {orientation : int | abs (orientation) == 1}
(t : triangle,
orientation : int orientation) : triangle =
(* Return an equivalent triangle that is definitely either
counterclockwise or clockwise, unless the original was
collinear. If the original was collinear, return it unchanged. *)
let
val @(p1, p2, p3) = t
(* If the triangle is counterclockwise, the grade-2 component of
the following outer product will be positive. *)
val r = outer_product (p2 - p1, p3 - p1)
in
if r.e1_e2 = 0.0 then
t
else
let
val sign =
(if r.e1_e2 > 0.0 then COUNTERCLOCKWISE else CLOCKWISE)
: [sign : int | abs sign == 1] int sign
in
if orientation = sign then t else @(p1, p3, p2)
end
end
fn
is_inside_triangle (pt : vector,
t : triangle) : bool =
let
val @(p1, p2, p3) = orient_triangle (t, COUNTERCLOCKWISE)
in
is_left_of (pt, @(p1, p2))
&& is_left_of (pt, @(p2, p3))
&& is_left_of (pt, @(p3, p1))
end
fn
fprint_vector (outf : FILEref,
v : vector) : void =
fprint! (outf, "(", v.e1, ",", v.e2, ")")
fn
fprint_triangle (outf : FILEref,
t : triangle) : void =
begin
fprint_vector (outf, t.0);
fprint! (outf, "--");
fprint_vector (outf, t.1);
fprint! (outf, "--");
fprint_vector (outf, t.2);
fprint! (outf, "--cycle")
end
fn
try_it (outf : FILEref,
pt : vector,
t : triangle) : void =
begin
fprint_vector (outf, pt);
fprint! (outf, " is inside ");
fprint_triangle (outf, t);
fprintln! (outf);
fprintln! (outf, is_inside_triangle (pt, t))
end
implement
main () =
let
val outf = stdout_ref
val t1 = @(@{e1 = 1.5, e2 = 2.4},
@{e1 = 5.1, e2 = ~3.1},
@{e1 = ~3.8, e2 = 1.2})
val p1 = @{e1 = 0.0, e2 = 0.0}
val p2 = @{e1 = 0.0, e2 = 1.0}
val p3 = @{e1 = 3.0, e2 = 1.0}
val p4 = @{e1 = 1.5, e2 = 2.4}
val p5 = @{e1 = 5.414286, e2 = 14.349206}
val t2 = @(@{e1 = 0.100000, e2 = 0.111111},
@{e1 = 12.500000, e2 = 33.333333},
@{e1 = 25.000000, e2 = 11.111111})
val t3 = @(@{e1 = 0.100000, e2 = 0.111111},
@{e1 = 12.500000, e2 = 33.333333},
@{e1 = ~12.500000, e2 = 16.666667})
in
try_it (outf, p1, t1);
try_it (outf, p2, t1);
try_it (outf, p3, t1);
try_it (outf, p4, t1);
fprintln! (outf);
try_it (outf, p5, t2);
fprintln! (outf);
fprintln! (outf, "Some programs are returning TRUE for ",
"the following. The Common Lisp uses");
fprintln! (outf, "the same",
" algorithm we do (presented differently),",
" and returns FALSE.");
fprintln! (outf);
try_it (outf, p5, t3);
0
end

View file

@ -1,9 +1,9 @@
map:
- (x):
- println:
- cond: [
zero?(mod(x 15)), "FizzBuzz",
zero?(mod(x 5)), "Buzz",
zero?(mod(x 3)), "Fizz",
:else, x ]
- range(1, 101)
map(say):
map:
- fn (x):
s =:
str:
- (zero? mod(x 3)) ?: "Fizz"
- (zero? mod(x 5)) ?: "Buzz"
if (empty? s): x, s
- (1 .. 100)

View file

@ -1,9 +1,9 @@
loop [i 1]:
- println:
cond(
zero?(mod(i 15)) "FizzBuzz"
zero?(mod(i 5)) "Buzz"
zero?(mod(i 3)) "Fizz"
:else i)
- if (i < 100):
recur: inc(i)
map(say):
map:
- fn (x):
???:
zero?(mod(x 15)) : "FizzBuzz"
zero?(mod(x 5)) : "Buzz"
zero?(mod(x 3)) : "Fizz"
:else: x
- (1 .. 100)

View file

@ -1,9 +1,13 @@
map:
- (x):
- s =:
str:
- if (zero? mod(x 3)): "Fizz"
- if (zero? mod(x 5)): "Buzz"
- println:
if (empty? s): [x, s]
- range(1 101)
map(say):
loop [i 1, l []]:
if (i > 100):
- l
- ^^^:
- inc(i)
- conj:
- l
- ???:
zero?(mod(i 15)) : "FizzBuzz"
zero?(mod(i 5)) : "Buzz"
zero?(mod(i 3)) : "Fizz"
:else: i

View file

@ -1,27 +1,22 @@
100 RANDOMIZE
110 LET T = 0
120 LET N = 20
130 LET R = INT(RND *N)+1
130 LET R = INT(RND*N)+1
140 PRINT "GUESS A WHOLE NUMBER BETWEEN 1 AND";N
150 REM LOOP
160 LET T = T+1
170 PRINT "ENTER YOUR NUMBER ";
180 INPUT G
190 IF G <> R THEN 220
200 PRINT "YOU GUESSED IT IN";T;"TRIES."
210 GOTO 360
220 REM ENDIF
230 IF G > R THEN 260
240 IF G < 1 THEN 260
250 PRINT "SORRY, YOUR NUMBER WAS TOO LOW"
260 REM ENDIF
270 IF G < R THEN 300
280 IF G > 100 THEN 300
290 PRINT "SORRY, YOUR NUMBER WAS TOO HIGH"
300 REM ENDIF
310 IF G >= 1 THEN 320
320 IF G <= 100 THEN 340
330 PRINT "THAT WAS AN INVALID NUMBER"
340 REM ENDIF
350 IF G <> R THEN 150
360 END
150 LET T = T+1
160 PRINT "ENTER YOUR NUMBER ";
170 INPUT G
180 IF G <> R THEN 210
190 PRINT "YOU GUESSED IT IN";T;"TRIES."
200 GOTO 310
210 IF G > R THEN 240
220 IF G < 1 THEN 240
230 PRINT "SORRY, YOUR NUMBER WAS TOO LOW"
240 IF G < R THEN 270
250 IF G > 100 THEN 270
260 PRINT "SORRY, YOUR NUMBER WAS TOO HIGH"
270 IF G >= 1 THEN 300
280 IF G <= 100 THEN 300
290 PRINT "THAT WAS AN INVALID NUMBER"
300 IF G <> R THEN 140
310 END

View file

@ -0,0 +1,25 @@
include "NSLog.incl"
#plist NSAppTransportSecurity @{NSAllowsArbitraryLoads:YES}
local fn URLSessionHandler( session as URLSessionRef, dta as CFDataRef, response as URLResponseRef, err as ErrorRef, userData as ptr )
if ( fn HTTPURLResponseStatusCode( (HTTPURLResponseRef)response ) == 200 )
NSLog( @"%@", fn StringWithData( dta, NSUTF8StringEncoding ) )
else
NSLog( @"%@", fn ErrorLocalizedDescription( err ) )
end if
NSLogScrollToTop
end fn
local fn URLSessionWithGetRequest( path as CFStringRef )
CFURLRef url = fn URLWithString( path )
MutableURLRequestRef urlRequest = fn MutableURLRequestWithURL( url )
MutableURLRequestSetHTTPMethod( urlRequest, @"HTTP" )
URLSessionRef session = fn URLSessionSharedSession
URLSessionDataTaskRef task = fn URLSessionDataTaskWithRequestCompletionHandler( session, urlRequest, @fn URLSessionHandler, NULL )
URLSessionTaskResume( task )
end fn
fn URLSessionWithGetRequest( @"http://rosettacode.org" )
HandleEvents

View file

@ -0,0 +1 @@
10 PRINT "Hello World"

View file

@ -0,0 +1 @@
(println "Hello world!")

View file

@ -0,0 +1,3 @@
# The . at the start of a value is way to indicate that the value is a scalar (string).
# Without the . this would be invalid YAML(Script).
say: ."Hello", "world!"

View file

@ -0,0 +1 @@
(say "Hello world!")

View file

@ -0,0 +1 @@
say("Hello world!")

View file

@ -0,0 +1 @@
say("Hello world!"):

View file

@ -0,0 +1,2 @@
say:
- "Hello world!"

View file

@ -0,0 +1 @@
say: ["Hello world!"]

View file

@ -0,0 +1 @@
say: "Hello world!"

View file

@ -0,0 +1 @@
say("Hello"): "world!"

View file

@ -0,0 +1 @@
say: ["Hello", "world!"]

View file

@ -0,0 +1,16 @@
PROGRAM endianness
IMPLICIT NONE
INTEGER(KIND=4) :: i = 1
!ISHFT(INTEGER, SHIFT) : Left shift if SHIFT > 0
!ISHFT(INTEGER, SHIFT) : Right shift if SHIFT < 0
IF (ISHFT(i,1) .EQ. 0) THEN
WRITE(*,FMT='(A)') 'Architechture is Big Endian'
ELSE
WRITE(*,FMT='(A)') 'Architecture is Little Endian'
END IF
RETURN
STOP
END PROGRAM endianness

View file

@ -0,0 +1,11 @@
10 REM JOSEPHUS PROBLEM
20 LET N=41,K=3,M=0
30 GOSUB 100
40 PRINT #1,"N =",N,", K =",K,", FINAL SURVIVOR =",L
50 STOP
90 REM ** JOSEPHUS
100 LET L=M
110 FOR A=M+1 TO N
120 LET L=L+K-((L+K)/A)*A
130 NEXT A
140 RETURN

View file

@ -0,0 +1,807 @@
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program kdtree64.s */
/* the coordinates of the points are integers numbers.
The displayed distance represents the square of the distance between 2 points */
/* This program draws heavily from the published C program. Thanks to its creator. */
/************************************/
/* Constantes */
/************************************/
.include "../includeConstantesARM64.inc"
.equ MAXI, 3
.equ NBPOINTSRAND, 2000
.equ MAXCOORD, 10000
/***********************************************/
/* structures */
/**********************************************/
/* Définition node */
.struct 0
nodeKD_val: // value array
.struct nodeKD_val + (8 * MAXI)
nodeKD_left: // left pointer
.struct nodeKD_left + 8
nodeKD_right: // right pointer
.struct nodeKD_right + 8
nodeKD_end:
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessAddressTree: .asciz "Node address : "
szMessTreeValue: .asciz " Value : "
szMessLeft: .asciz " Left : "
szMessRight: .asciz " Right : "
szMessResult: .asciz "Nearest point = "
szMessRandCoor: .asciz "\n\nRandom point coordonnés = "
szMessVisited: .asciz "Node visited = "
szMessDistance: .asciz "square distance :"
szMessStart: .asciz "Program 64 bits start.\n"
szCarriageReturn: .asciz "\n"
.align 4
tabPoint1: .quad 2,3, 5,4, 9,6, 4,7, 8,1, 7,2
//tabPoint1: .quad 1,7, 3,4, 4,6, 6,2, 8,12, 10,9, 12,3, 14,1
//tabPoint1: .quad 3,5, 1,3, 2,8, 4,6, 5,4
.equ NBPOINTS, (. - tabPoint1) / 8
tabPoint2: .quad 9,2
//tabPoint2: .quad 3,7
.equ NBPOINTS2, (. - tabPoint2) / 8
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
stNode1: .skip nodeKD_end
KDtree1: .skip nodeKD_end * NBPOINTS
KDtree2: .skip nodeKD_end * NBPOINTS2
KdtreeRand: .skip nodeKD_end * NBPOINTSRAND
tabPointsRand: .skip nodeKD_end
sZoneConv: .skip 24 // conversion buffer
sZoneConv1: .skip 24 // conversion buffer
sBufferConv16: .skip 24
iDistance: .skip 8 // best distance
stNearest: .skip nodeKD_end // best node
nbNodeVi: .skip 8 // visited node
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdrszMessStart
bl affichageMess
ldr x0,qAdrtabPoint1 // points array address
ldr x1,qAdrKDtree1 // KD tree address
mov x2,#NBPOINTS // array points size
mov x3,#2 // domension 2
bl initKDTree // init tree
ldr x0,qAdrKDtree1 // KD tree address
mov x1,#0 // start index
mov x2,#NBPOINTS / 2 // end = array points size
mov x3,#0 // level
mov x4,#2 // dimension 2
bl createTree
mov x8,x0 // save median
cmp x0,#-1
beq 100f
ldr x0,qAdrKDtree1 // KD tree address
mov x1,#2 // dimension 2
bl displayTree
ldr x0,qAdrtabPoint2 // points array address
ldr x1,qAdrKDtree2 // search KDtree address
mov x2,#NBPOINTS2 // search array points size
mov x3,#2 // dimension 2
bl initKDTree // init search tree
ldr x0,qAdrKDtree1 // KDtree address
mov x1,#nodeKD_end
madd x0,x8,x1,x0 // compute median address
ldr x1,qAdrKDtree2 // search KDtree address
mov x2,#0 // first index
mov x3,#2 // dimension 2
bl searchNearest // search nearest point
ldr x0,qAdrszMessResult // display résult
bl affichageMess
ldr x0,qAdrstNearest // nearest point address
ldr x0,[x0]
mov x1,#2
bl displayCoord // coordonnés display
ldr x0,qAdrnbNodeVi // visited nodes
ldr x0,[x0]
ldr x1,qAdrsZoneConv
bl conversion10
mov x0,#3
ldr x1,qAdrszMessVisited
ldr x2,qAdrsZoneConv
ldr x3,qAdrszCarriageReturn
bl displayStrings
ldr x0,qAdriDistance // best distance address
ldr x0,[x0]
ldr x1,qAdrsZoneConv
bl conversion10
mov x0,#3
ldr x1,qAdrszMessDistance
ldr x2,qAdrsZoneConv
ldr x3,qAdrszCarriageReturn
bl displayStrings
bl traitRandom
100: // standard end of the program
mov x0, #0 // return code
mov x8,EXIT
svc #0 // perform the system call
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrsZoneConv: .quad sZoneConv
qAdrszMessDistance: .quad szMessDistance
qAdrszMessResult: .quad szMessResult
qAdrszMessVisited: .quad szMessVisited
qAdrszMessStart: .quad szMessStart
qAdrtabPoint1: .quad tabPoint1
qAdrtabPoint2: .quad tabPoint2
qAdrKDtree1: .quad KDtree1
qAdrKDtree2: .quad KDtree2
/***************************************************/
/* traitement random points */
/***************************************************/
traitRandom:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
ldr x8,qAdrKdtreeRand // KD tree address
mov x7,#nodeKD_end
ldr x10,iNbPointsRand
mov x3,#0
1: // loop generate random coordonnes
mov x0,0
mov x1,#MAXCOORD
bl extRandom // X
mov x4,x0
mov x0,0
mov x1,#MAXCOORD
bl extRandom // Y
mov x5,x0
mov x0,0
mov x1,#MAXCOORD
bl extRandom // Z
mov x6,x0
madd x0,x3,x7,x8
add x1,x0,#nodeKD_val // node address
str x4,[x1] // store X,Y,Z
str x5,[x1,#8]
str x6,[x1,#16]
mov x4,#-1 // init pointer left and right
str x4,[x0,#nodeKD_left]
str x4,[x0,#nodeKD_right]
add x3,x3,#1
cmp x3,x10
blt 1b
mov x0,x8 // KD tree address
mov x1,#0 // start indice
mov x2,x10 // array points size
mov x3,#0 // level
mov x4,#3 // dimension 2
bl createTree
mov x9,x0 // save median
// create random search point
mov x0,0
mov x1,#MAXCOORD
bl extRandom
mov x4,x0
mov x0,0
mov x1,#MAXCOORD
bl extRandom
mov x5,x0
mov x0,0
mov x1,#MAXCOORD
bl extRandom
mov x6,x0
ldr x3,qAdrtabPointsRand
add x0,x3,#nodeKD_val
str x4,[x0]
str x5,[x0,#8]
str x6,[x0,#16]
ldr x0,qAdrszMessRandCoor
bl affichageMess
mov x0,x3
mov x1,#3
bl displayCoord // search
ldr x0,qAdriDistance // init best distance address
mov x1,#0
str x1,[x0]
madd x0,x9,x7,x8 // median KD tree address
mov x1,x3 // search point address
mov x2,#0 // index
mov x3,#3 // dimension 2
bl searchNearest
ldr x0,qAdrszMessResult
bl affichageMess
ldr x0,qAdrstNearest
ldr x0,[x0]
mov x1,#3
bl displayCoord
ldr x0,qAdrnbNodeVi
ldr x0,[x0]
ldr x1,qAdrsZoneConv
bl conversion10
mov x0,#3
ldr x1,qAdrszMessVisited
ldr x2,qAdrsZoneConv
ldr x3,qAdrszCarriageReturn
bl displayStrings
ldr x0,qAdriDistance // best distance address
ldr x0,[x0]
ldr x1,qAdrsZoneConv
bl conversion10
mov x0,#3
ldr x1,qAdrszMessDistance
ldr x2,qAdrsZoneConv
ldr x3,qAdrszCarriageReturn
bl displayStrings
100:
ldp x2,x3,[sp],16 // restaur registers
ldp x1,lr,[sp],16 // restaur registers
ret
qAdrKdtreeRand: .quad KdtreeRand
qAdrtabPointsRand: .quad tabPointsRand
qAdrszMessRandCoor: .quad szMessRandCoor
iNbPointsRand: .quad NBPOINTSRAND
/***************************************************/
/* init KN tree */
/***************************************************/
/* x0 array points */
/* x1 array tree address */
/* x2 points number */
/* x3 dimension */
initKDTree:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
stp x6,x7,[sp,-16]! // save registers
stp x8,x9,[sp,-16]! // save registers
mov x8,#0 // points indice
mov x4,#0 // node tree indice
mov x6,#nodeKD_end // structure size
1:
madd x5,x4,x6,x1 // compute node address
mov x9,#0 // index value
2:
ldr x7,[x0,x8,lsl #3] // load one point coord
str x7,[x5,x9,lsl #3] // store in node value
add x8,x8,#1 // next point
add x9,x9,#1 // next node value
cmp x9,x3 // = dimension ?
blt 2b // no loop
mov x7,#-1 // init pointer left and right
str x7,[x5,#nodeKD_left]
str x7,[x5,#nodeKD_right]
add x4,x4,#1 // increment node tree indice
cmp x8,x2 // end points ?
blt 1b
100:
ldp x8,x9,[sp],16 // restaur registers
ldp x6,x7,[sp],16 // restaur registers
ldp x4,x5,[sp],16 // restaur registers
ldp x2,x3,[sp],16 // restaur registers
ldp x1,lr,[sp],16 // restaur registers
ret
/***************************************************/
/* create KD tree */
/***************************************************/
/* x0 array tree address */
/* x1 start index */
/* x2 end index
/* x3 level */
/* x4 dimention */
createTree:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
stp x6,x7,[sp,-16]! // save registers
stp x8,x9,[sp,-16]! // save registers
stp x10,x11,[sp,-16]! // save registers
stp x12,x13,[sp,-16]! // save registers
cmp x1,x2 // if start = end -> return -1
mov x5,-1
csel x0,x5,x0,ge
//movge x0,#-1
bge 100f
add x5,x1,#1 // if start + 1 = end -> return start
cmp x5,x2
csel x0,x1,x0,eq
//moveq x0,x1
beq 100f
mov x8,x0 // save address
mov x7,x1 // save start index
mov x12,x2 // save end index
mov x5,x3 // save level
mov x10,x4 // save dimension
mov x9,#nodeKD_end // node structure size
mov x1,x7 // start
mov x2,x12 // end
bl findMedian
cmp x0,#0 //
mov x6,-1
csel x0,x6,x0,lt
//movlt x0,#-1
blt 100f
mov x6,x0 // save indice median
add x5,x5,#1 // compute new value index
cmp x5,x10 // => dimension ?
csel x5,xzr,x5,ge
//movge x5,#0
mov x0,x8 // tree address
mov x1,x7 // start
mov x2,x6 // end = median
mov x3,x5 // index
mov x4,x10 // dimension
bl createTree
madd x1,x6,x9,x8 // compute median address
cmp x0,#-1 // left address is ok ?
beq 1f
madd x0,x9,x0,x8 // yes compute address
1:
str x0,[x1,#nodeKD_left] // and store
mov x0,x8 // KDtree address
add x1,x6,#1 // start = indice median + 1
mov x2,x12 // end
mov x3,x5 // index
mov x4,x10 // dimension
bl createTree
madd x1,x6,x9,x8 // compute median address
cmp x0,#-1 // indice right ok ?
beq 2f
madd x0,x9,x0,x8 // yes compute address
2:
str x0,[x1,#nodeKD_right] // and store in pointer
mov x0,x6 // return indice median node
100:
ldp x12,x13,[sp],16 // restaur registers
ldp x10,x11,[sp],16 // restaur registers
ldp x8,x9,[sp],16 // restaur registers
ldp x6,x7,[sp],16 // restaur registers
ldp x4,x5,[sp],16 // restaur registers
ldp x2,x3,[sp],16 // restaur registers
ldp x1,lr,[sp],16 // restaur registers
ret
/***************************************************/
/* find median and sort points */
/***************************************************/
/* x0 tree address */
/* x1 start tree indice
/* x2 end tree indice */
/* x3 indice */
/* x0 return median point index */
findMedian:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
stp x6,x7,[sp,-16]! // save registers
stp x8,x9,[sp,-16]! // save registers
stp x10,x11,[sp,-16]! // save registers
stp x12,x13,[sp,-16]! // save registers
cmp x2,x1
mov x7,-1
csel x0,x7,x0,le
//movle x0,#-1
ble 100f
mov x7,#nodeKD_end // node size
add x5,x1,#1 // next node address
cmp x2,x5 // equal to end ?
csel x0,x1,x0,eq
//moveq x0,x1
beq 100f // yes return
mov x8,x1 // save start
mov x12,x0 // save tree address
add x4,x2,x1 // end + start
lsr x9,x4,#1 // divide by 2 = median index
madd x10,x7,x9,x0 // mediam md address
lsl x5,x3,#2 // index * 4
1:
cmp x2,x8 // end <= start
csel x0,x2,x0,le // stop ?
//movle x0,x2 // stop ?
ble 100f
add x6,x10,#nodeKD_val
add x11,x6,x5 // add shift index
ldr x6,[x11] // load pivot value
mov x0,x10 // median address
sub x1,x2,#1 // compute address end - 1
mul x1,x7,x1
add x1,x1,x12
bl inversion // inversion median and end - 1
mov x11,x8 // store=indice start
mov x4,x8 // p =indice start
2:
cmp x4,x2 // compare p and end
bge 5f
madd x3,x4,x7,x12 // compute p address
add x3,x3,x5 // add shift index
ldr x0,[x3] // load value
cmp x0,x6 // compare to pivot
bge 4f
cmp x4,x11 // compare p et store
beq 3f
madd x0,x4,x7,x12 // compute p address
madd x1,x11,x7,x12 // compute store address
bl inversion // inversion p and store
3:
add x11,x11,#1 // increment store
4:
add x4,x4,#1 // increment p
b 2b
5:
csel x0,x9,x0,eq // equal return median index
//moveq x0,x9 // equal return median index
beq 100f
madd x0,x11,x7,x12 // store address
sub x1,x2,#1 // end - 1
madd x1,x7,x1,x12 // compute address
bl inversion // inversion store and end - 1
ldr x0,[x0,#nodeKD_val] // load store value
add x0,x0,x5 // add shift index
ldr x1,[x10,#nodeKD_val] // load median value
add x1,x1,x5 // add shift index
cmp x0,x1 // compare values
csel x0,x9,x0,eq // equal return median index
// moveq x0,x9 // equal return median index
beq 100f
cmp x11,x9 // compare index store and median
csel x2,x11,x2,gt // new end
csel x8,x11,x8,le // new start
//movgt x2,x11 // new end
//movle x8,x11 // new start
b 1b // and loop
100:
ldp x12,x13,[sp],16 // restaur registers
ldp x10,x11,[sp],16 // restaur registers
ldp x8,x9,[sp],16 // restaur registers
ldp x6,x7,[sp],16 // restaur registers
ldp x4,x5,[sp],16 // restaur registers
ldp x2,x3,[sp],16 // restaur registers
ldp x1,lr,[sp],16 // restaur registers
ret
/***************************************************/
/* compute distanceo 2 */
/***************************************************/
/* x0 tree node address */
/* x1 search points address */
/* x2 dimension */
distance:
stp x3,lr,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
stp x6,x7,[sp,-16]! // save registers
add x0,x0,#nodeKD_val // root node values array address
add x1,x1,#nodeKD_val // search node values array addresse
mov x3,#0 // first value index
mov x7,#0 // init distance
1:
ldr x4,[x0,x3,lsl #3] // load value
ldr x5,[x1,x3,lsl #3] // load value
sub x6,x5,x4 // différence
add x3,x3,#1
madd x7,x6,x6,x7 // compute square TODO: overflow
cmp x3,x2 // end ?
blt 1b // no -> loop
mov x0,x7 // return distance
100:
ldp x6,x7,[sp],16 // restaur registers
ldp x4,x5,[sp],16 // restaur registers
ldp x3,lr,[sp],16 // restaur registers
ret
/***************************************************/
/* search nearest point */
/***************************************************/
/* x0 tree address */
/* x1 search points address */
/* x2 index */
/* x3 dimension */
searchNearest:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
stp x6,x7,[sp,-16]! // save registers
stp x8,x9,[sp,-16]! // save registers
stp x10,x11,[sp,-16]! // save registers
stp x12,x13,[sp,-16]! // save registers
cmp x0,#-1
beq 100f
mov x7,x0 // start with median
mov x8,x1 // save serach point address
lsl x9,x2,#2 // shift index
mov x10,x3 // save dimension
mov x2,x3 // dimension
bl distance // compute distance
mov x11,x0
ldr x1,[x7,x9]
ldr x12,[x8,x9]
sub x12,x12,x1
mul x6,x12,x12 // distance axis
ldr x4,qAdriDistance
ldr x5,[x4]
cmp x5,#0 // first distance ?
csel x5,x11,x5,eq
csel x3,x7,x3,eq
//moveq x5,x11 // new best distance
//moveq x3,x7 // new best node
beq 1f
cmp x11,x5 // compare new distance and best distance
bgt 2f
mov x5,x11 // new best distance
mov x3,x7 // new best node
1:
str x5,[x4] // store new best distance
ldr x4,qAdrstNearest // and store best node address
str x3,[x4]
2:
ldr x1,qAdrnbNodeVi // increment visited node
ldr x3,[x1]
add x3,x3,#1
str x3,[x1]
cmp x5,#0 // distance = 0 -> end //
beq 100f
cmp x12,#0 // else search in childen tree
bge 3f
ldr x0,[x7,#nodeKD_left]
b 4f
3:
ldr x0,[x7,#nodeKD_right]
4:
mov x1,x8
lsr x2,x9,#2
add x2,x2,#1
cmp x2,x10
csel x2,xzr,x2,ge
//movge x2,#0
mov x3,x10
bl searchNearest
ldr x4,qAdriDistance // best distance
ldr x5,[x4]
cmp x6,x5 // compare distance
bge 100f
cmp x12,#0 // else search in childen tree
blt 5f
ldr x0,[x7,#nodeKD_left]
b 6f
5:
ldr x0,[x7,#nodeKD_right]
6:
bl searchNearest
100:
ldp x12,x13,[sp],16 // restaur registers
ldp x10,x11,[sp],16 // restaur registers
ldp x8,x9,[sp],16 // restaur registers
ldp x6,x7,[sp],16 // restaur registers
ldp x4,x5,[sp],16 // restaur registers
ldp x2,x3,[sp],16 // restaur registers
ldp x1,lr,[sp],16 // restaur registers
ret
qAdrstNearest: .quad stNearest
qAdriDistance: .quad iDistance
qAdrnbNodeVi: .quad nbNodeVi
/***************************************************/
/* inversion */
/***************************************************/
/* x0 tree address */
/* x1 tree */
inversion:
stp x2,lr,[sp,-16]! // save registers
stp x3,x4,[sp,-16]! // save registers
add x0,x0,#nodeKD_val
add x1,x1,#nodeKD_val
mov x2,#0
1:
ldr x4,[x0,x2,lsl #3]
ldr x3,[x1,x2,lsl #3]
str x3,[x0,x2,lsl #3]
str x4,[x1,x2,lsl #3]
add x2,x2,#1
cmp x2,#MAXI
blt 1b
100:
ldp x3,x4,[sp],16 // restaur registers
ldp x2,lr,[sp],16 // restaur registers
ret
/***************************************************/
/* display tree */
/***************************************************/
/* x0 tree address */
/* x1 dimension */
displayTree:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
stp x6,x7,[sp,-16]! // save registers
stp x8,x9,[sp,-16]! // save registers
stp x10,x11,[sp,-16]! // save registers
stp x12,x13,[sp,-16]! // save registers
mov x10,x0
mov x7,x1
mov x11,#0
mov x12,#nodeKD_end
1:
madd x9,x12,x11,x10
mov x0,x9
ldr x1,qAdrsBufferConv16
bl conversion16
mov x0,#2
ldr x1,qAdrszMessAddressTree
ldr x2,qAdrsBufferConv16
bl displayStrings
mov x8,#0
2:
add x4,x9,#nodeKD_val
ldr x0,[x4,x8,lsl #3]
ldr x1,qAdrsZoneConv
bl conversion10
mov x0,#2
ldr x1,qAdrszMessTreeValue
ldr x2,qAdrsZoneConv
bl displayStrings
add x8,x8,#1
cmp x8,x7
blt 2b
ldr x0,qAdrszCarriageReturn
bl affichageMess
add x0,x9,#nodeKD_left
ldr x0,[x0]
ldr x1,qAdrsZoneConv
bl conversion16
add x0,x9,#nodeKD_right
ldr x0,[x0]
ldr x1,qAdrsZoneConv1
bl conversion16
mov x0,#5
ldr x1,qAdrszMessLeft
ldr x2,qAdrsZoneConv
ldr x3,qAdrszMessRight
ldr x4,qAdrsZoneConv1
ldr x5,qAdrszCarriageReturn
bl displayStrings
add x11,x11,#1
cmp x11,#NBPOINTS / 2
blt 1b
100:
ldp x12,x13,[sp],16 // restaur registers
ldp x10,x11,[sp],16 // restaur registers
ldp x8,x9,[sp],16 // restaur registers
ldp x6,x7,[sp],16 // restaur registers
ldp x4,x5,[sp],16 // restaur registers
ldp x2,x3,[sp],16 // restaur registers
ldp x1,lr,[sp],16 // restaur registers
ret
qAdrszMessAddressTree: .quad szMessAddressTree
qAdrszMessTreeValue: .quad szMessTreeValue
qAdrsBufferConv16: .quad sBufferConv16
qAdrszMessLeft: .quad szMessLeft
qAdrszMessRight: .quad szMessRight
qAdrsZoneConv1: .quad sZoneConv1
/***************************************************/
/* display node coordonnées */
/***************************************************/
/* x0 node address */
/* x1 dimension */
displayCoord:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
add x4,x0,#nodeKD_val
mov x3,x1 // save dimension
mov x5,#0
1:
ldr x0,[x4,x5,lsl #3]
ldr x1,qAdrsZoneConv
bl conversion10
mov x0,#2
ldr x1,qAdrszMessTreeValue
ldr x2,qAdrsZoneConv
bl displayStrings
add x5,x5,#1
cmp x5,x3
blt 1b
ldr x0,qAdrszCarriageReturn
bl affichageMess
100:
ldp x4,x5,[sp],16 // restaur registers
ldp x2,x3,[sp],16 // restaur registers
ldp x1,lr,[sp],16 // restaur registers
ret
/***************************************************/
/* display multi strings */
/* new version 24/05/2023 */
/***************************************************/
/* x0 contains number strings address */
/* x1 address string1 */
/* x2 address string2 */
/* x3 address string3 */
/* x4 address string4 */
/* x5 address string5 */
/* x6 address string5 */
/* x7 address string6 */
displayStrings: // INFO: displayStrings
stp x8,lr,[sp,-16]! // save registers
stp x2,fp,[sp,-16]! // save registers
add fp,sp,#32 // save paraméters address (4 registers saved * 8 bytes)
mov x8,x0 // save strings number
cmp x8,#0 // 0 string -> end
ble 100f
mov x0,x1 // string 1
bl affichageMess
cmp x8,#1 // number > 1
ble 100f
mov x0,x2
bl affichageMess
cmp x8,#2
ble 100f
mov x0,x3
bl affichageMess
cmp x8,#3
ble 100f
mov x0,x4
bl affichageMess
cmp x8,#4
ble 100f
mov x0,x5
bl affichageMess
cmp x8,#5
ble 100f
mov x0,x6
bl affichageMess
cmp x8,#6
ble 100f
mov x0,x7
bl affichageMess
100:
ldp x2,fp,[sp],16 // restaur registers
ldp x8,lr,[sp],16 // restaur registers
ret
/******************************************************************/
/* random number */
/******************************************************************/
/* x0 contains inferior value */
/* x1 contains maxi value */
/* x0 return random number */
extRandom:
stp x1,lr,[sp,-16]! // save registers
stp x2,x8,[sp,-16]! // save registers
stp x19,x20,[sp,-16]! // save registers
sub sp,sp,16 // reserve 16 octets on stack
mov x19,x0
add x20,x1,1
mov x0,sp // store result on stack
mov x1,8 // length 8 bytes
mov x2,0
mov x8,278 // call system Linux 64 bits Urandom
svc 0
mov x0,sp // load résult on stack
ldr x0,[x0]
sub x2,x20,x19 // calculation of the range of values
udiv x1,x0,x2 // calculation range modulo
msub x0,x1,x2,x0
add x0,x0,x19 // and add inferior value
100:
add sp,sp,16 // alignement stack
ldp x19,x20,[sp],16 // restaur 2 registers
ldp x2,x8,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // retour adresse lr x30
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../includeARM64.inc"

View file

@ -21,8 +21,6 @@
.equ NBPOINTSRAND, 2000
.equ MAXCOORD, 10000
.include "../../ficmacros32.inc"
/***********************************************/
/* structures */
/**********************************************/
@ -159,9 +157,6 @@ iAdrKDtree2: .int KDtree2
/***************************************************/
/* traitement random points */
/***************************************************/
/* r0 array tree address */
/* r2 points number */
/* r3 dimension */
traitRandom:
push {r1-r10,lr} @ save des registres
ldr r8,iAdrKdtreeRand @ KD tree address

View file

@ -0,0 +1,35 @@
global found dig[] .
proc test . .
for i to len dig[]
n = n * 10 + dig[i]
.
for i to len dig[]
if n mod dig[i] <> 0
break 2
.
.
found = 1
print n
.
len use[] 9
proc perm pos . .
if found = 1
break 1
.
for i = 9 downto 1
dig[pos] = i
if use[i] = 0
use[i] = 1
if pos = len dig[]
call test
else
call perm pos + 1
.
use[i] = 0
.
.
.
for ndig = 9 downto 1
len dig[] ndig
call perm 1
.

View file

@ -0,0 +1,10 @@
10 REM LARGEST PROPER DIVISOR OF N
20 PRINT "THE LARGEST PROPER DIVISOR OF N IS:"
30 PRINT;PRINT #3,1,1,
40 FOR I=3 TO 100
50 FOR J=I-1 TO 1 STEP -1
60 IF I=(I/J)*J PRINT #3,J,;GOTO 80
70 NEXT J
80 IF I=(I/10)*10 PRINT
90 NEXT I
100 STOP

View file

@ -0,0 +1,21 @@
include "cowgol.coh";
sub longyear(year: uint16): (r: uint8) is
sub p(y: uint16): (d: uint8) is
d := ((y + y/4 - y/100 + y/400) % 7) as uint8;
end sub;
r := 0;
if p(year) == 4 or p(year-1) == 3 then
r := 1;
end if;
end sub;
var year: uint16 := 2000;
while year <= 2100 loop
if longyear(year) != 0 then
print_i16(year);
print_nl();
end if;
year := year + 1;
end loop;

View file

@ -0,0 +1,14 @@
proc p(word y) word:
(y + y/4 - y/100 + y/400) % 7
corp
proc longyear(word y) bool:
p(y) = 4 or p(y-1) = 3
corp
proc main() void:
word y;
for y from 2000 upto 2100 do
if longyear(y) then writeln(y) fi
od
corp

View file

@ -1,13 +1,25 @@
/*REXX program determines if a (calendar) year is a SHORT or LONG year (52 or 53 weeks).*/
parse arg LO HI . /*obtain optional args. */
if LO=='' | LO=="," | LO=='*' then LO= left( date('S'), 4) /*Not given? Use default.*/
if HI=='' | HI=="," then HI= LO /* " " " " */
if HI=='*' then HI= left( date('S'), 4) /*an asterisk ≡ current yr*/
/*REXX program determines If a (calendar) year is a short or long year */
/* (52 or 53 weeks). */
Parse Arg lo hi . /* obtain optional args. */
current=left(date('S'),4)
If lo=='' | lo=="," | lo=='*' Then lo=current /*Not given? Use default.*/
If hi=='' | hi=="," Then hi=lo /* " " " " */
If hi=='*' Then hi=current /*an asterisk: current yr*/
do j=LO to HI /*process single yr or range of years.*/
say ' year ' j " is a " right( word('short long', weeks(j)-51),5) " year"
end /*j*/
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
pWeek: parse arg #; return (# + # % 4 - # % 100 + # % 400) // 7
weeks: parse arg y; if pWeek(y)==4 | pWeek(y-1)==3 then return 53; return 52
Do yr=lo To hi /* process single yr or range of */
Say ' year ' yr ' is a ',
right(word('short long',is_long(yr)+1),5) ' year'
End
Exit
/*----------------------------------------------------------------------*/
wd_1231:
/*************************************************************************
* returns the day of the week of 31 December year
*************************************************************************/
Parse Arg year
Return (year+year%4-year%100+year%400)//7
is_long:
Parse Arg year
Return wd_1231(year)==4 |, /* year ends in a Thursday */
wd_1231(year-1)==3 /* or previous year ends in a Wednesday */

View file

@ -1,5 +1,6 @@
x, y, z, one, three, seven = 5, -5, -2, 1, 3, 7
enums = (-three).step(3**3, three) +
(-seven).step(seven, x) +
555 .step(550-y, -1) +

View file

@ -1,32 +1,11 @@
(let ()
(defun matrices-multiply (m1 m2)
(let (fn-row-mult)
(setq fn-row-mult
(lambda (row col-idx)
(let ((col (cl-loop for m2-row in m2
collect (nth col-idx m2-row))))
(apply '+ (cl-loop for v1 in row for v2 in col
collect (* v1 v2))) ) ) )
(defvar M1 '((2 1 4)
(0 1 1)))
(cl-loop for m1-row in m1 collect
(seq-map-indexed (lambda (v col-idx)
(funcall fn-row-mult m1-row col-idx) )
(nth 0 m2) ) ) ) )
(defvar M2 '(( 6 3 -1 0)
( 1 1 0 4)
(-2 5 0 2)))
(let ((m1 '((2 1 4)
(0 1 1)))
(m2 '((6 3 -1 0)
(1 1 0 4)
(-2 5 0 2)))
result-matrix)
(switch-to-buffer-other-window "**matrix-result**")
(erase-buffer)
(setq result-matrix (matrices-multiply m1 m2))
(cl-loop for line in result-matrix do
(insert (format "%s\n"
(apply 'concat
(seq-map (lambda (item) (format "%5s " item)) line) ) ) ) ) )
)
(seq-map (lambda (a1)
(seq-map (lambda (a2) (apply #'+ (seq-mapn #'* a1 a2)))
(apply #'seq-mapn #'list M2)))
M1)

View file

@ -0,0 +1,31 @@
local fn IsPrime( n as NSUInteger ) as BOOL
BOOL isPrime = YES
NSUInteger i
if n < 2 then exit fn = NO
if n = 2 then exit fn = YES
if n mod 2 == 0 then exit fn = NO
for i = 3 to int(n^.5) step 2
if n mod i == 0 then exit fn = NO
next
end fn = isPrime
local fn IsMotzkin
NSUInteger M(42) : M(0) = 1 : M(1) = 1
NSInteger i, n
printf @" 0.%20ld\n 1.%20ld", 1, 1
for n = 2 to 41
M(n) = M(n-1)
for i = 0 to n-2
M(n) += M(i) * M(n-2-i)
next
printf @"%2ld.%20ld\b", n, M(n)
if fn IsPrime( M(n) ) then print " <-- is a prime" else print
next
end fn
fn IsMotzkin
HandleEvents

View file

@ -0,0 +1,38 @@
def fn F( n as long ) as long
def fn M( n as long ) as long
local fn F( n as long ) as long
long result
if n == 0 then exit fn = 1
result = n - fn M( fn F( n-1 ) )
end fn = result
local fn M( n as long ) as long
long result
if n == 0 then exit fn = 0
result = n - fn F( fn M( n-1 ) )
end fn = result
long i, counter
counter = 0
for i = 0 to 19
printf @"%3ld\b", fn F( i )
counter++
if counter mod 5 == 0 then print : counter = 0
next
print : print
counter = 0
for i = 0 to 19
printf @"%3ld\b", fn M( i )
counter++
if counter mod 5 == 0 then print : counter = 0
next
NSLog( @"%@", fn WindowPrintViewString( 1 ) )
HandleEvents

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