Data Update

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

1
Lang/ALGOL-68/FASTA-format Symbolic link
View File

@ -0,0 +1 @@
../../Task/FASTA-format/ALGOL-68

View File

@ -0,0 +1 @@
../../Task/Next-highest-int-from-digits/ALGOL-68

View File

@ -28,6 +28,9 @@ Awe correctly compiles Tony Marsland's computer [[wp:chess|chess]] player
and Hendrik Boom's [http://mtn-host.prjek.net/projects/a68h/ A68H]
[[Algol 68]] compiler.
==To do==
[[Tasks not implemented in ALGOL W]]
==See also==
*[[wp:ALGOL_W|Algol W on Wikipedia]]
*[[ALGOL 60]]

View File

@ -0,0 +1 @@
../../Task/Numbers-which-are-the-cube-roots-of-the-product-of-their-proper-divisors/ALGOL-W

View File

@ -0,0 +1 @@
../../Task/Horizontal-sundial-calculations/ANSI-BASIC

View File

@ -0,0 +1 @@
../../Task/Largest-proper-divisor-of-n/ANSI-BASIC

1
Lang/ANSI-BASIC/Nth Symbolic link
View File

@ -0,0 +1 @@
../../Task/Nth/ANSI-BASIC

View File

@ -0,0 +1 @@
../../Task/Averages-Median/ARM-Assembly

View File

@ -0,0 +1 @@
../../Task/Determine-if-two-triangles-overlap/ATS

View File

@ -0,0 +1 @@
../../Task/ASCII-art-diagram-converter/AutoHotkey

View File

@ -12,7 +12,7 @@
|LCT=yes
|bnf=http://cpp.comsci.us/syntax/statement/index.html}}{{codepad}}{{allows|Network access}}{{allows|Database access
}}{{allows|Concurrency}}{{provides|Run time polymorphism}}{{provides|Compile time polymorphism}}{{allows|Windowing UI}}{{allows|Graphics}}{{allows|OpenGL}}{{allows|Dynamic linking}}{{provides|File access}}{{allows|File system access}}{{provides|Objects}}{{allows|Signal handling}}{{provides|Mutable state}}
'''C++''' is named after the [[derived from::compatible with::C]] language, from which it is derived. C++ extends C into an [[object-oriented language]]. However, unlike other object-oriented languages, it doesn't try to force you into [[object-oriented programming]], but is a multi-[[:Category:Programming Paradigms|paradigm]] language. Besides conventional [[procedural programming]] and object-oriented programming, it also supports [[generic programming]].
'''C++''' is named after the C language, from which it is derived. C++ extends C into an [[object-oriented language]]. However, unlike other object-oriented languages, it doesn't try to force you into [[object-oriented programming]], but is a multi-[[:Category:Programming Paradigms|paradigm]] language. Besides conventional [[procedural programming]] and object-oriented programming, it also supports [[generic programming]].
If you can't find an implementation for your task in the C++ category below, please look in the [[C]] category, as many of the tasks can be implemented identically in C and C++.

View File

@ -0,0 +1 @@
../../Task/B-zier-curves-Intersections/C++

1
Lang/C++/Deconvolution-1D Symbolic link
View File

@ -0,0 +1 @@
../../Task/Deconvolution-1D/C++

1
Lang/C++/Demings-funnel Symbolic link
View File

@ -0,0 +1 @@
../../Task/Demings-funnel/C++

View File

@ -0,0 +1 @@
../../Task/Determine-sentence-type/C++

View File

@ -0,0 +1 @@
../../Task/Distance-and-Bearing/C++

View File

@ -0,0 +1 @@
../../Task/EKG-sequence-convergence/C++

1
Lang/C++/Pisano-period Symbolic link
View File

@ -0,0 +1 @@
../../Task/Pisano-period/C++

View File

@ -0,0 +1 @@
../../Task/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k/C

View File

@ -0,0 +1 @@
../../Task/Harmonic-series/Craft-Basic

View File

@ -0,0 +1 @@
../../Task/Largest-proper-divisor-of-n/Craft-Basic

1
Lang/EMal/Comments Symbolic link
View File

