diff --git a/Lang/AArch64-Assembly/Averages-Median b/Lang/AArch64-Assembly/Averages-Median new file mode 120000 index 0000000000..ae6afbd2a3 --- /dev/null +++ b/Lang/AArch64-Assembly/Averages-Median @@ -0,0 +1 @@ +../../Task/Averages-Median/AArch64-Assembly \ No newline at end of file diff --git a/Lang/ALGOL-68/Pell-numbers b/Lang/ALGOL-68/Pell-numbers new file mode 120000 index 0000000000..1815b001cf --- /dev/null +++ b/Lang/ALGOL-68/Pell-numbers @@ -0,0 +1 @@ +../../Task/Pell-numbers/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-W/Ascending-primes b/Lang/ALGOL-W/Ascending-primes new file mode 120000 index 0000000000..06be81c726 --- /dev/null +++ b/Lang/ALGOL-W/Ascending-primes @@ -0,0 +1 @@ +../../Task/Ascending-primes/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Descending-primes b/Lang/ALGOL-W/Descending-primes new file mode 120000 index 0000000000..eb1b26cbcd --- /dev/null +++ b/Lang/ALGOL-W/Descending-primes @@ -0,0 +1 @@ +../../Task/Descending-primes/ALGOL-W \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Bell-numbers b/Lang/ANSI-BASIC/Bell-numbers new file mode 120000 index 0000000000..ce789dbea6 --- /dev/null +++ b/Lang/ANSI-BASIC/Bell-numbers @@ -0,0 +1 @@ +../../Task/Bell-numbers/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Remove-duplicate-elements b/Lang/ANSI-BASIC/Remove-duplicate-elements new file mode 120000 index 0000000000..76d3035dcb --- /dev/null +++ b/Lang/ANSI-BASIC/Remove-duplicate-elements @@ -0,0 +1 @@ +../../Task/Remove-duplicate-elements/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Trabb-Pardo-Knuth-algorithm b/Lang/ANSI-BASIC/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..a19f987c84 --- /dev/null +++ b/Lang/ANSI-BASIC/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/ANSI-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Duffinian-numbers b/Lang/Applesoft-BASIC/Duffinian-numbers new file mode 120000 index 0000000000..803f0d38f7 --- /dev/null +++ b/Lang/Applesoft-BASIC/Duffinian-numbers @@ -0,0 +1 @@ +../../Task/Duffinian-numbers/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Loop-over-multiple-arrays-simultaneously b/Lang/Applesoft-BASIC/Loop-over-multiple-arrays-simultaneously new file mode 120000 index 0000000000..a4b41c4dcd --- /dev/null +++ b/Lang/Applesoft-BASIC/Loop-over-multiple-arrays-simultaneously @@ -0,0 +1 @@ +../../Task/Loop-over-multiple-arrays-simultaneously/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Primality-by-trial-division b/Lang/Applesoft-BASIC/Primality-by-trial-division new file mode 120000 index 0000000000..68cfa97935 --- /dev/null +++ b/Lang/Applesoft-BASIC/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/C++/Find-Chess960-starting-position-identifier b/Lang/C++/Find-Chess960-starting-position-identifier new file mode 120000 index 0000000000..c936ac89a0 --- /dev/null +++ b/Lang/C++/Find-Chess960-starting-position-identifier @@ -0,0 +1 @@ +../../Task/Find-Chess960-starting-position-identifier/C++ \ No newline at end of file diff --git a/Lang/C++/Find-palindromic-numbers-in-both-binary-and-ternary-bases b/Lang/C++/Find-palindromic-numbers-in-both-binary-and-ternary-bases new file mode 120000 index 0000000000..8aca209101 --- /dev/null +++ b/Lang/C++/Find-palindromic-numbers-in-both-binary-and-ternary-bases @@ -0,0 +1 @@ +../../Task/Find-palindromic-numbers-in-both-binary-and-ternary-bases/C++ \ No newline at end of file diff --git a/Lang/Chipmunk-Basic/Strip-a-set-of-characters-from-a-string b/Lang/Chipmunk-Basic/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..74bd1a6833 --- /dev/null +++ b/Lang/Chipmunk-Basic/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/Chipmunk-Basic/Tau-number b/Lang/Chipmunk-Basic/Tau-number new file mode 120000 index 0000000000..fd1213a751 --- /dev/null +++ b/Lang/Chipmunk-Basic/Tau-number @@ -0,0 +1 @@ +../../Task/Tau-number/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/Chipmunk-Basic/Temperature-conversion b/Lang/Chipmunk-Basic/Temperature-conversion new file mode 120000 index 0000000000..e5069477ac --- /dev/null +++ b/Lang/Chipmunk-Basic/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/GW-BASIC/Tau-number b/Lang/GW-BASIC/Tau-number new file mode 120000 index 0000000000..90b8a7571d --- /dev/null +++ b/Lang/GW-BASIC/Tau-number @@ -0,0 +1 @@ +../../Task/Tau-number/GW-BASIC \ No newline at end of file diff --git a/Lang/Gambas/Sum-digits-of-an-integer b/Lang/Gambas/Sum-digits-of-an-integer new file mode 120000 index 0000000000..ab60fee73a --- /dev/null +++ b/Lang/Gambas/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/Gambas \ No newline at end of file diff --git a/Lang/Insitux/Even-or-odd b/Lang/Insitux/Even-or-odd new file mode 120000 index 0000000000..292912454d --- /dev/null +++ b/Lang/Insitux/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/Insitux \ No newline at end of file diff --git a/Lang/Insitux/FizzBuzz b/Lang/Insitux/FizzBuzz new file mode 120000 index 0000000000..23775b88a9 --- /dev/null +++ b/Lang/Insitux/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Insitux \ No newline at end of file diff --git a/Lang/Insitux/Look-and-say-sequence b/Lang/Insitux/Look-and-say-sequence new file mode 120000 index 0000000000..960b5f2081 --- /dev/null +++ b/Lang/Insitux/Look-and-say-sequence @@ -0,0 +1 @@ +../../Task/Look-and-say-sequence/Insitux \ No newline at end of file diff --git a/Lang/Insitux/Loop-over-multiple-arrays-simultaneously b/Lang/Insitux/Loop-over-multiple-arrays-simultaneously new file mode 120000 index 0000000000..9fba1a9ccf --- /dev/null +++ b/Lang/Insitux/Loop-over-multiple-arrays-simultaneously @@ -0,0 +1 @@ +../../Task/Loop-over-multiple-arrays-simultaneously/Insitux \ No newline at end of file diff --git a/Lang/Insitux/Palindrome-detection b/Lang/Insitux/Palindrome-detection new file mode 120000 index 0000000000..40463b37e2 --- /dev/null +++ b/Lang/Insitux/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/Insitux \ No newline at end of file diff --git a/Lang/Insitux/Quine b/Lang/Insitux/Quine new file mode 120000 index 0000000000..ad36372f10 --- /dev/null +++ b/Lang/Insitux/Quine @@ -0,0 +1 @@ +../../Task/Quine/Insitux \ No newline at end of file diff --git a/Lang/Insitux/Reverse-words-in-a-string b/Lang/Insitux/Reverse-words-in-a-string new file mode 120000 index 0000000000..bdb507781e --- /dev/null +++ b/Lang/Insitux/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Insitux \ No newline at end of file diff --git a/Lang/Insitux/Rot-13 b/Lang/Insitux/Rot-13 new file mode 120000 index 0000000000..5f3bb99c82 --- /dev/null +++ b/Lang/Insitux/Rot-13 @@ -0,0 +1 @@ +../../Task/Rot-13/Insitux \ No newline at end of file diff --git a/Lang/Insitux/Sorting-algorithms-Bogosort b/Lang/Insitux/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..481b0e62e6 --- /dev/null +++ b/Lang/Insitux/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/Insitux \ No newline at end of file diff --git a/Lang/Insitux/Strip-a-set-of-characters-from-a-string b/Lang/Insitux/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..08ad3cef6b --- /dev/null +++ b/Lang/Insitux/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Insitux \ No newline at end of file diff --git a/Lang/Insitux/Temperature-conversion b/Lang/Insitux/Temperature-conversion new file mode 120000 index 0000000000..6c37692ca1 --- /dev/null +++ b/Lang/Insitux/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Insitux \ No newline at end of file diff --git a/Lang/Insitux/Test-a-function b/Lang/Insitux/Test-a-function new file mode 120000 index 0000000000..ee2b60c155 --- /dev/null +++ b/Lang/Insitux/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/Insitux \ No newline at end of file diff --git a/Lang/Insitux/Time-a-function b/Lang/Insitux/Time-a-function new file mode 120000 index 0000000000..c5dcc0b8b6 --- /dev/null +++ b/Lang/Insitux/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Insitux \ No newline at end of file diff --git a/Lang/Insitux/Variadic-function b/Lang/Insitux/Variadic-function new file mode 120000 index 0000000000..280f56268f --- /dev/null +++ b/Lang/Insitux/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Insitux \ No newline at end of file diff --git a/Lang/Java/Elementary-cellular-automaton-Infinite-length b/Lang/Java/Elementary-cellular-automaton-Infinite-length new file mode 120000 index 0000000000..601d065264 --- /dev/null +++ b/Lang/Java/Elementary-cellular-automaton-Infinite-length @@ -0,0 +1 @@ +../../Task/Elementary-cellular-automaton-Infinite-length/Java \ No newline at end of file diff --git a/Lang/Java/Elementary-cellular-automaton-Random-number-generator b/Lang/Java/Elementary-cellular-automaton-Random-number-generator new file mode 120000 index 0000000000..7c32d62ee3 --- /dev/null +++ b/Lang/Java/Elementary-cellular-automaton-Random-number-generator @@ -0,0 +1 @@ +../../Task/Elementary-cellular-automaton-Random-number-generator/Java \ No newline at end of file diff --git a/Lang/Java/Equal-prime-and-composite-sums b/Lang/Java/Equal-prime-and-composite-sums new file mode 120000 index 0000000000..6a52f9a890 --- /dev/null +++ b/Lang/Java/Equal-prime-and-composite-sums @@ -0,0 +1 @@ +../../Task/Equal-prime-and-composite-sums/Java \ No newline at end of file diff --git a/Lang/Java/File-size-distribution b/Lang/Java/File-size-distribution new file mode 120000 index 0000000000..c7b9a4a145 --- /dev/null +++ b/Lang/Java/File-size-distribution @@ -0,0 +1 @@ +../../Task/File-size-distribution/Java \ No newline at end of file diff --git a/Lang/Lua/Golden-ratio-Convergence b/Lang/Lua/Golden-ratio-Convergence new file mode 120000 index 0000000000..97162496ab --- /dev/null +++ b/Lang/Lua/Golden-ratio-Convergence @@ -0,0 +1 @@ +../../Task/Golden-ratio-Convergence/Lua \ No newline at end of file diff --git a/Lang/MSX-Basic/Sum-digits-of-an-integer b/Lang/MSX-Basic/Sum-digits-of-an-integer new file mode 120000 index 0000000000..3ba32eb8b2 --- /dev/null +++ b/Lang/MSX-Basic/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/MSX-Basic \ No newline at end of file diff --git a/Lang/MSX-Basic/Tau-number b/Lang/MSX-Basic/Tau-number new file mode 120000 index 0000000000..f8d4ed9df7 --- /dev/null +++ b/Lang/MSX-Basic/Tau-number @@ -0,0 +1 @@ +../../Task/Tau-number/MSX-Basic \ No newline at end of file diff --git a/Lang/Modula-2/Bell-numbers b/Lang/Modula-2/Bell-numbers new file mode 120000 index 0000000000..f2ddee022f --- /dev/null +++ b/Lang/Modula-2/Bell-numbers @@ -0,0 +1 @@ +../../Task/Bell-numbers/Modula-2 \ No newline at end of file diff --git a/Lang/Quite-BASIC/Temperature-conversion b/Lang/Quite-BASIC/Temperature-conversion new file mode 120000 index 0000000000..4333fdddcb --- /dev/null +++ b/Lang/Quite-BASIC/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Quite-BASIC \ No newline at end of file diff --git a/Lang/REXX/Radical-of-an-integer b/Lang/REXX/Radical-of-an-integer new file mode 120000 index 0000000000..923b4de0fe --- /dev/null +++ b/Lang/REXX/Radical-of-an-integer @@ -0,0 +1 @@ +../../Task/Radical-of-an-integer/REXX \ No newline at end of file diff --git a/Lang/Raku/Jordan-P-lya-numbers b/Lang/Raku/Jordan-P-lya-numbers new file mode 120000 index 0000000000..9f0af2f41e --- /dev/null +++ b/Lang/Raku/Jordan-P-lya-numbers @@ -0,0 +1 @@ +../../Task/Jordan-P-lya-numbers/Raku \ No newline at end of file diff --git a/Lang/Raku/Prime-numbers-whose-neighboring-pairs-are-tetraprimes b/Lang/Raku/Prime-numbers-whose-neighboring-pairs-are-tetraprimes new file mode 120000 index 0000000000..faf86def6f --- /dev/null +++ b/Lang/Raku/Prime-numbers-whose-neighboring-pairs-are-tetraprimes @@ -0,0 +1 @@ +../../Task/Prime-numbers-whose-neighboring-pairs-are-tetraprimes/Raku \ No newline at end of file diff --git a/Lang/Rust/ADFGVX-cipher b/Lang/Rust/ADFGVX-cipher new file mode 120000 index 0000000000..77d41b8198 --- /dev/null +++ b/Lang/Rust/ADFGVX-cipher @@ -0,0 +1 @@ +../../Task/ADFGVX-cipher/Rust \ No newline at end of file diff --git a/Lang/Rust/Digital-root-Multiplicative-digital-root b/Lang/Rust/Digital-root-Multiplicative-digital-root new file mode 120000 index 0000000000..9b320bd4d1 --- /dev/null +++ b/Lang/Rust/Digital-root-Multiplicative-digital-root @@ -0,0 +1 @@ +../../Task/Digital-root-Multiplicative-digital-root/Rust \ No newline at end of file diff --git a/Lang/Rust/EKG-sequence-convergence b/Lang/Rust/EKG-sequence-convergence new file mode 120000 index 0000000000..0b9134a2aa --- /dev/null +++ b/Lang/Rust/EKG-sequence-convergence @@ -0,0 +1 @@ +../../Task/EKG-sequence-convergence/Rust \ No newline at end of file diff --git a/Lang/Rust/Soundex b/Lang/Rust/Soundex new file mode 120000 index 0000000000..0aa161607f --- /dev/null +++ b/Lang/Rust/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/Rust \ No newline at end of file diff --git a/Task/ABC-problem/Elena/abc-problem.elena b/Task/ABC-problem/Elena/abc-problem.elena index 41a57202a0..0428eced88 100644 --- a/Task/ABC-problem/Elena/abc-problem.elena +++ b/Task/ABC-problem/Elena/abc-problem.elena @@ -1,5 +1,6 @@ import system'routines; import system'collections; +import system'culture; import extensions; import extensions'routines; @@ -9,7 +10,7 @@ extension op { var list := ArrayList.load(blocks); - ^ nil == (cast string(self)).upperCase().seekEach:(ch) + ^ nil == (cast string(self)).toUpper().seekEach:(ch) { var index := list.indexOfElement ((word => word.indexOf(0, ch) != -1).asComparator()); diff --git a/Task/ADFGVX-cipher/Rust/adfgvx-cipher.rust b/Task/ADFGVX-cipher/Rust/adfgvx-cipher.rust new file mode 100644 index 0000000000..d14d245d36 --- /dev/null +++ b/Task/ADFGVX-cipher/Rust/adfgvx-cipher.rust @@ -0,0 +1,150 @@ +// This version formats the encrypted text in 5 character blocks, as the historical version apparently did. + +use fastrand::shuffle; +use std::collections::HashMap; + +static ADFGVX: &str = "ADFGVX"; + +#[derive(Clone, Eq, Hash, PartialEq)] +struct CPair(char, char); + +/// The WWI German ADFGVX cipher. +struct AdfgvxCipher { + polybius: Vec, + key: Vec, + encode: HashMap, + decode: HashMap, +} + +/// Set up the encoding and decoding for the ADFGVX cipher. +fn cipher(allowed_chars: String, encrypt_key: String) -> AdfgvxCipher { + let alphabet = allowed_chars.to_uppercase().chars().collect::>(); + assert!(alphabet.len() == ADFGVX.len() * ADFGVX.len()); + let mut polybius = alphabet.clone(); + shuffle(&mut polybius); + let key = encrypt_key.to_uppercase().chars().collect::>(); + let adfgvx: Vec = String::from(ADFGVX).chars().collect(); + let mut pairs: Vec = [CPair(' ', ' '); 0].to_vec(); + for c1 in &adfgvx { + for c2 in &adfgvx { + pairs.push(CPair(*c1, *c2)); + } + } + let mut encode: HashMap = HashMap::new(); + for i in 0..pairs.len() { + encode.insert(polybius[i], pairs[i].clone()); + } + let mut decode = HashMap::new(); + for (k, v) in &encode { + decode.insert(v.clone(), *k); + } + return AdfgvxCipher { + polybius, + key, + encode, + decode, + }; +} + +/// Encrypt with the ADFGVX cipher. +fn encrypt(a: &AdfgvxCipher, msg: String) -> String { + let umsg: Vec = msg + .clone() + .to_uppercase() + .chars() + .filter(|c| a.polybius.contains(c)) + .collect(); + let mut fractionated = vec![' '; 0].to_vec(); + for c in umsg { + let cp = a.encode.get(&c).unwrap(); + fractionated.push(cp.0); + fractionated.push(cp.1); + } + let ncols = a.key.len(); + let extra = fractionated.len() % ncols; + if extra > 0 { + fractionated.append(&mut vec!['\u{00}'; ncols - extra]); + } + let nrows = fractionated.len() / ncols; + let mut sortedkey = a.key.clone(); + sortedkey.sort(); + let mut ciphertext = String::from(""); + let mut textlen = 0; + for j in 0..ncols { + let k = a.key.iter().position(|c| *c == sortedkey[j]).unwrap(); + for i in 0..nrows { + let ch: char = fractionated[i * ncols + k]; + if ch != '\u{00}' { + ciphertext.push(ch); + textlen += 1; + if textlen % 5 == 0 { + ciphertext.push(' '); + } + } + } + } + return ciphertext; +} + +/// Decrypt with the ADFGVX cipher. Does not depend on spacing of encoded text +fn decrypt(a: &AdfgvxCipher, cod: String) -> String { + let chars: Vec = cod.chars().filter(|c| *c != ' ').collect(); + let mut sortedkey = a.key.clone(); + sortedkey.sort(); + let order: Vec = sortedkey + .iter() + .map(|c| a.key.iter().position(|kc| kc == c).unwrap()) + .collect(); + let originalorder: Vec = a + .key + .iter() + .map(|c| sortedkey.iter().position(|kc| kc == c).unwrap()) + .collect(); + let q = chars.len() / a.key.len(); + let r = chars.len() % a.key.len(); + let strides: Vec = order + .iter() + .map(|i| {q + {if r > *i {1} else {0}}}).collect(); + let mut starts: Vec = vec![0_usize; 1].to_vec(); + let mut stridesum = 0; + for i in 0..strides.len() - 1 { + stridesum += strides[i]; + starts.push(stridesum); + } + let ends: Vec = (0..a.key.len()).map(|i| (starts[i] + strides[i])).collect(); // shuffled ends of columns + let cols: Vec> = originalorder + .iter() + .map(|i| (chars[starts[*i]..ends[*i]]).to_vec()) + .collect(); // get reordered columns + let nrows = (chars.len() - 1) / a.key.len() + 1; + let mut fractionated = vec![' '; 0].to_vec(); + for i in 0..nrows { + for j in 0..a.key.len() { + if i < cols[j].len() { + fractionated.push(cols[j][i]); + } + } + } + let mut decoded = String::from(""); + for i in 0..fractionated.len() - 1 { + if i % 2 == 0 { + let cp = CPair(fractionated[i], fractionated[i + 1]); + decoded.push(*a.decode.get(&cp).unwrap()); + } + } + return decoded; +} + +fn main() { + let msg = String::from("ATTACKAT1200AM"); + let encrypt_key = String::from("volcanism"); + let allowed_chars: String = String::from("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"); + let adf = cipher(allowed_chars, encrypt_key.clone()); + println!("Message: {msg}"); + println!("Polybius: {:?}", adf.polybius.iter().collect::()); + println!("Key: {encrypt_key}"); + let encrypted_message = encrypt(&adf, msg.clone()); + println!("Encoded: {encrypted_message}"); + let decoded = decrypt(&adf, encrypted_message); + println!("Decoded: {decoded:?}"); +} diff --git a/Task/Ascending-primes/ALGOL-W/ascending-primes.alg b/Task/Ascending-primes/ALGOL-W/ascending-primes.alg new file mode 100644 index 0000000000..cf7ab2201e --- /dev/null +++ b/Task/Ascending-primes/ALGOL-W/ascending-primes.alg @@ -0,0 +1,82 @@ +begin % find all primes with strictly ascending digits - translation of Lua % + + % quicksorts v, the bounds of v must be specified in lb and ub % + procedure quicksort ( integer array v( * ) + ; integer value lb, ub + ) ; + if ub > lb then begin + % more than one element, so must sort % + integer left, right, pivot; + left := lb; + right := ub; + % choosing the middle element of the array as the pivot % + pivot := v( left + ( ( right + 1 ) - left ) div 2 ); + while begin + while left <= ub and v( left ) < pivot do left := left + 1; + while right >= lb and v( right ) > pivot do right := right - 1; + left <= right + end do begin + integer swap; + swap := v( left ); + v( left ) := v( right ); + v( right ) := swap; + left := left + 1; + right := right - 1 + end while_left_le_right ; + quicksort( v, lb, right ); + quicksort( v, left, ub ) + end quicksort ; + + % returns true if n is prime, false otherwise % + logical procedure is_prime( integer value n ) ; + if n < 2 then false + else if n rem 2 = 0 then n = 2 + else if n rem 3 = 0 then n = 3 + else begin + logical prime; prime := true; + for f := 5 step 6 until entier( sqrt( n ) ) do begin + if n rem f = 0 or n rem ( f + 2 ) = 0 then begin + prime := false; + goto done + end if_n_rem_f_eq_0_or_n_rem_f_plus_2_eq_0 + end for_f; +done: prime + end is_prime ; + + % increments n and also returns its new value % + integer procedure inc ( integer value result n ) ; begin n := n + 1; n end; + + % sets primes to the list of ascending primes and lenPrimes to the % + % number of ascending primes - primes must be big enough, e.g. have 511 % + % elements % + procedure ascending_primes ( integer array primes ( * ) + ; integer result lenPrimes + ) ; + begin + integer array digits ( 1 :: 9 ); + integer array candidates ( 1 :: 6000 ); + integer lenCandidates; + candidates( 1 ) := 0; + lenCandidates := 1; + lenPrimes := 0; + for i := 1 until 9 do digits( i ) := i; + for i := 1 until 9 do begin + for j := 1 until lenCandidates do begin + integer cValue; cValue := candidates( j ) * 10 + digits( i ); + if is_prime( cValue ) then primes( inc( lenPrimes ) ) := cValue; + candidates( inc( lenCandidates ) ) := cValue + end for_j + end for_i ; + quickSort( primes, 1, lenPrimes ); + end ascending_primes ; + + begin % find the ascending primes and print them % + integer array primes ( 1 :: 512 ); + integer lenPrimes; + ascending_primes( primes, lenPrimes ); + for i := 1 until lenPrimes do begin + writeon( i_w := 8, s_w := 0, " ", primes( i ) ); + if i rem 10 = 0 then write() + end for_i + end +end. diff --git a/Task/Averages-Median/AArch64-Assembly/averages-median.aarch64 b/Task/Averages-Median/AArch64-Assembly/averages-median.aarch64 new file mode 100644 index 0000000000..bba61974dc --- /dev/null +++ b/Task/Averages-Median/AArch64-Assembly/averages-median.aarch64 @@ -0,0 +1,583 @@ +/* ARM assembly AARCH64 Raspberry PI 3B */ +/* program averageMed64.s */ +/* use quickselect look pseudo code in wikipedia quickselect */ + +/************************************/ +/* Constantes */ +/************************************/ +/* for this file see task include a file in language AArch64 assembly*/ +.include "../includeConstantesARM64.inc" + +/*********************************/ +/* Initialized data */ +/*********************************/ +.data +szMessResultValue: .asciz "Result : " +szCarriageReturn: .asciz "\n" + +.align 4 +TableNumber: .double 4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2 +.equ NBELEMENTS, (. - TableNumber) / 8 +TableNumber2: .double 4.1, 7.2, 1.7, 9.3, 4.4, 3.2 +.equ NBELEMENTS2, (. - TableNumber2) / 8 +/*********************************/ +/* UnInitialized data */ +/*********************************/ +.bss +sZoneConv: .skip 24 +sZoneConv1: .skip 24 +/*********************************/ +/* code section */ +/*********************************/ +.text +.global main +main: // entry of program + ldr x0,qAdrTableNumber // address number table + mov x1,#0 // index first item + mov x2,#NBELEMENTS -1 // index last item + bl searchMedian + ldr x0,qAdrTableNumber2 // address number table 2 + mov x1,#0 // index first item + mov x2,#NBELEMENTS2 -1 // index last item + bl searchMedian + +100: // standard end of the program + mov x0, #0 // return code + mov x8, #EXIT // request to exit program + svc #0 // perform the system call + +qAdrszCarriageReturn: .quad szCarriageReturn +qAdrTableNumber: .quad TableNumber +qAdrTableNumber2: .quad TableNumber2 +qAdrsZoneConv: .quad sZoneConv +qAdrszMessResultValue: .quad szMessResultValue +/***************************************************/ +/* search median term in float array */ +/***************************************************/ +/* x0 contains the address of table */ +/* x1 contains index of first item */ +/* x2 contains index of last item */ +searchMedian: + stp x1,lr,[sp,-16]! // save registers TODO: à revoir génération + stp x2,x3,[sp,-16]! // save registers + stp x4,x5,[sp,-16]! // save registers + + mov x19,x0 // save array address + add x4,x1,x2 + add x4,x4,#1 // sum numbers terms + tst x4,#1 // odd ? + bne 1f + lsr x3,x4,#1 // compute median index + bl select // call selection + fmov d0,x0 // save first result + sub x3,x3,#1 // second term + mov x0,x19 + bl select // call selection + fmov d1,x0 // save 2ieme résult + fadd d0,d0,d1 // compute average two résults + mov x0,#2 + fmov d1,x0 + scvtf d1,d1 // conversion integer -> float + fdiv d0,d0,d1 + b 2f +1: // even + lsr x3,x4,#1 + bl select // call selection + fmov d0,x0 +2: + ldr x0,qAdrsZoneConv // conversion float in decimal string + bl convertirFloat + mov x0,#3 // and display result + ldr x1,qAdrszMessResultValue + ldr x2,qAdrsZoneConv + ldr x3,qAdrszCarriageReturn + bl displayStrings +100: // end function + + ldp x4,x5,[sp],16 // restaur 2 registers + ldp x2,x3,[sp],16 // restaur 2 registers + ldp x1,lr,[sp],16 // restaur 2 registers + ret + +/***************************************************/ +/* Appel récursif selection */ +/***************************************************/ +/* x0 contains the address of table */ +/* x1 contains index of first item */ +/* x2 contains index of last item */ +/* x3 contains search index */ +select: + 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 + mov x6,x3 // save search index + cmp x1,x2 // first = last ? + bne 1f + ldr x0,[x0,x1,lsl #3] // return value of first index + b 100f // yes -> end +1: + add x3,x1,x2 + lsr x3,x3,#1 // compute median pivot + mov x4,x0 // save x0 + mov x5,x2 // save x2 + bl partition // cutting.quado 2 parts + cmp x6,x0 // pivot is ok ? + bne 2f + ldr x0,[x4,x0,lsl #3] // yes -> return value + b 100f + 2: + bgt 3f + sub x2,x0,#1 // index partition - 1 + mov x0,x4 // array address + mov x3,x6 // search index + bl select // select lower part + b 100f +3: + add x1,x0,#1 // index begin = index partition + 1 + mov x0,x4 // array address + mov x2,x5 // last item + mov x3,x6 // search index + bl select // select higter part + + 100: // end function + ldp x6,x7,[sp],16 // restaur 2 registers + ldp x4,x5,[sp],16 // restaur 2 registers + ldp x2,x3,[sp],16 // restaur 2 registers + ldp x1,lr,[sp],16 // restaur 2 registers + ret // return to address lr x30 +/******************************************************************/ +/* Partition table elements */ +/******************************************************************/ +/* x0 contains the address of table */ +/* x1 contains index of first item */ +/* x2 contains index of last item */ +/* x3 contains index of pivot */ +partition: + 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 + ldr x4,[x0,x3,lsl #3] // load value of pivot + ldr x5,[x0,x2,lsl #3] // load value last index + str x5,[x0,x3,lsl #3] // swap value of pivot + str x4,[x0,x2,lsl #3] // and value last index + mov x3,x1 // init with first index +1: // begin loop + ldr x6,[x0,x3,lsl #3] // load value + cmp x6,x4 // compare loop value and pivot value + bge 2f + ldr x5,[x0,x1,lsl #3] // if < swap value table + str x6,[x0,x1,lsl #3] + str x5,[x0,x3,lsl #3] + add x1,x1,#1 // and increment index 1 +2: + add x3,x3,#1 // increment index 2 + cmp x3,x2 // end ? + blt 1b // no loop + ldr x5,[x0,x1,lsl #3] // swap value + str x4,[x0,x1,lsl #3] + str x5,[x0,x2,lsl #3] + mov x0,x1 // return index partition +100: + ldp x6,x7,[sp],16 // restaur 2 registers + ldp x4,x5,[sp],16 // restaur 2 registers + ldp x2,x3,[sp],16 // restaur 2 registers + ldp x1,lr,[sp],16 // restaur 2 registers + ret // return to address lr x30 + + /***************************************************/ +/* 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 +/******************************************************************/ +/* Conversion Float */ +/******************************************************************/ +/* d0 contains Float */ +/* x0 contains address conversion area mini 20 charactèrs */ +/* x0 return result length */ +/* see https://blog.benoitblanchon.fr/lightweight-float-to-string/ */ +convertirFloat: + stp x1,lr,[sp,-16]! // save registres + stp x2,x3,[sp,-16]! // save registres + stp x4,x5,[sp,-16]! // save registres + stp x6,x7,[sp,-16]! // save registres + stp x8,x9,[sp,-16]! // save registres + stp d1,d2,[sp,-16]! // save registres + mov x6,x0 // save area address + fmov x0,d0 + mov x8,#0 // result length + mov x3,#'+' + strb w3,[x6] // signe + forcing + mov x2,x0 + tbz x2,63,1f + mov x2,1 + lsl x2,x2,63 + bic x0,x0,x2 + mov x3,#'-' // sign - + strb w3,[x6] +1: + adds x8,x8,#1 // next position + cmp x0,#0 // case 0 positive or negative + bne 2f + mov x3,#'0' + strb w3,[x6,x8] // store character 0 + adds x8,x8,#1 + strb wzr,[x6,x8] // store 0 final + mov x0,x8 // return length + b 100f +2: + ldr x2,iMaskExposant + mov x1,x0 + and x1,x1,x2 // exposant + cmp x1,x2 + bne 4f + tbz x0,51,3f // test bit 51 to zéro + mov x2,#'N' // case Nan. store byte no possible store integer + strb w2,[x6] // area no aligned + mov x2,#'a' + strb w2,[x6,#1] + mov x2,#'n' + strb w2,[x6,#2] + mov x2,#0 // 0 final + strb w2,[x6,#3] + mov x0,#3 + b 100f +3: // case infini positive or négative + mov x2,#'I' + strb w2,[x6,x8] + adds x8,x8,#1 + mov x2,#'n' + strb w2,[x6,x8] + adds x8,x8,#1 + mov x2,#'f' + strb w2,[x6,x8] + adds x8,x8,#1 + mov x2,#0 + strb w2,[x6,x8] + mov x0,x8 + b 100f +4: + bl normaliserFloat + mov x5,x0 // save exposant + fcvtzu d2,d0 + fmov x0,d2 // part integer + scvtf d1,d2 // conversion float + fsub d1,d0,d1 // extraction part fractional + ldr d2,dConst1 + fmul d1,d2,d1 // to crop it in full + fcvtzu d1,d1 // convertion integer + fmov x4,d1 // fract value + // conversion part integer to x0 + mov x2,x6 // save address begin area + adds x6,x6,x8 + mov x1,x6 + bl conversion10 + add x6,x6,x0 + mov x3,#',' + strb w3,[x6] + adds x6,x6,#1 + + mov x0,x4 // conversion part fractionnaire + mov x1,x6 + bl conversion10SP + add x6,x6,x0 + sub x6,x6,#1 + // remove trailing zeros +5: + ldrb w0,[x6] + cmp w0,#'0' + bne 6f + sub x6,x6,#1 + b 5b +6: + cmp w0,#',' + bne 7f + sub x6,x6,#1 +7: + cmp x5,#0 // if exposant = 0 no display + bne 8f + add x6,x6,#1 + b 10f +8: + add x6,x6,#1 + mov x3,#'E' + strb w3,[x6] + add x6,x6,#1 + mov x0,x5 // conversion exposant + mov x3,x0 + tbz x3,63,9f // exposant negative ? + neg x0,x0 + mov x3,#'-' + strb w3,[x6] + adds x6,x6,#1 +9: + mov x1,x6 + bl conversion10 + add x6,x6,x0 +10: + strb wzr,[x6] // store 0 final + adds x6,x6,#1 + mov x0,x6 + subs x0,x0,x2 // retour de la longueur de la zone + subs x0,x0,#1 // sans le 0 final + +100: + ldp d1,d2,[sp],16 // restaur registres + ldp x8,x9,[sp],16 // restaur registres + ldp x6,x7,[sp],16 // restaur registres + ldp x4,x5,[sp],16 // restaur registres + ldp x2,x3,[sp],16 // restaur registres + ldp x1,lr,[sp],16 // restaur registres + ret + +iMaskExposant: .quad 0x7FF<<52 +dConst1: .double 0f1E17 + +/***************************************************/ +/* normaliser float */ +/***************************************************/ +/* x0 contain float value (always positive value and <> Nan) */ +/* d0 return new value */ +/* x0 return exposant */ +normaliserFloat: + stp x1,lr,[sp,-16]! // save registers + fmov d0,x0 // value float + mov x0,#0 // exposant + ldr d1,dConstE7 // no normalisation for value < 1E7 + fcmp d0,d1 + blo 10f // if d0 < dConstE7 + + ldr d1,dConstE256 + fcmp d0,d1 + blo 1f + fdiv d0,d0,d1 + adds x0,x0,#256 +1: + + ldr d1,dConstE128 + fcmp d0,d1 + blo 1f + fdiv d0,d0,d1 + adds x0,x0,#128 +1: + ldr d1,dConstE64 + fcmp d0,d1 + blo 1f + fdiv d0,d0,d1 + adds x0,x0,#64 +1: + ldr d1,dConstE32 + fcmp d0,d1 + blo 1f + fdiv d0,d0,d1 + adds x0,x0,#32 +1: + ldr d1,dConstE16 + fcmp d0,d1 + blo 2f + fdiv d0,d0,d1 + adds x0,x0,#16 +2: + ldr d1,dConstE8 + fcmp d0,d1 + blo 3f + fdiv d0,d0,d1 + adds x0,x0,#8 +3: + ldr d1,dConstE4 + fcmp d0,d1 + blo 4f + fdiv d0,d0,d1 + adds x0,x0,#4 +4: + ldr d1,dConstE2 + fcmp d0,d1 + blo 5f + fdiv d0,d0,d1 + adds x0,x0,#2 +5: + ldr d1,dConstE1 + fcmp d0,d1 + blo 10f + fdiv d0,d0,d1 + adds x0,x0,#1 + +10: + ldr d1,dConstME5 // pas de normalisation pour les valeurs > 1E-5 + fcmp d0,d1 + bhi 100f // fin + + ldr d1,dConstME255 + fcmp d0,d1 + bhi 11f + ldr d1,dConstE256 + + fmul d0,d0,d1 + subs x0,x0,#256 +11: + + ldr d1,dConstME127 + fcmp d0,d1 + bhi 11f + ldr d1,dConstE128 + + fmul d0,d0,d1 + subs x0,x0,#128 +11: + + ldr d1,dConstME63 + fcmp d0,d1 + bhi 11f + ldr d1,dConstE64 + + fmul d0,d0,d1 + subs x0,x0,#64 +11: + + ldr d1,dConstME31 + fcmp d0,d1 + bhi 11f + ldr d1,dConstE32 + + fmul d0,d0,d1 + subs x0,x0,#32 +11: + ldr d1,dConstME15 + fcmp d0,d1 + bhi 12f + ldr d1,dConstE16 + fmul d0,d0,d1 + subs x0,x0,#16 +12: + ldr d1,dConstME7 + fcmp d0,d1 + bhi 13f + ldr d1,dConstE8 + fmul d0,d0,d1 + subs x0,x0,#8 +13: + ldr d1,dConstME3 + fcmp d0,d1 + bhi 14f + ldr d1,dConstE4 + fmul d0,d0,d1 + subs x0,x0,#4 +14: + ldr d1,dConstME1 + fcmp d0,d1 + bhi 15f + ldr d1,dConstE2 + fmul d0,d0,d1 + subs x0,x0,#2 +15: + ldr d1,dConstE0 + fcmp d0,d1 + bhi 100f + ldr d1,dConstE1 + fmul d0,d0,d1 + subs x0,x0,#1 + +100: // fin standard de la fonction + ldp x1,lr,[sp],16 // restaur registres + ret +.align 2 +dConstE7: .double 0f1E7 +dConstE256: .double 0f1E256 +dConstE128: .double 0f1E128 +dConstE64: .double 0f1E64 +dConstE32: .double 0f1E32 +dConstE16: .double 0f1E16 +dConstE8: .double 0f1E8 +dConstE4: .double 0f1E4 +dConstE2: .double 0f1E2 +dConstE1: .double 0f1E1 +dConstME5: .double 0f1E-5 +dConstME255: .double 0f1E-255 +dConstME127: .double 0f1E-127 +dConstME63: .double 0f1E-63 +dConstME31: .double 0f1E-31 +dConstME15: .double 0f1E-15 +dConstME7: .double 0f1E-7 +dConstME3: .double 0f1E-3 +dConstME1: .double 0f1E-1 +dConstE0: .double 0f1E0 + +/******************************************************************/ +/* Décimal Conversion */ +/******************************************************************/ +/* x0 contain value et x1 address conversion area */ +conversion10SP: + stp x1,lr,[sp,-16]! // save registers + stp x2,x3,[sp,-16]! // save registers + stp x4,x5,[sp,-16]! // save registers + mov x5,x1 + mov x4,#16 + mov x2,x0 + mov x1,#10 // décimal conversion +1: // conversion loop + mov x0,x2 // copy begin number or quotient + udiv x2,x0,x1 // division by 10 + msub x3,x1,x2,x0 // compute remainder + add x3,x3,#48 // compute digit + strb w3,[x5,x4] // store byte address area (x5) + offset (x4) + subs x4,x4,#1 // position precedente + bge 1b + strb wzr,[x5,16] // 0 final +100: + ldp x4,x5,[sp],16 // restaur registers + ldp x2,x3,[sp],16 // restaur registers + ldp x1,lr,[sp],16 // restaur registers + ret + +/***************************************************/ +/* ROUTINES INCLUDE */ +/***************************************************/ +/* for this file see task include a file in language AArch64 assembly*/ +.include "../includeARM64.inc" diff --git a/Task/Averages-Median/ARM-Assembly/averages-median.arm b/Task/Averages-Median/ARM-Assembly/averages-median.arm index 5b06da83df..ce7a525e15 100644 --- a/Task/Averages-Median/ARM-Assembly/averages-median.arm +++ b/Task/Averages-Median/ARM-Assembly/averages-median.arm @@ -202,6 +202,7 @@ displayStrings: @ INFO: displayStrings /* s0 contains Float */ /* r0 contains address conversion area mini 20 charactèrs*/ /* r0 return result length */ +/* see https://blog.benoitblanchon.fr/lightweight-float-to-string/ */ convertirFloat: push {r1-r7,lr} vpush {s0-s2} diff --git a/Task/Bell-numbers/ANSI-BASIC/bell-numbers.basic b/Task/Bell-numbers/ANSI-BASIC/bell-numbers.basic new file mode 100644 index 0000000000..f164dbfea7 --- /dev/null +++ b/Task/Bell-numbers/ANSI-BASIC/bell-numbers.basic @@ -0,0 +1,19 @@ +100 REM Bell numbers +110 LET MaxN = 14 +120 OPTION BASE 0 +130 DIM A(13) ! i.e. DIM A(MaxN - 1), ANSI BASIC does not allow expressions in the bound arguments. +140 FOR I = 0 TO MaxN - 1 +150 LET A(I) = 0 +160 NEXT I +170 LET N = 0 +180 LET A(0) = 1 +190 PRINT USING "B(##) = #########": N, A(0) +200 DO WHILE N < MaxN +210 LET A(N) = A(0) +220 FOR J = N TO 1 STEP -1 +230 LET A(J - 1) = A(J - 1) + A(J) +240 NEXT J +250 LET N = N + 1 +260 PRINT USING "B(##) = #########": N, A(0) +270 LOOP +280 END diff --git a/Task/Bell-numbers/Delphi/bell-numbers.delphi b/Task/Bell-numbers/Delphi/bell-numbers.delphi index 6f2108ea2b..3cca7aaf15 100644 --- a/Task/Bell-numbers/Delphi/bell-numbers.delphi +++ b/Task/Bell-numbers/Delphi/bell-numbers.delphi @@ -9,11 +9,11 @@ program BellNumbers; uses SysUtils; // only for the display const - MAX_INDEX = 25; // maximum index within the limits of int64 + MAX_N = 25; // maximum index of Bell number within the limits of int64 var n : integer; // index of Bell number j : integer; // loop variable - a : array [0..MAX_INDEX - 1] of int64; // working array to build up B_n + a : array [0..MAX_N - 1] of int64; // working array to build up B_n { Subroutine to display that a[0] is the Bell number B_n } procedure Display(); @@ -26,7 +26,7 @@ begin n := 0; a[0] := 1; Display(); // some programmers would prefer Display; - while (n < MAX_INDEX) do begin // and give begin a line to itself + while (n < MAX_N) do begin // and give begin a line to itself a[n] := a[0]; for j := n downto 1 do inc( a[j - 1], a[j]); inc(n); diff --git a/Task/Bell-numbers/Modula-2/bell-numbers.mod2 b/Task/Bell-numbers/Modula-2/bell-numbers.mod2 new file mode 100644 index 0000000000..18481eab96 --- /dev/null +++ b/Task/Bell-numbers/Modula-2/bell-numbers.mod2 @@ -0,0 +1,39 @@ +MODULE BellNumbers; + +FROM STextIO IMPORT + WriteLn, WriteString; +FROM SWholeIO IMPORT + WriteInt; + +CONST + MaxN = 14; + +VAR + A: ARRAY [0 .. MaxN - 1] OF CARDINAL; + I, J, N: CARDINAL; + +PROCEDURE DisplayRow(N, BellNum: CARDINAL); +BEGIN + WriteString("B("); + WriteInt(N, 2); + WriteString(") = "); + WriteInt(BellNum, 9); + WriteLn +END DisplayRow; + +BEGIN + FOR I := 0 TO MaxN - 1 DO + A[I] := 0 + END; + N := 0; + A[0] := 1; + DisplayRow(N, A[0]); + WHILE N < MaxN DO + A[N] := A[0]; + FOR J := N TO 1 BY -1 DO + A[J - 1] := A[J - 1] + A[J] + END; + N := N + 1; + DisplayRow(N, A[0]) + END +END BellNumbers. diff --git a/Task/Bell-numbers/QuickBASIC/bell-numbers.basic b/Task/Bell-numbers/QuickBASIC/bell-numbers.basic index 4e44c5a639..db6a4a289b 100644 --- a/Task/Bell-numbers/QuickBASIC/bell-numbers.basic +++ b/Task/Bell-numbers/QuickBASIC/bell-numbers.basic @@ -1,26 +1,18 @@ ' Bell numbers -DECLARE SUB DisplayRow (N%, BellNum&) -CONST MAXINDEX% = 14 -DIM A&(MAXINDEX% - 1) -FOR I% = 0 TO MAXINDEX% - 1 +CONST MAXN% = 14 +DIM A&(MAXN% - 1) +FOR I% = 0 TO MAXN% - 1 A&(I%) = 0 NEXT I% N% = 0 A&(0) = 1 -DisplayRow N%, A&(0) -WHILE N% < MAXINDEX% +PRINT USING "B(##) = #########"; N%; A&(0) +WHILE N% < MAXN% A&(N%) = A&(0) FOR J% = N% TO 1 STEP -1 A&(J% - 1) = A&(J% - 1) + A&(J%) NEXT J% N% = N% + 1 - DisplayRow N%, A&(0) + PRINT USING "B(##) = #########"; N%; A&(0) WEND END - -SUB DisplayRow (N%, BellNum&) - PRINT "B("; - PRINT USING "##"; N%; - PRINT ") = "; - PRINT USING "#########"; BellNum& -END SUB diff --git a/Task/Bell-numbers/RapidQ/bell-numbers.rapidq b/Task/Bell-numbers/RapidQ/bell-numbers.rapidq index 44fd655262..01615d9065 100644 --- a/Task/Bell-numbers/RapidQ/bell-numbers.rapidq +++ b/Task/Bell-numbers/RapidQ/bell-numbers.rapidq @@ -1,13 +1,13 @@ ' Bell numbers -CONST MAXINDEX% = 14 -DIM A&(MAXINDEX% - 1) -FOR I% = 0 TO MAXINDEX% - 1 +CONST MAXN% = 14 +DIM A&(MAXN% - 1) +FOR I% = 0 TO MAXN% - 1 A&(I%) = 0 NEXT I% N% = 0 A&(0) = 1 PRINT FORMAT$("B(%2d) = %9d", N%, A&(0)) -WHILE N% < MAXINDEX% +WHILE N% < MAXN% A&(N%) = A&(0) FOR J% = N% TO 1 STEP -1 A&(J% - 1) = A&(J% - 1) + A&(J%) diff --git a/Task/Bell-numbers/XPL0/bell-numbers.xpl0 b/Task/Bell-numbers/XPL0/bell-numbers.xpl0 index 0b46ff8442..ef2485d8a2 100644 --- a/Task/Bell-numbers/XPL0/bell-numbers.xpl0 +++ b/Task/Bell-numbers/XPL0/bell-numbers.xpl0 @@ -1,13 +1,13 @@ \Bell numbers code CrLf=9, IntOut=11, Text=12; -define MaxIndex = 14; -integer A(MaxIndex), I, J, N; +define MaxN = 14; +integer A(MaxN), I, J, N; begin -for I:= 0 to MaxIndex - 1 do A(I):= 0; +for I:= 0 to MaxN - 1 do A(I):= 0; N:= 0; A(0):= 1; Text(0, "B("); IntOut(0, N); Text(0, ") = "); IntOut(0, A(0)); CrLf(0); -while N < MaxIndex do +while N < MaxN do begin A(N):= A(0); for J:= N downto 1 do A(J - 1):= A(J - 1) + A(J); diff --git a/Task/Bifid-cipher/C++/bifid-cipher.cpp b/Task/Bifid-cipher/C++/bifid-cipher.cpp index 1d29e8b427..0e93a81f8a 100644 --- a/Task/Bifid-cipher/C++/bifid-cipher.cpp +++ b/Task/Bifid-cipher/C++/bifid-cipher.cpp @@ -11,7 +11,7 @@ class Bifid { public: Bifid(const int32_t n, std::string_view text) { if ( text.length() != n * n ) { - throw new std::invalid_argument("Incorrect length of text"); + throw std::invalid_argument("Incorrect length of text"); } grid.resize(n); diff --git a/Task/Check-that-file-exists/Forth/check-that-file-exists.fth b/Task/Check-that-file-exists/Forth/check-that-file-exists.fth index e87e4b4914..485c931bb3 100644 --- a/Task/Check-that-file-exists/Forth/check-that-file-exists.fth +++ b/Task/Check-that-file-exists/Forth/check-that-file-exists.fth @@ -1,5 +1,13 @@ -: .exists ( str len -- ) 2dup file-status nip 0= if ." exists" else ." does not exist" then type ; - s" input.txt" .exists -s" /input.txt" .exists - s" docs" .exists -s" /docs" .exists +: .exists ( str len -- ) + 2dup file-status nip 0= if + ." exists: " + else + ." does not exist: " + then + type +; + +s" input.txt" .exists cr +s" /input.txt" .exists cr +s" docs" .exists cr +s" /docs" .exists cr diff --git a/Task/Currying/Julia/currying.julia b/Task/Currying/Julia/currying-1.julia similarity index 100% rename from Task/Currying/Julia/currying.julia rename to Task/Currying/Julia/currying-1.julia diff --git a/Task/Currying/Julia/currying-2.julia b/Task/Currying/Julia/currying-2.julia new file mode 100644 index 0000000000..9638ad02a4 --- /dev/null +++ b/Task/Currying/Julia/currying-2.julia @@ -0,0 +1 @@ +addN(n) = x -> n + x diff --git a/Task/Descending-primes/ALGOL-W/descending-primes.alg b/Task/Descending-primes/ALGOL-W/descending-primes.alg new file mode 100644 index 0000000000..7476b6261e --- /dev/null +++ b/Task/Descending-primes/ALGOL-W/descending-primes.alg @@ -0,0 +1,82 @@ +begin % find all primes with strictly descending digits - translation of Lua % + + % quicksorts v, the bounds of v must be specified in lb and ub % + procedure quicksort ( integer array v( * ) + ; integer value lb, ub + ) ; + if ub > lb then begin + % more than one element, so must sort % + integer left, right, pivot; + left := lb; + right := ub; + % choosing the middle element of the array as the pivot % + pivot := v( left + ( ( right + 1 ) - left ) div 2 ); + while begin + while left <= ub and v( left ) < pivot do left := left + 1; + while right >= lb and v( right ) > pivot do right := right - 1; + left <= right + end do begin + integer swap; + swap := v( left ); + v( left ) := v( right ); + v( right ) := swap; + left := left + 1; + right := right - 1 + end while_left_le_right ; + quicksort( v, lb, right ); + quicksort( v, left, ub ) + end quicksort ; + + % returns true if n is prime, false otherwise % + logical procedure is_prime( integer value n ) ; + if n < 2 then false + else if n rem 2 = 0 then n = 2 + else if n rem 3 = 0 then n = 3 + else begin + logical prime; prime := true; + for f := 5 step 6 until entier( sqrt( n ) ) do begin + if n rem f = 0 or n rem ( f + 2 ) = 0 then begin + prime := false; + goto done + end if_n_rem_f_eq_0_or_n_rem_f_plus_2_eq_0 + end for_f; +done: prime + end is_prime ; + + % increments n and also returns its new value % + integer procedure inc ( integer value result n ) ; begin n := n + 1; n end; + + % sets primes to the list of descending primes and lenPrimes to the % + % number of descending primes - primes must be big enough, e.g. have 511 % + % elements % + procedure descending_primes ( integer array primes ( * ) + ; integer result lenPrimes + ) ; + begin + integer array digits ( 1 :: 9 ); + integer array candidates ( 1 :: 6000 ); + integer lenCandidates; + candidates( 1 ) := 0; + lenCandidates := 1; + lenPrimes := 0; + for i := 1 until 9 do digits( i ) := 10 - i; + for i := 1 until 9 do begin + for j := 1 until lenCandidates do begin + integer cValue; cValue := candidates( j ) * 10 + digits( i ); + if is_prime( cValue ) then primes( inc( lenPrimes ) ) := cValue; + candidates( inc( lenCandidates ) ) := cValue + end for_j + end for_i ; + quickSort( primes, 1, lenPrimes ); + end descending_primes ; + + begin % find the descending primes and print them % + integer array primes ( 1 :: 512 ); + integer lenPrimes; + descending_primes( primes, lenPrimes ); + for i := 1 until lenPrimes do begin + writeon( i_w := 8, s_w := 0, " ", primes( i ) ); + if i rem 10 = 0 then write() + end for_i + end +end. diff --git a/Task/Digital-root-Multiplicative-digital-root/Rust/digital-root-multiplicative-digital-root.rust b/Task/Digital-root-Multiplicative-digital-root/Rust/digital-root-multiplicative-digital-root.rust new file mode 100644 index 0000000000..ac36cc43c1 --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/Rust/digital-root-multiplicative-digital-root.rust @@ -0,0 +1,35 @@ +// Multiplicative digital root +fn mdroot(n: u32) -> (u32, u32) { + let mut count = 0; + let mut mdr = n; + while mdr > 9 { + let mut m = mdr; + let mut digits_mul = 1; + while m > 0 { + digits_mul *= m % 10; + m /= 10; + } + mdr = digits_mul; + count += 1; + } + return (count, mdr); +} + +fn main() { + println!("Number: (MP, MDR)\n====== ========="); + for n in [123321, 7739, 893, 899998] { + println!("{:6}: {:?}", n, mdroot(n)); + } + let mut table = vec![vec![0_u32; 0]; 10]; + let mut n = 0; + while table.iter().map(|row| row.len()).min().unwrap() < 5 { + let (_, mdr) = mdroot(n); + table[mdr as usize].push(n); + n += 1; + } + println!("\nMDR First 5 with matching MDR\n=== ========================="); + table.sort(); + for a in table { + println!("{:2}: {:5}{:6}{:6}{:6}{:6}", a[0], a[0], a[1], a[2], a[3], a[4]); + } +} diff --git a/Task/Duffinian-numbers/Applesoft-BASIC/duffinian-numbers.basic b/Task/Duffinian-numbers/Applesoft-BASIC/duffinian-numbers.basic new file mode 100644 index 0000000000..1dbdd40b2e --- /dev/null +++ b/Task/Duffinian-numbers/Applesoft-BASIC/duffinian-numbers.basic @@ -0,0 +1,56 @@ + 100 DEF FN MOD(NUM) = NUM - INT (NUM / DIV) * DIV: REM NUM MOD DIV + 110 M = 50:N = 4 + 120 PRINT "FIRST "M" DUFFINIAN NUMBERS:" + 130 FOR C = 0 TO M STEP 0 + 140 GOSUB 600"DUFF + 150 IF DUFF THEN PRINT RIGHT$ (" " + STR$ (N),4);:C = C + 1 + 160 N = N + 1 + 170 NEXT C + 180 M = 15:S = 4:M$ = CHR$ (13) + 190 PRINT M$M$"FIRST "M" DUFFINIAN TRIPLETS:" + 200 FOR C = 0 TO M STEP 0 + 210 FOR D = 2 TO 0 STEP - 1:N = S + D: GOSUB 600: IF DUFF THEN NEXT D + 220 IF D < 0 THEN C = C + 1: PRINT RIGHT$ (" " + STR$ (S) + "-",5) LEFT$ ( STR$ (S + 2) + " ",5);:D = 0 + 230 S = S + D + 1 + 240 NEXT C + 250 END + + REM ISPRIME V RETURNS ISPRIME + 260 ISPRIME = FALSE: IF V < 2 THEN RETURN + 270 DIV = 2:ISPRIME = FN MOD(V): IF NOT ISPRIME THEN ISPRIME = V = 2: RETURN + 280 LIMIT = SQR (V): IF LIMIT > = 3 THEN FOR DIV = 3 TO LIMIT STEP 2:ISPRIME = FN MOD(V): IF ISPRIME THEN NEXT DIV + 290 RETURN + + REM GREATEST COMMON DIVISOR (GCD) A B RETURNS GCD + 300 A = ABS ( INT (A)) + 310 B = ABS ( INT (B)) + 320 GCD = A * NOT NOT B + 330 FOR B = B + A * NOT B TO 0 STEP 0 + 340 A = GCD + 350 GCD = B + 360 B = A - INT (A / GCD) * GCD + 370 NEXT B + 380 RETURN + + REM SUMDIV NUM RETURNS SUM + 400 DIV = 2 + 410 SUM = 0 + 420 QUOT = NUM / DIV + 430 IF DIV > QUOT THEN SUM = 1: RETURN + 440 FOR LOOP = 0 TO 1 STEP 0 + 450 IF FN MOD(NUM) = 0 THEN SUM = SUM + DIV: IF DIV < > QUOT THEN SUM = SUM + QUOT + 460 DIV = DIV + 1 + 470 QUOT = NUM / DIV + 480 LOOP = DIV > QUOT + 500 NEXT LOOP + 510 SUM = SUM + 1 + 520 RETURN + + REM DUFF N RETURNS DUFF + 600 DUFF = FALSE + 610 V = N: GOSUB 260"ISPRIME + 620 IF ISPRIME THEN RETURN + 630 NUM = N: GOSUB 400"SUMDIV + 640 A = SUM:B = N: GOSUB 300"GCD + 650 DUFF = GCD = 1 + 660 RETURN diff --git a/Task/EKG-sequence-convergence/Rust/ekg-sequence-convergence.rust b/Task/EKG-sequence-convergence/Rust/ekg-sequence-convergence.rust new file mode 100644 index 0000000000..bae4e3df9c --- /dev/null +++ b/Task/EKG-sequence-convergence/Rust/ekg-sequence-convergence.rust @@ -0,0 +1,34 @@ +use gcd::Gcd; + +fn ekg_sequence(n: u64, limit: usize) -> Vec { + let mut ekg = [1_u64, n].to_vec(); + while ekg.len() < limit { + for i in 2..2<<18 { + if ekg.iter().all(|j| *j != i) && Gcd::gcd(ekg[ekg.len()-1], i) > 1 { + ekg.push(i); + break; + } + } + } + return ekg; +} + + +fn converge_at(n: u64, m: u64, tmax: usize) -> usize { + let a = ekg_sequence(n, tmax); + let b = ekg_sequence(m, tmax); + for i in 2..tmax { + if a[i] == b[i] && a[0..i+1].iter().sum::() == (b[0..i+1]).iter().sum::() { + return i + 1; + } + } + println!("Error: no convergence in {tmax} terms"); + return 0; +} + +fn main() { + for i in [2_u64, 5, 7, 9, 10] { + println!("EKG({i:2}): {:?}", ekg_sequence(i, 30_usize)); + } + println!("EKGs of 5 & 7 converge after term {:?}", converge_at(5, 7, 50)); +} diff --git a/Task/Elementary-cellular-automaton-Infinite-length/Java/elementary-cellular-automaton-infinite-length.java b/Task/Elementary-cellular-automaton-Infinite-length/Java/elementary-cellular-automaton-infinite-length.java new file mode 100644 index 0000000000..a2b06e59d2 --- /dev/null +++ b/Task/Elementary-cellular-automaton-Infinite-length/Java/elementary-cellular-automaton-infinite-length.java @@ -0,0 +1,46 @@ +public final class ElementaryCellularAutomatonInfiniteLength { + + public static void main(String[] aArgs) { + evolve(35, 90); + System.out.println(); + } + + private static void evolve(int aLimit, int aRule) { + System.out.println(" Rule# " + aRule); + StringBuilder cells = new StringBuilder(Character.toString(STAR)); + for ( int i = 0; i < aLimit; i++ ) { + addCells(cells); + final int width = 40 - ( cells.length() >> 1 ); + System.out.println(" ".repeat(width) + cells); + cells = nextStep(cells, aRule); + } + } + + private static void addCells(StringBuilder aCells) { + final char left = ( aCells.charAt(0) == STAR ) ? DOT : STAR; + final char right = ( aCells.charAt(aCells.length() - 1 ) == STAR ) ? DOT : STAR; + for ( int i = 0; i < 2; i++ ) { + aCells.insert(0, left); + aCells.append(right); + } + } + + private static StringBuilder nextStep(StringBuilder aCells, int aRule) { + StringBuilder nextCells = new StringBuilder(); + for ( int i = 0; i < aCells.length() - 2; i++ ) { + int binary = 0; + int shift = 2; + for ( int j = i; j < i + 3; j++ ) { + binary += ( ( aCells.charAt(j) == STAR ) ? 1 : 0 ) << shift; + shift >>= 1; + } + final char symbol = ( ( aRule & ( 1 << binary ) ) == 0 ) ? DOT : STAR; + nextCells.append(symbol); + } + return nextCells; + } + + private static final char DOT = '.'; + private static final char STAR = '*'; + +} diff --git a/Task/Elementary-cellular-automaton-Random-number-generator/00-TASK.txt b/Task/Elementary-cellular-automaton-Random-number-generator/00-TASK.txt index d3f6ba18ff..2719954a02 100644 --- a/Task/Elementary-cellular-automaton-Random-number-generator/00-TASK.txt +++ b/Task/Elementary-cellular-automaton-Random-number-generator/00-TASK.txt @@ -1,4 +1,4 @@ -[[wp:Rule 30|Rule 30]] is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, rule 30 is used by the [[wp:Mathematica|Mathematica]] software for its default random number generator. +[[wp:Rule 30|Rule 30]] is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, for a long time rule 30 was used by the [[wp:Mathematica|Mathematica]] software for its default random number generator. Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed position in the array of cells, as the automaton changes state. diff --git a/Task/Elementary-cellular-automaton-Random-number-generator/Java/elementary-cellular-automaton-random-number-generator.java b/Task/Elementary-cellular-automaton-Random-number-generator/Java/elementary-cellular-automaton-random-number-generator.java new file mode 100644 index 0000000000..f1ee6b9ea6 --- /dev/null +++ b/Task/Elementary-cellular-automaton-Random-number-generator/Java/elementary-cellular-automaton-random-number-generator.java @@ -0,0 +1,30 @@ +public class ElementaryCellularAutomatonRandomNumberGenerator { + + public static void main(String[] aArgs) { + final int seed = 989898989; + evolve(seed, 30); + } + + private static void evolve(int aState, int aRule) { + long state = aState; + for ( int i = 0; i <= 9; i++ ) { + int b = 0; + for ( int q = 7; q >= 0; q-- ) { + long stateCopy = state; + b |= ( stateCopy & 1 ) << q; + state = 0; + for ( int j = 0; j < BIT_COUNT; j++ ) { + long t = ( stateCopy >>> ( j - 1 ) ) | ( stateCopy << ( BIT_COUNT + 1 - j ) ) & 7; + if ( ( aRule & ( 1L << t ) ) != 0 ) { + state |= 1 << j; + } + } + } + System.out.print(" " + b); + } + System.out.println(); + } + + private static final int BIT_COUNT = 64; + +} diff --git a/Task/Elementary-cellular-automaton-Random-number-generator/Raku/elementary-cellular-automaton-random-number-generator.raku b/Task/Elementary-cellular-automaton-Random-number-generator/Raku/elementary-cellular-automaton-random-number-generator.raku index 432ccdb181..d86fd0d065 100644 --- a/Task/Elementary-cellular-automaton-Random-number-generator/Raku/elementary-cellular-automaton-random-number-generator.raku +++ b/Task/Elementary-cellular-automaton-Random-number-generator/Raku/elementary-cellular-automaton-random-number-generator.raku @@ -1,6 +1,6 @@ class Automaton { has $.rule; - has @.cells; + has @.cells handles ; has @.code = $!rule.fmt('%08b').flip.comb».Int; method gist { "|{ @!cells.map({+$_ ?? '#' !! ' '}).join }|" } @@ -18,4 +18,4 @@ class Automaton { my Automaton $a .= new: :rule(30), :cells( flat 1, 0 xx 100 ); -say :2[$a++.cells[0] xx 8] xx 10; +say :2[$a++[0] xx 8] xx 10; diff --git a/Task/Equal-prime-and-composite-sums/Java/equal-prime-and-composite-sums.java b/Task/Equal-prime-and-composite-sums/Java/equal-prime-and-composite-sums.java new file mode 100644 index 0000000000..8736564e73 --- /dev/null +++ b/Task/Equal-prime-and-composite-sums/Java/equal-prime-and-composite-sums.java @@ -0,0 +1,106 @@ +import java.util.BitSet; +import java.util.Objects; + +public final class EqualPrimeAndCompositeSums { + + public static void main(String[] aArgs) { + PrimeIterator primeIterator = new PrimeIterator(); + CompositeIterator compositeIterator = new CompositeIterator(); + long primeSum = primeIterator.next(); + long compositeSum = compositeIterator.next(); + int primeIndex = 1; + int compositeIndex = 1; + + System.out.println("Sum | Prime Index | Composite Index"); + System.out.println("----------------------------------------------"); + int count = 0; + while ( count < 8 ) { + if ( primeSum == compositeSum ) { + System.out.println(String.format("%13d%s%12d%s%15d", + primeSum, " | ", primeIndex, " | ", compositeIndex)); + + primeSum += primeIterator.next(); + primeIndex += 1; + compositeSum += compositeIterator.next(); + compositeIndex += 1; + count += 1; + } else if ( primeSum < compositeSum ) { + primeSum += primeIterator.next(); + primeIndex += 1; + } else { + compositeSum += compositeIterator.next(); + compositeIndex += 1; + } + } + } + + private static class CompositeIterator { + + public CompositeIterator() { + primeIterator = new PrimeIterator(); + prime = primeIterator.next(); + composite = prime; + while ( composite == prime ) { + prime = primeIterator.next(); + composite += 1; + } + } + + public int next() { + final int result = composite; + while ( ++composite == prime ) { + prime = primeIterator.next(); + } + return result; + } + + public int prime, composite; + private PrimeIterator primeIterator; + + } + + private static class PrimeIterator { + + public PrimeIterator() { + if ( Objects.isNull(sieve) ) { + listPrimeNumbers(10_000_000); + } + } + + public int next() { + if ( lastPrime < sieve.cardinality() ) { + lastPrime = sieve.nextSetBit(lastPrime + 1); + } else { + do { + lastPrime += 2; + } + while ( ! isPrime(lastPrime) ); + } + return lastPrime; + } + + private static boolean isPrime(int aCandidate) { + for ( int i = 2; i <= Math.sqrt(aCandidate); i = sieve.nextSetBit(i + 1) ) { + if ( aCandidate % i == 0 ) { + return false; + } + } + return true; + } + + private static void listPrimeNumbers(int aN) { + sieve = new BitSet(aN + 1); + sieve.set(2, aN + 1); + for ( int i = 2; i <= Math.sqrt(aN); i = sieve.nextSetBit(i + 1) ) { + for ( int j = i * i; j <= aN; j = j + i ) { + sieve.clear(j); + } + } + } + + private int lastPrime; + private static BitSet sieve; + + } + +} diff --git a/Task/Euclid-Mullin-sequence/Java/euclid-mullin-sequence.java b/Task/Euclid-Mullin-sequence/Java/euclid-mullin-sequence.java index 5b6dd746e1..cd1a31d838 100644 --- a/Task/Euclid-Mullin-sequence/Java/euclid-mullin-sequence.java +++ b/Task/Euclid-Mullin-sequence/Java/euclid-mullin-sequence.java @@ -4,17 +4,16 @@ import java.util.BitSet; import java.util.List; import java.util.concurrent.ThreadLocalRandom; -public class EulerMullinSequence { +public final class EulerMullinSequence { public static void main(String[] aArgs) { primes = listPrimesUpTo(1_000_000); System.out.println("The first 27 terms of the Euler-Mullin sequence:"); - System.out.println(2); + System.out.print(2 + " "); for ( int i = 1; i < 27; i++ ) { - System.out.println(nextEulerMullin()); + System.out.print(String.format("%s%s", nextEulerMullin(), ( i == 14 || i == 27 ) ? "\n" : " ")); } - } private static BigInteger nextEulerMullin() { @@ -25,7 +24,7 @@ public class EulerMullinSequence { } private static BigInteger smallestPrimeFactor(BigInteger aNumber) { - if ( aNumber.isProbablePrime(probabilityLevel) ) { + if ( aNumber.isProbablePrime(CERTAINTY_LEVEL) ) { return aNumber; } @@ -86,6 +85,6 @@ public class EulerMullinSequence { private static BigInteger product = BigInteger.TWO; private static ThreadLocalRandom random = ThreadLocalRandom.current(); - private static final int probabilityLevel = 20; + private static final int CERTAINTY_LEVEL = 20; } diff --git a/Task/Even-or-odd/Insitux/even-or-odd.insitux b/Task/Even-or-odd/Insitux/even-or-odd.insitux new file mode 100644 index 0000000000..75d0ec88bc --- /dev/null +++ b/Task/Even-or-odd/Insitux/even-or-odd.insitux @@ -0,0 +1,2 @@ +(if (even? some-var) (do-even-stuff)) +(if (odd? some-var) (do-odd-stuff)) diff --git a/Task/Fibonacci-sequence/Perl/fibonacci-sequence-4.pl b/Task/Fibonacci-sequence/Perl/fibonacci-sequence-4.pl new file mode 100644 index 0000000000..3580e43de0 --- /dev/null +++ b/Task/Fibonacci-sequence/Perl/fibonacci-sequence-4.pl @@ -0,0 +1,15 @@ +sub fibonacci { + my $n = shift; + + return 0 if $n < 1; + return 1 if $n == 1; + + my @numbers = (0, 1); + + push @numbers, $numbers[-1] + $numbers[-2] foreach 2 .. $n; + + return $numbers[-1]; +} + +print "Fibonacci($_) -> ", (fibonacci $_), "\n" + foreach (0 .. 20, 50, 93, 94, 100, 200, 1000, 1476, 1477); diff --git a/Task/File-input-output/Forth/file-input-output-1.fth b/Task/File-input-output/Forth/file-input-output-1.fth index ea758af5b4..aa0150f952 100644 --- a/Task/File-input-output/Forth/file-input-output-1.fth +++ b/Task/File-input-output/Forth/file-input-output-1.fth @@ -3,8 +3,8 @@ r/o open-file throw >r w/o create-file throw r> begin - pad maxstring 2 pick read-file throw - ?dup while + pad 84 2 pick read-file throw + ?dup while pad swap 3 pick write-file throw repeat close-file throw diff --git a/Task/File-size-distribution/Java/file-size-distribution.java b/Task/File-size-distribution/Java/file-size-distribution.java new file mode 100644 index 0000000000..832795af32 --- /dev/null +++ b/Task/File-size-distribution/Java/file-size-distribution.java @@ -0,0 +1,33 @@ +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public final class FileSizeDistribution { + + public static void main(String[] aArgs) throws IOException { + List fileNames = Files.list(Path.of(".")) + .filter( file -> ! Files.isDirectory(file) ) + .map(Path::getFileName) + .toList(); + + Map fileSizes = new HashMap(); + for ( Path path : fileNames ) { + fileSizes.merge(String.valueOf(Files.size(path)).length(), 1, Integer::sum); + } + + final int fileCount = fileSizes.values().stream().mapToInt(Integer::valueOf).sum(); + + System.out.println("File size distribution for directory \".\":" + System.lineSeparator()); + System.out.println("File size in bytes | Number of files | Percentage"); + System.out.println("-------------------------------------------------"); + for ( int key : fileSizes.keySet() ) { + final int value = fileSizes.get(key); + System.out.println(String.format("%s%d%s%d%15d%15.1f%%", + " 10^", ( key - 1 ), " to 10^", key, value, ( 100.0 * value ) / fileCount)); + } + } + +} diff --git a/Task/Find-Chess960-starting-position-identifier/C++/find-chess960-starting-position-identifier.cpp b/Task/Find-Chess960-starting-position-identifier/C++/find-chess960-starting-position-identifier.cpp new file mode 100644 index 0000000000..a4c0cc223c --- /dev/null +++ b/Task/Find-Chess960-starting-position-identifier/C++/find-chess960-starting-position-identifier.cpp @@ -0,0 +1,85 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +const std::set> correct_pieces = { std::make_pair('R', 2), std::make_pair('N', 2), + std::make_pair('B', 2), std::make_pair('Q', 1), std::make_pair('K', 1) }; + +std::map, int32_t> knights_table = { + { std::vector{ 0, 1 }, 0 }, + { std::vector{ 0, 2 }, 1 }, + { std::vector{ 0, 3 }, 2 }, + { std::vector{ 0, 4 }, 3 }, + { std::vector{ 1, 2 }, 4 }, + { std::vector{ 1, 3 }, 5 }, + { std::vector{ 1, 4 }, 6 }, + { std::vector{ 2, 3 }, 7 }, + { std::vector{ 2, 4 }, 8 }, + { std::vector{ 3, 4 }, 9 } }; + +void validate(const std::string& position) { + if ( position.length() != 8 ) { + throw std::invalid_argument("Chess position has invalid length" + std::to_string(position.length())); + } + + std::map position_map; + for ( const char& ch : position ) { + if ( position_map.find(ch) == position_map.end() ) { + position_map.emplace(ch, 1); + } else { + position_map[ch]++; + } + } + + std::set> pieces; + std::transform(position_map.begin(), position_map.end(), std::inserter(pieces, pieces.begin()), + [](const std::pair& entry) { return entry; }); + + if ( pieces != correct_pieces ) { + throw std::invalid_argument("Chess position contains incorrect pieces."); + } + + const std::vector bishops = { position.find_first_of('B'), position.find_last_of('B') }; + if ( ( bishops[1] - bishops[0] ) % 2 == 0 ) { + throw std::invalid_argument("Bishops must be on different coloured squares."); + } + + std::vector rook_king = + { position.find_first_of('R'), position.find_first_of('K'), position.find_last_of('R') }; + if ( ! ( rook_king[0] < rook_king[1] && rook_king[1] < rook_king[2] ) ) { + throw std::invalid_argument("The king must be between the two rooks."); + } +} + +int32_t calculate_SPID(std::string& position) { + + const int32_t index_one = position.find_first_of('B'); + const int32_t index_two = position.find_last_of('B'); + const int32_t D = ( index_one % 2 == 0 ) ? index_one / 2 : index_two / 2; + const int32_t L = ( index_one % 2 == 0 ) ? index_two / 2 : index_one / 2; + + position.erase(remove_if(position.begin(), position.end(), + [](const char& ch){ return ch == 'B'; }), position.end()); + const uint64_t Q = position.find_first_of('Q'); + + position.erase(remove_if(position.begin(), position.end(), + [](const char& ch){ return ch == 'Q'; }), position.end()); + const int32_t N = + knights_table[ { (int32_t) position.find_first_of('N'), (int32_t) position.find_last_of('N') } ]; + + return 96 * N + 16 * Q + 4 * D + L; +} + +int main() { + std::vector positions = { "QNRBBNKR", "RNBQKBNR", "RQNBBKRN", "RNQBBKRN" }; + + for ( std::string& position : positions ) { + validate(position); + std::cout << "Position " << position << " has Chess960 SP-ID = " << calculate_SPID(position) << std::endl; + } +} diff --git a/Task/Find-Chess960-starting-position-identifier/Java/find-chess960-starting-position-identifier.java b/Task/Find-Chess960-starting-position-identifier/Java/find-chess960-starting-position-identifier.java index cd04c88e6d..673afa3542 100644 --- a/Task/Find-Chess960-starting-position-identifier/Java/find-chess960-starting-position-identifier.java +++ b/Task/Find-Chess960-starting-position-identifier/Java/find-chess960-starting-position-identifier.java @@ -10,9 +10,10 @@ public final class Chess960SPID { String[] positions = { "QNRBBNKR", "RNBQKBNR", "RQNBBKRN", "RNQBBKRN" }; createKnightsTable(); + createCorrectPieces(); for ( String position : positions ) { - validate("RQNBBKRN"); + validate(position); System.out.println("Position " + position + " has Chess960 SP-ID = " + calculateSPID(position)); } } @@ -26,8 +27,7 @@ public final class Chess960SPID { for ( char ch : aPosition.toCharArray() ) { pieces.merge(ch, 1, (oldV, newV) -> oldV + 1); } - Set> correctPieces = - Set.of(Map.entry('R', 2), Map.entry('N', 2), Map.entry('B', 2), Map.entry('Q', 1), Map.entry('K', 1)); + if ( ! pieces.entrySet().equals(correctPieces) ) { throw new AssertionError("Chess position contains incorrect pieces."); } @@ -78,8 +78,14 @@ public final class Chess960SPID { knightsTable.put(List.of(2, 3), 7); knightsTable.put(List.of(2, 4), 8); knightsTable.put(List.of(3, 4), 9); - } + } + + private static void createCorrectPieces() { + correctPieces = Set.of( + Map.entry('R', 2), Map.entry('N', 2), Map.entry('B', 2), Map.entry('Q', 1), Map.entry('K', 1) ); + } private static Map, Integer> knightsTable; + private static Set> correctPieces; } diff --git a/Task/Find-palindromic-numbers-in-both-binary-and-ternary-bases/C++/find-palindromic-numbers-in-both-binary-and-ternary-bases.cpp b/Task/Find-palindromic-numbers-in-both-binary-and-ternary-bases/C++/find-palindromic-numbers-in-both-binary-and-ternary-bases.cpp new file mode 100644 index 0000000000..e76ce55424 --- /dev/null +++ b/Task/Find-palindromic-numbers-in-both-binary-and-ternary-bases/C++/find-palindromic-numbers-in-both-binary-and-ternary-bases.cpp @@ -0,0 +1,73 @@ +#include +#include +#include + +// Convert the given decimal number to the given number base +// and return it converted to a string +std::string to_base_string(const uint64_t& number, const uint32_t& base) { + uint64_t n = number; + if ( n == 0 ) { + return "0"; + } + + std::string result; + while ( n > 0 ) { + result += std::to_string(n % base); + n /= base; + } + std::reverse(result.begin(), result.end()); + return result; +} + +void display(const uint64_t& number) { + std::cout << "Decimal: " << number << std::endl; + std::cout << "Binary : " << to_base_string(number, 2) << std::endl; + std::cout << "Ternary: " << to_base_string(number, 3) << std::endl << std::endl; +} + +bool is_palindromic(const std::string& number) { + std::string copy = number; + std::reverse(copy.begin(), copy.end()); + return number == copy; +} + +// Create a ternary palindrome whose left part is the ternary equivalent of the given number +// and return it converted to a decimal +uint64_t create_ternary_palindrome(const uint64_t& number) { + std::string ternary = to_base_string(number, 3); + uint64_t power_of_3 = 1; + uint64_t result = 0; + for ( uint64_t i = 0; i < ternary.length(); ++i ) { // Right part of palindrome is the mirror image of left part + if ( ternary[i] > '0' ) { + result += ( ternary[i] - '0' ) * power_of_3; + } + power_of_3 *= 3; + } + result += power_of_3; // Middle digit must be 1 + power_of_3 *= 3; + result += number * power_of_3; // Left part is the given number multiplied by the appropriate power of 3 + return result; +} + +int main() { + std::cout << "The first 6 numbers which are palindromic in both binary and ternary are:" << std::endl; + display(0); // 0 is a palindrome in all 3 bases + display(1); // 1 is a palindrome in all 3 bases + + uint64_t number = 1; + uint32_t count = 2; + do { + uint64_t ternary = create_ternary_palindrome(number); + if ( ternary % 2 == 1 ) { // Cannot be an even number since its binary equivalent would end in zero + std::string binary = to_base_string(ternary, 2); + if ( binary.length() % 2 == 1 ) { // Binary palindrome must have an odd number of digits + if ( is_palindromic(binary) ) { + display(ternary); + count++; + } + } + } + number++; + } + while ( count < 6 ); +} diff --git a/Task/Find-palindromic-numbers-in-both-binary-and-ternary-bases/Java/find-palindromic-numbers-in-both-binary-and-ternary-bases.java b/Task/Find-palindromic-numbers-in-both-binary-and-ternary-bases/Java/find-palindromic-numbers-in-both-binary-and-ternary-bases-1.java similarity index 100% rename from Task/Find-palindromic-numbers-in-both-binary-and-ternary-bases/Java/find-palindromic-numbers-in-both-binary-and-ternary-bases.java rename to Task/Find-palindromic-numbers-in-both-binary-and-ternary-bases/Java/find-palindromic-numbers-in-both-binary-and-ternary-bases-1.java diff --git a/Task/Find-palindromic-numbers-in-both-binary-and-ternary-bases/Java/find-palindromic-numbers-in-both-binary-and-ternary-bases-2.java b/Task/Find-palindromic-numbers-in-both-binary-and-ternary-bases/Java/find-palindromic-numbers-in-both-binary-and-ternary-bases-2.java new file mode 100644 index 0000000000..633645a06c --- /dev/null +++ b/Task/Find-palindromic-numbers-in-both-binary-and-ternary-bases/Java/find-palindromic-numbers-in-both-binary-and-ternary-bases-2.java @@ -0,0 +1,72 @@ +public final class FindPalindromicNumbersBases23 { + + public static void main(String[] aArgs) { + System.out.println("The first 7 numbers which are palindromic in both binary and ternary are:"); + display(0); // 0 is a palindrome in all 3 bases + display(1); // 1 is a palindrome in all 3 bases + + long number = 1; + int count = 2; + do { + long ternary = createTernaryPalindrome(number); + if ( ternary % 2 == 1 ) { // Cannot be an even number since its binary equivalent would end in zero + String binary = toBinaryString(ternary); + if ( binary.length() % 2 == 1 ) { // Binary palindrome must have an odd number of digits + if ( isPalindromic(binary) ) { + display(ternary); + count++; + } + } + } + number++; + } + while ( count < 7 ); + } + + // Create a ternary palindrome whose left part is the ternary equivalent of the given number + // and return its decimal equivalent + private static long createTernaryPalindrome(long aNumber) { + String ternary = toTernaryString(aNumber); + long powerOf3 = 1; + long sum = 0; + for ( int i = 0; i < ternary.length(); i++ ) { // Right part of a palindrome is the mirror image of left part + if ( ternary.charAt(i) > '0' ) { + sum += ( ternary.charAt(i) - '0' ) * powerOf3; + } + powerOf3 *= 3; + } + sum += powerOf3; // Middle digit must be 1 + powerOf3 *= 3; + sum += aNumber * powerOf3; // Left part is the given number multiplied by the appropriate power of 3 + return sum; + } + + private static boolean isPalindromic(String aNumber) { + return aNumber.equals( new StringBuilder(aNumber).reverse().toString() ); + } + + private static String toTernaryString(long aNumber) { + if ( aNumber == 0 ) { + return "0"; + } + + StringBuilder result = new StringBuilder(); + while ( aNumber > 0 ) { + result.append(aNumber % 3); + aNumber /= 3; + } + return result.reverse().toString(); + } + + private static String toBinaryString(long aNumber) { + return Long.toBinaryString(aNumber); + } + + private static void display(long aNumber) { + System.out.println("Decimal: " + aNumber); + System.out.println("Binary : " + toBinaryString(aNumber)); + System.out.println("Ternary: " + toTernaryString(aNumber)); + System.out.println(); + } + +} diff --git a/Task/Find-the-last-Sunday-of-each-month/C++/find-the-last-sunday-of-each-month-3.cpp b/Task/Find-the-last-Sunday-of-each-month/C++/find-the-last-sunday-of-each-month-3.cpp new file mode 100644 index 0000000000..5a989272cc --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/C++/find-the-last-sunday-of-each-month-3.cpp @@ -0,0 +1,20 @@ +#include +#include + +int main() { + std::cout << "The dates of the last Sunday in each month of 2023:" << std::endl; + + for ( unsigned int m = 1; m <= 12; ++m ) { + std::chrono::days days_in_month = std::chrono::sys_days{std::chrono::year{2023}/m/std::chrono::last} + - std::chrono::sys_days{std::chrono::year{2023}/m/1} + std::chrono::days{1}; + + const unsigned int last_day = days_in_month / std::chrono::days{1}; + std::chrono::year_month_day ymd{std::chrono::year{2023}, std::chrono::month{m}, std::chrono::day{last_day}}; + + while ( std::chrono::weekday{ymd} != std::chrono::Sunday ) { + ymd = std::chrono::sys_days{ymd} - std::chrono::days{1}; + } + + std::cout << ymd << std::endl; + } +} diff --git a/Task/Five-weekends/C++/five-weekends.cpp b/Task/Five-weekends/C++/five-weekends-1.cpp similarity index 100% rename from Task/Five-weekends/C++/five-weekends.cpp rename to Task/Five-weekends/C++/five-weekends-1.cpp diff --git a/Task/Five-weekends/C++/five-weekends-2.cpp b/Task/Five-weekends/C++/five-weekends-2.cpp new file mode 100644 index 0000000000..2109e2b6e6 --- /dev/null +++ b/Task/Five-weekends/C++/five-weekends-2.cpp @@ -0,0 +1,27 @@ +#include +#include +#include + +int main() { + const std::vector long_months = { std::chrono::January, std::chrono::March, + std::chrono::May, std::chrono::July, std::chrono::August, std::chrono::October, std::chrono::December }; + + int month_count = 0; + int blank_years = 0; + for ( int y = 1900; y <= 2100; ++y ) { + bool blank_year = true; + for ( std::chrono::month m : long_months ) { + std::chrono::year_month_day first_of_month{std::chrono::year{y}, m, std::chrono::day{1}}; + if ( std::chrono::weekday{first_of_month} == std::chrono::Friday ) { + std::cout << first_of_month.year() << " " << first_of_month.month() << std::endl; + month_count++; + blank_year = false; + } + } + if ( blank_year ) { + blank_years++; + } + } + std::cout << "Found " << month_count << " months with five Fridays, Saturdays and Sundays." << std::endl; + std::cout << "There were " << blank_years << " years with no such months." << std::endl; +} diff --git a/Task/FizzBuzz/BQN/fizzbuzz-3.bqn b/Task/FizzBuzz/BQN/fizzbuzz-3.bqn new file mode 100644 index 0000000000..94d7252c53 --- /dev/null +++ b/Task/FizzBuzz/BQN/fizzbuzz-3.bqn @@ -0,0 +1 @@ +(3‿5 (0=|)◶[⊢‿"fizz","buzz"‿"fizzbuzz"] ⊢)¨ 1+↕100 diff --git a/Task/FizzBuzz/Insitux/fizzbuzz.insitux b/Task/FizzBuzz/Insitux/fizzbuzz.insitux new file mode 100644 index 0000000000..4e9378fe29 --- /dev/null +++ b/Task/FizzBuzz/Insitux/fizzbuzz.insitux @@ -0,0 +1,9 @@ +(function fizzbuzz n + (match (map (rem n) [3 5]) + [0 0] "FizzBuzz" + [0 _] "Fizz" + [_ 0] "Buzz" + n)) + +(loop 100 i + (-> i inc fizzbuzz print)) diff --git a/Task/FizzBuzz/Lua/fizzbuzz-5.lua b/Task/FizzBuzz/Lua/fizzbuzz-5.lua index 70b1536063..18fbcde424 100644 --- a/Task/FizzBuzz/Lua/fizzbuzz-5.lua +++ b/Task/FizzBuzz/Lua/fizzbuzz-5.lua @@ -1,20 +1,16 @@ -#!/usr/bin/env luajit -local to=arg[1] or tonumber(arg[1]) or 100 -local CF,CB=3,5 -local cf,cb=CF,CB -for i=1,to do - cf,cb=cf-1,cb-1 - if cf~=0 and cb~=0 then - io.write(i) - else - if cf==0 then - cf=CF - io.write("Fizz") - end - if cb==0 then - cb=CB - io.write("Buzz") - end - end - io.write(", ") -end +local mt = { + __newindex = (function (t, k, v) + if type(k) ~= "number" then rawset(t, k, v) + elseif 0 == (k % 15) then rawset(t, k, "fizzbuzz") + elseif 0 == (k % 5) then rawset(t, k, "fizz") + elseif 0 == (k % 3) then rawset(t, k, "buzz") + else rawset(t, k, k) end + return t[k] +end) +} + +local fizzbuzz = {} +setmetatable(fizzbuzz, mt) + +for i=1,100 do fizzbuzz[i] = i end +for i=1,100 do print(fizzbuzz[i]) end diff --git a/Task/FizzBuzz/Lua/fizzbuzz-6.lua b/Task/FizzBuzz/Lua/fizzbuzz-6.lua new file mode 100644 index 0000000000..70b1536063 --- /dev/null +++ b/Task/FizzBuzz/Lua/fizzbuzz-6.lua @@ -0,0 +1,20 @@ +#!/usr/bin/env luajit +local to=arg[1] or tonumber(arg[1]) or 100 +local CF,CB=3,5 +local cf,cb=CF,CB +for i=1,to do + cf,cb=cf-1,cb-1 + if cf~=0 and cb~=0 then + io.write(i) + else + if cf==0 then + cf=CF + io.write("Fizz") + end + if cb==0 then + cb=CB + io.write("Buzz") + end + end + io.write(", ") +end diff --git a/Task/Golden-ratio-Convergence/Lua/golden-ratio-convergence.lua b/Task/Golden-ratio-Convergence/Lua/golden-ratio-convergence.lua new file mode 100644 index 0000000000..6d87e32847 --- /dev/null +++ b/Task/Golden-ratio-Convergence/Lua/golden-ratio-convergence.lua @@ -0,0 +1,7 @@ +local phi, phi0, expected, iters = 1, 0, (1 + math.sqrt(5)) / 2, 0 +repeat + phi0, phi = phi, 1 + 1 / phi + iters = iters + 1 +until math.abs(phi0 - phi) < 1e-5 +io.write( "after ", iters, " iterations, phi = ", phi ) +io.write( ", expected value: ", expected, ", diff: ", math.abs( expected - phi ), "\n" ) diff --git a/Task/Jordan-P-lya-numbers/Raku/jordan-p-lya-numbers.raku b/Task/Jordan-P-lya-numbers/Raku/jordan-p-lya-numbers.raku new file mode 100644 index 0000000000..c69a328db1 --- /dev/null +++ b/Task/Jordan-P-lya-numbers/Raku/jordan-p-lya-numbers.raku @@ -0,0 +1,33 @@ +# 20230719 Raku programming solution + +my \factorials = 1, | [\*] 1..18; # with 0! + +sub JordanPolya (\limit) { + my \ix = (factorials.keys.first: factorials[*] >= limit) // factorials.end; + my ($k, @res) = 2, |factorials[0..ix]; + + while $k < @res.elems { + my \rk = @res[$k]; + for 2 .. @res.elems -> \l { + my \kl = $ = @res[l] * rk; + last if kl > limit; + loop { + my \p = @res.keys.first: { @res[$_] >= kl } # performance + if p < @res.elems and @res[p] != kl { + @res = |@res[^p], kl, |@res[p..*] + } elsif p == @res.elems { + @res.append: kl + } + kl > limit/rk ?? ( last ) !! kl *= rk + } + } + $k++ + } + return @res[1..*] +} + +my @result = JordanPolya 2**30 ; +say "First 50 Jordan-Pólya numbers:"; +say [~] $_>>.fmt('%5s') for @result[^50].rotor(10); +print "\nThe largest Jordan-Pólya number before 100 million: "; +say @result.first: * < 100_000_000, :end; diff --git a/Task/Last-Friday-of-each-month/C++/last-friday-of-each-month.cpp b/Task/Last-Friday-of-each-month/C++/last-friday-of-each-month-1.cpp similarity index 100% rename from Task/Last-Friday-of-each-month/C++/last-friday-of-each-month.cpp rename to Task/Last-Friday-of-each-month/C++/last-friday-of-each-month-1.cpp diff --git a/Task/Last-Friday-of-each-month/C++/last-friday-of-each-month-2.cpp b/Task/Last-Friday-of-each-month/C++/last-friday-of-each-month-2.cpp new file mode 100644 index 0000000000..a6f039c937 --- /dev/null +++ b/Task/Last-Friday-of-each-month/C++/last-friday-of-each-month-2.cpp @@ -0,0 +1,20 @@ +#include +#include + +int main() { + std::cout << "The dates of the last Friday in each month of 2023:" << std::endl; + + for ( unsigned int m = 1; m <= 12; ++m ) { + std::chrono::days days_in_month = std::chrono::sys_days{std::chrono::year{2023}/m/std::chrono::last} + - std::chrono::sys_days{std::chrono::year{2023}/m/1} + std::chrono::days{1}; + + const unsigned int last_day = days_in_month / std::chrono::days{1}; + std::chrono::year_month_day ymd{std::chrono::year{2023}, std::chrono::month{m}, std::chrono::day{last_day}}; + + while ( std::chrono::weekday{ymd} != std::chrono::Friday ) { + ymd = std::chrono::sys_days{ymd} - std::chrono::days{1}; + } + + std::cout << ymd << std::endl; + } +} diff --git a/Task/Look-and-say-sequence/Insitux/look-and-say-sequence.insitux b/Task/Look-and-say-sequence/Insitux/look-and-say-sequence.insitux new file mode 100644 index 0000000000..3add58298c --- /dev/null +++ b/Task/Look-and-say-sequence/Insitux/look-and-say-sequence.insitux @@ -0,0 +1,9 @@ +(function look-and-say n x + (return-when (empty? n) x) + (var digit (0 n) + [before after] ((juxt take-while skip-while) (= digit) n)) + (recur after (strn x (len before) digit))) + +(var result "1") +(loop 10 i + (print (var! result look-and-say))) diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Applesoft-BASIC/loop-over-multiple-arrays-simultaneously.basic b/Task/Loop-over-multiple-arrays-simultaneously/Applesoft-BASIC/loop-over-multiple-arrays-simultaneously.basic new file mode 100644 index 0000000000..94a9cb0413 --- /dev/null +++ b/Task/Loop-over-multiple-arrays-simultaneously/Applesoft-BASIC/loop-over-multiple-arrays-simultaneously.basic @@ -0,0 +1,7 @@ +REM DEFINE THE ARRAYS AND POPULATE THEM + 0 SIZE = 3: DIM A$(SIZE),B$(SIZE),C(SIZE): FOR I = 1 TO SIZE:A$(I) = CHR$ (96 + I):B$(I) = CHR$ (64 + I):C(I) = I: NEXT + +REM LOOP OVER MULTIPLE ARRAYS SIMULTANEOUSLY + 1 FOR I = 1 TO SIZE + 2 PRINT A$(I)B$(I)C(I) + 3 NEXT I diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Insitux/loop-over-multiple-arrays-simultaneously-1.insitux b/Task/Loop-over-multiple-arrays-simultaneously/Insitux/loop-over-multiple-arrays-simultaneously-1.insitux new file mode 100644 index 0000000000..abf39919a2 --- /dev/null +++ b/Task/Loop-over-multiple-arrays-simultaneously/Insitux/loop-over-multiple-arrays-simultaneously-1.insitux @@ -0,0 +1,2 @@ +(map str "abc" "ABC" "123") +["aA1" "bB2" "cC3"] diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Insitux/loop-over-multiple-arrays-simultaneously-2.insitux b/Task/Loop-over-multiple-arrays-simultaneously/Insitux/loop-over-multiple-arrays-simultaneously-2.insitux new file mode 100644 index 0000000000..1e0d9176b1 --- /dev/null +++ b/Task/Loop-over-multiple-arrays-simultaneously/Insitux/loop-over-multiple-arrays-simultaneously-2.insitux @@ -0,0 +1,2 @@ +(map str ["a" "b" "c"] ["A" "B" "C"] ["1" "2" "3"]) +["aA1" "bB2" "cC3"] diff --git a/Task/Loop-over-multiple-arrays-simultaneously/ZX-Spectrum-Basic/loop-over-multiple-arrays-simultaneously-1.basic b/Task/Loop-over-multiple-arrays-simultaneously/ZX-Spectrum-Basic/loop-over-multiple-arrays-simultaneously-1.basic index e69242b61b..3ccd00e49c 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/ZX-Spectrum-Basic/loop-over-multiple-arrays-simultaneously-1.basic +++ b/Task/Loop-over-multiple-arrays-simultaneously/ZX-Spectrum-Basic/loop-over-multiple-arrays-simultaneously-1.basic @@ -13,7 +13,7 @@ columns 120 IF l <= szb THEN READ b$(l): PRINT b$(l); 130 IF l <= szc THEN READ c$(l): PRINT c$(l); 140 PRINT: REM newline -150 NEXT l +145 NEXT l 150 PRINT "The arrays are shown in columns." 160 PRINT "A$ runs down the left hand side," 170 PRINT "and C$ runs down the right." diff --git a/Task/Mandelbrot-set/Julia/mandelbrot-set-4.julia b/Task/Mandelbrot-set/Julia/mandelbrot-set-4.julia index 272d45f3ac..30bf757b41 100644 --- a/Task/Mandelbrot-set/Julia/mandelbrot-set-4.julia +++ b/Task/Mandelbrot-set/Julia/mandelbrot-set-4.julia @@ -4,39 +4,32 @@ gr(aspect_ratio=:equal, axis=true, ticks=true, legend=false, dpi=200) d, h = 800, 500 # pixel density (= image width) and image height n, r = 200, 500 # number of iterations and escape radius (r > 2) -direction, height = 45, 1.5 # direction and height of the incoming light -stripes, damping = 4, 2.0 # stripe density and damping parameter - x = range(0, 2, length=d+1) y = range(0, 2 * h / d, length=h+1) A, B = collect(x) .- 1, collect(y) .- h / d -C = (2.0 + 1.0im) .* (A' .+ B .* im) .- 0.5 +C = 2.0 .* (A' .+ B .* im) .- 0.5 -Z, dZ, ddZ = zero(C), zero(C), zero(C) +Z, dZ = zero(C), zero(C) D, S, T = zeros(size(C)), zeros(size(C)), zeros(size(C)) for k in 1:n M = abs.(Z) .< r - S[M], T[M] = S[M] .+ cos.(stripes .* angle.(Z[M])), T[M] .+ 1 - Z[M], dZ[M], ddZ[M] = Z[M] .^ 2 .+ C[M], 2 .* Z[M] .* dZ[M] .+ 1, 2 .* (dZ[M] .^ 2 .+ Z[M] .* ddZ[M]) + S[M], T[M] = S[M] .+ exp.(.- abs.(Z[M])), T[M] .+ 1 + Z[M], dZ[M] = Z[M] .^ 2 .+ C[M], 2 .* Z[M] .* dZ[M] .+ 1 end -N = abs.(Z) .>= r # normal map effect 1 (potential function) -P, Q = S[N] ./ T[N], (S[N] .+ cos.(stripes .* angle.(Z[N]))) ./ (T[N] .+ 1) -F = log2.(log.(abs.(Z[N])) ./ log(r)) # fraction between 0 and 1 (for interpolation) -R = Q .+ (P .- Q) .* F .* F .* (3 .- 2 .* F) # hermite interpolation (r is between q and p) -U, H = Z[N] ./ dZ[N], 1 .+ R ./ damping # normal vectors to the equipotential lines and height perturbation -U, v = U ./ abs.(U), exp(direction / 180 * pi * im) # unit normal vectors and vector in light direction -D[N] = max.((real.(U) .* real(v) .+ imag.(U) .* imag(v) .+ H .* height) ./ (1 + height), 0) +heatmap(S .^ 0.1, c=:balance) +savefig("Mandelbrot_set_1.png") -heatmap(D .^ 1.0, c=:bone_1) -savefig("Mandelbrot_normal_map_1.png") +N = abs.(Z) .>= r # normalized iteration count +T[N] = T[N] .- log2.(log.(abs.(Z[N])) ./ log(r)) -N = abs.(Z) .>= r # normal map effect 2 (distance estimation) -U = Z[N] .* dZ[N] .* ((1 .+ log.(abs.(Z[N]))) .* conj.(dZ[N] .^ 2) .- log.(abs.(Z[N])) .* conj.(Z[N] .* ddZ[N])) -U, v = U ./ abs.(U), exp(direction / 180 * pi * im) # unit normal vectors and vector in light direction -D[N] = max.((real.(U) .* real(v) .+ imag.(U) .* imag(v) .+ height) ./ (1 + height), 0) +heatmap(T .^ 0.1, c=:balance) +savefig("Mandelbrot_set_2.png") -heatmap(D .^ 1.0, c=:afmhot) -savefig("Mandelbrot_normal_map_2.png") +N = abs.(Z) .> 2 # exterior distance estimation +D[N] = 0.5 .* log.(abs.(Z[N])) .* abs.(Z[N]) ./ abs.(dZ[N]) + +heatmap(D .^ 0.1, c=:balance) +savefig("Mandelbrot_set_3.png") diff --git a/Task/Mandelbrot-set/Julia/mandelbrot-set-5.julia b/Task/Mandelbrot-set/Julia/mandelbrot-set-5.julia index 1f2373f04e..b2c8d1371d 100644 --- a/Task/Mandelbrot-set/Julia/mandelbrot-set-5.julia +++ b/Task/Mandelbrot-set/Julia/mandelbrot-set-5.julia @@ -1,39 +1,41 @@ using Plots gr(aspect_ratio=:equal, axis=true, ticks=true, legend=false, dpi=200) -d, h = 200, 1200 # pixel density (= image width) and image height -n, r = 8000, 10000 # number of iterations and escape radius (r > 2) +d, h = 800, 500 # pixel density (= image width) and image height +n, r = 200, 500 # number of iterations and escape radius (r > 2) -a = -.743643887037158704752191506114774 # real coordinate of the zoom center -b = 0.131825904205311970493132056385139 # imaginary coordinate of the center +direction, height = 45, 1.5 # direction and height of the incoming light +stripes, damping = 4.0, 2.0 # stripe density and damping parameter x = range(0, 2, length=d+1) y = range(0, 2 * h / d, length=h+1) -A, B = collect(x) .* pi, collect(y) .* pi -C = 8.0 .* exp.((A' .+ B .* im) .* im) .+ (a + b * im) +A, B = collect(x) .- 1, collect(y) .- h / d +C = (2.0 + 1.0im) .* (A' .+ B .* im) .- 0.5 -Z, dZ = zero(C), zero(C) -D = zeros(size(C)) +Z, dZ, ddZ = zero(C), zero(C), zero(C) +D, S, T = zeros(size(C)), zeros(size(C)), zeros(size(C)) for k in 1:n - M = abs2.(Z) .< abs2(r) - Z[M], dZ[M] = Z[M] .^ 2 .+ C[M], 2 .* Z[M] .* dZ[M] .+ 1 + M = abs.(Z) .< r + S[M], T[M] = S[M] .+ cos.(stripes .* angle.(Z[M])), T[M] .+ 1 + Z[M], dZ[M], ddZ[M] = Z[M] .^ 2 .+ C[M], 2 .* Z[M] .* dZ[M] .+ 1, 2 .* (dZ[M] .^ 2 .+ Z[M] .* ddZ[M]) end -N = abs.(Z) .> 2 # exterior distance estimation -D[N] = log.(abs.(Z[N])) .* abs.(Z[N]) ./ abs.(dZ[N]) +N = abs.(Z) .>= r # normal map effect 1 (equipotential lines) +P, Q = S[N] ./ T[N], (S[N] .+ cos.(stripes .* angle.(Z[N]))) ./ (T[N] .+ 1) +R = Q .+ (P .- Q) .* log2.(log.(abs.(Z[N])) ./ log(r)) # linear interpolation +U, V = Z[N] ./ dZ[N], 1 .+ R ./ damping # normal vectors and variations in inclination +U, v = U ./ abs.(U), exp(direction / 180 * pi * im) # unit vectors +D[N] = max.((real.(U) .* real(v) .+ imag.(U) .* imag(v) .+ V .* height) ./ (1 + height), 0) -heatmap(D' .^ 0.05, c=:nipy_spectral) -savefig("Mercator_Mandelbrot_map.png") +heatmap(D .^ 1.0, c=:bone_1) +savefig("Mandelbrot_normal_map_1.png") -X, Y = real(C), imag(C) # zoom images (adjust circle size 50 and zoom level 20 as needed) -R, c, z = 50 * (2 / d) * pi .* exp.(.- B), min(d, h) + 1, max(0, h - d) ÷ 20 +N = abs.(Z) .> 2 # normal map effect 2 (equidistant lines) +U = Z[N] .* dZ[N] .* ((1 .+ log.(abs.(Z[N]))) .* conj.(dZ[N] .^ 2) .- log.(abs.(Z[N])) .* conj.(Z[N] .* ddZ[N])) +U, v = U ./ abs.(U), exp(direction / 180 * pi * im) # unit vectors +D[N] = max.((real.(U) .* real(v) .+ imag.(U) .* imag(v) .+ height) ./ (1 + height), 0) -gr(c=:nipy_spectral, axis=true, ticks=true, legend=false, markerstrokewidth=0) -p1 = scatter(X[1z+1:1z+c,1:d], Y[1z+1:1z+c,1:d], markersize=R[1:c].^0.5, marker_z=D[1z+1:1z+c,1:d].^0.5) -p2 = scatter(X[2z+1:2z+c,1:d], Y[2z+1:2z+c,1:d], markersize=R[1:c].^0.5, marker_z=D[2z+1:2z+c,1:d].^0.4) -p3 = scatter(X[3z+1:3z+c,1:d], Y[3z+1:3z+c,1:d], markersize=R[1:c].^0.5, marker_z=D[3z+1:3z+c,1:d].^0.3) -p4 = scatter(X[4z+1:4z+c,1:d], Y[4z+1:4z+c,1:d], markersize=R[1:c].^0.5, marker_z=D[4z+1:4z+c,1:d].^0.2) -plot(p1, p2, p3, p4, layout=(2, 2)) -savefig("Mercator_Mandelbrot_zoom.png") +heatmap(D .^ 1.0, c=:afmhot) +savefig("Mandelbrot_normal_map_2.png") diff --git a/Task/Mandelbrot-set/Julia/mandelbrot-set-6.julia b/Task/Mandelbrot-set/Julia/mandelbrot-set-6.julia index ee9e72e8f7..1f2373f04e 100644 --- a/Task/Mandelbrot-set/Julia/mandelbrot-set-6.julia +++ b/Task/Mandelbrot-set/Julia/mandelbrot-set-6.julia @@ -1,46 +1,39 @@ using Plots gr(aspect_ratio=:equal, axis=true, ticks=true, legend=false, dpi=200) -setprecision(BigFloat, 256) # set precision to 256 bits (default) -setrounding(BigFloat, RoundNearest) # set rounding mode (default) +d, h = 200, 1200 # pixel density (= image width) and image height +n, r = 8000, 10000 # number of iterations and escape radius (r > 2) -d, h = 50, 1000 # pixel density (= image width) and image height -n, r = 80000, 100000 # number of iterations and escape radius (r > 2) - -a = BigFloat("-1.256827152259138864846434197797294538253477389787308085590211144291") -b = BigFloat(".37933802890364143684096784819544060002129071484943239316486643285025") - -S = zeros(Complex{Float64}, n+1) -let c = a + b * im, z = zero(c) - for k in 1:n+1 - S[k] = z - if abs2(z) < abs2(r) - z = z ^ 2 + c - else - println("The reference sequence diverges within $(k-1) iterations.") - break - end - end -end +a = -.743643887037158704752191506114774 # real coordinate of the zoom center +b = 0.131825904205311970493132056385139 # imaginary coordinate of the center x = range(0, 2, length=d+1) y = range(0, 2 * h / d, length=h+1) A, B = collect(x) .* pi, collect(y) .* pi -C = 8.0 .* exp.((A' .+ B .* im) .* im) +C = 8.0 .* exp.((A' .+ B .* im) .* im) .+ (a + b * im) -E, Z, dZ = zero(C), zero(C), zero(C) -D, I, J = zeros(size(C)), ones(Int64, size(C)), ones(Int64, size(C)) +Z, dZ = zero(C), zero(C) +D = zeros(size(C)) for k in 1:n - M, R = abs2.(Z) .< abs2(r), abs2.(Z) .< abs2.(E) - E[R], I[R] = Z[R], J[R] # rebase when z is closer to zero - E[M], I[M] = (2 .* S[I[M]] .+ E[M]) .* E[M] .+ C[M], I[M] .+ 1 - Z[M], dZ[M] = S[I[M]] .+ E[M], 2 .* Z[M] .* dZ[M] .+ 1 + M = abs2.(Z) .< abs2(r) + Z[M], dZ[M] = Z[M] .^ 2 .+ C[M], 2 .* Z[M] .* dZ[M] .+ 1 end N = abs.(Z) .> 2 # exterior distance estimation D[N] = log.(abs.(Z[N])) .* abs.(Z[N]) ./ abs.(dZ[N]) -heatmap(D' .^ 0.015, c=:nipy_spectral) -savefig("Mercator_Mandelbrot_deep_map.png") +heatmap(D' .^ 0.05, c=:nipy_spectral) +savefig("Mercator_Mandelbrot_map.png") + +X, Y = real(C), imag(C) # zoom images (adjust circle size 50 and zoom level 20 as needed) +R, c, z = 50 * (2 / d) * pi .* exp.(.- B), min(d, h) + 1, max(0, h - d) ÷ 20 + +gr(c=:nipy_spectral, axis=true, ticks=true, legend=false, markerstrokewidth=0) +p1 = scatter(X[1z+1:1z+c,1:d], Y[1z+1:1z+c,1:d], markersize=R[1:c].^0.5, marker_z=D[1z+1:1z+c,1:d].^0.5) +p2 = scatter(X[2z+1:2z+c,1:d], Y[2z+1:2z+c,1:d], markersize=R[1:c].^0.5, marker_z=D[2z+1:2z+c,1:d].^0.4) +p3 = scatter(X[3z+1:3z+c,1:d], Y[3z+1:3z+c,1:d], markersize=R[1:c].^0.5, marker_z=D[3z+1:3z+c,1:d].^0.3) +p4 = scatter(X[4z+1:4z+c,1:d], Y[4z+1:4z+c,1:d], markersize=R[1:c].^0.5, marker_z=D[4z+1:4z+c,1:d].^0.2) +plot(p1, p2, p3, p4, layout=(2, 2)) +savefig("Mercator_Mandelbrot_zoom.png") diff --git a/Task/Mandelbrot-set/Julia/mandelbrot-set-7.julia b/Task/Mandelbrot-set/Julia/mandelbrot-set-7.julia new file mode 100644 index 0000000000..ee9e72e8f7 --- /dev/null +++ b/Task/Mandelbrot-set/Julia/mandelbrot-set-7.julia @@ -0,0 +1,46 @@ +using Plots +gr(aspect_ratio=:equal, axis=true, ticks=true, legend=false, dpi=200) + +setprecision(BigFloat, 256) # set precision to 256 bits (default) +setrounding(BigFloat, RoundNearest) # set rounding mode (default) + +d, h = 50, 1000 # pixel density (= image width) and image height +n, r = 80000, 100000 # number of iterations and escape radius (r > 2) + +a = BigFloat("-1.256827152259138864846434197797294538253477389787308085590211144291") +b = BigFloat(".37933802890364143684096784819544060002129071484943239316486643285025") + +S = zeros(Complex{Float64}, n+1) +let c = a + b * im, z = zero(c) + for k in 1:n+1 + S[k] = z + if abs2(z) < abs2(r) + z = z ^ 2 + c + else + println("The reference sequence diverges within $(k-1) iterations.") + break + end + end +end + +x = range(0, 2, length=d+1) +y = range(0, 2 * h / d, length=h+1) + +A, B = collect(x) .* pi, collect(y) .* pi +C = 8.0 .* exp.((A' .+ B .* im) .* im) + +E, Z, dZ = zero(C), zero(C), zero(C) +D, I, J = zeros(size(C)), ones(Int64, size(C)), ones(Int64, size(C)) + +for k in 1:n + M, R = abs2.(Z) .< abs2(r), abs2.(Z) .< abs2.(E) + E[R], I[R] = Z[R], J[R] # rebase when z is closer to zero + E[M], I[M] = (2 .* S[I[M]] .+ E[M]) .* E[M] .+ C[M], I[M] .+ 1 + Z[M], dZ[M] = S[I[M]] .+ E[M], 2 .* Z[M] .* dZ[M] .+ 1 +end + +N = abs.(Z) .> 2 # exterior distance estimation +D[N] = log.(abs.(Z[N])) .* abs.(Z[N]) ./ abs.(dZ[N]) + +heatmap(D' .^ 0.015, c=:nipy_spectral) +savefig("Mercator_Mandelbrot_deep_map.png") diff --git a/Task/Mandelbrot-set/Python/mandelbrot-set-10.py b/Task/Mandelbrot-set/Python/mandelbrot-set-10.py new file mode 100644 index 0000000000..5da9f4d0dd --- /dev/null +++ b/Task/Mandelbrot-set/Python/mandelbrot-set-10.py @@ -0,0 +1,5 @@ +from functools import reduce + +def mandelbrot(x, y, c): return ' *'[abs(reduce(lambda z, _: z*z + c, range(99), 0)) < 2] + +print('\n'.join(''.join(mandelbrot(x, y, x/50 + y/50j) for x in range(-100, 25)) for y in range(-50, 50))) diff --git a/Task/Mandelbrot-set/Python/mandelbrot-set-5.py b/Task/Mandelbrot-set/Python/mandelbrot-set-5.py index c7acbea306..f4024408ba 100644 --- a/Task/Mandelbrot-set/Python/mandelbrot-set-5.py +++ b/Task/Mandelbrot-set/Python/mandelbrot-set-5.py @@ -4,38 +4,31 @@ import matplotlib.pyplot as plt d, h = 800, 500 # pixel density (= image width) and image height n, r = 200, 500 # number of iterations and escape radius (r > 2) -direction, height = 45, 1.5 # direction and height of the incoming light -stripes, damping = 4, 2.0 # stripe density and damping parameter - x = np.linspace(0, 2, num=d+1) y = np.linspace(0, 2 * h / d, num=h+1) A, B = np.meshgrid(x - 1, y - h / d) -C = (2.0 + 1.0j) * (A + B * 1j) - 0.5 +C = 2.0 * (A + B * 1j) - 0.5 -Z, dZ, ddZ = np.zeros_like(C), np.zeros_like(C), np.zeros_like(C) +Z, dZ = np.zeros_like(C), np.zeros_like(C) D, S, T = np.zeros(C.shape), np.zeros(C.shape), np.zeros(C.shape) for k in range(n): M = abs(Z) < r - S[M], T[M] = S[M] + np.cos(stripes * np.angle(Z[M])), T[M] + 1 - Z[M], dZ[M], ddZ[M] = Z[M] ** 2 + C[M], 2 * Z[M] * dZ[M] + 1, 2 * (dZ[M] ** 2 + Z[M] * ddZ[M]) + S[M], T[M] = S[M] + np.exp(- abs(Z[M])), T[M] + 1 + Z[M], dZ[M] = Z[M] ** 2 + C[M], 2 * Z[M] * dZ[M] + 1 -N = abs(Z) >= r # normal map effect 1 (potential function) -P, Q = S[N] / T[N], (S[N] + np.cos(stripes * np.angle(Z[N]))) / (T[N] + 1) -F = np.log2(np.log(np.abs(Z[N])) / np.log(r)) # fraction between 0 and 1 (for interpolation) -R = Q + (P - Q) * F * F * (3 - 2 * F) # hermite interpolation (r is between q and p) -U, H = Z[N] / dZ[N], 1 + R / damping # normal vectors to the equipotential lines and height perturbation -U, v = U / abs(U), np.exp(direction / 180 * np.pi * 1j) # unit normal vectors and vector in light direction -D[N] = np.maximum((U.real * v.real + U.imag * v.imag + H * height) / (1 + height), 0) +plt.imshow(S ** 0.1, cmap=plt.cm.twilight_shifted, origin="lower") +plt.savefig("Mandelbrot_set_1.png", dpi=200) -plt.imshow(D ** 1.0, cmap=plt.cm.bone, origin="lower") -plt.savefig("Mandelbrot_normal_map_1.png", dpi=200) +N = abs(Z) >= r # normalized iteration count +T[N] = T[N] - np.log2(np.log(np.abs(Z[N])) / np.log(r)) -N = abs(Z) >= r # normal map effect 2 (distance estimation) -U = Z[N] * dZ[N] * ((1 + np.log(abs(Z[N]))) * np.conj(dZ[N] ** 2) - np.log(abs(Z[N])) * np.conj(Z[N] * ddZ[N])) -U, v = U / abs(U), np.exp(direction / 180 * np.pi * 1j) # unit normal vectors and vector in light direction -D[N] = np.maximum((U.real * v.real + U.imag * v.imag + height) / (1 + height), 0) +plt.imshow(T ** 0.1, cmap=plt.cm.twilight_shifted, origin="lower") +plt.savefig("Mandelbrot_set_2.png", dpi=200) -plt.imshow(D ** 1.0, cmap=plt.cm.afmhot, origin="lower") -plt.savefig("Mandelbrot_normal_map_2.png", dpi=200) +N = abs(Z) > 2 # exterior distance estimation +D[N] = np.log(abs(Z[N])) * abs(Z[N]) / abs(dZ[N]) + +plt.imshow(D ** 0.1, cmap=plt.cm.twilight_shifted, origin="lower") +plt.savefig("Mandelbrot_set_3.png", dpi=200) diff --git a/Task/Mandelbrot-set/Python/mandelbrot-set-6.py b/Task/Mandelbrot-set/Python/mandelbrot-set-6.py index b471cfbc31..02ca4a2693 100644 --- a/Task/Mandelbrot-set/Python/mandelbrot-set-6.py +++ b/Task/Mandelbrot-set/Python/mandelbrot-set-6.py @@ -1,37 +1,40 @@ import numpy as np import matplotlib.pyplot as plt -d, h = 200, 1200 # pixel density (= image width) and image height -n, r = 8000, 10000 # number of iterations and escape radius (r > 2) +d, h = 800, 500 # pixel density (= image width) and image height +n, r = 200, 500 # number of iterations and escape radius (r > 2) -a = -.743643887037158704752191506114774 # real coordinate of the zoom center -b = 0.131825904205311970493132056385139 # imaginary coordinate of the center +direction, height = 45, 1.5 # direction and height of the incoming light +stripes, damping = 4.0, 2.0 # stripe density and damping parameter x = np.linspace(0, 2, num=d+1) y = np.linspace(0, 2 * h / d, num=h+1) -A, B = np.meshgrid(x * np.pi, y * np.pi) -C = 8.0 * np.exp((A + B * 1j) * 1j) + (a + b * 1j) +A, B = np.meshgrid(x - 1, y - h / d) +C = (2.0 + 1.0j) * (A + B * 1j) - 0.5 -Z, dZ = np.zeros_like(C), np.zeros_like(C) -D = np.zeros(C.shape) +Z, dZ, ddZ = np.zeros_like(C), np.zeros_like(C), np.zeros_like(C) +D, S, T = np.zeros(C.shape), np.zeros(C.shape), np.zeros(C.shape) for k in range(n): - M = Z.real ** 2 + Z.imag ** 2 < r ** 2 - Z[M], dZ[M] = Z[M] ** 2 + C[M], 2 * Z[M] * dZ[M] + 1 + M = abs(Z) < r + S[M], T[M] = S[M] + np.cos(stripes * np.angle(Z[M])), T[M] + 1 + Z[M], dZ[M], ddZ[M] = Z[M] ** 2 + C[M], 2 * Z[M] * dZ[M] + 1, 2 * (dZ[M] ** 2 + Z[M] * ddZ[M]) -N = abs(Z) > 2 # exterior distance estimation -D[N] = np.log(abs(Z[N])) * abs(Z[N]) / abs(dZ[N]) +N = abs(Z) >= r # normal map effect 1 (equipotential lines) +P, Q = S[N] / T[N], (S[N] + np.cos(stripes * np.angle(Z[N]))) / (T[N] + 1) +R = Q + (P - Q) * np.log2(np.log(np.abs(Z[N])) / np.log(r)) # linear interpolation +U, V = Z[N] / dZ[N], 1 + R / damping # normal vectors and variations in inclination +U, v = U / abs(U), np.exp(direction / 180 * np.pi * 1j) # unit vectors +D[N] = np.maximum((U.real * v.real + U.imag * v.imag + V * height) / (1 + height), 0) -plt.imshow(D.T ** 0.05, cmap=plt.cm.nipy_spectral, origin="lower") -plt.savefig("Mercator_Mandelbrot_map.png", dpi=200) +plt.imshow(D ** 1.0, cmap=plt.cm.bone, origin="lower") +plt.savefig("Mandelbrot_normal_map_1.png", dpi=200) -X, Y = C.real, C.imag # zoom images (adjust circle size 100 and zoom level 20 as needed) -R, c, z = 100 * (2 / d) * np.pi * np.exp(- B), min(d, h) + 1, max(0, h - d) // 20 +N = abs(Z) > 2 # normal map effect 2 (equidistant lines) +U = Z[N] * dZ[N] * ((1 + np.log(abs(Z[N]))) * np.conj(dZ[N] ** 2) - np.log(abs(Z[N])) * np.conj(Z[N] * ddZ[N])) +U, v = U / abs(U), np.exp(direction / 180 * np.pi * 1j) # unit vectors +D[N] = np.maximum((U.real * v.real + U.imag * v.imag + height) / (1 + height), 0) -fig, ax = plt.subplots(2, 2, figsize=(12, 12)) -ax[0, 0].scatter(X[1*z:1*z+c,0:d], Y[1*z:1*z+c,0:d], s=R[0:c,0:d]**2.0, c=D[1*z:1*z+c,0:d]**0.5, cmap=plt.cm.nipy_spectral) -ax[0, 1].scatter(X[2*z:2*z+c,0:d], Y[2*z:2*z+c,0:d], s=R[0:c,0:d]**2.0, c=D[2*z:2*z+c,0:d]**0.4, cmap=plt.cm.nipy_spectral) -ax[1, 0].scatter(X[3*z:3*z+c,0:d], Y[3*z:3*z+c,0:d], s=R[0:c,0:d]**2.0, c=D[3*z:3*z+c,0:d]**0.3, cmap=plt.cm.nipy_spectral) -ax[1, 1].scatter(X[4*z:4*z+c,0:d], Y[4*z:4*z+c,0:d], s=R[0:c,0:d]**2.0, c=D[4*z:4*z+c,0:d]**0.2, cmap=plt.cm.nipy_spectral) -plt.savefig("Mercator_Mandelbrot_zoom.png", dpi=100) +plt.imshow(D ** 1.0, cmap=plt.cm.afmhot, origin="lower") +plt.savefig("Mandelbrot_normal_map_2.png", dpi=200) diff --git a/Task/Mandelbrot-set/Python/mandelbrot-set-7.py b/Task/Mandelbrot-set/Python/mandelbrot-set-7.py index 960c57501e..b471cfbc31 100644 --- a/Task/Mandelbrot-set/Python/mandelbrot-set-7.py +++ b/Task/Mandelbrot-set/Python/mandelbrot-set-7.py @@ -1,44 +1,37 @@ import numpy as np import matplotlib.pyplot as plt -import decimal as dc # decimal floating point arithmetic with arbitrary precision -dc.getcontext().prec = 80 # set precision to 80 digits (about 256 bits) +d, h = 200, 1200 # pixel density (= image width) and image height +n, r = 8000, 10000 # number of iterations and escape radius (r > 2) -d, h = 50, 1000 # pixel density (= image width) and image height -n, r = 80000, 100000 # number of iterations and escape radius (r > 2) - -a = dc.Decimal("-1.256827152259138864846434197797294538253477389787308085590211144291") -b = dc.Decimal(".37933802890364143684096784819544060002129071484943239316486643285025") - -S = np.zeros(n+1, dtype=np.complex128) -u, v = dc.Decimal(0), dc.Decimal(0) - -for k in range(n+1): - S[k] = float(u) + float(v) * 1j - if u ** 2 + v ** 2 < r ** 2: - u, v = u ** 2 - v ** 2 + a, 2 * u * v + b - else: - print("The reference sequence diverges within %s iterations." % k) - break +a = -.743643887037158704752191506114774 # real coordinate of the zoom center +b = 0.131825904205311970493132056385139 # imaginary coordinate of the center x = np.linspace(0, 2, num=d+1) y = np.linspace(0, 2 * h / d, num=h+1) A, B = np.meshgrid(x * np.pi, y * np.pi) -C = 8.0 * np.exp((A + B * 1j) * 1j) +C = 8.0 * np.exp((A + B * 1j) * 1j) + (a + b * 1j) -E, Z, dZ = np.zeros_like(C), np.zeros_like(C), np.zeros_like(C) -D, I, J = np.zeros(C.shape), np.zeros(C.shape, dtype=np.int64), np.zeros(C.shape, dtype=np.int64) +Z, dZ = np.zeros_like(C), np.zeros_like(C) +D = np.zeros(C.shape) for k in range(n): - Z2 = Z.real ** 2 + Z.imag ** 2 - M, R = Z2 < r ** 2, Z2 < E.real ** 2 + E.imag ** 2 - E[R], I[R] = Z[R], J[R] # rebase when z is closer to zero - E[M], I[M] = (2 * S[I[M]] + E[M]) * E[M] + C[M], I[M] + 1 - Z[M], dZ[M] = S[I[M]] + E[M], 2 * Z[M] * dZ[M] + 1 + M = Z.real ** 2 + Z.imag ** 2 < r ** 2 + Z[M], dZ[M] = Z[M] ** 2 + C[M], 2 * Z[M] * dZ[M] + 1 N = abs(Z) > 2 # exterior distance estimation D[N] = np.log(abs(Z[N])) * abs(Z[N]) / abs(dZ[N]) -plt.imshow(D.T ** 0.015, cmap=plt.cm.nipy_spectral, origin="lower") -plt.savefig("Mercator_Mandelbrot_deep_map.png", dpi=200) +plt.imshow(D.T ** 0.05, cmap=plt.cm.nipy_spectral, origin="lower") +plt.savefig("Mercator_Mandelbrot_map.png", dpi=200) + +X, Y = C.real, C.imag # zoom images (adjust circle size 100 and zoom level 20 as needed) +R, c, z = 100 * (2 / d) * np.pi * np.exp(- B), min(d, h) + 1, max(0, h - d) // 20 + +fig, ax = plt.subplots(2, 2, figsize=(12, 12)) +ax[0, 0].scatter(X[1*z:1*z+c,0:d], Y[1*z:1*z+c,0:d], s=R[0:c,0:d]**2.0, c=D[1*z:1*z+c,0:d]**0.5, cmap=plt.cm.nipy_spectral) +ax[0, 1].scatter(X[2*z:2*z+c,0:d], Y[2*z:2*z+c,0:d], s=R[0:c,0:d]**2.0, c=D[2*z:2*z+c,0:d]**0.4, cmap=plt.cm.nipy_spectral) +ax[1, 0].scatter(X[3*z:3*z+c,0:d], Y[3*z:3*z+c,0:d], s=R[0:c,0:d]**2.0, c=D[3*z:3*z+c,0:d]**0.3, cmap=plt.cm.nipy_spectral) +ax[1, 1].scatter(X[4*z:4*z+c,0:d], Y[4*z:4*z+c,0:d], s=R[0:c,0:d]**2.0, c=D[4*z:4*z+c,0:d]**0.2, cmap=plt.cm.nipy_spectral) +plt.savefig("Mercator_Mandelbrot_zoom.png", dpi=100) diff --git a/Task/Mandelbrot-set/Python/mandelbrot-set-8.py b/Task/Mandelbrot-set/Python/mandelbrot-set-8.py index 6cce0c0708..960c57501e 100644 --- a/Task/Mandelbrot-set/Python/mandelbrot-set-8.py +++ b/Task/Mandelbrot-set/Python/mandelbrot-set-8.py @@ -1,8 +1,44 @@ -print( -'\n'.join( - ''.join( - ' *'[(z:=0, c:=x/50+y/50j, [z:=z*z+c for _ in range(99)], abs(z))[-1]<2] - for x in range(-100,25) - ) - for y in range(-50,50) -)) +import numpy as np +import matplotlib.pyplot as plt + +import decimal as dc # decimal floating point arithmetic with arbitrary precision +dc.getcontext().prec = 80 # set precision to 80 digits (about 256 bits) + +d, h = 50, 1000 # pixel density (= image width) and image height +n, r = 80000, 100000 # number of iterations and escape radius (r > 2) + +a = dc.Decimal("-1.256827152259138864846434197797294538253477389787308085590211144291") +b = dc.Decimal(".37933802890364143684096784819544060002129071484943239316486643285025") + +S = np.zeros(n+1, dtype=np.complex128) +u, v = dc.Decimal(0), dc.Decimal(0) + +for k in range(n+1): + S[k] = float(u) + float(v) * 1j + if u ** 2 + v ** 2 < r ** 2: + u, v = u ** 2 - v ** 2 + a, 2 * u * v + b + else: + print("The reference sequence diverges within %s iterations." % k) + break + +x = np.linspace(0, 2, num=d+1) +y = np.linspace(0, 2 * h / d, num=h+1) + +A, B = np.meshgrid(x * np.pi, y * np.pi) +C = 8.0 * np.exp((A + B * 1j) * 1j) + +E, Z, dZ = np.zeros_like(C), np.zeros_like(C), np.zeros_like(C) +D, I, J = np.zeros(C.shape), np.zeros(C.shape, dtype=np.int64), np.zeros(C.shape, dtype=np.int64) + +for k in range(n): + Z2 = Z.real ** 2 + Z.imag ** 2 + M, R = Z2 < r ** 2, Z2 < E.real ** 2 + E.imag ** 2 + E[R], I[R] = Z[R], J[R] # rebase when z is closer to zero + E[M], I[M] = (2 * S[I[M]] + E[M]) * E[M] + C[M], I[M] + 1 + Z[M], dZ[M] = S[I[M]] + E[M], 2 * Z[M] * dZ[M] + 1 + +N = abs(Z) > 2 # exterior distance estimation +D[N] = np.log(abs(Z[N])) * abs(Z[N]) / abs(dZ[N]) + +plt.imshow(D.T ** 0.015, cmap=plt.cm.nipy_spectral, origin="lower") +plt.savefig("Mercator_Mandelbrot_deep_map.png", dpi=200) diff --git a/Task/Mandelbrot-set/Python/mandelbrot-set-9.py b/Task/Mandelbrot-set/Python/mandelbrot-set-9.py index 5da9f4d0dd..6cce0c0708 100644 --- a/Task/Mandelbrot-set/Python/mandelbrot-set-9.py +++ b/Task/Mandelbrot-set/Python/mandelbrot-set-9.py @@ -1,5 +1,8 @@ -from functools import reduce - -def mandelbrot(x, y, c): return ' *'[abs(reduce(lambda z, _: z*z + c, range(99), 0)) < 2] - -print('\n'.join(''.join(mandelbrot(x, y, x/50 + y/50j) for x in range(-100, 25)) for y in range(-50, 50))) +print( +'\n'.join( + ''.join( + ' *'[(z:=0, c:=x/50+y/50j, [z:=z*z+c for _ in range(99)], abs(z))[-1]<2] + for x in range(-100,25) + ) + for y in range(-50,50) +)) diff --git a/Task/Palindrome-detection/Insitux/palindrome-detection-1.insitux b/Task/Palindrome-detection/Insitux/palindrome-detection-1.insitux new file mode 100644 index 0000000000..062ffe9212 --- /dev/null +++ b/Task/Palindrome-detection/Insitux/palindrome-detection-1.insitux @@ -0,0 +1,3 @@ +(var palindrome? (= (reverse %))) + +(palindrome? "deified") ;returns true diff --git a/Task/Palindrome-detection/Insitux/palindrome-detection-2.insitux b/Task/Palindrome-detection/Insitux/palindrome-detection-2.insitux new file mode 100644 index 0000000000..8c5eec3cdf --- /dev/null +++ b/Task/Palindrome-detection/Insitux/palindrome-detection-2.insitux @@ -0,0 +1,3 @@ +(var palindrome? (comp (filter letter?) lower-case (= (reverse %)))) + +(palindrome? "In girum imus nocte et consumimur igni.") ;returns true diff --git a/Task/Pell-numbers/ALGOL-68/pell-numbers.alg b/Task/Pell-numbers/ALGOL-68/pell-numbers.alg new file mode 100644 index 0000000000..8e9cb40bb7 --- /dev/null +++ b/Task/Pell-numbers/ALGOL-68/pell-numbers.alg @@ -0,0 +1,75 @@ +BEGIN # find some Pell numbers - trans FreeBASIC ( which is trans Phix ) # + + PR read "primes.incl.a68" PR + + PROC is prime = ( LONG INT v )BOOL: + IF v < 2 THEN FALSE + ELIF v MOD 2 = 0 THEN v = 2 + ELIF v MOD 3 = 0 THEN v = 3 + ELSE + LONG INT d := 5; + BOOL result := TRUE; + WHILE result AND d * d <= v DO + IF v MOD d = 0 + THEN result := FALSE + ELSE + d +:= 2; + IF v MOD d = 0 + THEN result := FALSE + ELSE d +:= 4 + FI + FI + OD; + result + FI # is prime # ; + + INT n; + [ 0 : 90 ]LONG INT p, pl; + p[ 0 ] := 0; p[ 1 ] := 1; + pl[ 0 ] := 2; pl[ 1 ] := 2; + FOR n FROM 2 TO UPB p DO + p[ n ] := 2 * p[ n - 1 ] + p[ n - 2 ]; + pl[ n ] := 2 * pl[ n - 1 ] + pl[ n - 2 ] + OD; + + print( ( "First 20 Pell numbers:", newline ) ); + FOR n FROM 0 TO 19 DO print( ( " ", whole( p[ n ], 0 ) ) ) OD; + print( ( newline, newline, "First 20 Pell-Lucas numbers:", newline ) ); + FOR n FROM 0 TO 19 DO print( ( " ", whole( pl[ n ], 0 ) ) ) OD; + + print( ( newline, newline, "First 20 rational approximations of sqrt(2) (" ) ); + print( ( fixed( sqrt( 2 ), -15, 13 ), "):", newline ) ); + FOR n TO 20 DO + LONG INT j = pl[ n ] OVER 2, d = p[ n ]; + print( ( " ", whole( j, 0 ), "/", whole( d, 0 ), " ~= ", fixed( j / d, -15, 13 ), newline ) ) + OD; + + print( ( newline, "First 10 Pell primes:", newline, "index Pell prime", newline ) ); + INT pdx := 2; + INT c := 0; + WHILE + IF is probably prime( p[ pdx ] ) THEN + print( ( whole( pdx, -5 ), " ", whole( p[ pdx ], 0 ), newline ) ); + c +:= 1 + FI; + pdx +:= 1; + c < 10 + DO SKIP OD; + + [ 0 : 20 ]LONG INT nsw; + FOR n FROM 0 TO 19 DO nsw[ n ] := p[ 2 * n ] + p[ 2 * n + 1 ] OD; + print( ( newline, newline, "First 20 Newman-Shank-Williams numbers:", newline ) ); + FOR n FROM 0 TO 19 DO print( ( " ", whole( nsw[ n ], 0 ) ) ); IF n = 13 THEN print( ( newline ) ) FI OD; + + print( ( newline, newline, "First 20 near isosceles right triangles:", newline ) ); + LONG INT i0 := 0, i1 := 1, t := 1, found := 0; + FOR i FROM 2 WHILE found < 20 DO + LONG INT i2 = i1*2 + i0; + IF ODD i THEN + print( ( " [", whole( t, 0 ), ", ", whole( t + 1, 0 ), ", ", whole( i2, 0 ), "]", newline ) ); + found +:= 1 + FI; + t +:= i2; i0 := i1; i1 := i2 + OD + +END diff --git a/Task/Primality-by-trial-division/Applesoft-BASIC/primality-by-trial-division.basic b/Task/Primality-by-trial-division/Applesoft-BASIC/primality-by-trial-division.basic new file mode 100644 index 0000000000..59f6134215 --- /dev/null +++ b/Task/Primality-by-trial-division/Applesoft-BASIC/primality-by-trial-division.basic @@ -0,0 +1,11 @@ + 100 DEF FN MOD(NUM) = NUM - INT (NUM / DIV) * DIV: REM NUM MOD DIV + 110 FOR I = 1 TO 99 + 120 V = I: GOSUB 200"ISPRIME + 130 IF ISPRIME THEN PRINT " "I; + 140 NEXT I + 150 END + + 200 ISPRIME = FALSE: IF V < 2 THEN RETURN + 210 DIV = 2:ISPRIME = FN MOD(V): IF NOT ISPRIME THEN ISPRIME = V = 2: RETURN + 220 LIMIT = SQR (V): IF LIMIT > = 3 THEN FOR DIV = 3 TO LIMIT STEP 2:ISPRIME = FN MOD(V): IF ISPRIME THEN NEXT DIV + 230 RETURN diff --git a/Task/Prime-numbers-whose-neighboring-pairs-are-tetraprimes/Raku/prime-numbers-whose-neighboring-pairs-are-tetraprimes.raku b/Task/Prime-numbers-whose-neighboring-pairs-are-tetraprimes/Raku/prime-numbers-whose-neighboring-pairs-are-tetraprimes.raku new file mode 100644 index 0000000000..99c06f426d --- /dev/null +++ b/Task/Prime-numbers-whose-neighboring-pairs-are-tetraprimes/Raku/prime-numbers-whose-neighboring-pairs-are-tetraprimes.raku @@ -0,0 +1,73 @@ +# 20230721 Raku programming solution + +my @primes = (2..1e7).grep: *.is-prime; # cannot do lazy here + +sub median { # based on https://rosettacode.org/wiki/Averages/Median#Raku + return { ( .[(*-1) div 2] + .[* div 2] ) / 2 }(@_) # for already sorted +} + +sub isTetraPrime ($n is copy) { # is cached { + my ($count,$prevFact) = 0, 1; + for @primes -> \p { + my $limit = p * p; + if $count == 0 { + $limit = $limit * $limit + } elsif $count == 1 { + $limit *= p + } + if $limit <= $n { + while $n %% p { + return False if ( $count == 4 or p == $prevFact ); + $count++; + $n div= p; + $prevFact = p + } + } else { + last + } + } + if $n > 1 { + return False if ( $count == 4 or $n == $prevFact ); + $count++ + } + return $count == 4 +} + +my ( $j, @tetras1, @tetras2, $sevens1, $sevens2 ) = 1e5; + +my \highest7 = @primes.[*-1]; +my \highest6 = @primes.first: * < 1e6, :end; +my \highest5 = @primes.first: * < 1e5, :end; + +for @primes -> \p { + if isTetraPrime p-1 and isTetraPrime p-2 { + @tetras1.push: p; + $sevens1++ if ( (p-1) %% 7 or (p-2) %% 7 ); + } + if isTetraPrime p+1 and isTetraPrime p+2 { + @tetras2.push: p; + $sevens2++ if ( (p+1) %% 7 or (p+2) %% 7 ); + } + if p == highest5 | highest6 | highest7 { + for 0,1 -> \i { + my (\sevens, \t, @tetras) := i == 0 + ?? ( $sevens1, "preceding", @tetras1 ) + !! ( $sevens2, "following", @tetras2 ); + my \c = @tetras.elems; + + say "Found {c} primes under $j whose {t} neighboring pair are tetraprimes:"; + if p == highest5 { + say [~] $_>>.fmt('%6s') for @tetras.rotor(10,:partial); + } + say "of which {sevens} have a neighboring pair one of whose factors is 7.\n"; + my \gaps = ( @tetras.rotor(2=>-1).map: { .[1] - .[0] } ).sort; + + my (\Min,\Max,\Med) = gaps[0], gaps[*-1], median(gaps); + say "Minimum gap between those {c} primes : {Min}"; + say "Median gap between those {c} primes : {Med}"; + say "Maximum gap between those {c} primes : {Max}"; + say() + } + $j *= 10 + } +} diff --git a/Task/Quine/Insitux/quine.insitux b/Task/Quine/Insitux/quine.insitux new file mode 100644 index 0000000000..db8ba01a85 --- /dev/null +++ b/Task/Quine/Insitux/quine.insitux @@ -0,0 +1 @@ +(#(join(char-code 34)[% %(char-code 41)])"(#(join(char-code 34)[% %(char-code 41)])") diff --git a/Task/Radical-of-an-integer/REXX/radical-of-an-integer.rexx b/Task/Radical-of-an-integer/REXX/radical-of-an-integer.rexx new file mode 100644 index 0000000000..446959e900 --- /dev/null +++ b/Task/Radical-of-an-integer/REXX/radical-of-an-integer.rexx @@ -0,0 +1,110 @@ +/* REXX */ +call setp +Numeric Digits 100 +/* 1. Radicals from 1 to 50 */ +Say 'Radicals of 1..50:' +ol='' +Do n=1 To 50 + ol=ol||right(rad(n),5) + If n//10=0 then Do + Say ol + ol='' + End + End + +Say '' +Call radt 99999 +Call radt 499999 +Call radt 999999 + +Say '' +Say 'Distribution of radicals:' +Call time 'R' +cnt.=0 +Do v=1 To 1000000 + If v//100000=1 Then Do + ti=v%100000 + etime.ti=format(time('E'),4,1) + End + p=rad(v,'cnt') + cnt.p+=1 + /************************************** + If p=7 Then + Say v':' rad(v,'lstx') '=' rad(v) + **************************************/ + End +etime.10=format(time('E'),4,1) +Do d=0 To 20 + If cnt.d>0 Then + Say d':' right(cnt.d,8) + End +Say '' +Say 'Timings:' +Do ti=1 To 10 + Say right(ti,2) etime.ti 'seconds' + End +Exit + +radt: + Parse Arg u + Say 'The radical of' u 'is' rad(u)'.' + Return + +rad: + Parse Arg z,what + zz=z + plist='' + exp.=0 + Do Until p*p>z + Do pi=1 By 1 Until p*p>z + p=word(primzahlen,pi) + exp.p=0 + Do while z//p=0 + exp.p+=1 + If pos(p,plist)=0 Then + plist=plist p + z=z%p + End + End + End + exp.z+=1 + If pos(z,plist)=0 &z<>1 Then + plist=plist z + Select + When what='lst' Then + Return plist + When what='lstx' Then Do + s='' + Do While plist<>'' + Parse Var plist p plist + if exp.p=1 Then + s=s'*'p + Else + s=s'*'p'**'exp.p + End + Return strip(s,,'*') + End + When what='cnt' Then + Return words(plist) + Otherwise Do + rad=1 + Do while plist>'' + Parse Var plist p plist + rad=rad*p + End + Return rad + End + End + +setp: +primzahlen=, +2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101, +103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197, +199 211 223 227 229 233 239 241 251 257 263 269 271 277 281 283 293 307 311, +313 317 331 337 347 349 353 359 367 373 379 383 389 397 401 409 419 421 431, +433 439 443 449 457 461 463 467 479 487 491 499 503 509 521 523 541 547 557, +563 569 571 577 587 593 599 601 607 613 617 619 631 641 643 647 653 659 661, +673 677 683 691 701 709 719 727 733 739 743 751 757 761 769 773 787 797 809, +811 821 823 827 829 839 853 857 859 863 877 881 883 887 907 911 919 929 937, +941 947 953 967 971 977 983 991 997 1009 1013 1019 1021 1031 1033 1039 1049 +Return diff --git a/Task/Read-a-configuration-file/Forth/read-a-configuration-file.fth b/Task/Read-a-configuration-file/Forth/read-a-configuration-file.fth index 9cdc629c4b..c2a1954c88 100644 --- a/Task/Read-a-configuration-file/Forth/read-a-configuration-file.fth +++ b/Task/Read-a-configuration-file/Forth/read-a-configuration-file.fth @@ -22,7 +22,7 @@ CONFIG DEFINITIONS \ put things in the n : RESET ( addr --) false swap ! ; : # ( -- ) 1 PARSE 2DROP ; \ parse line and throw away : = ( addr --) 1 PARSE trim ROT PLACE ; \ string assignment operator -synonym ; # \ 2nd comment operator is simple +' # alias ; \ 2nd comment operator is simple FORTH DEFINITIONS \ this command reads and interprets the config.txt file diff --git a/Task/Reduced-row-echelon-form/00-META.yaml b/Task/Reduced-row-echelon-form/00-META.yaml index 4affffb8b2..c102287f22 100644 --- a/Task/Reduced-row-echelon-form/00-META.yaml +++ b/Task/Reduced-row-echelon-form/00-META.yaml @@ -1,3 +1,2 @@ --- from: http://rosettacode.org/wiki/Reduced_row_echelon_form -note: Matrices diff --git a/Task/Reduced-row-echelon-form/00-TASK.txt b/Task/Reduced-row-echelon-form/00-TASK.txt index 6113293c38..53a11be788 100644 --- a/Task/Reduced-row-echelon-form/00-TASK.txt +++ b/Task/Reduced-row-echelon-form/00-TASK.txt @@ -1,3 +1,9 @@ + +{{wikipedia|Rref#Pseudocode}} +{{task|Matrices}} +{{omit from|GUISS}} + + ;Task: Show how to compute the '''reduced row echelon form''' (a.k.a. '''row canonical form''') of a matrix. diff --git a/Task/Remove-duplicate-elements/ANSI-BASIC/remove-duplicate-elements.basic b/Task/Remove-duplicate-elements/ANSI-BASIC/remove-duplicate-elements.basic new file mode 100644 index 0000000000..98858677f3 --- /dev/null +++ b/Task/Remove-duplicate-elements/ANSI-BASIC/remove-duplicate-elements.basic @@ -0,0 +1,29 @@ +100 REM Remove duplicate elements +110 DIM DataArray(1 TO 7), ResultArray(1 TO 7) +120 ! Set the data. +130 FOR I = 1 TO 7 +140 READ DataArray(I) +150 NEXT I +160 ! Remove duplicates +170 LET ResultArray(1) = DataArray(1) +180 LET LastResultIndex = 1 +190 LET Position = 1 +200 DO WHILE Position < UBOUND(DataArray) +210 LET Position = Position + 1 +220 LET IsNewNumber = -1 +230 FOR ResultIndex = 1 TO LastResultIndex +240 IF DataArray(Position) = ResultArray(ResultIndex) THEN +250 LET IsNewNumber = 0 +260 EXIT FOR +270 END IF +280 NEXT ResultIndex +290 IF IsNewNumber = -1 THEN +300 LET LastResultIndex = LastResultIndex + 1 +310 LET ResultArray(LastResultIndex) = DataArray(Position) +320 END IF +330 LOOP +340 FOR ResultIndex = 1 TO LastResultIndex +350 PRINT ResultArray(ResultIndex) +360 NEXT ResultIndex +370 DATA 1, 2, 2, 3, 4, 5, 5 +380 END diff --git a/Task/Remove-duplicate-elements/Liberty-BASIC/remove-duplicate-elements.basic b/Task/Remove-duplicate-elements/Liberty-BASIC/remove-duplicate-elements.basic index 8827ecf924..d9dd52c898 100644 --- a/Task/Remove-duplicate-elements/Liberty-BASIC/remove-duplicate-elements.basic +++ b/Task/Remove-duplicate-elements/Liberty-BASIC/remove-duplicate-elements.basic @@ -1,9 +1,7 @@ a$ =" 1 $23.19 2 elbow 3 2 Bork 4 3 elbow 2 $23.19 " print "Original set of elements = ["; a$; "]" - b$ =removeDuplicates$( a$) print "With duplicates removed = ["; b$; "]" - end function removeDuplicates$( in$) diff --git a/Task/Reverse-words-in-a-string/Insitux/reverse-words-in-a-string.insitux b/Task/Reverse-words-in-a-string/Insitux/reverse-words-in-a-string.insitux new file mode 100644 index 0000000000..271a45d26c --- /dev/null +++ b/Task/Reverse-words-in-a-string/Insitux/reverse-words-in-a-string.insitux @@ -0,0 +1,16 @@ +(var poem + "---------- Ice and Fire ------------ + + fire, in end will world the say Some + ice. in say Some + desire of tasted I've what From + fire. favor who those with hold I + + ... elided paragraph last ... + + Frost Robert -----------------------") + +(function split-join by then x + (-> x (split by) then (join by))) + +(split-join "\n" (map @(split-join " " reverse)) poem) diff --git a/Task/Rot-13/Insitux/rot-13.insitux b/Task/Rot-13/Insitux/rot-13.insitux new file mode 100644 index 0000000000..7dddcffd2c --- /dev/null +++ b/Task/Rot-13/Insitux/rot-13.insitux @@ -0,0 +1,12 @@ +(function ROT-13-char ch + (let x (char-code ch) + x- (or (< 109 x 123) (< 77 x 91))) + (if (or (< 96 x 123) (< 64 x 91)) + (char-code ((x- - +) x 13)) + ch)) + +(function ROT-13 text + (.. str (map ROT-13-char text))) + +(ROT-13 "The Quick Brown Fox Jumped Over The Lazy Dog!") +;returns "Gur Dhvpx Oebja Sbk Whzcrq Bire Gur Ynml Qbt!" diff --git a/Task/Sorting-algorithms-Bogosort/Insitux/sorting-algorithms-bogosort.insitux b/Task/Sorting-algorithms-Bogosort/Insitux/sorting-algorithms-bogosort.insitux new file mode 100644 index 0000000000..56d84c6fb0 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Insitux/sorting-algorithms-bogosort.insitux @@ -0,0 +1,7 @@ +(function bogo-sort order list + (return-when (empty? list) []) + (if (.. order list) + list + (recur order (shuffle list)))) + +(bogo-sort < [7 5 12 1 4 2 23 18]) diff --git a/Task/Soundex/Rust/soundex.rust b/Task/Soundex/Rust/soundex.rust new file mode 100644 index 0000000000..8dadfa124f --- /dev/null +++ b/Task/Soundex/Rust/soundex.rust @@ -0,0 +1,74 @@ +use std::ops::Deref; +use regex::Regex; +use once_cell::sync::Lazy; + +pub trait Soundex { + fn soundex(&self) -> String; +} + +fn soundex_match(c: char) -> char { + return match c.to_ascii_lowercase() { + 'b' | 'f' | 'p' | 'v' => Some('1'), + 'c' | 'g' | 'j' | 'k' | 'q' | 's' | 'x' | 'z' => Some('2'), + 'd' | 't' => Some('3'), + 'l' => Some('4'), + 'm' | 'n' => Some('5'), + 'r' => Some('6'), + _ => Some('0'), + }.unwrap(); +} + +static RE: Lazy = Lazy::new(|| {Regex::new("[^a-zA-Z]").unwrap()}); + +impl> Soundex for T { + fn soundex(&self) -> String { + let s = RE.replace(self, "").chars().collect::>(); + if s.len() == 0 { + return String::new(); + } + let mut a = vec![s[0].to_ascii_uppercase(); 1].to_vec(); + let mut last_sdex = soundex_match(a[0]); + let mut hadvowel = false; + for ch in &s[1..s.len()] { + let lc_ch = ch.to_ascii_lowercase(); + let sdex = soundex_match(lc_ch); + if sdex != '0' { + if sdex != last_sdex || hadvowel { + a.push(sdex); + last_sdex = sdex; + hadvowel = false; + } + } + else if "aeiouy".contains(lc_ch) { + hadvowel = true; + } + } + if a.len() < 4 { + for _ in 0..(4 - a.len()) { + a.push('0'); + } + } + return a[0..4].into_iter().collect(); + } +} + +fn main() { + assert_eq!("Ascroft".soundex(), "A261".to_string()); + assert_eq!("Euler".soundex(), "E460".to_string()); + assert_eq!("Gausss".soundex(), "G200".to_string()); + assert_eq!("Hilbert".soundex(), "H416".to_string()); + assert_eq!("Knuth".soundex(), "K530".to_string()); + assert_eq!("Lloyd".soundex(), "L300".to_string()); + assert_eq!("Lukasiewicz".soundex(), "L222".to_string()); + assert_eq!("Ellery".soundex(), "E460".to_string()); + assert_eq!("Ghosh".soundex(), "G200".to_string()); + assert_eq!("Heilbronn".soundex(), "H416".to_string()); + assert_eq!("Kant".soundex(), "K530".to_string()); + assert_eq!("Ladd".soundex(), "L300".to_string()); + assert_eq!("Lissajous".soundex(), "L222".to_string()); + assert_eq!("Wheaton".soundex(), "W350".to_string()); + assert_eq!("Ashcraft".soundex(), "A261".to_string()); + assert_eq!("Burroughs".soundex(), "B620".to_string()); + assert_eq!("Burrows".soundex(), "B620".to_string()); + assert_eq!("O'Hara".soundex(), "O600".to_string()); +} diff --git a/Task/Strip-a-set-of-characters-from-a-string/Chipmunk-Basic/strip-a-set-of-characters-from-a-string.basic b/Task/Strip-a-set-of-characters-from-a-string/Chipmunk-Basic/strip-a-set-of-characters-from-a-string.basic new file mode 100644 index 0000000000..e21db7c419 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Chipmunk-Basic/strip-a-set-of-characters-from-a-string.basic @@ -0,0 +1,17 @@ +100 cls +110 print stripchars$("She was a soul stripper. She took my heart!","aei") +120 sub stripchars$(src$,remove$) +130 s$ = src$ +140 for l0 = 1 to len(remove$) +150 do +160 t = instr(s$,mid$(remove$,l0,1)) +170 if t then +180 s$ = left$(s$,t-1)+mid$(s$,t+1) +190 else +200 exit do +210 endif +220 loop +230 next +240 stripchars$ = s$ +250 end sub +260 end diff --git a/Task/Strip-a-set-of-characters-from-a-string/Insitux/strip-a-set-of-characters-from-a-string.insitux b/Task/Strip-a-set-of-characters-from-a-string/Insitux/strip-a-set-of-characters-from-a-string.insitux new file mode 100644 index 0000000000..74395d1a0c --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Insitux/strip-a-set-of-characters-from-a-string.insitux @@ -0,0 +1,5 @@ +(function strip from what + (remove (to-vec what) from)) + +(strip "She was a soul stripper. She took my heart!" "aei") +;returns "Sh ws soul strppr. Sh took my hrt!" diff --git a/Task/Sum-digits-of-an-integer/Gambas/sum-digits-of-an-integer.gambas b/Task/Sum-digits-of-an-integer/Gambas/sum-digits-of-an-integer.gambas new file mode 100644 index 0000000000..079848ddba --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Gambas/sum-digits-of-an-integer.gambas @@ -0,0 +1,22 @@ +Public Sub Main() + + Print "The sums of the digits are:\n" + Print "1 base 10 : "; SumDigits(1, 10) + Print "1234 base 10 : "; SumDigits(1234, 10) + Print "fe base 16 : "; SumDigits(&Hfe, 16) + Print "f0e base 16 : "; SumDigits(&Hf0e, 16) + +End + +Function SumDigits(number As Integer, nBase As Integer) As Integer + + If number < 0 Then number = -number ' convert negative numbers to positive + If nBase < 2 Then nBase = 2 ' nBase can't be less than 2 + Dim sum As Integer = 0 + While number > 0 + sum += number Mod nBase + number \= nBase + Wend + Return sum + +End Function diff --git a/Task/Sum-digits-of-an-integer/MSX-Basic/sum-digits-of-an-integer.basic b/Task/Sum-digits-of-an-integer/MSX-Basic/sum-digits-of-an-integer.basic new file mode 100644 index 0000000000..4c8e1c9570 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/MSX-Basic/sum-digits-of-an-integer.basic @@ -0,0 +1,21 @@ +10 CLS +20 PRINT "The sums of the digits are:" : PRINT +30 B = 10 +40 N$ = "1" : GOSUB 100 : PRINT "1 base 10 :" N +50 N$ = "1234" : GOSUB 100 : PRINT "1234 base 10 :" N +60 B = 16 +70 N$ = "FE" : GOSUB 100 : PRINT "FE base 16 :" N +80 N$ = "F0E" : GOSUB 100 : PRINT "F0E base 16 :" N +90 END +100 REM SUM DIGITS OF N$, B +110 IF B = 1 THEN N = LEN(N$) : RETURN +120 IF B < 2 THEN B = 10 +130 N = 0 +140 V$ = LEFT$("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", B) +150 FOR I = 1 TO LEN(N$) +160 C$ = MID$(N$, I, 1) +170 FOR J = 1 TO LEN(V$) +180 IF C$ <> MID$(V$, J, 1) THEN NEXT J : N = SQR(-1) : STOP +190 N = N + J - 1 +200 NEXT I +210 RETURN diff --git a/Task/Tau-function/Haskell/tau-function.hs b/Task/Tau-function/Haskell/tau-function-1.hs similarity index 100% rename from Task/Tau-function/Haskell/tau-function.hs rename to Task/Tau-function/Haskell/tau-function-1.hs diff --git a/Task/Tau-function/Haskell/tau-function-2.hs b/Task/Tau-function/Haskell/tau-function-2.hs new file mode 100644 index 0000000000..a9bff127c7 --- /dev/null +++ b/Task/Tau-function/Haskell/tau-function-2.hs @@ -0,0 +1,29 @@ +import Data.Numbers.Primes +import Data.List (group, intercalate, transpose) +import Data.List.Split (chunksOf) +import Text.Printf + +----------------------- OEISA000005 ---------------------- + +oeisA000005 :: [Int] +oeisA000005 = tau <$> [1..] + +tau :: Integer -> Int +tau = product . fmap (succ . length) . group . primeFactors + + +--------------------------- TEST ------------------------- + +main :: IO () +main = putStrLn $ + (table " " . chunksOf 10 . fmap show . take 100) + oeisA000005 + + +------------------------ FORMATTING ---------------------- + +table :: String -> [[String]] -> String +table gap rows = + let ws = maximum . fmap length <$> transpose rows + pw = printf . flip intercalate ["%", "s"] . show + in unlines $ intercalate gap . zipWith pw ws <$> rows diff --git a/Task/Tau-number/Chipmunk-Basic/tau-number.basic b/Task/Tau-number/Chipmunk-Basic/tau-number.basic new file mode 100644 index 0000000000..2648fe0314 --- /dev/null +++ b/Task/Tau-number/Chipmunk-Basic/tau-number.basic @@ -0,0 +1,19 @@ +100 cls +110 print "The first 100 tau numbers are:" +120 n = 0 +130 num = 0 +140 limit = 100 +150 while num < limit +160 n = n+1 +170 tau = 0 +180 for m = 1 to n +190 if n mod m = 0 then tau = tau+1 +200 next m +210 if n mod tau = 0 then +220 num = num+1 +230 if num mod 10 = 1 then print +240 print n, +250 endif +260 wend +270 print +280 end diff --git a/Task/Tau-number/GW-BASIC/tau-number.basic b/Task/Tau-number/GW-BASIC/tau-number.basic new file mode 100644 index 0000000000..7550d6cbaa --- /dev/null +++ b/Task/Tau-number/GW-BASIC/tau-number.basic @@ -0,0 +1,14 @@ +100 CLS +110 PRINT "The first 100 tau numbers are:" +120 N = 0 +130 NUM = 0 +140 LIMIT = 100 +150 WHILE NUM < LIMIT +160 N = N+1 +170 TAU = 0 +180 FOR M = 1 TO N +190 IF N MOD M = 0 THEN TAU = TAU+1 +200 NEXT M +210 IF N MOD TAU = 0 THEN NUM = NUM+1 : PRINT N; " "; +220 WEND +230 END diff --git a/Task/Tau-number/MSX-Basic/tau-number.basic b/Task/Tau-number/MSX-Basic/tau-number.basic new file mode 100644 index 0000000000..7015d80153 --- /dev/null +++ b/Task/Tau-number/MSX-Basic/tau-number.basic @@ -0,0 +1,14 @@ +100 CLS +110 PRINT "The first 100 tau numbers are:" +120 N = 0 +130 NUM = 0 +140 LIMIT = 100 +150 IF NUM > LIMIT THEN GOTO 270 +160 N = N+1 +170 TAU = 0 +180 FOR M = 1 TO N +190 IF N MOD M = 0 THEN TAU = TAU+1 +200 NEXT M +210 IF N MOD TAU = 0 THEN NUM = NUM+1 : PRINT N; +220 GOTO 150 +230 END diff --git a/Task/Temperature-conversion/Chipmunk-Basic/temperature-conversion.basic b/Task/Temperature-conversion/Chipmunk-Basic/temperature-conversion.basic new file mode 100644 index 0000000000..f96749e0cf --- /dev/null +++ b/Task/Temperature-conversion/Chipmunk-Basic/temperature-conversion.basic @@ -0,0 +1,13 @@ +10 CLS : REM 10 HOME for Applesoft BASIC : DELETE for Minimal BASIC +20 PRINT "Kelvin Degrees "; +30 INPUT K +40 IF K <= 0 THEN 130 +50 LET C = K-273.15 +60 LET F = K*1.8-459.67 +70 LET R = K*1.8 +80 PRINT K;" Kelvin is equivalent to" +90 PRINT C;" Degrees Celsius" +100 PRINT F;" Degrees Fahrenheit" +110 PRINT R;" Degrees Rankine" +120 GOTO 20 +130 END diff --git a/Task/Temperature-conversion/Insitux/temperature-conversion.insitux b/Task/Temperature-conversion/Insitux/temperature-conversion.insitux new file mode 100644 index 0000000000..efebfa012d --- /dev/null +++ b/Task/Temperature-conversion/Insitux/temperature-conversion.insitux @@ -0,0 +1,11 @@ +(var K->C (+ -273.15)) +(var K->R (* 1.8)) +(var K->F (comp K->R (+ -459.67))) + +(function kelvin-conversions K + (let [C R F] ((juxt K->C K->R K->F) K) + [C R F] (map @(round 2) [C R F])) + (print K " K / " C " °C / " R " °R / " F " °F")) + +(kelvin-conversions 21.0) +;prints "21 K / -252.15 °C / 37.8 °R / -421.87 °F" diff --git a/Task/Temperature-conversion/Quite-BASIC/temperature-conversion.basic b/Task/Temperature-conversion/Quite-BASIC/temperature-conversion.basic new file mode 100644 index 0000000000..29be777622 --- /dev/null +++ b/Task/Temperature-conversion/Quite-BASIC/temperature-conversion.basic @@ -0,0 +1,11 @@ +10 PRINT "Kelvin Degrees "; +20 INPUT ""; K +30 IF K <= 0 THEN END +40 LET C = K-273.15 +50 LET F = K*1.8-459.67 +60 LET R = K*1.8 +70 PRINT K;" Kelvin is equivalent to" +80 PRINT C;" Degrees Celsius" +90 PRINT F;" Degrees Fahrenheit" +100 PRINT R;" Degrees Rankine" +110 GOTO 10 diff --git a/Task/Test-a-function/Insitux/test-a-function.insitux b/Task/Test-a-function/Insitux/test-a-function.insitux new file mode 100644 index 0000000000..38185cc47b --- /dev/null +++ b/Task/Test-a-function/Insitux/test-a-function.insitux @@ -0,0 +1,28 @@ +(var palindrome? (comp (filter letter?) lower-case (= (reverse %)))) + +;Arrange +(var calls []) +(function record f + (fn (var! calls (append f)) + (... (unmocked f) args))) + +(mock comp (record comp) + filter (record filter) + letter? (record letter?) + lower-case (record lower-case) + = (record =) + reverse (record reverse)) + +(var sentence "In girum imus nocte et consumimur igni.") + +;Act +(var result (palindrome? sentence)) + +(unmock comp filter letter? lower-case = reverse) + +;Assert +(assert result) + +(var occurred (freqs calls)) +(assert (= (len sentence) (occurred letter?))) ;letter? is called (len sentence) times +(assert (... = 1 (map occurred [filter lower-case reverse =]))) ;other functions are called only once diff --git a/Task/Time-a-function/Insitux/time-a-function.insitux b/Task/Time-a-function/Insitux/time-a-function.insitux new file mode 100644 index 0000000000..ff9da5b26e --- /dev/null +++ b/Task/Time-a-function/Insitux/time-a-function.insitux @@ -0,0 +1,11 @@ +(function measure + (let [start result end] [(time) (... . args) (time)]) + (str result " took " (- end start) "ms")) + +(function fib n + (if (< n 2) n + (+ (fib (dec n)) + (fib (- n 2))))) + +(measure fib 35) +;returns "9227465 took 26497ms" diff --git a/Task/Trabb-Pardo-Knuth-algorithm/ANSI-BASIC/trabb-pardo-knuth-algorithm.basic b/Task/Trabb-Pardo-Knuth-algorithm/ANSI-BASIC/trabb-pardo-knuth-algorithm.basic new file mode 100644 index 0000000000..2a7c459998 --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/ANSI-BASIC/trabb-pardo-knuth-algorithm.basic @@ -0,0 +1,26 @@ +100 REM Trabb Pardo-Knuth algorithm +110 REM Used "magic numbers" because of strict specification of the algorithm. +120 DEF FNF(N) = SQR(ABS(N)) + 5 * N * N * N +130 DIM S(0 TO 10) +140 PRINT "Enter 11 numbers." +150 FOR I = 0 TO 10 +160 INPUT PROMPT STR$(I + 1) & ":": S(I) +170 NEXT I +180 PRINT +190 REM Reverse +200 FOR I = 0 TO INT(10 / 2) +210 LET Tmp = S(I) +220 LET S(I) = S(10 - I) +230 LET S(10 - I) = Tmp +240 NEXT I +250 REM Results +260 FOR I = 0 TO 10 +270 LET R = FNF(S(I)) +280 PRINT USING "f(####.###) = ": S(I); +290 IF R > 400 THEN +300 PRINT "overflow" +310 ELSE +320 PRINT USING "####.###": R +330 END IF +340 NEXT I +350 END diff --git a/Task/Trabb-Pardo-Knuth-algorithm/Modula-2/trabb-pardo-knuth-algorithm.mod2 b/Task/Trabb-Pardo-Knuth-algorithm/Modula-2/trabb-pardo-knuth-algorithm.mod2 index f7285909d7..d2450c48f0 100644 --- a/Task/Trabb-Pardo-Knuth-algorithm/Modula-2/trabb-pardo-knuth-algorithm.mod2 +++ b/Task/Trabb-Pardo-Knuth-algorithm/Modula-2/trabb-pardo-knuth-algorithm.mod2 @@ -32,18 +32,9 @@ BEGIN END; END ReverseSequence; -PROCEDURE RealAbs(Item: REAL): REAL; -BEGIN - IF Item < 0.0 THEN - RETURN -Item - ELSE - RETURN Item - END -END RealAbs; - PROCEDURE DoOperation(Item: REAL): REAL; BEGIN - RETURN sqrt(RealAbs(Item)) + 5.0 * Item * Item * Item; + RETURN sqrt(ABS(Item)) + 5.0 * Item * Item * Item; END DoOperation; BEGIN diff --git a/Task/Variadic-function/Insitux/variadic-function.insitux b/Task/Variadic-function/Insitux/variadic-function.insitux new file mode 100644 index 0000000000..365cf73ae7 --- /dev/null +++ b/Task/Variadic-function/Insitux/variadic-function.insitux @@ -0,0 +1,5 @@ +(function f + (loop-over args a + (print a))) + +(f 1 2 3 4)