@ -0,0 +1 @@
../../Task/Comments/EMal

1
Lang/EMal/Enumerations Symbolic link
View File

@ -0,0 +1 @@
../../Task/Enumerations/EMal

1
Lang/EMal/Filter Symbolic link
View File

@ -0,0 +1 @@
../../Task/Filter/EMal

View File

@ -0,0 +1 @@
../../Task/Hash-from-two-arrays/EMal

View File

@ -0,0 +1 @@
../../Task/Inheritance-Single/EMal

1
Lang/EMal/String-prepend Symbolic link
View File

@ -0,0 +1 @@
../../Task/String-prepend/EMal

View File

@ -0,0 +1 @@
../../Task/Minkowski-question-mark-function/F-Sharp

View File

@ -0,0 +1 @@
../../Task/Abundant-deficient-and-perfect-number-classifications/Free-Pascal-Lazarus

View File

@ -0,0 +1 @@
../../Task/Canonicalize-CIDR/FreeBASIC

View File

@ -0,0 +1 @@
../../Task/Nautical-bell/FreeBASIC

View File

@ -0,0 +1 @@
../../Task/Sum-and-product-puzzle/J

1
Lang/Java/15-puzzle-solver Symbolic link
View File

@ -0,0 +1 @@
../../Task/15-puzzle-solver/Java

View File

@ -0,0 +1 @@
../../Task/B-zier-curves-Intersections/Java

View File

@ -0,0 +1 @@
../../Task/Color-quantization/Java

View File

@ -0,0 +1 @@
../../Task/Compile-time-calculation/Java

View File

@ -0,0 +1 @@
../../Task/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k/Java

View File

@ -0,0 +1 @@
../../Task/Consecutive-primes-with-ascending-or-descending-differences/Java

1
Lang/Java/Curzon-numbers Symbolic link
View File

@ -0,0 +1 @@
../../Task/Curzon-numbers/Java

1
Lang/Java/Deceptive-numbers Symbolic link
View File

@ -0,0 +1 @@
../../Task/Deceptive-numbers/Java

1
Lang/Java/Descending-primes Symbolic link
View File

@ -0,0 +1 @@
../../Task/Descending-primes/Java

View File

@ -0,0 +1 @@
../../Task/Determine-sentence-type/Java

1
Lang/Java/Duffinian-numbers Symbolic link
View File

@ -0,0 +1 @@
../../Task/Duffinian-numbers/Java

View File

@ -0,0 +1 @@
../../Task/Old-Russian-measure-of-length/Jq

View File

@ -21,358 +21,4 @@ As a result, the base language is light—in fact, the full reference interprete
* [[wp:Lua_%28programming_language%29|Wikipedia:Lua (programming language)]]
==Unimplemented programming tasks==
Output from [[Find_unimplemented_tasks]] :
Lua has 355 unimplemented programming tasks:
15 puzzle solver
2048
4-rings or 4-squares puzzle
9 billion names of God the integer
AKS test for primes
Abbreviations, automatic
Abbreviations, easy
Abbreviations, simple
Active Directory/Connect
Active Directory/Search for a user
Active object
Address of a variable
Aliquot sequence classifications
Anagrams/Deranged anagrams
Animation
Append a record to the end of a text file
Apply a digital filter (direct form II transposed)
Arbitrary-precision integers (included)
Archimedean spiral
Arena storage pool
Arithmetic-geometric mean/Calculate Pi
Atomic updates
Average loop length
Balanced ternary
Best shuffle
Bitcoin/address validation
Bitcoin/public point to address
Bitmap/Bresenham's line algorithm
Bitmap/Bézier curves/Cubic
Bitmap/Bézier curves/Quadratic
Bitmap/Flood fill
Bitmap/Midpoint circle algorithm
Bitmap/PPM conversion through a pipe
Bitmap/Read an image through a pipe
Bitwise IO
Brace expansion
Break OO privacy
Bulls and cows/Player
Call a function in a shared library
Canny edge detector
Carmichael 3 strong pseudoprimes
Casting out nines
CatmullClark subdivision surface
Chat server
Check Machin-like formulas
Checkpoint synchronization
Chinese zodiac
Cholesky decomposition
Church Numerals
Circles of given radius through two points
Closest-pair problem
Color of a screen pixel
Color quantization
Colour bars/Display
Colour pinstripe/Display
Colour pinstripe/Printer
Combinations and permutations
Commatizing numbers
Compare sorting algorithms' performance
Compile-time calculation
Compiler/AST interpreter
Compiler/code generator
Compiler/lexical analyzer
Compiler/syntax analyzer
Compiler/virtual machine interpreter
Conjugate transpose
Constrained genericity
Constrained random points on a circle
Continued fraction
Continued fraction/Arithmetic/Construct from rational number
Convert decimal number to rational
Create a file on magnetic tape
Create an object at a given address
Currency
Cut a rectangle
Death Star
Deconvolution/2D+
Define a primitive data type
Delegates
Determine if only one instance is running
Digital root/Multiplicative digital root
Dining philosophers
Discordian date
Distributed programming
Documentation
Doubly-linked list/Definition
Doubly-linked list/Element definition
Doubly-linked list/Element insertion
Doubly-linked list/Traversal
Draw a cuboid
Draw a pixel
Draw a rotating cube
Dutch national flag problem
EKG sequence convergence
Eertree
Egyptian division
Egyptian fractions
Element-wise operations
Elementary cellular automaton
Enforced immutability
Equilibrium index
Euler's identity
Events
Extend your language
Extensible prime generator
FTP
Factors of a Mersenne number
Find common directory path
Find largest left truncatable prime in a given base
Find palindromic numbers in both binary and ternary bases
Floyd-Warshall algorithm
Four is magic
Four is the number of letters in the ...
Fractran
Function frequency
GUI component interaction
GUI enabling/disabling of controls
GUI/Maximum window dimensions
Galton box animation
Gaussian elimination
Generate random chess position
Go Fish
Greyscale bars/Display
HTTPS/Client-authenticated
Handle a signal
Hash join
Hello world/Line printer
Hello world/Web server
Hickerson series of almost integers
History variables
Hofstadter Figure-Figure sequences
Hofstadter Q sequence
Honeycombs
Horizontal sundial calculations
Host introspection
Hough transform
Hunt The Wumpus
Image convolution
Image noise
Index finite lists of positive integers
Inheritance/Single
Integer overflow
Inverted index
Inverted syntax
Jaro distance
Jewels and Stones
Joystick position
Julia set
K-d tree
K-means++ clustering
Keyboard input/Flush the keyboard buffer
Keyboard input/Keypress check
Keyboard input/Obtain a Y or N response
Keyboard macros
Knapsack problem/0-1
Knapsack problem/Bounded
Knapsack problem/Continuous
Knuth's algorithm S
Knuth's power tree
Kolakoski sequence
LU decomposition
Largest number divisible by its digits
Last letter-first letter
Law of cosines - triples
Long multiplication
Long primes
Loops/Increment loop index within loop body
Loops/Wrong ranges
Lucas-Lehmer test
Lucky and even lucky numbers
Lychrel numbers
MD5/Implementation
Machine code
Mad Libs
Main step of GOST 28147-89
Maze solving
Median filter
Memory allocation
Memory layout of a data structure
Metered concurrency
Metronome
MillerRabin primality test
Mind boggling card trick
Minesweeper game
Modular exponentiation
Modular inverse
Mouse position
Multiple regression
Multiplicative order
Narcissist
Natural sorting
Nautical bell
Negative base numbers
Nested templated data
Non-continuous subsequences
Nonogram solver
Numeric error propagation
OLE Automation
Object serialization
Odd word problem
OpenWebNet Password
Paraffins
Parallel Brute Force
Parallel calculations
Parametric polymorphism
Parametrized SQL statement
Parse an IP Address
Parsing/RPN to infix conversion
Parsing/Shunting-yard algorithm
Partition an integer X into N primes
Pascal's triangle/Puzzle
Pathological floating point problems
Pattern matching
Pentagram
Percentage difference between images
Percolation/Bond percolation
Percolation/Mean cluster density
Percolation/Mean run density
Percolation/Site percolation
Permutation test
Permutations/Rank of a permutation
Pig the dice game/Player
Pinstripe/Printer
Play recorded sounds
Plot coordinate pairs
Polymorphic copy
Polynomial long division
Polynomial regression
Pragmatic directives
Primes - allocate descendants to their ancestors
Primorial numbers
Problem of Apollonius
Pythagoras tree
Pythagorean quadruples
Pythagorean triples
QR decomposition
RCRPG
RPG Attributes Generator
RSA code
Ramer-Douglas-Peucker line simplification
Random number generator (device)
Ranking methods
Rate counter
Ray-casting algorithm
Recaman's sequence
Record sound
Reflection/Get source
Reflection/List methods
Reflection/List properties
Rendezvous
Rep-string
Resistor mesh
Retrieve and search chat history
Rosetta Code/Count examples
Rosetta Code/Find bare lang tags
Rosetta Code/Rank languages by popularity
Runge-Kutta method
S-Expressions
SEDOLs
SOAP
SQL-based authentication
Safe addition
Sailors, coconuts and a monkey problem
Same Fringe
Scope modifiers
Scope/Function names and labels
Sequence of primorial primes
Set consolidation
Set of real numbers
Set puzzle
Shortest common supersequence
Sierpinski carpet
Sierpinski pentagon
Sierpinski triangle
Simple database
Simulate input/Keyboard
Simulate input/Mouse
Singleton
Singly-linked list/Element definition
Singly-linked list/Element insertion
Singly-linked list/Traversal
Sokoban
Solve a Hidato puzzle
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
Sorting algorithms/Heapsort
Sorting algorithms/Radix sort
Sorting algorithms/Strand sort
Sparkline in unicode
Speech synthesis
Spelling of ordinal numbers
Spinning rod animation/Text
Square but not cube
Start from a main routine
State name puzzle
Stream Merge
Subtractive generator
Sum and Product Puzzle
Sum to 100
Superellipse
Superpermutation minimisation
Taxicab numbers
Terminal control/Coloured text
Terminal control/Cursor movement
Terminal control/Cursor positioning
Terminal control/Dimensions
Terminal control/Hiding the cursor
Terminal control/Inverse video
Terminal control/Positional read
Terminal control/Preserve screen
Terminal control/Unicode output
Ternary logic
The ISAAC Cipher
The Name Game
Thiele's interpolation formula
Topic variable
Topological sort
Total circles area
Tree traversal
Truth table
Twelve statements
URL parser
Ulam spiral (for primes)
Unicode strings
Update a configuration file
Use another language to call a function
User input/Graphical
Vampire number
Variable size/Get
Variable size/Set
Variable-length quantity
Verify distribution uniformity/Chi-squared test
Verify distribution uniformity/Naive
Video display modes
Vigenère cipher/Cryptanalysis
Visualize a tree
Vogel's approximation method
Walk a directory/Recursively
Water collected between towers
Window creation/X11
Window management
Word search
World Cup group stage
Write to Windows event log
Xiaolin Wu's line algorithm
Yahoo! search interface
Yin and yang
Zebra puzzle
Zeckendorf arithmetic
See also [[Reports:Tasks_not_implemented_in_Lua]]
[[Tasks not implemented in Lua]]

1
Lang/Lua/Factorial-primes Symbolic link
View File

@ -0,0 +1 @@
../../Task/Factorial-primes/Lua

1
Lang/Lua/Particle-fountain Symbolic link
View File

@ -0,0 +1 @@
../../Task/Particle-fountain/Lua

View File

@ -0,0 +1 @@
../../Task/Last-Friday-of-each-month/M2000-Interpreter

View File

@ -0,0 +1 @@
../../Task/Attractive-numbers/Maxima

1
Lang/MiniScript/Anti-primes Symbolic link
View File

@ -0,0 +1 @@
../../Task/Anti-primes/MiniScript

View File

@ -0,0 +1 @@
../../Task/Trabb-Pardo-Knuth-algorithm/Modula-2

1
Lang/Odin/Anti-primes Symbolic link
View File

@ -0,0 +1 @@
../../Task/Anti-primes/Odin

View File

@ -0,0 +1 @@
../../Task/Fibonacci-sequence/Odin

View File

@ -0,0 +1 @@
../../Task/Pseudo-random-numbers-Splitmix64/Odin

1
Lang/PL-M/FASTA-format Symbolic link
View File

@ -0,0 +1 @@
../../Task/FASTA-format/PL-M

View File

@ -15,6 +15,18 @@ Palo Alto Tiny BASIC has some features that distinguish it from other Tiny BASIC
* Lack of <code>THEN</code> in an <code>IF</code> command.
* Numeric results of compare operations: 1 (if true), 0 (if false). Thus, one can use them in arithmetic expression. Note: <syntaxhighlight lang="basic">LET A=B=0</syntaxhighlight> means "set <code>A</code> to the result of comparing <code>B</code> with 0".
* A prompt in an <code>INPUT</code> command. If the prompt is omitted, the default is a name of the variable. E.g. <syntaxhighlight lang="basic">INPUT "WHAT IS THE HEIGHT"H</syntaxhighlight> will print <code>WHAT IS THE HEIGHT:</code> and wait to read an expression from the input device.<syntaxhighlight lang="basic">INPUT H</syntaxhighlight> will print <code>H:</code> and so on.
* The function <code>RND(X)</code> that returns a random number between 1 and X (inclusive).
* Separating print items with <code>,</code> (comma).
* Setting widths of numeric print items. A number preceeded by <code>#</code> sets the width (6 by default) of following numeric print items. It does not count leading spaces. For example,
<syntaxhighlight lang="basic">
10 PRINT "X",#2,1,10,"X"
20 PRINT 1,#4,10,20,#2,30,40
</syntaxhighlight>
displays
<pre>
X 1 10X
1 10 20 30 40
</pre>
==Implementations==
Palo Alto Tiny BASIC was adapted for many implementations:

View File

@ -1 +0,0 @@
../../Task/Abundant-deficient-and-perfect-number-classifications/Pascal

View File

@ -0,0 +1 @@
../../Task/Canonicalize-CIDR/QBasic

View File

@ -0,0 +1 @@
../../Task/Arithmetic-derivative/Rust

View File

@ -0,0 +1 @@
../../Task/Cistercian-numerals/Rust

1
Lang/Rust/Colorful-numbers Symbolic link
View File

@ -0,0 +1 @@
../../Task/Colorful-numbers/Rust

View File

@ -0,0 +1 @@
../../Task/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k/Rust

View File

@ -0,0 +1 @@
../../Task/Dinesmans-multiple-dwelling-problem/Rust

View File

@ -0,0 +1 @@
../../Task/Modified-random-distribution/Rust

View File

@ -0,0 +1 @@
../../Task/Sum-and-product-puzzle/Rust

1
Lang/S-BASIC/Array-length Symbolic link
View File

@ -0,0 +1 @@
../../Task/Array-length/S-BASIC

View File

@ -25,4 +25,8 @@ The language is mostly used as a research programming language.
For more details, see:
* Gitbook: [https://trizen.gitbook.io/sidef-lang/ https://trizen.gitbook.io/sidef-lang/]
* Tutorial: [https://notabug.org/trizen/sidef/wiki https://notabug.org/trizen/sidef/wiki]
* Development page: [https://github.com/trizen/sidef https://github.com/trizen/sidef]
* Development page: [https://github.com/trizen/sidef https://github.com/trizen/sidef]
==Todo==
[[Tasks_not_implemented_in_Sidef]]

1
Lang/Sidef/Factorial-primes Symbolic link
View File

@ -0,0 +1 @@
../../Task/Factorial-primes/Sidef

1
Lang/Tcl/Harmonic-series Symbolic link
View File

@ -0,0 +1 @@
../../Task/Harmonic-series/Tcl

View File

@ -0,0 +1 @@
../../Task/Pseudo-random-numbers-Middle-square-method/Tcl

1
Lang/Transact-SQL/Julia-set Symbolic link
View File

@ -0,0 +1 @@
../../Task/Julia-set/Transact-SQL

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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