task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Send_an_unknown_method_call
Send an unknown method call
Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
#MATLAB_.2F_Octave
MATLAB / Octave
  funName = 'foo'; % generate function name feval (funNAME, ...) % evaluation function with optional parameters   funName = 'a=atan(pi)'; % generate function name eval (funName, 'printf(''Error\n'')')  
http://rosettacode.org/wiki/Send_an_unknown_method_call
Send an unknown method call
Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
#Objective-C
Objective-C
#import <Foundation/Foundation.h>   @interface Example : NSObject - (NSNumber *)foo; @end   @implementation Example - (NSNumber *)foo { return @42; } @end   int main (int argc, const char *argv[]) { @autoreleasepool {   id example = [[Example alloc] init]; SEL selector = @selector(foo); // or = NSSelectorFromString(@"foo"); NSLog(@"%@", [example performSelector:selector]);   } return 0; }
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Agda
Agda
  -- imports open import Data.Nat as ℕ using (ℕ; suc; zero; _+_; _∸_) open import Data.Vec as Vec using (Vec; _∷_; []; tabulate; foldr) open import Data.Fin as Fin using (Fin; suc; zero) open import Function using (_∘_; const; id) open import Data.List as List using (List; _∷_; []) open import Data.Maybe using (Maybe; just; nothing)   -- Without square cutoff optimization module Simple where primes : ∀ n → List (Fin n) primes zero = [] primes (suc zero) = [] primes (suc (suc zero)) = [] primes (suc (suc (suc m))) = sieve (tabulate (just ∘ suc)) where sieve : ∀ {n} → Vec (Maybe (Fin (2 + m))) n → List (Fin (3 + m)) sieve [] = [] sieve (nothing ∷ xs) = sieve xs sieve (just x ∷ xs) = suc x ∷ sieve (foldr B remove (const []) xs x) where B = λ n → ∀ {i} → Fin i → Vec (Maybe (Fin (2 + m))) n   remove : ∀ {n} → Maybe (Fin (2 + m)) → B n → B (suc n) remove _ ys zero = nothing ∷ ys x remove y ys (suc z) = y ∷ ys z   -- With square cutoff optimization module SquareOpt where primes : ∀ n → List (Fin n) primes zero = [] primes (suc zero) = [] primes (suc (suc zero)) = [] primes (suc (suc (suc m))) = sieve 1 m (Vec.tabulate (just ∘ Fin.suc ∘ Fin.suc)) where sieve : ∀ {n} → ℕ → ℕ → Vec (Maybe (Fin (3 + m))) n → List (Fin (3 + m)) sieve _ zero = List.mapMaybe id ∘ Vec.toList sieve _ (suc _) [] = [] sieve i (suc l) (nothing ∷ xs) = sieve (suc i) (l ∸ i ∸ i) xs sieve i (suc l) (just x ∷ xs) = x ∷ sieve (suc i) (l ∸ i ∸ i) (Vec.foldr B remove (const []) xs i) where B = λ n → ℕ → Vec (Maybe (Fin (3 + m))) n   remove : ∀ {i} → Maybe (Fin (3 + m)) → B i → B (suc i) remove _ ys zero = nothing ∷ ys i remove y ys (suc j) = y ∷ ys j  
http://rosettacode.org/wiki/Sequence_of_primorial_primes
Sequence of primorial primes
The sequence of primorial primes is given as the increasing values of n where primorial(n) ± 1 is prime. Noting that the n'th primorial is defined as the multiplication of the smallest n primes, the sequence is of the number of primes, in order that when multiplied together is one-off being a prime number itself. Task Generate and show here the first ten values of the sequence. Optional extended task Show the first twenty members of the series. Notes This task asks for the primorial indices that create the final primorial prime numbers, so there should be no ten-or-more digit numbers in the program output (although extended precision integers will be needed for intermediate results). There is some confusion in the references, but for the purposes of this task the sequence begins with n = 1. Probabilistic primality tests are allowed, as long as they are good enough such that the output shown is correct. Related tasks Primorial numbers Factorial See also Primorial prime Wikipedia. Primorial prime from The Prime Glossary. Sequence A088411 from The On-Line Encyclopedia of Integer Sequences
#PARI.2FGP
PARI/GP
n=0; P=1; forprime(p=2,, P*=p; n++; if(ispseudoprime(P+1) || ispseudoprime(P-1), print1(n", ")))
http://rosettacode.org/wiki/Sequence_of_primorial_primes
Sequence of primorial primes
The sequence of primorial primes is given as the increasing values of n where primorial(n) ± 1 is prime. Noting that the n'th primorial is defined as the multiplication of the smallest n primes, the sequence is of the number of primes, in order that when multiplied together is one-off being a prime number itself. Task Generate and show here the first ten values of the sequence. Optional extended task Show the first twenty members of the series. Notes This task asks for the primorial indices that create the final primorial prime numbers, so there should be no ten-or-more digit numbers in the program output (although extended precision integers will be needed for intermediate results). There is some confusion in the references, but for the purposes of this task the sequence begins with n = 1. Probabilistic primality tests are allowed, as long as they are good enough such that the output shown is correct. Related tasks Primorial numbers Factorial See also Primorial prime Wikipedia. Primorial prime from The Prime Glossary. Sequence A088411 from The On-Line Encyclopedia of Integer Sequences
#Perl
Perl
use ntheory ":all"; my $i = 0; for (1..1e6) { my $n = pn_primorial($_); if (is_prime($n-1) || is_prime($n+1)) { print "$_\n"; last if ++$i >= 20; } }
http://rosettacode.org/wiki/Sequence:_nth_number_with_exactly_n_divisors
Sequence: nth number with exactly n divisors
Calculate the sequence where each term an is the nth that has n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A073916 Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: smallest number with exactly n divisors
#Sidef
Sidef
func f(n {.is_prime}) { n.prime**(n-1) }   func f(n) { n.th { .sigma0 == n } }   say 20.of { f(_+1) }
http://rosettacode.org/wiki/Sequence:_nth_number_with_exactly_n_divisors
Sequence: nth number with exactly n divisors
Calculate the sequence where each term an is the nth that has n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A073916 Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: smallest number with exactly n divisors
#Wren
Wren
import "/math" for Int import "/big" for BigInt import "/fmt" for Fmt   var MAX = 33 var primes = Int.primeSieve(MAX * 5) System.print("The first %(MAX) terms in the sequence are:") for (i in 1..MAX) { if (Int.isPrime(i)) { var z = BigInt.new(primes[i-1]).pow(i-1) Fmt.print("$2d : $i", i, z) } else { var count = 0 var j = 1 while (true) { var cont = false if (i % 2 == 1) { var sq = j.sqrt.floor if (sq * sq != j) { j = j + 1 cont = true } } if (!cont) { if (Int.divisors(j).count == i) { count = count + 1 if (count == i) { Fmt.print("$2d : $d", i, j) break } } j = j + 1 } } } }
http://rosettacode.org/wiki/Set_consolidation
Set consolidation
Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is: The two input sets if no common item exists between the two input sets of items. The single set that is the union of the two input sets if they share a common item. Given N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible. If N<2 then consolidation has no strict meaning and the input can be returned. Example 1: Given the two sets {A,B} and {C,D} then there is no common element between the sets and the result is the same as the input. Example 2: Given the two sets {A,B} and {B,D} then there is a common element B between the sets and the result is the single set {B,D,A}. (Note that order of items in a set is immaterial: {A,B,D} is the same as {B,D,A} and {D,A,B}, etc). Example 3: Given the three sets {A,B} and {C,D} and {D,B} then there is no common element between the sets {A,B} and {C,D} but the sets {A,B} and {D,B} do share a common element that consolidates to produce the result {B,D,A}. On examining this result with the remaining set, {C,D}, they share a common element and so consolidate to the final output of the single set {A,B,C,D} Example 4: The consolidation of the five sets: {H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H} Is the two sets: {A, C, B, D}, and {G, F, I, H, K} See also Connected component (graph theory) Range consolidation
#Kotlin
Kotlin
// version 1.0.6   fun<T : Comparable<T>> consolidateSets(sets: Array<Set<T>>): Set<Set<T>> { val size = sets.size val consolidated = BooleanArray(size) // all false by default var i = 0 while (i < size - 1) { if (!consolidated[i]) { while (true) { var intersects = 0 for (j in (i + 1) until size) { if (consolidated[j]) continue if (sets[i].intersect(sets[j]).isNotEmpty()) { sets[i] = sets[i].union(sets[j]) consolidated[j] = true intersects++ } } if (intersects == 0) break } } i++ } return (0 until size).filter { !consolidated[it] }.map { sets[it].toSortedSet() }.toSet() }   fun main(args: Array<String>) { val unconsolidatedSets = arrayOf( arrayOf(setOf('A', 'B'), setOf('C', 'D')), arrayOf(setOf('A', 'B'), setOf('B', 'D')), arrayOf(setOf('A', 'B'), setOf('C', 'D'), setOf('D', 'B')), arrayOf(setOf('H', 'I', 'K'), setOf('A', 'B'), setOf('C', 'D'), setOf('D', 'B'), setOf('F', 'G', 'H')) ) for (sets in unconsolidatedSets) println(consolidateSets(sets)) }
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors
Sequence: smallest number with exactly n divisors
Calculate the sequence where each term   an   is the smallest natural number that has exactly   n   divisors. Task Show here, on this page, at least the first  15  terms of the sequence. Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: nth number with exactly n divisors‎‎ See also OEIS:A005179
#Perl
Perl
use strict; use warnings; use ntheory 'divisors';   print "First 15 terms of OEIS: A005179\n"; for my $n (1..15) { my $l = 0; while (++$l) { print "$l " and last if $n == divisors($l); } }
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors
Sequence: smallest number with exactly n divisors
Calculate the sequence where each term   an   is the smallest natural number that has exactly   n   divisors. Task Show here, on this page, at least the first  15  terms of the sequence. Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: nth number with exactly n divisors‎‎ See also OEIS:A005179
#Phix
Phix
with javascript_semantics constant limit = 15 sequence res = repeat(0,limit) integer found = 0, n = 1 while found<limit do integer k = length(factors(n,1)) if k<=limit and res[k]=0 then res[k] = n found += 1 end if n += 1 end while printf(1,"The first %d terms are: %V\n",{limit,res})
http://rosettacode.org/wiki/SHA-256
SHA-256
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details. Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
#PureBasic
PureBasic
a$="Rosetta code" bit.i= 256   UseSHA2Fingerprint() : b$=StringFingerprint(a$, #PB_Cipher_SHA2, bit)   OpenConsole() Print("[SHA2 "+Str(bit)+" bit] Text: "+a$+" ==> "+b$) Input()
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors
Sequence: smallest number greater than previous term with exactly n divisors
Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A069654 Related tasks Sequence: smallest number with exactly n divisors Sequence: nth number with exactly n divisors‎‎
#REXX
REXX
/*REXX program finds and displays N numbers of the "anti─primes plus" sequence. */ parse arg N . /*obtain optional argument from the CL.*/ if N=='' | N=="," then N= 15 /*Not specified? Then use the default.*/ idx= 1 /*the maximum number of divisors so far*/ say '──index── ──anti─prime plus──' /*display a title for the numbers shown*/ #= 0 /*the count of anti─primes found " " */ do i=1 until #==N /*step through possible numbers by twos*/ d= #divs(i); if d\==idx then iterate /*get # divisors; Is too small? Skip.*/ #= # + 1; idx= idx + 1 /*found an anti─prime #; set new minD.*/ say center(#, 8) right(i, 15) /*display the index and the anti─prime.*/ end /*i*/ exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ #divs: procedure; parse arg x 1 y /*X and Y: both set from 1st argument.*/ if x<7 then do /*handle special cases for numbers < 7.*/ if x<3 then return x /* " " " " one and two.*/ if x<5 then return x - 1 /* " " " " three & four*/ if x==5 then return 2 /* " " " " five. */ if x==6 then return 4 /* " " " " six. */ end odd= x // 2 /*check if X is odd or not. */ if odd then #= 1; /*Odd? Assume Pdivisors count of 1.*/ else do; #= 3; y= x % 2 /*Even? " " " " 3.*/ end /* [↑] Even, so add 2 known divisors.*/ /* [↓] start with known number of Pdivs*/ do k=3 for x%2-3 by 1+odd while k<y /*for odd numbers, skip over the evens.*/ if x//k==0 then do /*if no remainder, then found a divisor*/ #= # + 2; y= x % k /*bump the # Pdivs; calculate limit Y.*/ if k>=y then do; #= # - 1; leave end /* [↑] has the limit been reached? */ end /* ___ */ else if k*k>x then leave /*only divide up to the √ x */ end /*k*/ /* [↑] this form of DO loop is faster.*/ return # + 1 /*bump "proper divisors" to "divisors".*/
http://rosettacode.org/wiki/SHA-1
SHA-1
SHA-1 or SHA1 is a one-way hash function; it computes a 160-bit message digest. SHA-1 often appears in security protocols; for example, many HTTPS websites use RSA with SHA-1 to secure their connections. BitTorrent uses SHA-1 to verify downloads. Git and Mercurial use SHA-1 digests to identify commits. A US government standard, FIPS 180-1, defines SHA-1. Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code. Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer. This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1. For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
#PureBasic
PureBasic
a$="Rosetta Code"   UseSHA1Fingerprint() : b$=StringFingerprint(a$, #PB_Cipher_SHA1)   OpenConsole() Print("[SHA1] Text: "+a$+" ==> "+b$) Input()
http://rosettacode.org/wiki/SHA-1
SHA-1
SHA-1 or SHA1 is a one-way hash function; it computes a 160-bit message digest. SHA-1 often appears in security protocols; for example, many HTTPS websites use RSA with SHA-1 to secure their connections. BitTorrent uses SHA-1 to verify downloads. Git and Mercurial use SHA-1 digests to identify commits. A US government standard, FIPS 180-1, defines SHA-1. Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code. Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer. This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1. For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
#Python
Python
import hashlib h = hashlib.sha1() h.update(bytes("Ars longa, vita brevis", encoding="ASCII")) h.hexdigest() # "e640d285242886eb96ab80cbf858389b3df52f43"
http://rosettacode.org/wiki/Show_ASCII_table
Show ASCII table
Task Show  the ASCII character set  from values   32   to   127   (decimal)   in a table format. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Lua
Lua
  -- map of character values to desired representation local chars = setmetatable({[32] = "Spc", [127] = "Del"}, {__index = function(_, k) return string.char(k) end})   -- row iterator local function iter(s,a) a = (a or s) + 16 if a <= 127 then return a, chars[a] end end   -- print loop for i = 0, 15 do for j, repr in iter, i+16 do io.write(("%3d : %3s "):format(j, repr)) end io.write"\n" end
http://rosettacode.org/wiki/Sierpinski_triangle
Sierpinski triangle
Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Related tasks Sierpinski triangle/Graphical for graphics images of this pattern. Sierpinski carpet
#Python
Python
def sierpinski(n): d = ["*"] for i in xrange(n): sp = " " * (2 ** i) d = [sp+x+sp for x in d] + [x+" "+x for x in d] return d   print "\n".join(sierpinski(4))
http://rosettacode.org/wiki/Sierpinski_carpet
Sierpinski carpet
Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ###### ### ########################### # ## ## ## ## ## ## ## ## # ########################### ######### ######### # ## ## # # ## ## # ######### ######### ### ### ### ### # # # # # # # # ### ### ### ### ######### ######### # ## ## # # ## ## # ######### ######### ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ###### ### ########################### # ## ## ## ## ## ## ## ## # ########################### The use of the   #   character is not rigidly required for ASCII art. The important requirement is the placement of whitespace and non-whitespace characters. Related task   Sierpinski triangle
#Order
Order
#include <order/interpreter.h>   #define ORDER_PP_DEF_8in_carpet ORDER_PP_FN( \ 8fn(8X, 8Y, \ 8if(8or(8is_0(8X), 8is_0(8Y)), \ 8true, \ 8let((8Q, 8quotient(8X, 3)) \ (8R, 8remainder(8X, 3)) \ (8S, 8quotient(8Y, 3)) \ (8T, 8remainder(8Y, 3)), \ 8and(8not(8and(8equal(8R, 1), 8equal(8T, 1))), \ 8in_carpet(8Q, 8S))))) )   #define ORDER_PP_DEF_8carpet ORDER_PP_FN( \ 8fn(8N, \ 8lets((8R, 8seq_iota(0, 8pow(3, 8N))) \ (8G, 8seq_map(8fn(8Y, 8seq_map(8fn(8X, 8pair(8X, 8Y)), \ 8R)), \ 8R)), \ 8seq_map(8fn(8S, 8seq_map(8fn(8P, 8apply(8in_carpet, 8P)), \ 8S)), \ 8G))) )   #define ORDER_PP_DEF_8carpet_to_string ORDER_PP_FN( \ 8fn(8C, \ 8seq_fold( \ 8fn(8R, 8S, \ 8adjoin(8R, \ 8seq_fold(8fn(8P, 8B, 8adjoin(8P, 8if(8B, 8("#"), 8(" ")))), \ 8nil, 8S), \ 8("\n"))), \ 8nil, 8C)) )   #include <stdio.h>   int main(void) { printf(ORDER_PP( 8carpet_to_string(8carpet(3)) )); return 0; }
http://rosettacode.org/wiki/Semordnilap
Semordnilap
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples. Two matching semordnilaps, such as lager and regal, should be counted as one unique pair. (Note that the word "semordnilap" is not in the above dictionary.) Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Arturo
Arturo
words: read.lines "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt" pairs: [] loop words 'wrd [ if and? contains? words reverse wrd wrd <> reverse wrd [ 'pairs ++ @[@[wrd reverse wrd]] print [wrd "-" reverse wrd] ] ]   unique 'pairs   print map 1..5 => [sample pairs]
http://rosettacode.org/wiki/Semordnilap
Semordnilap
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples. Two matching semordnilaps, such as lager and regal, should be counted as one unique pair. (Note that the word "semordnilap" is not in the above dictionary.) Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#AutoHotkey
AutoHotkey
S := [], M := []   FileRead, dict, unixdict.txt Loop, Parse, dict, `n, `r`n { r := Reverse(A_LoopField) if (S[r]) M.Insert(r " / " A_LoopField) else S[A_LoopField] := 1 }   Loop, 5 Out .= "`t" M[A_Index] "`n"   MsgBox, % "5 Examples:`n" Out "`nTotal Pairs:`n`t" M.MaxIndex()   Reverse(s) { Loop, Parse, s r := A_LoopField . r return r }
http://rosettacode.org/wiki/Short-circuit_evaluation
Short-circuit evaluation
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Assume functions   a   and   b   return boolean values,   and further, the execution of function   b   takes considerable resources without side effects, and is to be minimized. If we needed to compute the conjunction   (and): x = a() and b() Then it would be best to not compute the value of   b()   if the value of   a()   is computed as   false,   as the value of   x   can then only ever be   false. Similarly, if we needed to compute the disjunction (or): y = a() or b() Then it would be best to not compute the value of   b()   if the value of   a()   is computed as   true,   as the value of   y   can then only ever be   true. Some languages will stop further computation of boolean equations as soon as the result is known, so-called   short-circuit evaluation   of boolean expressions Task Create two functions named   a   and   b,   that take and return the same boolean value. The functions should also print their name whenever they are called. Calculate and assign the values of the following equations to a variable in such a way that function   b   is only called when necessary: x = a(i) and b(j) y = a(i) or b(j) If the language does not have short-circuit evaluation, this might be achieved with nested     if     statements.
#PowerShell
PowerShell
# Simulated fast function function a ( [boolean]$J ) { return $J }   # Simulated slow function function b ( [boolean]$J ) { Sleep -Seconds 2; return $J }   # These all short-circuit and do not evaluate the right hand function ( a $True ) -or ( b $False ) ( a $True ) -or ( b $True ) ( a $False ) -and ( b $False ) ( a $False ) -and ( b $True )   # Measure of execution time Measure-Command { ( a $True ) -or ( b $False ) ( a $True ) -or ( b $True ) ( a $False ) -and ( b $False ) ( a $False ) -and ( b $True ) } | Select TotalMilliseconds   # These all appropriately do evaluate the right hand function ( a $False ) -or ( b $False ) ( a $False ) -or ( b $True ) ( a $True ) -and ( b $False ) ( a $True ) -and ( b $True )   # Measure of execution time Measure-Command { ( a $False ) -or ( b $False ) ( a $False ) -or ( b $True ) ( a $True ) -and ( b $False ) ( a $True ) -and ( b $True ) } | Select TotalMilliseconds
http://rosettacode.org/wiki/Selectively_replace_multiple_instances_of_a_character_within_a_string
Selectively replace multiple instances of a character within a string
Task This is admittedly a trivial task but I thought it would be interesting to see how succinctly (or otherwise) different languages can handle it. Given the string: "abracadabra", replace programatically: the first 'a' with 'A' the second 'a' with 'B' the fourth 'a' with 'C' the fifth 'a' with 'D' the first 'b' with 'E' the second 'r' with 'F' Note that there is no replacement for the third 'a', second 'b' or first 'r'. The answer should, of course, be : "AErBcadCbFD". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Phix
Phix
with javascript_semantics function replace_nth(string s, r) string res = s for i=1 to length(r) by 3 do res[find_all(r[i],s)[r[i+1]-'0']] = r[i+2] end for return res end function ?replace_nth("abracadabra","a1Aa2Ba4Ca5Db1Er2F") -- Alternative version function replace_nths(string s, sequence r) for icr in r do {sequence idx, integer ch, string reps} = icr s = reinstate(s,extract(find_all(ch,s),idx),reps) end for return s end function constant r = {{{1,2,4,5},'a',"ABCD"}, {{1},'b',"E"}, {{2},'r',"F"}} ?replace_nths("abracadabra",r)
http://rosettacode.org/wiki/Selectively_replace_multiple_instances_of_a_character_within_a_string
Selectively replace multiple instances of a character within a string
Task This is admittedly a trivial task but I thought it would be interesting to see how succinctly (or otherwise) different languages can handle it. Given the string: "abracadabra", replace programatically: the first 'a' with 'A' the second 'a' with 'B' the fourth 'a' with 'C' the fifth 'a' with 'D' the first 'b' with 'E' the second 'r' with 'F' Note that there is no replacement for the third 'a', second 'b' or first 'r'. The answer should, of course, be : "AErBcadCbFD". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Python
Python
from collections import defaultdict   rep = {'a' : {1 : 'A', 2 : 'B', 4 : 'C', 5 : 'D'}, 'b' : {1 : 'E'}, 'r' : {2 : 'F'}}   def trstring(oldstring, repdict): seen, newchars = defaultdict(lambda:1, {}), [] for c in oldstring: i = seen[c] newchars.append(repdict[c][i] if c in repdict and i in repdict[c] else c) seen[c] += 1 return ''.join(newchars)   print('abracadabra ->', trstring('abracadabra', rep))  
http://rosettacode.org/wiki/Send_email
Send email
Task Write a function to send an email. The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details. If appropriate, explain what notifications of problems/success are given. Solutions using libraries or functions from the language are preferred, but failing that, external programs can be used with an explanation. Note how portable the solution given is between operating systems when multi-OS languages are used. (Remember to obfuscate any sensitive data used in examples)
#Factor
Factor
  USING: accessors io.sockets locals namespaces smtp ; IN: scratchpad :: send-mail ( f t c s b -- ) default-smtp-config "smtp.gmail.com" 587 <inet> >>server t >>tls? "my.gmail.address@gmail.com" "qwertyuiasdfghjk" <plain-auth> >>auth \ smtp-config set-global <email> f >>from t >>to c >>cc s >>subject b >>body send-email ;
http://rosettacode.org/wiki/Send_email
Send email
Task Write a function to send an email. The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details. If appropriate, explain what notifications of problems/success are given. Solutions using libraries or functions from the language are preferred, but failing that, external programs can be used with an explanation. Note how portable the solution given is between operating systems when multi-OS languages are used. (Remember to obfuscate any sensitive data used in examples)
#Fantom
Fantom
  using email   class Mail { // create a client for sending email - add your own host/username/password static SmtpClient makeClient () { client := SmtpClient { host = "yourhost" username = "yourusername" password = "yourpassword" } return client }   public static Void main() { // create email email := Email { to = ["to@addr"] from = "from@addr" cc = ["cc@addr"] subject = test" body = TextPart { text = "test email" } }   // create client and send email makeClient.send (email) } }  
http://rosettacode.org/wiki/Semiprime
Semiprime
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers. Semiprimes   are also known as:   semi-primes   biprimes   bi-primes   2-almost   primes   or simply:   P2 Example 1679 = 23 × 73 (This particular number was chosen as the length of the Arecibo message). Task Write a function determining whether a given number is semiprime. See also The Wikipedia article:  semiprime. The Wikipedia article:  almost prime. The OEIS sequence:  A001358: semiprimes  which has a shorter definition: the product of two primes.
#AWK
AWK
  # syntax: GAWK -f SEMIPRIME.AWK BEGIN { main(0,100) main(1675,1680) exit(0) } function main(lo,hi, i) { printf("%d-%d:",lo,hi) for (i=lo; i<=hi; i++) { if (is_semiprime(i)) { printf(" %d",i) } } printf("\n") } function is_semiprime(n, i,nf) { nf = 0 for (i=2; i<=n; i++) { while (n % i == 0) { if (nf == 2) { return(0) } nf++ n /= i } } return(nf == 2) }  
http://rosettacode.org/wiki/Self-describing_numbers
Self-describing numbers
Self-describing numbers You are encouraged to solve this task according to the task description, using any language you may know. There are several so-called "self-describing" or "self-descriptive" integers. An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number. For example,   2020   is a four-digit self describing number:   position   0   has value   2   and there are two 0s in the number;   position   1   has value   0   and there are no 1s in the number;   position   2   has value   2   and there are two 2s;   position   3   has value   0   and there are zero 3s. Self-describing numbers < 100.000.000  are:     1210,   2020,   21200,   3211000,   42101000. Task Description Write a function/routine/method/... that will check whether a given positive integer is self-describing. As an optional stretch goal - generate and display the set of self-describing numbers. Related tasks   Fours is the number of letters in the ...   Look-and-say sequence   Number names   Self-referential sequence   Spelling of ordinal numbers
#ALGOL_68
ALGOL 68
BEGIN   # return TRUE if number is self describing, FALSE otherwise # OP SELFDESCRIBING = ( INT number )BOOL: BEGIN   [10]INT counts := ( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ); INT n := number; INT digits := 0;   # count the occurances of each digit # WHILE n /= 0 DO digits +:= 1; counts[ ( n MOD 10 ) + 1 ] +:= 1; n OVERAB 10 OD;   # construct the number that the counts would describe, # # if the number was self describing #   INT described number := 0; FOR i TO digits DO described number *:= 10; described number +:= counts[ i ] OD;   # if the described number is the input number, # # it is self describing # ( number = described number ) END; # SELFDESCRIBING #   main: (   FOR i TO 100 000 000 DO IF SELFDESCRIBING i THEN print( ( i, " is self describing", newline ) ) FI OD )   END
http://rosettacode.org/wiki/Self_numbers
Self numbers
A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43. The task is: Display the first 50 self numbers; I believe that the 100000000th self number is 1022727208. You should either confirm or dispute my conjecture. 224036583-1 is a Mersenne prime, claimed to also be a self number. Extra credit to anyone proving it. See also OEIS: A003052 - Self numbers or Colombian numbers Wikipedia: Self numbers
#AWK
AWK
  # syntax: GAWK -f SELF_NUMBERS.AWK # converted from Go (low memory example) BEGIN { print("HH:MM:SS INDEX SELF") print("-------- ---------- ----------") count = 0 digits = 1 i = 1 last_self = 0 offset = 9 pow = 10 while (count < 1E8) { is_self = 1 start = max(i-offset,0) sum = sum_digits(start) for (j=start; j<i; j++) { if (j + sum == i) { is_self = 0 break } sum = ((j+1) % 10 != 0) ? ++sum : sum_digits(j+1) } if (is_self) { last_self = i if (++count <= 50) { selfs = selfs i " " } } if (++i % pow == 0) { pow *= 10 digits++ offset = digits * 9 } if (count ~ /^10*$/ && arr[count]++ == 0) { printf("%8s %10s %10s\n",strftime("%H:%M:%S"),count,last_self) } } printf("\nfirst 50 self numbers:\n%s\n",selfs) exit(0) } function sum_digits(x, sum,y) { while (x) { y = x % 10 sum += y x = int(x/10) } return(sum) } function max(x,y) { return((x > y) ? x : y) }  
http://rosettacode.org/wiki/Set_of_real_numbers
Set of real numbers
All real numbers form the uncountable set ℝ. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers a and b where a ≤ b. There are actually four cases for the meaning of "between", depending on open or closed boundary: [a, b]: {x | a ≤ x and x ≤ b } (a, b): {x | a < x and x < b } [a, b): {x | a ≤ x and x < b } (a, b]: {x | a < x and x ≤ b } Note that if a = b, of the four only [a, a] would be non-empty. Task Devise a way to represent any set of real numbers, for the definition of 'any' in the implementation notes below. Provide methods for these common set operations (x is a real number; A and B are sets): x ∈ A: determine if x is an element of A example: 1 is in [1, 2), while 2, 3, ... are not. A ∪ B: union of A and B, i.e. {x | x ∈ A or x ∈ B} example: [0, 2) ∪ (1, 3) = [0, 3); [0, 1) ∪ (2, 3] = well, [0, 1) ∪ (2, 3] A ∩ B: intersection of A and B, i.e. {x | x ∈ A and x ∈ B} example: [0, 2) ∩ (1, 3) = (1, 2); [0, 1) ∩ (2, 3] = empty set A - B: difference between A and B, also written as A \ B, i.e. {x | x ∈ A and x ∉ B} example: [0, 2) − (1, 3) = [0, 1] Test your implementation by checking if numbers 0, 1, and 2 are in any of the following sets: (0, 1] ∪ [0, 2) [0, 2) ∩ (1, 2] [0, 3) − (0, 1) [0, 3) − [0, 1] Implementation notes 'Any' real set means 'sets that can be expressed as the union of a finite number of convex real sets'. Cantor's set needs not apply. Infinities should be handled gracefully; indeterminate numbers (NaN) can be ignored. You can use your machine's native real number representation, which is probably IEEE floating point, and assume it's good enough (it usually is). Optional work Create a function to determine if a given set is empty (contains no element). Define A = {x | 0 < x < 10 and |sin(π x²)| > 1/2 }, B = {x | 0 < x < 10 and |sin(π x)| > 1/2}, calculate the length of the real axis covered by the set A − B. Note that |sin(π x)| > 1/2 is the same as n + 1/6 < x < n + 5/6 for all integers n; your program does not need to derive this by itself.
#Icon_and_Unicon
Icon and Unicon
procedure main(A) s1 := RealSet("(0,1]").union(RealSet("[0,2)")) s2 := RealSet("[0,2)").intersect(RealSet("(1,2)")) s3 := RealSet("[0,3)").difference(RealSet("(0,1)")) s4 := RealSet("[0,3)").difference(RealSet("[0,1]")) every s := s1|s2|s3|s4 do { every n := 0 to 2 do write(s.toString(),if s.contains(n) then " contains " else " doesn't contain ",n) write() } end   class Range(a,b,lbnd,rbnd,ltest,rtest)   method contains(x); return ((ltest(a,x),rtest(x,b)),self); end method toString(); return lbnd||a||","||b||rbnd; end method notEmpty(); return (ltest(a,b),rtest(a,b),self); end method makeLTest(); return proc(if lbnd == "(" then "<" else "<=",2); end method makeRTest(); return proc(if rbnd == "(" then "<" else "<=",2); end   method intersect(r) if a < r.a then (na := r.a, nlb := r.lbnd) else if a > r.a then (na := a, nlb := lbnd) else (na := a, nlb := if "(" == (lbnd|r.lbnd) then "(" else "[") if b < r.b then ( nb := b, nrb := rbnd) else if b > r.b then (nb := r.b, nrb := r.rbnd) else (nb := b, nrb := if ")" == (rbnd|r.rbnd) then ")" else "]") range := Range(nlb||na||","||nb||nrb) return range end   method difference(r) if /r then return RealSet(toString()) r1 := lbnd||a||","||min(b,r.a)||map(r.lbnd,"([","])") r2 := map(r.rbnd,")]","[(")||max(a,r.b)||","||b||rbnd return RealSet(r1).union(RealSet(r2)) end   initially(s) static lbnds, rbnds initial (lbnds := '([', rbnds := '])') if \s then { s ? { lbnd := (tab(upto(lbnds)),move(1)) a := 1(tab(upto(',')),move(1)) b := tab(upto(rbnds)) rbnd := move(1) } ltest := proc(if lbnd == "(" then "<" else "<=",2) rtest := proc(if rbnd == ")" then "<" else "<=",2) } end   class RealSet(ranges)   method contains(x); return ((!ranges).contains(x), self); end method notEmpty(); return ((!ranges).notEmpty(), self); end   method toString() sep := s := "" every r := (!ranges).toString() do s ||:= .sep || 1(r, sep := " + ") return s end   method clone() newR := RealSet() newR.ranges := (copy(\ranges) | []) return newR end   method union(B) newR := clone() every put(newR.ranges, (!B.ranges).notEmpty()) return newR end   method intersect(B) newR := clone() newR.ranges := [] every (r1 := !ranges, r2 := !B.ranges) do { range := r1.intersect(r2) put(newR.ranges, range.notEmpty()) } return newR end   method difference(B) newR := clone() newR.ranges := [] every (r1 := !ranges, r2 := !B.ranges) do { rs := r1.difference(r2) if rs.notEmpty() then every put(newR.ranges, !rs.ranges) } return newR end   initially(s) put(ranges := [],Range(\s).notEmpty()) end
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
Sequence of primes by trial division
Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by other numbers. You may use primes, or any numbers of your choosing, as long as the result is indeed a sequence of primes. The sequence may be bounded (i.e. up to some limit), unbounded, starting from the start (i.e. 2) or above some given value. Organize your function as you wish, in particular, it might resemble a filtering operation, or a sieving operation. If you want to use a ready-made is_prime function, use one from the Primality by trial division page (i.e., add yours there if it isn't there already). Related tasks   count in factors   prime decomposition   factors of an integer   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes
#BASIC256
BASIC256
function isPrime(v) if v < 2 then return False if v mod 2 = 0 then return v = 2 if v mod 3 = 0 then return v = 3 d = 5 while d * d <= v if v mod d = 0 then return False else d += 2 end while return True end function   for i = 101 to 999 if isPrime(i) then print string(i); " "; next i end
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
Sequence of primes by trial division
Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by other numbers. You may use primes, or any numbers of your choosing, as long as the result is indeed a sequence of primes. The sequence may be bounded (i.e. up to some limit), unbounded, starting from the start (i.e. 2) or above some given value. Organize your function as you wish, in particular, it might resemble a filtering operation, or a sieving operation. If you want to use a ready-made is_prime function, use one from the Primality by trial division page (i.e., add yours there if it isn't there already). Related tasks   count in factors   prime decomposition   factors of an integer   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes
#Batch_File
Batch File
  @echo off ::Prime list using trial division :: Unbounded (well, up to 2^31-1, but you'll kill it before :) :: skips factors of 2 and 3 in candidates and in divisors :: uses integer square root to find max divisor to test :: outputs numbers in rows of 10 right aligned primes setlocal enabledelayedexpansion   cls echo prime list set lin= 0: set /a num=1, inc1=4, cnt=0 call :line 2 call :line 3     :nxtcand set /a num+=inc1, inc1=6-inc1,div=1, inc2=4 call :sqrt2 %num% & set maxdiv=!errorlevel!   :nxtdiv set /a div+=inc2, inc2=6-inc2, res=(num%%div) if %div% gtr !maxdiv! call :line %num% & goto nxtcand if %res% equ 0 (goto :nxtcand ) else ( goto nxtdiv)   :sqrt2 [num] calculates integer square root if %1 leq 0 exit /b 0 set /A "x=%1/(11*1024)+40, x=(%1/x+x)>>1, x=(%1/x+x)>>1, x=(%1/x+x)>>1, x=(%1/x+x)>>1, x=(%1/x+x)>>1, x+=(%1-x*x)>>31,sq=x*x if sq gtr %1 set x-=1 exit /b !x! goto:eof   :line formats output in 10 right aligned columns set num1=  %1 set lin=!lin!%num1:~-7% set /a cnt+=1,res1=(cnt%%10) if %res1% neq 0 goto:eof echo %lin% set cnt1=  !cnt! set lin=!cnt1:~-5!: goto:eof  
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#BASIC
BASIC
DIM i AS Integer DIM j AS Double DIM found AS Integer   FUNCTION nonsqr (n AS Integer) AS Integer nonsqr = n + INT(0.5 + SQR(n)) END FUNCTION   ' Display first 22 values FOR i = 1 TO 22 PRINT nonsqr(i); " "; NEXT i PRINT   ' Check for squares up to one million found = 0 FOR i = 1 TO 1000000 j = SQR(nonsqr(i)) IF j = INT(j) THEN found = 1 PRINT "Found square: "; i EXIT FOR END IF NEXT i IF found=0 THEN PRINT "No squares found"
http://rosettacode.org/wiki/Set
Set
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A   set  is a collection of elements, without duplicates and without order. Task Show each of these set operations: Set creation Test m ∈ S -- "m is an element in set S" A ∪ B -- union; a set of all elements either in set A or in set B. A ∩ B -- intersection; a set of all elements in both set A and set B. A ∖ B -- difference; a set of all elements in set A, except those in set B. A ⊆ B -- subset; true if every element in set A is also in set B. A = B -- equality; true if every element of set A is in set B and vice versa. As an option, show some other set operations. (If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.) As another option, show how to modify a mutable set. One might implement a set using an associative array (with set elements as array keys and some dummy value as the values). One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators). The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#ATS
ATS
(*------------------------------------------------------------------*)   #define ATS_DYNLOADFLAG 0   #include "share/atspre_staload.hats"   (*------------------------------------------------------------------*) (* String hashing using XXH3_64bits from the xxHash suite. *)   #define ATS_EXTERN_PREFIX "hashsets_postiats_"   %{^ /* Embedded C code. */   #include <xxhash.h>   ATSinline() atstype_uint64 hashsets_postiats_mem_hash (atstype_ptr data, atstype_size len) { return (atstype_uint64) XXH3_64bits (data, len); }   %}   extern fn mem_hash : (ptr, size_t) -<> uint64 = "mac#%"   fn string_hash (s : string) :<> uint64 = let val len = string_length s in mem_hash ($UNSAFE.cast{ptr} s, len) end   (*------------------------------------------------------------------*) (* A trimmed down version of the AVL trees from the AVL Tree task. *)   datatype bal_t = | bal_minus1 | bal_zero | bal_plus1   datatype avl_t (key_t  : t@ype+, data_t : t@ype+, size  : int) = | avl_t_nil (key_t, data_t, 0) | {size_L, size_R : nat} avl_t_cons (key_t, data_t, size_L + size_R + 1) of (key_t, data_t, bal_t, avl_t (key_t, data_t, size_L), avl_t (key_t, data_t, size_R)) typedef avl_t (key_t  : t@ype+, data_t : t@ype+) = [size : int] avl_t (key_t, data_t, size)   extern fun {key_t : t@ype} avl_t$compare (u : key_t, v : key_t) :<> int   #define NIL avl_t_nil () #define CONS avl_t_cons #define LNIL list_nil () #define :: list_cons #define F false #define T true   typedef fixbal_t = bool   prfn lemma_avl_t_param {key_t : t@ype} {data_t : t@ype} {size : int} (avl : avl_t (key_t, data_t, size)) :<prf> [0 <= size] void = case+ avl of NIL => () | CONS _ => ()   fn {} minus_neg_bal (bal : bal_t) :<> bal_t = case+ bal of | bal_minus1 () => bal_plus1 | _ => bal_zero ()   fn {} minus_pos_bal (bal : bal_t) :<> bal_t = case+ bal of | bal_plus1 () => bal_minus1 | _ => bal_zero ()   fn avl_t_is_empty {key_t : t@ype} {data_t : t@ype} {size  : int} (avl : avl_t (key_t, data_t, size)) :<> [b : bool | b == (size == 0)] bool b = case+ avl of | NIL => T | CONS _ => F   fn avl_t_isnot_empty {key_t : t@ype} {data_t : t@ype} {size  : int} (avl : avl_t (key_t, data_t, size)) :<> [b : bool | b == (size <> 0)] bool b = ~avl_t_is_empty avl   fn {key_t : t@ype} {data_t : t@ype} avl_t_search_ref {size  : int} (avl  : avl_t (key_t, data_t, size), key  : key_t, data  : &data_t? >> opt (data_t, found), found : &bool? >> bool found) :<!wrt> #[found : bool] void = let fun search (p  : avl_t (key_t, data_t), data  : &data_t? >> opt (data_t, found), found : &bool? >> bool found) :<!wrt,!ntm> #[found : bool] void = case+ p of | NIL => { prval _ = opt_none {data_t} data val _ = found := F } | CONS (k, d, _, left, right) => begin case+ avl_t$compare<key_t> (key, k) of | cmp when cmp < 0 => search (left, data, found) | cmp when cmp > 0 => search (right, data, found) | _ => { val _ = data := d prval _ = opt_some {data_t} data val _ = found := T } end in $effmask_ntm search (avl, data, found) end   fn {key_t : t@ype} {data_t : t@ype} avl_t_search_opt {size : int} (avl  : avl_t (key_t, data_t, size), key  : key_t) :<> Option (data_t) = let var data : data_t? var found : bool? val _ = $effmask_wrt avl_t_search_ref (avl, key, data, found) in if found then let prval _ = opt_unsome data in Some {data_t} data end else let prval _ = opt_unnone data in None {data_t} () end end   fn {key_t : t@ype} {data_t : t@ype} avl_t_insert_or_replace {size : int} (avl  : avl_t (key_t, data_t, size), key  : key_t, data : data_t) :<> [sz : pos] (avl_t (key_t, data_t, sz), bool) = let fun search {size  : nat} (p  : avl_t (key_t, data_t, size), fixbal : fixbal_t, found  : bool) :<!ntm> [sz : pos] (avl_t (key_t, data_t, sz), fixbal_t, bool) = case+ p of | NIL => (CONS (key, data, bal_zero, NIL, NIL), T, F) | CONS (k, d, bal, left, right) => case+ avl_t$compare<key_t> (key, k) of | cmp when cmp < 0 => let val (p1, fixbal, found) = search (left, fixbal, found) in case+ (fixbal, bal) of | (F, _) => (CONS (k, d, bal, p1, right), F, found) | (T, bal_plus1 ()) => (CONS (k, d, bal_zero (), p1, right), F, found) | (T, bal_zero ()) => (CONS (k, d, bal_minus1 (), p1, right), fixbal, found) | (T, bal_minus1 ()) => let val+ CONS (k1, d1, bal1, left1, right1) = p1 in case+ bal1 of | bal_minus1 () => let val q = CONS (k, d, bal_zero (), right1, right) val q1 = CONS (k1, d1, bal_zero (), left1, q) in (q1, F, found) end | _ => let val p2 = right1 val- CONS (k2, d2, bal2, left2, right2) = p2 val q = CONS (k, d, minus_neg_bal bal2, right2, right) val q1 = CONS (k1, d1, minus_pos_bal bal2, left1, left2) val q2 = CONS (k2, d2, bal_zero (), q1, q) in (q2, F, found) end end end | cmp when cmp > 0 => let val (p1, fixbal, found) = search (right, fixbal, found) in case+ (fixbal, bal) of | (F, _) => (CONS (k, d, bal, left, p1), F, found) | (T, bal_minus1 ()) => (CONS (k, d, bal_zero (), left, p1), F, found) | (T, bal_zero ()) => (CONS (k, d, bal_plus1 (), left, p1), fixbal, found) | (T, bal_plus1 ()) => let val+ CONS (k1, d1, bal1, left1, right1) = p1 in case+ bal1 of | bal_plus1 () => let val q = CONS (k, d, bal_zero (), left, left1) val q1 = CONS (k1, d1, bal_zero (), q, right1) in (q1, F, found) end | _ => let val p2 = left1 val- CONS (k2, d2, bal2, left2, right2) = p2 val q = CONS (k, d, minus_pos_bal bal2, left, left2) val q1 = CONS (k1, d1, minus_neg_bal bal2, right2, right1) val q2 = CONS (k2, d2, bal_zero (), q, q1) in (q2, F, found) end end end | _ => (CONS (key, data, bal, left, right), F, T) in if avl_t_is_empty avl then (CONS (key, data, bal_zero, NIL, NIL), F) else let prval _ = lemma_avl_t_param avl val (avl, _, found) = $effmask_ntm search (avl, F, F) in (avl, found) end end   fn {key_t : t@ype} {data_t : t@ype} avl_t_insert {size : int} (avl  : avl_t (key_t, data_t, size), key  : key_t, data : data_t) :<> [sz : pos] avl_t (key_t, data_t, sz) = (avl_t_insert_or_replace<key_t><data_t> (avl, key, data)).0   fun {key_t : t@ype} {data_t : t@ype} push_all_the_way_left (stack : List (avl_t (key_t, data_t)), p  : avl_t (key_t, data_t)) : List0 (avl_t (key_t, data_t)) = let prval _ = lemma_list_param stack in case+ p of | NIL => stack | CONS (_, _, _, left, _) => push_all_the_way_left (p :: stack, left) end   fun {key_t : t@ype} {data_t : t@ype} update_generator_stack (stack  : List (avl_t (key_t, data_t)), right  : avl_t (key_t, data_t)) : List0 (avl_t (key_t, data_t)) = let prval _ = lemma_list_param stack in if avl_t_is_empty right then stack else push_all_the_way_left<key_t><data_t> (stack, right) end   fn {key_t : t@ype} {data_t : t@ype} avl_t_make_data_generator {size : int} (avl  : avl_t (key_t, data_t, size)) : () -<cloref1> Option data_t = let typedef avl_t = avl_t (key_t, data_t)   val stack = push_all_the_way_left<key_t><data_t> (LNIL, avl) val stack_ref = ref stack   (* Cast stack_ref to its (otherwise untyped) pointer, so it can be enclosed within ‘generate’. *) val p_stack_ref = $UNSAFE.castvwtp0{ptr} stack_ref   fun generate () :<cloref1> Option data_t = let (* Restore the type information for stack_ref. *) val stack_ref = $UNSAFE.castvwtp0{ref (List avl_t)} p_stack_ref   var stack : List0 avl_t = !stack_ref var retval : Option data_t in begin case+ stack of | LNIL => retval := None () | p :: tail => let val- CONS (_, d, _, left, right) = p in retval := Some d; stack := update_generator_stack<key_t><data_t> (tail, right) end end;  !stack_ref := stack; retval end in generate end   (*------------------------------------------------------------------*) (* Sets implemented with a hash function, AVL trees and association *) (* lists. *)   (* The interface - - - - - - - - - - - - - - - - - - - - - - - - - *)   (* For simplicity, let us support only 64-bit hashes. *)   typedef hashset_t (key_t : t@ype+) = avl_t (uint64, List1 key_t)   extern fun {key_t : t@ype} (* Implement a hash function with this. *) hashset_t$hashfunc : key_t -<> uint64   extern fun {key_t : t@ype} (* Implement key equality with this. *) hashset_t$key_eq : (key_t, key_t) -<> bool   extern fun hashset_t_nil : {key_t : t@ype} () -<> hashset_t key_t   extern fun {key_t : t@ype} hashset_t_add_member : (hashset_t key_t, key_t) -<> hashset_t key_t   (* "remove_member" is not implemented here, because the trimmed down AVL tree implementation above does not include deletion. We shall implement everything else without using a member deletion routine.   extern fun {key_t : t@ype} hashset_t_remove_member : (hashset_t key_t, key_t) -<> hashset_t key_t   Of course you can remove a member by using hashset_t_difference. *)   extern fun {key_t : t@ype} hashset_t_has_member : (hashset_t key_t, key_t) -<> bool   typedef hashset_t_binary_operation (key_t : t@ype) = (hashset_t key_t, hashset_t key_t) -> hashset_t key_t   extern fun {key_t : t@ype} hashset_t_union : hashset_t_binary_operation key_t   extern fun {key_t : t@ype} hashset_t_intersection : hashset_t_binary_operation key_t   extern fun {key_t : t@ype} hashset_t_difference : hashset_t_binary_operation key_t   extern fun {key_t : t@ype} hashset_t_subset : (hashset_t key_t, hashset_t key_t) -> bool   extern fun {key_t : t@ype} hashset_t_equal : (hashset_t key_t, hashset_t key_t) -> bool   (* Note: generators for hashset_t produce their output in unspecified order. *) extern fun {key_t : t@ype} hashset_t_make_generator : hashset_t key_t -> () -<cloref1> Option key_t   (* The implementation - - - - - - - - - - - - - - - - - - - - - - - *)   (* I make no promises that these are the most efficient implementations I could devise. They certainly are not! But they were easy to write and will work. *)   implement hashset_t_nil () = avl_t_nil ()   fun {key_t  : t@ype} find_key {n : nat} .<n>. (lst : list (key_t, n), key : key_t) :<> List0 key_t = (* This implementation is tail recursive. It will not build up the stack. *) case+ lst of | list_nil () => lst | list_cons (head, tail) => if hashset_t$key_eq<key_t> (key, head) then lst else find_key (tail, key)   implement {key_t} hashset_t_add_member (set, key) = (* The following implementation assumes equal keys are interchangeable. *) let implement avl_t$compare<uint64> (u, v) = if u < v then ~1 else if v < u then 1 else 0 typedef lst_t = List1 key_t val hash = hashset_t$hashfunc<key_t> key val lst_opt = avl_t_search_opt<uint64><lst_t> (set, hash) in case+ lst_opt of | Some lst => begin case+ find_key<key_t> (lst, key) of | list_cons _ => set | list_nil () => avl_t_insert<uint64><lst_t> (set, hash, list_cons (key, lst)) end | None () => avl_t_insert<uint64><lst_t> (set, hash, list_cons (key, list_nil ())) end   implement {key_t} hashset_t_has_member (set, key) = let implement avl_t$compare<uint64> (u, v) = if u < v then ~1 else if v < u then 1 else 0 typedef lst_t = List1 key_t val hash = hashset_t$hashfunc<key_t> key val lst_opt = avl_t_search_opt<uint64><lst_t> (set, hash) in case+ lst_opt of | None () => false | Some lst => begin case+ find_key<key_t> (lst, key) of | list_nil () => false | list_cons _ => true end end   implement {key_t} hashset_t_union (u, v) = let val gen_u = hashset_t_make_generator<key_t> u val gen_v = hashset_t_make_generator<key_t> v var w : hashset_t key_t = hashset_t_nil () var k_opt : Option key_t in for (k_opt := gen_u (); option_is_some k_opt; k_opt := gen_u ()) w := hashset_t_add_member (w, option_unsome k_opt); for (k_opt := gen_v (); option_is_some k_opt; k_opt := gen_v ()) w := hashset_t_add_member (w, option_unsome k_opt); w end   implement {key_t} hashset_t_intersection (u, v) = let val gen_u = hashset_t_make_generator<key_t> u var w : hashset_t key_t = hashset_t_nil () var k_opt : Option key_t in for (k_opt := gen_u (); option_is_some k_opt; k_opt := gen_u ()) let val+ Some k = k_opt in if hashset_t_has_member<key_t> (v, k) then w := hashset_t_add_member (w, k) end; w end   implement {key_t} hashset_t_difference (u, v) = let val gen_u = hashset_t_make_generator<key_t> u var w : hashset_t key_t = hashset_t_nil () var k_opt : Option key_t in for (k_opt := gen_u (); option_is_some k_opt; k_opt := gen_u ()) let val+ Some k = k_opt in if ~hashset_t_has_member<key_t> (v, k) then w := hashset_t_add_member (w, k) end; w end   implement {key_t} hashset_t_subset (u, v) = let val gen_u = hashset_t_make_generator<key_t> u var subset : bool = true var done : bool = false in while (~done) case+ gen_u () of | None () => done := true | Some k => if ~hashset_t_has_member<key_t> (v, k) then begin subset := false; done := true end; subset end   implement {key_t} hashset_t_equal (u, v) = hashset_t_subset<key_t> (u, v) && hashset_t_subset<key_t> (v, u)   implement {key_t} hashset_t_make_generator (set) = let typedef lst_t = List1 key_t typedef lst_t_0 = List0 key_t   val avl_gen = avl_t_make_data_generator<uint64><lst_t> (set)   val current_list_ref : ref lst_t_0 = ref (list_nil ()) val current_list_ptr = $UNSAFE.castvwtp0{ptr} current_list_ref in lam () => let val current_list_ref = $UNSAFE.castvwtp0{ref lst_t_0} current_list_ptr in case+ !current_list_ref of | list_nil () => begin case+ avl_gen () of | None () => None () | Some lst => begin case+ lst of | list_cons (head, tail) => begin  !current_list_ref := tail; Some head end end end | list_cons (head, tail) => begin  !current_list_ref := tail; Some head end end end   (*------------------------------------------------------------------*)   implement hashset_t$hashfunc<string> (s) = string_hash s   implement hashset_t$key_eq<string> (s, t) = s = t   typedef strset_t = hashset_t string   fn {} strset_t_nil () :<> strset_t = hashset_t_nil ()   fn strset_t_add_member (set  : strset_t, member : string) :<> strset_t = hashset_t_add_member<string> (set, member)   fn {} strset_t_member_add (member : string, set  : strset_t) :<> strset_t = strset_t_add_member (set, member)   #define SNIL strset_t_nil () infixr ( :: ) ++ (* Right associative, same precedence as :: *) overload ++ with strset_t_member_add   fn strset_t_has_member (set  : strset_t, member : string) :<> bool = hashset_t_has_member<string> (set, member) overload [] with strset_t_has_member   fn strset_t_union (u : strset_t, v : strset_t) : strset_t = hashset_t_union<string> (u, v) overload + with strset_t_union   fn strset_t_intersection (u : strset_t, v : strset_t) : strset_t = hashset_t_intersection<string> (u, v) infixl ( + ) ^ overload ^ with strset_t_intersection   fn strset_t_difference (u : strset_t, v : strset_t) : strset_t = hashset_t_difference<string> (u, v) overload - with strset_t_difference   fn strset_t_subset (u : strset_t, v : strset_t) : bool = hashset_t_subset<string> (u, v) overload <= with strset_t_subset   fn strset_t_equal (u : strset_t, v : strset_t) : bool = hashset_t_equal<string> (u, v) overload = with strset_t_equal   fn strset_t_make_generator (set : strset_t) : () -<cloref1> Option string = hashset_t_make_generator<string> set   fn strset_t_print (set : strset_t) : void = let val gen = strset_t_make_generator set var s_opt : Option string var separator : string = "" in print! ("#<strset_t "); for (s_opt := gen (); option_is_some s_opt; s_opt := gen ()) case+ s_opt of | Some s => begin (* The following quick and dirty implemenetation does not insert escape sequences. *) print! (separator, "\"", s, "\""); separator := " " end; print! (">") end   implement main0 () = let val set1 = "one" ++ "two" ++ "three" ++ "guide" ++ "design" ++ SNIL val set2 = "ett" ++ "två" ++ "tre" ++ "guide" ++ "design" ++ SNIL in print! ("set1 = "); strset_t_print set1;   println! (); println! (); println! ("set1[\"one\"] = ", set1["one"]); println! ("set1[\"two\"] = ", set1["two"]); println! ("set1[\"three\"] = ", set1["three"]); println! ("set1[\"four\"] = ", set1["four"]);   println! (); print! ("set2 = "); strset_t_print set2;   println! (); println! (); println! ("set2[\"ett\"] = ", set2["ett"]); println! ("set2[\"två\"] = ", set2["två"]); println! ("set2[\"tre\"] = ", set2["tre"]); println! ("set2[\"fyra\"] = ", set2["fyra"]);   println! (); print! ("Union\nset1 + set2 = "); strset_t_print (set1 + set2); println! ();   println! (); print! ("Intersection\nset1 ^ set2 = "); strset_t_print (set1 ^ set2); println! ();   println! (); print! ("Difference\nset1 - set2 = "); strset_t_print (set1 - set2); println! ();   println! (); println! ("Subset"); println! ("set1 <= set1: ", set1 <= set1); println! ("set2 <= set2: ", set2 <= set2); println! ("set1 <= set2: ", set1 <= set2); println! ("set2 <= set1: ", set2 <= set1); println! ("(set1 ^ set2) <= set1: ", (set1 ^ set2) <= set1); println! ("(set1 ^ set2) <= set2: ", (set1 ^ set2) <= set2);   println! (); println! ("Equal"); println! ("set1 = set1: ", set1 = set1); println! ("set2 = set2: ", set2 = set2); println! ("set1 = set2: ", set1 = set2); println! ("set2 = set1: ", set2 = set1); println! ("(set1 ^ set2) = (set2 ^ set1): ", (set1 ^ set2) = (set2 ^ set1)); println! ("(set1 ^ set2) = set1: ", (set1 ^ set2) = set1); println! ("(set1 ^ set2) = set2: ", (set1 ^ set2) = set2) end   (*------------------------------------------------------------------*)
http://rosettacode.org/wiki/Send_an_unknown_method_call
Send an unknown method call
Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
#Oforth
Oforth
16 "sqrt" asMethod perform
http://rosettacode.org/wiki/Send_an_unknown_method_call
Send an unknown method call
Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
#PARI.2FGP
PARI/GP
foo()=5; eval(Str("foo","()"))
http://rosettacode.org/wiki/Send_an_unknown_method_call
Send an unknown method call
Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
#Perl
Perl
package Example; sub new { bless {} } sub foo { my ($self, $x) = @_; return 42 + $x; }   package main; my $name = "foo"; print Example->new->$name(5), "\n"; # prints "47"
http://rosettacode.org/wiki/Send_an_unknown_method_call
Send an unknown method call
Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
#Phix
Phix
with javascript_semantics procedure Hello() ?"Hello" end procedure string erm = "Hemmm" for i=3 to 5 do erm[i]+=-1+(i=5)*3 end for call_proc(routine_id(erm),{})
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Agena
Agena
# Sieve of Eratosthenes   # generate and return a sequence containing the primes up to sieveSize sieve := proc( sieveSize :: number ) :: sequence is local sieve, result;   result := seq(); # sequence of primes - initially empty create register sieve( sieveSize ); # "vector" to be sieved   sieve[ 1 ] := false; for sPos from 2 to sieveSize do sieve[ sPos ] := true od;   # sieve the primes for sPos from 2 to entier( sqrt( sieveSize ) ) do if sieve[ sPos ] then for p from sPos * sPos to sieveSize by sPos do sieve[ p ] := false od fi od;   # construct the sequence of primes for sPos from 1 to sieveSize do if sieve[ sPos ] then insert sPos into result fi od   return result end; # sieve     # test the sieve proc for i in sieve( 100 ) do write( " ", i ) od; print();
http://rosettacode.org/wiki/Sequence_of_primorial_primes
Sequence of primorial primes
The sequence of primorial primes is given as the increasing values of n where primorial(n) ± 1 is prime. Noting that the n'th primorial is defined as the multiplication of the smallest n primes, the sequence is of the number of primes, in order that when multiplied together is one-off being a prime number itself. Task Generate and show here the first ten values of the sequence. Optional extended task Show the first twenty members of the series. Notes This task asks for the primorial indices that create the final primorial prime numbers, so there should be no ten-or-more digit numbers in the program output (although extended precision integers will be needed for intermediate results). There is some confusion in the references, but for the purposes of this task the sequence begins with n = 1. Probabilistic primality tests are allowed, as long as they are good enough such that the output shown is correct. Related tasks Primorial numbers Factorial See also Primorial prime Wikipedia. Primorial prime from The Prime Glossary. Sequence A088411 from The On-Line Encyclopedia of Integer Sequences
#Phix
Phix
with javascript_semantics include mpfr.e constant limit = 9999, flimit = iff(platform()=JS?15:20) mpz {p,p1} = mpz_inits(2,1) atom t0 = time() integer found = 0, i for n=1 to limit do mpz_mul_si(p, p, get_prime(n)) for i=-1 to +1 do mpz_add_si(p1, p, i) if mpz_prime(p1) then integer l = mpz_sizeinbase(p,10) string ps = iff(l>20?sprintf("%d digits",l) :mpz_get_str(p)) printf(1,"%d (%s) is a primorial prime\n",{n,ps}) found += 1 exit end if end for if found>=flimit then exit end if end for {p,p1} = mpz_free({p,p1}) ?elapsed(time()-t0)
http://rosettacode.org/wiki/Sequence:_nth_number_with_exactly_n_divisors
Sequence: nth number with exactly n divisors
Calculate the sequence where each term an is the nth that has n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A073916 Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: smallest number with exactly n divisors
#zkl
zkl
var [const] BI=Import("zklBigNum"), pmax=25; // libGMP p:=BI(1); primes:=pmax.pump(List(0), p.nextPrime, "copy"); //-->(0,3,5,7,11,13,17,19,...)   fcn countDivisors(n){ count:=1; while(n%2==0){ n/=2; count+=1; } foreach d in ([3..*,2]){ q,r := n/d, n%d; if(r==0){ dc:=0; while(r==0){ dc+=count; n,q,r = q, n/d, n%d; } count+=dc; } if(d*d > n) break; } if(n!=1) count*=2; count }   println("The first ", pmax, " terms in the sequence are:"); foreach i in ([1..pmax]){ if(BI(i).probablyPrime()) println("%2d : %,d".fmt(i,primes[i].pow(i-1))); else{ count:=0; foreach j in ([1..*]){ if(i%2==1 and j != j.toFloat().sqrt().toInt().pow(2)) continue; if(countDivisors(j) == i){ count+=1; if(count==i){ println("%2d : %,d".fmt(i,j)); break; } } } } }
http://rosettacode.org/wiki/Set_consolidation
Set consolidation
Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is: The two input sets if no common item exists between the two input sets of items. The single set that is the union of the two input sets if they share a common item. Given N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible. If N<2 then consolidation has no strict meaning and the input can be returned. Example 1: Given the two sets {A,B} and {C,D} then there is no common element between the sets and the result is the same as the input. Example 2: Given the two sets {A,B} and {B,D} then there is a common element B between the sets and the result is the single set {B,D,A}. (Note that order of items in a set is immaterial: {A,B,D} is the same as {B,D,A} and {D,A,B}, etc). Example 3: Given the three sets {A,B} and {C,D} and {D,B} then there is no common element between the sets {A,B} and {C,D} but the sets {A,B} and {D,B} do share a common element that consolidates to produce the result {B,D,A}. On examining this result with the remaining set, {C,D}, they share a common element and so consolidate to the final output of the single set {A,B,C,D} Example 4: The consolidation of the five sets: {H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H} Is the two sets: {A, C, B, D}, and {G, F, I, H, K} See also Connected component (graph theory) Range consolidation
#Lua
Lua
-- SUPPORT: function T(t) return setmetatable(t, {__index=table}) end function S(t) local s=T{} for k,v in ipairs(t) do s[v]=v end return s end table.each = function(t,f,...) for _,v in pairs(t) do f(v,...) end end table.copy = function(t) local s=T{} for k,v in pairs(t) do s[k]=v end return s end table.keys = function(t) local s=T{} for k,_ in pairs(t) do s[#s+1]=k end return s end table.intersects = function(t1,t2) for k,_ in pairs(t1) do if t2[k] then return true end end return false end table.union = function(t1,t2) local s=t1:copy() for k,_ in pairs(t2) do s[k]=k end return s end table.dump = function(t) print('{ '..table.concat(t, ', ')..' }') end   -- TASK: table.consolidate = function(t) for a = #t, 1, -1 do local seta = t[a] for b = #t, a+1, -1 do local setb = t[b] if setb and seta:intersects(setb) then t[a], t[b] = seta:union(setb), nil end end end return t end   -- TESTING: examples = { T{ S{"A","B"}, S{"C","D"} }, T{ S{"A","B"}, S{"B","D"} }, T{ S{"A","B"}, S{"C","D"}, S{"D","B"} }, T{ S{"H","I","K"}, S{"A","B"}, S{"C","D"}, S{"D","B"}, S{"F","G","H"} }, } for i,example in ipairs(examples) do print("Given input sets:") example:each(function(set) set:keys():dump() end) print("Consolidated output sets:") example:consolidate():each(function(set) set:keys():dump() end) print("") end
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors
Sequence: smallest number with exactly n divisors
Calculate the sequence where each term   an   is the smallest natural number that has exactly   n   divisors. Task Show here, on this page, at least the first  15  terms of the sequence. Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: nth number with exactly n divisors‎‎ See also OEIS:A005179
#Python
Python
def divisors(n): divs = [1] for ii in range(2, int(n ** 0.5) + 3): if n % ii == 0: divs.append(ii) divs.append(int(n / ii)) divs.append(n) return list(set(divs))     def sequence(max_n=None): n = 0 while True: n += 1 ii = 0 if max_n is not None: if n > max_n: break while True: ii += 1 if len(divisors(ii)) == n: yield ii break     if __name__ == '__main__': for item in sequence(15): print(item)
http://rosettacode.org/wiki/SHA-256
SHA-256
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details. Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
#Python
Python
>>> import hashlib >>> hashlib.sha256( "Rosetta code".encode() ).hexdigest() '764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf' >>>
http://rosettacode.org/wiki/SHA-256
SHA-256
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details. Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
#R
R
  library(digest)   input <- "Rosetta code" cat(digest(input, algo = "sha256", serialize = FALSE), "\n")  
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors
Sequence: smallest number greater than previous term with exactly n divisors
Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A069654 Related tasks Sequence: smallest number with exactly n divisors Sequence: nth number with exactly n divisors‎‎
#Ring
Ring
  # Project : ANti-primes   see "working..." + nl see "wait for done..." + nl + nl see "the first 15 Anti-primes Plus are:" + nl + nl num = 1 n = 0 result = list(15) while num < 16 n = n + 1 div = factors(n) if div = num result[num] = n num = num + 1 ok end see "[" for n = 1 to len(result) if n < len(result) see string(result[n]) + "," else see string(result[n]) + "]" + nl + nl ok next see "done..." + nl   func factors(an) ansum = 2 if an < 2 return(1) ok for nr = 2 to an/2 if an%nr = 0 ansum = ansum+1 ok next return ansum  
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors
Sequence: smallest number greater than previous term with exactly n divisors
Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A069654 Related tasks Sequence: smallest number with exactly n divisors Sequence: nth number with exactly n divisors‎‎
#Ruby
Ruby
require 'prime'   def num_divisors(n) n.prime_division.inject(1){|prod, (_p,n)| prod *= (n + 1) } end   seq = Enumerator.new do |y| cur = 0 (1..).each do |i| if num_divisors(i) == cur + 1 then y << i cur += 1 end end end   p seq.take(15)  
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors
Sequence: smallest number greater than previous term with exactly n divisors
Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A069654 Related tasks Sequence: smallest number with exactly n divisors Sequence: nth number with exactly n divisors‎‎
#Sidef
Sidef
func n_divisors(n, from=1) { from..Inf -> first_by { .sigma0 == n } }   with (1) { |from| say 15.of { from = n_divisors(_+1, from) } }
http://rosettacode.org/wiki/SHA-1
SHA-1
SHA-1 or SHA1 is a one-way hash function; it computes a 160-bit message digest. SHA-1 often appears in security protocols; for example, many HTTPS websites use RSA with SHA-1 to secure their connections. BitTorrent uses SHA-1 to verify downloads. Git and Mercurial use SHA-1 digests to identify commits. A US government standard, FIPS 180-1, defines SHA-1. Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code. Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer. This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1. For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
#R
R
  library(digest)   input <- "Rosetta Code" cat(digest(input, algo = "sha1", serialize = FALSE), "\n")  
http://rosettacode.org/wiki/SHA-1
SHA-1
SHA-1 or SHA1 is a one-way hash function; it computes a 160-bit message digest. SHA-1 often appears in security protocols; for example, many HTTPS websites use RSA with SHA-1 to secure their connections. BitTorrent uses SHA-1 to verify downloads. Git and Mercurial use SHA-1 digests to identify commits. A US government standard, FIPS 180-1, defines SHA-1. Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code. Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer. This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1. For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
#Racket
Racket
  #lang racket (require file/sha1) (sha1 (open-input-string "Rosetta Code"))  
http://rosettacode.org/wiki/Show_ASCII_table
Show ASCII table
Task Show  the ASCII character set  from values   32   to   127   (decimal)   in a table format. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#M2000_Interpreter
M2000 Interpreter
  Function ProduceAscii$ { Document Ascii$="\" DelUnicode$=ChrCode$(0x2421) j=2 Print Ascii$; For i=0 to 15 Print Hex$(i, .5); Ascii$=Hex$(i, .5) Next For i=32 to 126 If pos>16 then Ascii$={ }+Hex$(j, .5) Print : Print Hex$(j, .5);: j++ End if Print Chr$(i); Ascii$=Chr$(i) Next Print DelUnicode$ =Ascii$+DelUnicode$+{ } } Clipboard ProduceAscii$()  
http://rosettacode.org/wiki/Sierpinski_triangle
Sierpinski triangle
Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Related tasks Sierpinski triangle/Graphical for graphics images of this pattern. Sierpinski carpet
#Quackery
Quackery
[ [ dup 1 & iff char * else space emit 1 >> dup while sp again ] drop ] is stars ( mask --> )   [ bit 1 over times [ cr over i^ - times sp dup stars dup 1 << ^ ] 2drop ] is triangle ( order --> )   4 triangle
http://rosettacode.org/wiki/Sierpinski_carpet
Sierpinski carpet
Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ###### ### ########################### # ## ## ## ## ## ## ## ## # ########################### ######### ######### # ## ## # # ## ## # ######### ######### ### ### ### ### # # # # # # # # ### ### ### ### ######### ######### # ## ## # # ## ## # ######### ######### ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ###### ### ########################### # ## ## ## ## ## ## ## ## # ########################### The use of the   #   character is not rigidly required for ASCII art. The important requirement is the placement of whitespace and non-whitespace characters. Related task   Sierpinski triangle
#Oz
Oz
declare %% A carpet is a list of lines. fun {NextCarpet Carpet} {Flatten [{Map Carpet XXX} {Map Carpet X_X} {Map Carpet XXX} ]} end   fun {XXX X} X#X#X end fun {X_X X} X#{Spaces {VirtualString.length X}}#X end fun {Spaces N} if N == 0 then nil else & |{Spaces N-1} end end   fun lazy {Iterate F X} X|{Iterate F {F X}} end   SierpinskiCarpets = {Iterate NextCarpet ["#"]} in %% print all lines of the Sierpinski carpet of order 3 {ForAll {Nth SierpinskiCarpets 4} System.showInfo}
http://rosettacode.org/wiki/Semordnilap
Semordnilap
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples. Two matching semordnilaps, such as lager and regal, should be counted as one unique pair. (Note that the word "semordnilap" is not in the above dictionary.) Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#AWK
AWK
  # syntax: GAWK -f SEMORDNILAP.AWK unixdict.txt { arr[$0]++ } END { PROCINFO["sorted_in"] = "@ind_str_asc" for (word in arr) { rword = "" for (j=length(word); j>0; j--) { rword = rword substr(word,j,1) } if (word == rword) { continue } # palindrome if (rword in arr) { if (word in shown || rword in shown) { continue } shown[word]++ shown[rword]++ if (n++ < 5) { printf("%s %s\n",word,rword) } } } printf("%d words\n",n) exit(0) }  
http://rosettacode.org/wiki/Short-circuit_evaluation
Short-circuit evaluation
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Assume functions   a   and   b   return boolean values,   and further, the execution of function   b   takes considerable resources without side effects, and is to be minimized. If we needed to compute the conjunction   (and): x = a() and b() Then it would be best to not compute the value of   b()   if the value of   a()   is computed as   false,   as the value of   x   can then only ever be   false. Similarly, if we needed to compute the disjunction (or): y = a() or b() Then it would be best to not compute the value of   b()   if the value of   a()   is computed as   true,   as the value of   y   can then only ever be   true. Some languages will stop further computation of boolean equations as soon as the result is known, so-called   short-circuit evaluation   of boolean expressions Task Create two functions named   a   and   b,   that take and return the same boolean value. The functions should also print their name whenever they are called. Calculate and assign the values of the following equations to a variable in such a way that function   b   is only called when necessary: x = a(i) and b(j) y = a(i) or b(j) If the language does not have short-circuit evaluation, this might be achieved with nested     if     statements.
#Prolog
Prolog
short_circuit :- ( a_or_b(true, true) -> writeln('==> true'); writeln('==> false')) , nl, ( a_or_b(true, false)-> writeln('==> true'); writeln('==> false')) , nl, ( a_or_b(false, true)-> writeln('==> true'); writeln('==> false')) , nl, ( a_or_b(false, false)-> writeln('==> true'); writeln('==> false')) , nl, ( a_and_b(true, true)-> writeln('==> true'); writeln('==> false')) , nl, ( a_and_b(true, false)-> writeln('==> true'); writeln('==> false')) , nl, ( a_and_b(false, true)-> writeln('==> true'); writeln('==> false')) , nl, ( a_and_b(false, false)-> writeln('==> true'); writeln('==> false')) .     a_and_b(X, Y) :- format('a(~w) and b(~w)~n', [X, Y]), ( a(X), b(Y)).   a_or_b(X, Y) :- format('a(~w) or b(~w)~n', [X, Y]), ( a(X); b(Y)).   a(X) :- format('a(~w)~n', [X]), X.   b(X) :- format('b(~w)~n', [X]), X.
http://rosettacode.org/wiki/Selectively_replace_multiple_instances_of_a_character_within_a_string
Selectively replace multiple instances of a character within a string
Task This is admittedly a trivial task but I thought it would be interesting to see how succinctly (or otherwise) different languages can handle it. Given the string: "abracadabra", replace programatically: the first 'a' with 'A' the second 'a' with 'B' the fourth 'a' with 'C' the fifth 'a' with 'D' the first 'b' with 'E' the second 'r' with 'F' Note that there is no replacement for the third 'a', second 'b' or first 'r'. The answer should, of course, be : "AErBcadCbFD". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Raku
Raku
sub mangle ($str is copy) { $str.match(:ex, 'a')».from.map: { $str.substr-rw($_, 1) = 'ABaCD'.comb[$++] }; $str.=subst('b', 'E'); $str.substr-rw($_, 1) = 'F' given $str.match(:ex, 'r')».from[1]; $str }   say $_, ' -> ', .&mangle given 'abracadabra';   say $_, ' -> ', .&mangle given 'abracadabra'.comb.pick(*).join;
http://rosettacode.org/wiki/Selectively_replace_multiple_instances_of_a_character_within_a_string
Selectively replace multiple instances of a character within a string
Task This is admittedly a trivial task but I thought it would be interesting to see how succinctly (or otherwise) different languages can handle it. Given the string: "abracadabra", replace programatically: the first 'a' with 'A' the second 'a' with 'B' the fourth 'a' with 'C' the fifth 'a' with 'D' the first 'b' with 'E' the second 'r' with 'F' Note that there is no replacement for the third 'a', second 'b' or first 'r'. The answer should, of course, be : "AErBcadCbFD". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Vlang
Vlang
fn selectively_replace_chars(s string, char_map map[string]string) string { mut bytes := s.bytes() mut counts := { 'a': 0 'b': 0 'r': 0 } for i := s.len - 1; i >= 0; i-- { c := s[i].ascii_str() if c in ['a', 'b', 'r'] { bytes[i] = char_map[c][counts[c]] counts[c]++ } } return bytes.bytestr() }   fn main() { char_map := { 'a': 'DCaBA' 'b': 'bE' 'r': 'Fr' } for old in ['abracadabra', 'caaarrbabad'] { new := selectively_replace_chars(old, char_map) println('$old -> $new') } }
http://rosettacode.org/wiki/Send_email
Send email
Task Write a function to send an email. The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details. If appropriate, explain what notifications of problems/success are given. Solutions using libraries or functions from the language are preferred, but failing that, external programs can be used with an explanation. Note how portable the solution given is between operating systems when multi-OS languages are used. (Remember to obfuscate any sensitive data used in examples)
#Fortran
Fortran
program sendmail use ifcom use msoutl implicit none integer(4) :: app, status, msg   call cominitialize(status) call comcreateobject("Outlook.Application", app, status) msg = $Application_CreateItem(app, olMailItem, status) call $MailItem_SetTo(msg, "somebody@somewhere", status) call $MailItem_SetSubject(msg, "Title", status) call $MailItem_SetBody(msg, "Hello", status) call $MailItem_Send(msg, status) call $Application_Quit(app, status) call comuninitialize() end program
http://rosettacode.org/wiki/Send_email
Send email
Task Write a function to send an email. The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details. If appropriate, explain what notifications of problems/success are given. Solutions using libraries or functions from the language are preferred, but failing that, external programs can be used with an explanation. Note how portable the solution given is between operating systems when multi-OS languages are used. (Remember to obfuscate any sensitive data used in examples)
#Go
Go
package main   import ( "bufio" "bytes" "errors" "flag" "fmt" "io/ioutil" "net/smtp" "os" "strings" )   type Message struct { From string To []string Cc []string Subject string Content string }   func (m Message) Bytes() (r []byte) { to := strings.Join(m.To, ",") cc := strings.Join(m.Cc, ",")   r = append(r, []byte("From: "+m.From+"\n")...) r = append(r, []byte("To: "+to+"\n")...) r = append(r, []byte("Cc: "+cc+"\n")...) r = append(r, []byte("Subject: "+m.Subject+"\n\n")...) r = append(r, []byte(m.Content)...)   return }   func (m Message) Send(host string, port int, user, pass string) (err error) { err = check(host, user, pass) if err != nil { return }   err = smtp.SendMail(fmt.Sprintf("%v:%v", host, port), smtp.PlainAuth("", user, pass, host), m.From, m.To, m.Bytes(), )   return }   func check(host, user, pass string) error { if host == "" { return errors.New("Bad host") } if user == "" { return errors.New("Bad username") } if pass == "" { return errors.New("Bad password") }   return nil }   func main() { var flags struct { host string port int user string pass string } flag.StringVar(&flags.host, "host", "", "SMTP server to connect to") flag.IntVar(&flags.port, "port", 587, "Port to connect to SMTP server on") flag.StringVar(&flags.user, "user", "", "Username to authenticate with") flag.StringVar(&flags.pass, "pass", "", "Password to authenticate with") flag.Parse()   err := check(flags.host, flags.user, flags.pass) if err != nil { flag.Usage() os.Exit(1) }   bufin := bufio.NewReader(os.Stdin)   fmt.Printf("From: ") from, err := bufin.ReadString('\n') if err != nil { fmt.Printf("Error: %v\n", err) os.Exit(1) } from = strings.Trim(from, " \t\n\r")   var to []string for { fmt.Printf("To (Blank to finish): ") tmp, err := bufin.ReadString('\n') if err != nil { fmt.Printf("Error: %v\n", err) os.Exit(1) } tmp = strings.Trim(tmp, " \t\n\r")   if tmp == "" { break }   to = append(to, tmp) }   var cc []string for { fmt.Printf("Cc (Blank to finish): ") tmp, err := bufin.ReadString('\n') if err != nil { fmt.Printf("Error: %v\n", err) os.Exit(1) } tmp = strings.Trim(tmp, " \t\n\r")   if tmp == "" { break }   cc = append(cc, tmp) }   fmt.Printf("Subject: ") subject, err := bufin.ReadString('\n') if err != nil { fmt.Printf("Error: %v\n", err) os.Exit(1) } subject = strings.Trim(subject, " \t\n\r")   fmt.Printf("Content (Until EOF):\n") content, err := ioutil.ReadAll(os.Stdin) if err != nil { fmt.Printf("Error: %v\n", err) os.Exit(1) } content = bytes.Trim(content, " \t\n\r")   m := Message{ From: from, To: to, Cc: cc, Subject: subject, Content: string(content), }   fmt.Printf("\nSending message...\n") err = m.Send(flags.host, flags.port, flags.user, flags.pass) if err != nil { fmt.Printf("Error: %v\n", err) os.Exit(1) }   fmt.Printf("Message sent.\n") }
http://rosettacode.org/wiki/Semiprime
Semiprime
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers. Semiprimes   are also known as:   semi-primes   biprimes   bi-primes   2-almost   primes   or simply:   P2 Example 1679 = 23 × 73 (This particular number was chosen as the length of the Arecibo message). Task Write a function determining whether a given number is semiprime. See also The Wikipedia article:  semiprime. The Wikipedia article:  almost prime. The OEIS sequence:  A001358: semiprimes  which has a shorter definition: the product of two primes.
#BASIC
BASIC
  REM Semiprime PRINT "Enter an integer "; INPUT N N = ABS(N)   Count = 0 IF N >= 2 THEN FOR Factor = 2 TO N NModFactor = N MOD Factor WHILE NModFactor = 0 Count = Count + 1 N = N / Factor NModFactor = N MOD Factor WEND NEXT Factor ENDIF   IF Count = 2 THEN PRINT "It is a semiprime." ELSE PRINT "It is not a semiprime." ENDIF END  
http://rosettacode.org/wiki/Semiprime
Semiprime
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers. Semiprimes   are also known as:   semi-primes   biprimes   bi-primes   2-almost   primes   or simply:   P2 Example 1679 = 23 × 73 (This particular number was chosen as the length of the Arecibo message). Task Write a function determining whether a given number is semiprime. See also The Wikipedia article:  semiprime. The Wikipedia article:  almost prime. The OEIS sequence:  A001358: semiprimes  which has a shorter definition: the product of two primes.
#Bracmat
Bracmat
semiprime= m n a b . 2^-64:?m & 2*!m:?n &  !arg^!m  : (#%?a^!m*#%?b^!m|#%?a^!n&!a:?b) & (!a.!b);
http://rosettacode.org/wiki/Self-describing_numbers
Self-describing numbers
Self-describing numbers You are encouraged to solve this task according to the task description, using any language you may know. There are several so-called "self-describing" or "self-descriptive" integers. An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number. For example,   2020   is a four-digit self describing number:   position   0   has value   2   and there are two 0s in the number;   position   1   has value   0   and there are no 1s in the number;   position   2   has value   2   and there are two 2s;   position   3   has value   0   and there are zero 3s. Self-describing numbers < 100.000.000  are:     1210,   2020,   21200,   3211000,   42101000. Task Description Write a function/routine/method/... that will check whether a given positive integer is self-describing. As an optional stretch goal - generate and display the set of self-describing numbers. Related tasks   Fours is the number of letters in the ...   Look-and-say sequence   Number names   Self-referential sequence   Spelling of ordinal numbers
#AppleScript
AppleScript
use AppleScript version "2.4" use framework "Foundation" use scripting additions     -- selfDescribes :: Int -> Bool on selfDescribes(x) set s to str(x) set descripn to my str(|λ|(my groupBy(my eq, my sort(characters of s))) of my ¬ described(characters of "0123456789")) 1 = (offset of descripn in s) and ¬ 0 = ((items ((length of descripn) + 1) thru -1 of s) as string as integer) end selfDescribes     -- described :: [Char] -> [[Char]] -> [Char] on described(digits) script on |λ|(groups) if 0 < length of digits and 0 < length of groups then set grp to item 1 of groups set go to described(rest of digits) if item 1 of digits = item 1 of (item 1 of grp) then {item 1 of my str(length of grp)} & |λ|(rest of groups) of go else {"0"} & |λ|(groups) of go end if else {} end if end |λ| end script end described     -------------------------- TEST --------------------------- on run script test on |λ|(n) str(n) & " -> " & str(selfDescribes(n)) end |λ| end script   unlines(map(test, ¬ {1210, 1211, 2020, 2022, 21200, 21203, 3211000, 3211004}))     end run     -------------------- GENERIC FUNCTIONS --------------------   -- True if every value in the list is true. -- and :: [Bool] -> Bool on |and|(xs) repeat with x in xs if not (contents of x) then return false end repeat return true end |and|     -- enumFromTo :: Int -> Int -> [Int] on enumFromTo(m, n) if m ≤ n then set lst to {} repeat with i from m to n set end of lst to i end repeat lst else {} end if end enumFromTo     -- eq (==) :: Eq a => a -> a -> Bool on eq(a, b) a = b end eq     -- filter :: (a -> Bool) -> [a] -> [a] on filter(p, xs) tell mReturn(p) set lst to {} set lng to length of xs repeat with i from 1 to lng set v to item i of xs if |λ|(v, i, xs) then set end of lst to v end repeat return lst end tell end filter     -- foldl :: (a -> b -> a) -> a -> [b] -> a on foldl(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs repeat with i from 1 to lng set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell end foldl     -- Typical usage: groupBy(on(eq, f), xs) -- groupBy :: (a -> a -> Bool) -> [a] -> [[a]] on groupBy(f, xs) set mf to mReturn(f)   script enGroup on |λ|(a, x) if length of (active of a) > 0 then set h to item 1 of active of a else set h to missing value end if   if h is not missing value and mf's |λ|(h, x) then {active:(active of a) & {x}, sofar:sofar of a} else {active:{x}, sofar:(sofar of a) & {active of a}} end if end |λ| end script   if length of xs > 0 then set dct to foldl(enGroup, {active:{item 1 of xs}, sofar:{}}, rest of xs) if length of (active of dct) > 0 then sofar of dct & {active of dct} else sofar of dct end if else {} end if end groupBy     -- map :: (a -> b) -> [a] -> [b] on map(f, xs) -- The list obtained by applying f -- to each element of xs. tell mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell end map     -- mReturn :: First-class m => (a -> b) -> m (a -> b) on mReturn(f) -- 2nd class handler function lifted into 1st class script wrapper. if script is class of f then f else script property |λ| : f end script end if end mReturn     -- sort :: Ord a => [a] -> [a] on sort(xs) ((current application's NSArray's arrayWithArray:xs)'s ¬ sortedArrayUsingSelector:"compare:") as list end sort     -- str :: a -> String on str(x) x as string end str     -- unlines :: [String] -> String on unlines(xs) -- A single string formed by the intercalation -- of a list of strings with the newline character. set {dlm, my text item delimiters} to ¬ {my text item delimiters, linefeed} set s to xs as text set my text item delimiters to dlm s end unlines
http://rosettacode.org/wiki/Self_numbers
Self numbers
A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43. The task is: Display the first 50 self numbers; I believe that the 100000000th self number is 1022727208. You should either confirm or dispute my conjecture. 224036583-1 is a Mersenne prime, claimed to also be a self number. Extra credit to anyone proving it. See also OEIS: A003052 - Self numbers or Colombian numbers Wikipedia: Self numbers
#C
C
#include <stdio.h> #include <stdlib.h> #include <time.h>   typedef unsigned char bool;   #define TRUE 1 #define FALSE 0 #define MILLION 1000000 #define BILLION 1000 * MILLION #define MAX_COUNT 2*BILLION + 9*9 + 1   void sieve(bool *sv) { int n = 0, s[8], a, b, c, d, e, f, g, h, i, j; for (a = 0; a < 2; ++a) { for (b = 0; b < 10; ++b) { s[0] = a + b; for (c = 0; c < 10; ++c) { s[1] = s[0] + c; for (d = 0; d < 10; ++d) { s[2] = s[1] + d; for (e = 0; e < 10; ++e) { s[3] = s[2] + e; for (f = 0; f < 10; ++f) { s[4] = s[3] + f; for (g = 0; g < 10; ++g) { s[5] = s[4] + g; for (h = 0; h < 10; ++h) { s[6] = s[5] + h; for (i = 0; i < 10; ++i) { s[7] = s[6] + i; for (j = 0; j < 10; ++j) { sv[s[7] + j+ n++] = TRUE; } } } } } } } } } } }   int main() { int count = 0; clock_t begin = clock(); bool *p, *sv = (bool*) calloc(MAX_COUNT, sizeof(bool)); sieve(sv); printf("The first 50 self numbers are:\n"); for (p = sv; p < sv + MAX_COUNT; ++p) { if (!*p) { if (++count <= 50) printf("%ld ", p-sv); if (count == 100 * MILLION) { printf("\n\nThe 100 millionth self number is %ld\n", p-sv); break; } } } free(sv); printf("Took %lf seconds.\n", (double)(clock() - begin) / CLOCKS_PER_SEC); return 0; }
http://rosettacode.org/wiki/Set_of_real_numbers
Set of real numbers
All real numbers form the uncountable set ℝ. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers a and b where a ≤ b. There are actually four cases for the meaning of "between", depending on open or closed boundary: [a, b]: {x | a ≤ x and x ≤ b } (a, b): {x | a < x and x < b } [a, b): {x | a ≤ x and x < b } (a, b]: {x | a < x and x ≤ b } Note that if a = b, of the four only [a, a] would be non-empty. Task Devise a way to represent any set of real numbers, for the definition of 'any' in the implementation notes below. Provide methods for these common set operations (x is a real number; A and B are sets): x ∈ A: determine if x is an element of A example: 1 is in [1, 2), while 2, 3, ... are not. A ∪ B: union of A and B, i.e. {x | x ∈ A or x ∈ B} example: [0, 2) ∪ (1, 3) = [0, 3); [0, 1) ∪ (2, 3] = well, [0, 1) ∪ (2, 3] A ∩ B: intersection of A and B, i.e. {x | x ∈ A and x ∈ B} example: [0, 2) ∩ (1, 3) = (1, 2); [0, 1) ∩ (2, 3] = empty set A - B: difference between A and B, also written as A \ B, i.e. {x | x ∈ A and x ∉ B} example: [0, 2) − (1, 3) = [0, 1] Test your implementation by checking if numbers 0, 1, and 2 are in any of the following sets: (0, 1] ∪ [0, 2) [0, 2) ∩ (1, 2] [0, 3) − (0, 1) [0, 3) − [0, 1] Implementation notes 'Any' real set means 'sets that can be expressed as the union of a finite number of convex real sets'. Cantor's set needs not apply. Infinities should be handled gracefully; indeterminate numbers (NaN) can be ignored. You can use your machine's native real number representation, which is probably IEEE floating point, and assume it's good enough (it usually is). Optional work Create a function to determine if a given set is empty (contains no element). Define A = {x | 0 < x < 10 and |sin(π x²)| > 1/2 }, B = {x | 0 < x < 10 and |sin(π x)| > 1/2}, calculate the length of the real axis covered by the set A − B. Note that |sin(π x)| > 1/2 is the same as n + 1/6 < x < n + 5/6 for all integers n; your program does not need to derive this by itself.
#J
J
has=: 1 :'(interval m)`:6' ing=: `''   interval=: 3 :0 if.0<L.y do.y return.end. assert. 5=#words=. ;:y assert. (0 { words) e. ;:'[(' assert. (2 { words) e. ;:',' assert. (4 { words) e. ;:'])' 'lo hi'=.(1 3{0".L:0 words) 'cL cH'=.0 4{words e.;:'[]' (lo&(<`<:@.cL) *. hi&(>`>:@.cH))ing )   union=: 4 :'(x has +. y has)ing' intersect=: 4 :'(x has *. y has)ing' without=: 4 :'(x has *. [: -. y has)ing'
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
Sequence of primes by trial division
Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by other numbers. You may use primes, or any numbers of your choosing, as long as the result is indeed a sequence of primes. The sequence may be bounded (i.e. up to some limit), unbounded, starting from the start (i.e. 2) or above some given value. Organize your function as you wish, in particular, it might resemble a filtering operation, or a sieving operation. If you want to use a ready-made is_prime function, use one from the Primality by trial division page (i.e., add yours there if it isn't there already). Related tasks   count in factors   prime decomposition   factors of an integer   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes
#Befunge
Befunge
2>:::"}"8*:*>`#@_48*:**2v v_v#`\*:%*:*84\/*:*84::+< v#>::48*:*/\48*:*%%!#v_1^ <^+1$_.#<5#<5#<+#<,#<<0:\
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
Sequence of primes by trial division
Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by other numbers. You may use primes, or any numbers of your choosing, as long as the result is indeed a sequence of primes. The sequence may be bounded (i.e. up to some limit), unbounded, starting from the start (i.e. 2) or above some given value. Organize your function as you wish, in particular, it might resemble a filtering operation, or a sieving operation. If you want to use a ready-made is_prime function, use one from the Primality by trial division page (i.e., add yours there if it isn't there already). Related tasks   count in factors   prime decomposition   factors of an integer   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes
#C
C
  #include<stdio.h>   int isPrime(unsigned int n) { unsigned int num;   if ( n < 2||!(n & 1)) return n == 2;   for (num = 3; num <= n/num; num += 2) if (!(n % num)) return 0; return 1; }   int main() { unsigned int l,u,i,sum=0;   printf("Enter lower and upper bounds: "); scanf("%ld%ld",&l,&u);   for(i=l;i<=u;i++){ if(isPrime(i)==1) { printf("\n%ld",i); sum++; } }   printf("\n\nPrime numbers found in [%ld,%ld] : %ld",l,u,sum);   return 0; }  
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#BASIC256
BASIC256
# Display first 22 values print "The first 22 numbers generated by the sequence are : " for i = 1 to 22 print nonSquare(i); " "; next i print   # Check for squares up to one million found = false for i = 1 to 1e6 j = sqrt(nonSquare(i)) if j = int(j) then found = true print i, " square numbers found" exit for end if next i if not found then print "No squares found" end   function nonSquare (n) return n + int(0.5 + sqrt(n)) end function
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#BBC_BASIC
BBC BASIC
FOR N% = 1 TO 22 S% = N% + SQR(N%) + 0.5 PRINT S% NEXT   PRINT '"Checking...." FOR N% = 1 TO 999999 S% = N% + SQR(N%) + 0.5 R% = SQR(S%) IF S%/R% = R% STOP NEXT PRINT "No squares occur for n < 1000000"
http://rosettacode.org/wiki/Set
Set
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A   set  is a collection of elements, without duplicates and without order. Task Show each of these set operations: Set creation Test m ∈ S -- "m is an element in set S" A ∪ B -- union; a set of all elements either in set A or in set B. A ∩ B -- intersection; a set of all elements in both set A and set B. A ∖ B -- difference; a set of all elements in set A, except those in set B. A ⊆ B -- subset; true if every element in set A is also in set B. A = B -- equality; true if every element of set A is in set B and vice versa. As an option, show some other set operations. (If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.) As another option, show how to modify a mutable set. One might implement a set using an associative array (with set elements as array keys and some dummy value as the values). One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators). The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#AutoHotkey
AutoHotkey
test(Set,element){ for i, val in Set if (val=element) return true return false }   Union(SetA,SetB){ SetC:=[], Temp:=[] for i, val in SetA SetC.Insert(val), Temp[val] := true for i, val in SetB if !Temp[val] SetC.Insert(val) return SetC }   intersection(SetA,SetB){ SetC:=[], Temp:=[] for i, val in SetA Temp[val] := true for i, val in SetB if Temp[val] SetC.Insert(val) return SetC }   difference(SetA,SetB){ SetC:=[], Temp:=[] for i, val in SetB Temp[val] := true for i, val in SetA if !Temp[val] SetC.Insert(val) return SetC }   subset(SetA,SetB){ Temp:=[], A:=B:=0 for i, val in SetA Temp[val] := true , A++ for i, val in SetB if Temp[val]{ B++ IfEqual, A, %B%, return 1 } return 0 }   equal(SetA,SetB){ return (SetA.MaxIndex() = SetB.MaxIndex() && subset(SetA,SetB)) ? 1: 0 }
http://rosettacode.org/wiki/Send_an_unknown_method_call
Send an unknown method call
Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
#PHP
PHP
<?php class Example { function foo($x) { return 42 + $x; } }   $example = new Example();   $name = 'foo'; echo $example->$name(5), "\n"; // prints "47"   // alternately: echo call_user_func(array($example, $name), 5), "\n"; ?>
http://rosettacode.org/wiki/Send_an_unknown_method_call
Send an unknown method call
Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
#Picat
Picat
go => println("Function: Use apply/n"), Fun = "fib", A = 10,  % Convert F to an atom println(apply(to_atom(Fun),A)), nl,   println("Predicate: use call/n"), Pred = "pyth", call(Pred.to_atom,3,4,Z), println(z=Z),    % Pred2 is an atom so it can be used directly with call/n. Pred2 = pyth, call(Pred.to_atom,13,14,Z2), println(z2=Z2),   nl.   % A function fib(1) = 1. fib(2) = 1. fib(N) = fib(N-1) + fib(N-2).   % A predicate pyth(X,Y,Z) => Z = X**2 + Y**2.
http://rosettacode.org/wiki/Send_an_unknown_method_call
Send an unknown method call
Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
#PicoLisp
PicoLisp
(send (expression) Obj arg1 arg2)
http://rosettacode.org/wiki/Send_an_unknown_method_call
Send an unknown method call
Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
#Pike
Pike
string unknown = "format_nice"; object now = Calendar.now(); now[unknown]();
http://rosettacode.org/wiki/Send_an_unknown_method_call
Send an unknown method call
Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
#PowerShell
PowerShell
  $method = ([Math] | Get-Member -MemberType Method -Static | Where-Object {$_.Definition.Split(',').Count -eq 1} | Get-Random).Name $number = (1..9 | Get-Random) / 10 $result = [Math]::$method($number) $output = [PSCustomObject]@{ Method = $method Number = $number Result = $result }   $output | Format-List  
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#ALGOL_60
ALGOL 60
comment Sieve of Eratosthenes; begin integer array t[0:1000]; integer i,j,k; for i:=0 step 1 until 1000 do t[i]:=1; t[0]:=0; t[1]:=0; i:=0; for i:=i while i<1000 do begin for i:=i while i<1000 and t[i]=0 do i:=i+1; if i<1000 then begin j:=2; k:=j*i; for k:=k while k<1000 do begin t[k]:=0; j:=j+1; k:=j*i end; i:=i+1 end end; for i:=0 step 1 until 999 do if t[i]≠0 then print(i,ꞌ is primeꞌ) end
http://rosettacode.org/wiki/Sequence_of_primorial_primes
Sequence of primorial primes
The sequence of primorial primes is given as the increasing values of n where primorial(n) ± 1 is prime. Noting that the n'th primorial is defined as the multiplication of the smallest n primes, the sequence is of the number of primes, in order that when multiplied together is one-off being a prime number itself. Task Generate and show here the first ten values of the sequence. Optional extended task Show the first twenty members of the series. Notes This task asks for the primorial indices that create the final primorial prime numbers, so there should be no ten-or-more digit numbers in the program output (although extended precision integers will be needed for intermediate results). There is some confusion in the references, but for the purposes of this task the sequence begins with n = 1. Probabilistic primality tests are allowed, as long as they are good enough such that the output shown is correct. Related tasks Primorial numbers Factorial See also Primorial prime Wikipedia. Primorial prime from The Prime Glossary. Sequence A088411 from The On-Line Encyclopedia of Integer Sequences
#Python
Python
import pyprimes   def primorial_prime(_pmax=500): isprime = pyprimes.isprime n, primo = 0, 1 for prime in pyprimes.nprimes(_pmax): n, primo = n+1, primo * prime if isprime(primo-1) or isprime(primo+1): yield n   if __name__ == '__main__': # Turn off warning on use of probabilistic formula for prime test pyprimes.warn_probably = False for i, n in zip(range(20), primorial_prime()): print('Primorial prime %2i at primorial index: %3i' % (i+1, n))
http://rosettacode.org/wiki/Sequence_of_primorial_primes
Sequence of primorial primes
The sequence of primorial primes is given as the increasing values of n where primorial(n) ± 1 is prime. Noting that the n'th primorial is defined as the multiplication of the smallest n primes, the sequence is of the number of primes, in order that when multiplied together is one-off being a prime number itself. Task Generate and show here the first ten values of the sequence. Optional extended task Show the first twenty members of the series. Notes This task asks for the primorial indices that create the final primorial prime numbers, so there should be no ten-or-more digit numbers in the program output (although extended precision integers will be needed for intermediate results). There is some confusion in the references, but for the purposes of this task the sequence begins with n = 1. Probabilistic primality tests are allowed, as long as they are good enough such that the output shown is correct. Related tasks Primorial numbers Factorial See also Primorial prime Wikipedia. Primorial prime from The Prime Glossary. Sequence A088411 from The On-Line Encyclopedia of Integer Sequences
#Racket
Racket
#lang racket   (require math/number-theory racket/generator)   (define-syntax-rule (define/cache (name arg) body ...) (begin (define cache (make-hash)) (define (name arg) (hash-ref! cache arg (lambda () body ...)))))   (define/cache (primorial n) (if (zero? n) 1 (* (nth-prime (sub1 n)) (primorial (sub1 n)))))   (for ([i (in-range 20)] [n (in-generator (for ([i (in-naturals 1)]) (define pr (primorial i)) (when (or (prime? (add1 pr)) (prime? (sub1 pr))) (yield i))))]) (displayln n))
http://rosettacode.org/wiki/Set_consolidation
Set consolidation
Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is: The two input sets if no common item exists between the two input sets of items. The single set that is the union of the two input sets if they share a common item. Given N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible. If N<2 then consolidation has no strict meaning and the input can be returned. Example 1: Given the two sets {A,B} and {C,D} then there is no common element between the sets and the result is the same as the input. Example 2: Given the two sets {A,B} and {B,D} then there is a common element B between the sets and the result is the single set {B,D,A}. (Note that order of items in a set is immaterial: {A,B,D} is the same as {B,D,A} and {D,A,B}, etc). Example 3: Given the three sets {A,B} and {C,D} and {D,B} then there is no common element between the sets {A,B} and {C,D} but the sets {A,B} and {D,B} do share a common element that consolidates to produce the result {B,D,A}. On examining this result with the remaining set, {C,D}, they share a common element and so consolidate to the final output of the single set {A,B,C,D} Example 4: The consolidation of the five sets: {H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H} Is the two sets: {A, C, B, D}, and {G, F, I, H, K} See also Connected component (graph theory) Range consolidation
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
reduce[x_] := Block[{pairs, unique}, pairs = DeleteCases[ Subsets[Range@ Length@x, {2}], _?(Intersection @@ x[[#]] == {} &)]; unique = Complement[Range@Length@x, Flatten@pairs]; Join[Union[Flatten[x[[#]]]] & /@ pairs, x[[unique]]]] consolidate[x__] := FixedPoint[reduce, {x}]
http://rosettacode.org/wiki/Set_consolidation
Set consolidation
Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is: The two input sets if no common item exists between the two input sets of items. The single set that is the union of the two input sets if they share a common item. Given N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible. If N<2 then consolidation has no strict meaning and the input can be returned. Example 1: Given the two sets {A,B} and {C,D} then there is no common element between the sets and the result is the same as the input. Example 2: Given the two sets {A,B} and {B,D} then there is a common element B between the sets and the result is the single set {B,D,A}. (Note that order of items in a set is immaterial: {A,B,D} is the same as {B,D,A} and {D,A,B}, etc). Example 3: Given the three sets {A,B} and {C,D} and {D,B} then there is no common element between the sets {A,B} and {C,D} but the sets {A,B} and {D,B} do share a common element that consolidates to produce the result {B,D,A}. On examining this result with the remaining set, {C,D}, they share a common element and so consolidate to the final output of the single set {A,B,C,D} Example 4: The consolidation of the five sets: {H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H} Is the two sets: {A, C, B, D}, and {G, F, I, H, K} See also Connected component (graph theory) Range consolidation
#Nim
Nim
proc consolidate(sets: varargs[set[char]]): seq[set[char]] = if len(sets) < 2: return @sets var (r, b) = (@[sets[0]], consolidate(sets[1..^1])) for x in b: if len(r[0] * x) != 0: r[0] = r[0] + x else: r.add(x) r   echo consolidate({'A', 'B'}, {'C', 'D'}) echo consolidate({'A', 'B'}, {'B', 'D'}) echo consolidate({'A', 'B'}, {'C', 'D'}, {'D', 'B'}) echo consolidate({'H', 'I', 'K'}, {'A', 'B'}, {'C', 'D'}, {'D', 'B'}, {'F', 'G', 'H'})
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors
Sequence: smallest number with exactly n divisors
Calculate the sequence where each term   an   is the smallest natural number that has exactly   n   divisors. Task Show here, on this page, at least the first  15  terms of the sequence. Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: nth number with exactly n divisors‎‎ See also OEIS:A005179
#Quackery
Quackery
[ 0 [ 1+ 2dup factors size = until ] nip ] is nfactors ( n --> n )   15 times [ i^ 1+ nfactors echo sp ]
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors
Sequence: smallest number with exactly n divisors
Calculate the sequence where each term   an   is the smallest natural number that has exactly   n   divisors. Task Show here, on this page, at least the first  15  terms of the sequence. Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: nth number with exactly n divisors‎‎ See also OEIS:A005179
#R
R
#Need to add 1 to account for skipping n. Not the most efficient way to count divisors, but quite clear. divisorCount <- function(n) length(Filter(function(x) n %% x == 0, seq_len(n %/% 2))) + 1 smallestWithNDivisors <- function(n) { i <- 1 while(divisorCount(i) != n) i <- i + 1 i } print(sapply(1:15, smallestWithNDivisors))
http://rosettacode.org/wiki/SHA-256
SHA-256
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details. Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
#Racket
Racket
  #lang racket/base   ;; define a quick SH256 FFI interface, similar to the Racket's default ;; SHA1 interface (require ffi/unsafe ffi/unsafe/define openssl/libcrypto (only-in openssl/sha1 bytes->hex-string)) (define-ffi-definer defcrypto libcrypto) (defcrypto SHA256_Init (_fun _pointer -> _int)) (defcrypto SHA256_Update (_fun _pointer _pointer _long -> _int)) (defcrypto SHA256_Final (_fun _pointer _pointer -> _int)) (define (sha256 bytes) (define ctx (malloc 128)) (define result (make-bytes 32)) (SHA256_Init ctx) (SHA256_Update ctx bytes (bytes-length bytes)) (SHA256_Final result ctx) (bytes->hex-string result))   ;; use the defined wrapper to solve the task (displayln (sha256 #"Rosetta code"))  
http://rosettacode.org/wiki/SHA-256
SHA-256
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details. Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
#Raku
Raku
say sha256 "Rosetta code";   sub init(&f) { map { my $f = $^p.&f; (($f - $f.Int)*2**32).Int }, state @ = grep *.is-prime, 2 .. *; }   sub infix:<m+> { ($^a + $^b) % 2**32 } sub rotr($n, $b) { $n +> $b +| $n +< (32 - $b) }   proto sha256($) returns Blob {*} multi sha256(Str $str where all($str.ords) < 128) { sha256 $str.encode: 'ascii' } multi sha256(Blob $data) { constant K = init(* **(1/3))[^64]; my @b = flat $data.list, 0x80; push @b, 0 until (8 * @b - 448) %% 512; push @b, slip reverse (8 * $data).polymod(256 xx 7); my @word = :256[@b.shift xx 4] xx @b/4;   my @H = init(&sqrt)[^8]; my @w; loop (my $i = 0; $i < @word; $i += 16) { my @h = @H; for ^64 -> $j { @w[$j] = $j < 16 ?? @word[$j + $i] // 0 !! [m+] rotr(@w[$j-15], 7) +^ rotr(@w[$j-15], 18) +^ @w[$j-15] +> 3, @w[$j-7], rotr(@w[$j-2], 17) +^ rotr(@w[$j-2], 19) +^ @w[$j-2] +> 10, @w[$j-16]; my $ch = @h[4] +& @h[5] +^ +^@h[4] % 2**32 +& @h[6]; my $maj = @h[0] +& @h[2] +^ @h[0] +& @h[1] +^ @h[1] +& @h[2]; my $σ0 = [+^] map { rotr @h[0], $_ }, 2, 13, 22; my $σ1 = [+^] map { rotr @h[4], $_ }, 6, 11, 25; my $t1 = [m+] @h[7], $σ1, $ch, K[$j], @w[$j]; my $t2 = $σ0 m+ $maj; @h = flat $t1 m+ $t2, @h[^3], @h[3] m+ $t1, @h[4..6]; } @H [Z[m+]]= @h; } return Blob.new: map { |reverse .polymod(256 xx 3) }, @H; }
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors
Sequence: smallest number greater than previous term with exactly n divisors
Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A069654 Related tasks Sequence: smallest number with exactly n divisors Sequence: nth number with exactly n divisors‎‎
#Swift
Swift
// See https://en.wikipedia.org/wiki/Divisor_function func divisorCount(number: Int) -> Int { var n = number var total = 1 // Deal with powers of 2 first while n % 2 == 0 { total += 1 n /= 2 } // Odd prime factors up to the square root var p = 3 while p * p <= n { var count = 1 while n % p == 0 { count += 1 n /= p } total *= count p += 2 } // If n > 1 then it's prime if n > 1 { total *= 2 } return total }   let limit = 32 var n = 1 var next = 1 while next <= limit { if next == divisorCount(number: n) { print(n, terminator: " ") next += 1 if next > 4 && divisorCount(number: next) == 2 { n = 1 << (next - 1) - 1; } } n += 1 } print()
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors
Sequence: smallest number greater than previous term with exactly n divisors
Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A069654 Related tasks Sequence: smallest number with exactly n divisors Sequence: nth number with exactly n divisors‎‎
#Wren
Wren
import "/math" for Int   var limit = 24 var res = List.filled(limit, 0) var next = 1 var n = 1 while (next <= limit) { var k = Int.divisors(n).count if (k == next) { res[k-1] = n next = next + 1 if (next > 4 && Int.isPrime(next)) n = 2.pow(next-1) - 1 } n = n + 1 } System.print("The first %(limit) terms are:") System.print(res)
http://rosettacode.org/wiki/SHA-1
SHA-1
SHA-1 or SHA1 is a one-way hash function; it computes a 160-bit message digest. SHA-1 often appears in security protocols; for example, many HTTPS websites use RSA with SHA-1 to secure their connections. BitTorrent uses SHA-1 to verify downloads. Git and Mercurial use SHA-1 digests to identify commits. A US government standard, FIPS 180-1, defines SHA-1. Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code. Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer. This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1. For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
#Raku
Raku
sub postfix:<mod2³²> { $^x % 2**32 } sub infix:<⊕> { ($^x + $^y)mod2³² } sub S { ($^x +< $^n)mod2³² +| ($x +> (32-$n)) }   my \f = -> \B,\C,\D { (B +& C) +| ((+^B)mod2³² +& D) }, -> \B,\C,\D { B +^ C +^ D }, -> \B,\C,\D { (B +& C) +| (B +& D) +| (C +& D) }, -> \B,\C,\D { B +^ C +^ D };   my \K = 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6;   sub sha1-pad(Blob $msg) { my \bits = 8 * $msg.elems; my @padded = flat $msg.list, 0x80, 0x00 xx (-($msg.elems + 1 + 8) % 64); flat @padded.map({ :256[$^a,$^b,$^c,$^d] }), (bits +> 32)mod2³², (bits)mod2³²; }   sub sha1-block(@H, @M is copy) { @M.push: S(1, [+^] @M[$_ «-« <3 8 14 16>] ) for 16 .. 79;   my ($A,$B,$C,$D,$E) = @H; for 0..79 -> \t { ($A, $B, $C, $D, $E) = S(5,$A) ⊕ f[t div 20]($B,$C,$D) ⊕ $E ⊕ @M[t] ⊕ K[t div 20], $A, S(30,$B), $C, $D; } @H »⊕=« ($A,$B,$C,$D,$E); }   sub sha1(Blob $msg) returns Blob { my @M = sha1-pad($msg); my @H = 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0; sha1-block(@H,@M[$_..$_+15]) for 0, 16...^ +@M; Blob.new: flat map { reverse .polymod(256 xx 3) }, @H; }   say sha1(.encode('ascii')), " $_" for 'abc', 'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq', 'Rosetta Code', 'Ars longa, vita brevis';
http://rosettacode.org/wiki/Show_ASCII_table
Show ASCII table
Task Show  the ASCII character set  from values   32   to   127   (decimal)   in a table format. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
StringRiffle[StringJoin@@@Transpose[Partition[ToString[#]<>": "<>Switch[#,32,"Spc ",127,"Del ",_,FromCharacterCode[#]<>" "]&/@Range[32,127],16]],"\n"]
http://rosettacode.org/wiki/Sierpinski_triangle
Sierpinski triangle
Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Related tasks Sierpinski triangle/Graphical for graphics images of this pattern. Sierpinski carpet
#R
R
sierpinski.triangle = function(n) { len <- 2^(n+1) b <- c(rep(FALSE,len/2),TRUE,rep(FALSE,len/2)) for (i in 1:(len/2)) { cat(paste(ifelse(b,"*"," "),collapse=""),"\n") n <- rep(FALSE,len+1) n[which(b)-1]<-TRUE n[which(b)+1]<-xor(n[which(b)+1],TRUE) b <- n } } sierpinski.triangle(5)
http://rosettacode.org/wiki/Sierpinski_carpet
Sierpinski carpet
Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ###### ### ########################### # ## ## ## ## ## ## ## ## # ########################### ######### ######### # ## ## # # ## ## # ######### ######### ### ### ### ### # # # # # # # # ### ### ### ### ######### ######### # ## ## # # ## ## # ######### ######### ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ###### ### ########################### # ## ## ## ## ## ## ## ## # ########################### The use of the   #   character is not rigidly required for ASCII art. The important requirement is the placement of whitespace and non-whitespace characters. Related task   Sierpinski triangle
#PARI.2FGP
PARI/GP
  \\ Improved simple plotting using matrix mat (color and scaling added). \\ Matrix should be filled with 0/1. 7/6/16 aev iPlotmat(mat,clr)={ my(xz=#mat[1,],yz=#mat[,1],vx=List(),vy=vx,xmin,xmax,ymin,ymax,c=0.625); for(i=1,yz, for(j=1,xz, if(mat[i,j]==0, next, listput(vx,i); listput(vy,j)))); xmin=listmin(vx); xmax=listmax(vx); ymin=listmin(vy); ymax=listmax(vy); plotinit(0); plotcolor(0,clr); plotscale(0, xmin,xmax,ymin,ymax); plotpoints(0, Vec(vx)*c,Vec(vy)); plotdraw([0,xmin,ymin]); print(" *** matrix: ",xz,"x",yz,", ",#vy," DOTS"); } \\ iPlotV2(): Improved plotting from a file written by the wrtmat(). (color added) \\ Saving possibly huge generation time if re-plotting needed. iPlotV2(fn, clr)={ my(F,nf,vx=List(),vy=vx,Vr,xmin,xmax,ymin,ymax,c=0.625); F=readstr(fn); nf=#F; print(" *** Plotting from: ", fn, " - ", nf, " DOTS"); for(i=1,nf, Vr=stok(F[i]," "); listput(vx,eval(Vr[1])); listput(vy,eval(Vr[2]))); xmin=listmin(vx); xmax=listmax(vx); ymin=listmin(vy); ymax=listmax(vy); plotinit(0); plotcolor(0,clr); plotscale(0, xmin,xmax,ymin,ymax); plotpoints(0, Vec(vx)*c,Vec(vy)); plotdraw([0,xmin,ymin]); } \\ Are x,y inside Sierpinski carpet? (1-yes, 0-no) 6/10/16 aev inSC(x,y)={ while(1, if(!x||!y,return(1)); if(x%3==1&&y%3==1, return(0)); x\=3; y\=3;);\\wend }  
http://rosettacode.org/wiki/Semordnilap
Semordnilap
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples. Two matching semordnilaps, such as lager and regal, should be counted as one unique pair. (Note that the word "semordnilap" is not in the above dictionary.) Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#BBC_BASIC
BBC BASIC
INSTALL @lib$+"SORTLIB" Sort% = FN_sortinit(0,0)   DIM dict$(26000*2)   REM Load the dictionary, eliminating palindromes: dict% = OPENIN("C:\unixdict.txt") IF dict%=0 ERROR 100, "No dictionary file" index% = 0 REPEAT A$ = GET$#dict% B$ = FNreverse(A$) IF A$<>B$ THEN dict$(index%) = A$ dict$(index%+1) = B$ index% += 2 ENDIF UNTIL EOF#dict% CLOSE #dict% Total% = index%   REM Sort the dictionary: C% = Total% CALL Sort%, dict$(0)   REM Find semordnilaps: pairs% = 0 examples% = 0 FOR index% = 0 TO Total%-2 IF dict$(index%)=dict$(index%+1) THEN IF examples%<5 IF LEN(dict$(index%))>4 THEN PRINT dict$(index%) " " FNreverse(dict$(index%)) examples% += 1 ENDIF pairs% += 1 ENDIF NEXT   PRINT "Total number of unique pairs = "; pairs%/2 END   DEF FNreverse(A$) LOCAL I%, L%, P% IF A$="" THEN ="" L% = LENA$ - 1 P% = !^A$ FOR I% = 0 TO L% DIV 2 SWAP P%?I%, L%?(P%-I%) NEXT = A$
http://rosettacode.org/wiki/Short-circuit_evaluation
Short-circuit evaluation
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Assume functions   a   and   b   return boolean values,   and further, the execution of function   b   takes considerable resources without side effects, and is to be minimized. If we needed to compute the conjunction   (and): x = a() and b() Then it would be best to not compute the value of   b()   if the value of   a()   is computed as   false,   as the value of   x   can then only ever be   false. Similarly, if we needed to compute the disjunction (or): y = a() or b() Then it would be best to not compute the value of   b()   if the value of   a()   is computed as   true,   as the value of   y   can then only ever be   true. Some languages will stop further computation of boolean equations as soon as the result is known, so-called   short-circuit evaluation   of boolean expressions Task Create two functions named   a   and   b,   that take and return the same boolean value. The functions should also print their name whenever they are called. Calculate and assign the values of the following equations to a variable in such a way that function   b   is only called when necessary: x = a(i) and b(j) y = a(i) or b(j) If the language does not have short-circuit evaluation, this might be achieved with nested     if     statements.
#PureBasic
PureBasic
Procedure a(arg) PrintN(" # Called function a("+Str(arg)+")") ProcedureReturn arg EndProcedure   Procedure b(arg) PrintN(" # Called function b("+Str(arg)+")") ProcedureReturn arg EndProcedure   OpenConsole() For a=#False To #True For b=#False To #True PrintN(#CRLF$+"Calculating: x = a("+Str(a)+") And b("+Str(b)+")") x= a(a) And b(b) PrintN("Calculating: x = a("+Str(a)+") Or b("+Str(b)+")") y= a(a) Or b(b) Next Next Input()
http://rosettacode.org/wiki/Selectively_replace_multiple_instances_of_a_character_within_a_string
Selectively replace multiple instances of a character within a string
Task This is admittedly a trivial task but I thought it would be interesting to see how succinctly (or otherwise) different languages can handle it. Given the string: "abracadabra", replace programatically: the first 'a' with 'A' the second 'a' with 'B' the fourth 'a' with 'C' the fifth 'a' with 'D' the first 'b' with 'E' the second 'r' with 'F' Note that there is no replacement for the third 'a', second 'b' or first 'r'. The answer should, of course, be : "AErBcadCbFD". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Wren
Wren
import "./seq" for Lst import "./str" for Str   var s = "abracadabra" var sl = s.toList var ixs = Lst.indicesOf(sl, "a")[2] var repl = "ABaCD" for (i in 0..4) sl[ixs[i]] = repl[i] s = sl.join() s = Str.replace(s, "b", "E", 1) s = Str.replace(s, "r", "F", 2, 1) System.print(s)
http://rosettacode.org/wiki/Selectively_replace_multiple_instances_of_a_character_within_a_string
Selectively replace multiple instances of a character within a string
Task This is admittedly a trivial task but I thought it would be interesting to see how succinctly (or otherwise) different languages can handle it. Given the string: "abracadabra", replace programatically: the first 'a' with 'A' the second 'a' with 'B' the fourth 'a' with 'C' the fifth 'a' with 'D' the first 'b' with 'E' the second 'r' with 'F' Note that there is no replacement for the third 'a', second 'b' or first 'r'. The answer should, of course, be : "AErBcadCbFD". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#XPL0
XPL0
string 0; proc Mangle(S); char S, A, B, R; [A:= "ABaCD"; B:= "Eb"; R:= "rF"; while S(0) do [case S(0) of ^a: [S(0):= A(0); A:= A+1]; ^b: [S(0):= B(0); B:= B+1]; ^r: [S(0):= R(0); R:= R+1] other []; S:= S+1; ]; ];   char S; [S:= "abracadabra"; Text(0, S); Text(0, " -> "); Mangle(S); Text(0, S); CrLf(0); S:= "caarabadrab"; Text(0, S); Text(0, " -> "); Mangle(S); Text(0, S); CrLf(0); ]
http://rosettacode.org/wiki/Send_email
Send email
Task Write a function to send an email. The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details. If appropriate, explain what notifications of problems/success are given. Solutions using libraries or functions from the language are preferred, but failing that, external programs can be used with an explanation. Note how portable the solution given is between operating systems when multi-OS languages are used. (Remember to obfuscate any sensitive data used in examples)
#Groovy
Groovy
  import javax.mail.* import javax.mail.internet.*   public static void simpleMail(String from, String password, String to, String subject, String body) throws Exception {   String host = "smtp.gmail.com"; Properties props = System.getProperties(); props.put("mail.smtp.starttls.enable",true); /* mail.smtp.ssl.trust is needed in script to avoid error "Could not convert socket to TLS" */ props.setProperty("mail.smtp.ssl.trust", host); props.put("mail.smtp.auth", true); props.put("mail.smtp.host", host); props.put("mail.smtp.user", from); props.put("mail.smtp.password", password); props.put("mail.smtp.port", "587");   Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from));   InternetAddress toAddress = new InternetAddress(to);   message.addRecipient(Message.RecipientType.TO, toAddress);   message.setSubject(subject); message.setText(body);   Transport transport = session.getTransport("smtp");   transport.connect(host, from, password);   transport.sendMessage(message, message.getAllRecipients()); transport.close(); }   /* Set email address sender */ String s1 = "example@gmail.com";   /* Set password sender */ String s2 = "";   /* Set email address sender */ String s3 = "example@gmail.com"   /*Call function */ simpleMail(s1, s2 , s3, "TITLE", "TEXT");  
http://rosettacode.org/wiki/Semiprime
Semiprime
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers. Semiprimes   are also known as:   semi-primes   biprimes   bi-primes   2-almost   primes   or simply:   P2 Example 1679 = 23 × 73 (This particular number was chosen as the length of the Arecibo message). Task Write a function determining whether a given number is semiprime. See also The Wikipedia article:  semiprime. The Wikipedia article:  almost prime. The OEIS sequence:  A001358: semiprimes  which has a shorter definition: the product of two primes.
#C
C
#include <stdio.h>   int semiprime(int n) { int p, f = 0; for (p = 2; f < 2 && p*p <= n; p++) while (0 == n % p) n /= p, f++;   return f + (n > 1) == 2; }   int main(void) { int i; for (i = 2; i < 100; i++) if (semiprime(i)) printf(" %d", i); putchar('\n');   return 0; }
http://rosettacode.org/wiki/SEDOLs
SEDOLs
Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7 B000300 Extra credit Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string. Related tasks   Luhn test   ISIN
#11l
11l
F char2value(c) assert(c !C ‘AEIOU’, ‘No vowels’) R Int(c, radix' 36)   V sedolweight = [1, 3, 1, 7, 3, 9]   F checksum(sedol) V tmp = sum(zip(sedol, :sedolweight).map((ch, weight) -> char2value(ch) * weight)) R String((10 - (tmp % 10)) % 10)   V sedols = |‘710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT’   L(sedol) sedols.split("\n") print(sedol‘’checksum(sedol))
http://rosettacode.org/wiki/Self-describing_numbers
Self-describing numbers
Self-describing numbers You are encouraged to solve this task according to the task description, using any language you may know. There are several so-called "self-describing" or "self-descriptive" integers. An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number. For example,   2020   is a four-digit self describing number:   position   0   has value   2   and there are two 0s in the number;   position   1   has value   0   and there are no 1s in the number;   position   2   has value   2   and there are two 2s;   position   3   has value   0   and there are zero 3s. Self-describing numbers < 100.000.000  are:     1210,   2020,   21200,   3211000,   42101000. Task Description Write a function/routine/method/... that will check whether a given positive integer is self-describing. As an optional stretch goal - generate and display the set of self-describing numbers. Related tasks   Fours is the number of letters in the ...   Look-and-say sequence   Number names   Self-referential sequence   Spelling of ordinal numbers
#Arturo
Arturo
selfDescribing?: function [x][ digs: digits x loop.with:'i digs 'd [ if d <> size select digs 'z [z=i] -> return false ] return true ]   print select 1..22000 => selfDescribing?
http://rosettacode.org/wiki/Self-describing_numbers
Self-describing numbers
Self-describing numbers You are encouraged to solve this task according to the task description, using any language you may know. There are several so-called "self-describing" or "self-descriptive" integers. An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number. For example,   2020   is a four-digit self describing number:   position   0   has value   2   and there are two 0s in the number;   position   1   has value   0   and there are no 1s in the number;   position   2   has value   2   and there are two 2s;   position   3   has value   0   and there are zero 3s. Self-describing numbers < 100.000.000  are:     1210,   2020,   21200,   3211000,   42101000. Task Description Write a function/routine/method/... that will check whether a given positive integer is self-describing. As an optional stretch goal - generate and display the set of self-describing numbers. Related tasks   Fours is the number of letters in the ...   Look-and-say sequence   Number names   Self-referential sequence   Spelling of ordinal numbers
#AutoHotkey
AutoHotkey
; The following directives and commands speed up execution: #NoEnv SetBatchlines -1 ListLines Off Process, Priority,, high   MsgBox % 2020 ": " IsSelfDescribing(2020) "`n" 1337 ": " IsSelfDescribing(1337) "`n" 1210 ": " IsSelfDescribing(1210) Loop 100000000 If IsSelfDescribing(A_Index) list .= A_Index "`n" MsgBox % "Self-describing numbers < 100000000 :`n" . list   CountSubstring(fullstring, substring){ StringReplace, junk, fullstring, %substring%, , UseErrorLevel return errorlevel }   IsSelfDescribing(number){ Loop Parse, number If Not CountSubString(number, A_Index-1) = A_LoopField return false return true }
http://rosettacode.org/wiki/Self_numbers
Self numbers
A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43. The task is: Display the first 50 self numbers; I believe that the 100000000th self number is 1022727208. You should either confirm or dispute my conjecture. 224036583-1 is a Mersenne prime, claimed to also be a self number. Extra credit to anyone proving it. See also OEIS: A003052 - Self numbers or Colombian numbers Wikipedia: Self numbers
#C.2B.2B
C++
#include <array> #include <iomanip> #include <iostream>   const int MC = 103 * 1000 * 10000 + 11 * 9 + 1; std::array<bool, MC + 1> SV;   void sieve() { std::array<int, 10000> dS; for (int a = 9, i = 9999; a >= 0; a--) { for (int b = 9; b >= 0; b--) { for (int c = 9, s = a + b; c >= 0; c--) { for (int d = 9, t = s + c; d >= 0; d--) { dS[i--] = t + d; } } } } for (int a = 0, n = 0; a < 103; a++) { for (int b = 0, d = dS[a]; b < 1000; b++, n += 10000) { for (int c = 0, s = d + dS[b] + n; c < 10000; c++) { SV[dS[c] + s++] = true; } } } }   int main() { sieve();   std::cout << "The first 50 self numbers are:\n"; for (int i = 0, count = 0; count <= 50; i++) { if (!SV[i]) { count++; if (count <= 50) { std::cout << i << ' '; } else { std::cout << "\n\n Index Self number\n"; } } } for (int i = 0, limit = 1, count = 0; i < MC; i++) { if (!SV[i]) { if (++count == limit) { //System.out.printf("%,12d  %,13d%n", count, i); std::cout << std::setw(12) << count << " " << std::setw(13) << i << '\n'; limit *= 10; } } }   return 0; }
http://rosettacode.org/wiki/Set_of_real_numbers
Set of real numbers
All real numbers form the uncountable set ℝ. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers a and b where a ≤ b. There are actually four cases for the meaning of "between", depending on open or closed boundary: [a, b]: {x | a ≤ x and x ≤ b } (a, b): {x | a < x and x < b } [a, b): {x | a ≤ x and x < b } (a, b]: {x | a < x and x ≤ b } Note that if a = b, of the four only [a, a] would be non-empty. Task Devise a way to represent any set of real numbers, for the definition of 'any' in the implementation notes below. Provide methods for these common set operations (x is a real number; A and B are sets): x ∈ A: determine if x is an element of A example: 1 is in [1, 2), while 2, 3, ... are not. A ∪ B: union of A and B, i.e. {x | x ∈ A or x ∈ B} example: [0, 2) ∪ (1, 3) = [0, 3); [0, 1) ∪ (2, 3] = well, [0, 1) ∪ (2, 3] A ∩ B: intersection of A and B, i.e. {x | x ∈ A and x ∈ B} example: [0, 2) ∩ (1, 3) = (1, 2); [0, 1) ∩ (2, 3] = empty set A - B: difference between A and B, also written as A \ B, i.e. {x | x ∈ A and x ∉ B} example: [0, 2) − (1, 3) = [0, 1] Test your implementation by checking if numbers 0, 1, and 2 are in any of the following sets: (0, 1] ∪ [0, 2) [0, 2) ∩ (1, 2] [0, 3) − (0, 1) [0, 3) − [0, 1] Implementation notes 'Any' real set means 'sets that can be expressed as the union of a finite number of convex real sets'. Cantor's set needs not apply. Infinities should be handled gracefully; indeterminate numbers (NaN) can be ignored. You can use your machine's native real number representation, which is probably IEEE floating point, and assume it's good enough (it usually is). Optional work Create a function to determine if a given set is empty (contains no element). Define A = {x | 0 < x < 10 and |sin(π x²)| > 1/2 }, B = {x | 0 < x < 10 and |sin(π x)| > 1/2}, calculate the length of the real axis covered by the set A − B. Note that |sin(π x)| > 1/2 is the same as n + 1/6 < x < n + 5/6 for all integers n; your program does not need to derive this by itself.
#Java
Java
import java.util.Objects; import java.util.function.Predicate;   public class RealNumberSet { public enum RangeType { CLOSED, BOTH_OPEN, LEFT_OPEN, RIGHT_OPEN, }   public static class RealSet { private Double low; private Double high; private Predicate<Double> predicate; private double interval = 0.00001;   public RealSet(Double low, Double high, Predicate<Double> predicate) { this.low = low; this.high = high; this.predicate = predicate; }   public RealSet(Double start, Double end, RangeType rangeType) { this(start, end, d -> { switch (rangeType) { case CLOSED: return start <= d && d <= end; case BOTH_OPEN: return start < d && d < end; case LEFT_OPEN: return start < d && d <= end; case RIGHT_OPEN: return start <= d && d < end; default: throw new IllegalStateException("Unhandled range type encountered."); } }); }   public boolean contains(Double d) { return predicate.test(d); }   public RealSet union(RealSet other) { double low2 = Math.min(low, other.low); double high2 = Math.max(high, other.high); return new RealSet(low2, high2, d -> predicate.or(other.predicate).test(d)); }   public RealSet intersect(RealSet other) { double low2 = Math.min(low, other.low); double high2 = Math.max(high, other.high); return new RealSet(low2, high2, d -> predicate.and(other.predicate).test(d)); }   public RealSet subtract(RealSet other) { return new RealSet(low, high, d -> predicate.and(other.predicate.negate()).test(d)); }   public double length() { if (low.isInfinite() || high.isInfinite()) return -1.0; // error value if (high <= low) return 0.0; Double p = low; int count = 0; do { if (predicate.test(p)) count++; p += interval; } while (p < high); return count * interval; }   public boolean isEmpty() { if (Objects.equals(high, low)) { return predicate.negate().test(low); } return length() == 0.0; } }   public static void main(String[] args) { RealSet a = new RealSet(0.0, 1.0, RangeType.LEFT_OPEN); RealSet b = new RealSet(0.0, 2.0, RangeType.RIGHT_OPEN); RealSet c = new RealSet(1.0, 2.0, RangeType.LEFT_OPEN); RealSet d = new RealSet(0.0, 3.0, RangeType.RIGHT_OPEN); RealSet e = new RealSet(0.0, 1.0, RangeType.BOTH_OPEN); RealSet f = new RealSet(0.0, 1.0, RangeType.CLOSED); RealSet g = new RealSet(0.0, 0.0, RangeType.CLOSED);   for (int i = 0; i <= 2; i++) { Double dd = (double) i; System.out.printf("(0, 1] ∪ [0, 2) contains %d is %s\n", i, a.union(b).contains(dd)); System.out.printf("[0, 2) ∩ (1, 2] contains %d is %s\n", i, b.intersect(c).contains(dd)); System.out.printf("[0, 3) − (0, 1) contains %d is %s\n", i, d.subtract(e).contains(dd)); System.out.printf("[0, 3) − [0, 1] contains %d is %s\n", i, d.subtract(f).contains(dd)); System.out.println(); }   System.out.printf("[0, 0] is empty is %s\n", g.isEmpty()); System.out.println();   RealSet aa = new RealSet( 0.0, 10.0, x -> (0.0 < x && x < 10.0) && Math.abs(Math.sin(Math.PI * x * x)) > 0.5 ); RealSet bb = new RealSet( 0.0, 10.0, x -> (0.0 < x && x < 10.0) && Math.abs(Math.sin(Math.PI * x)) > 0.5 ); RealSet cc = aa.subtract(bb); System.out.printf("Approx length of A - B is %f\n", cc.length()); } }
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
Sequence of primes by trial division
Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by other numbers. You may use primes, or any numbers of your choosing, as long as the result is indeed a sequence of primes. The sequence may be bounded (i.e. up to some limit), unbounded, starting from the start (i.e. 2) or above some given value. Organize your function as you wish, in particular, it might resemble a filtering operation, or a sieving operation. If you want to use a ready-made is_prime function, use one from the Primality by trial division page (i.e., add yours there if it isn't there already). Related tasks   count in factors   prime decomposition   factors of an integer   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes
#C.23
C#
using System; using System.Collections.Generic; using System.Linq;   public class Program { static void Main() { Console.WriteLine(string.Join(" ", Primes(100))); }   static IEnumerable<int> Primes(int limit) => Enumerable.Range(2, limit-1).Where(IsPrime); static bool IsPrime(int n) => Enumerable.Range(2, (int)Math.Sqrt(n)-1).All(i => n % i != 0); }
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
Sequence of primes by trial division
Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by other numbers. You may use primes, or any numbers of your choosing, as long as the result is indeed a sequence of primes. The sequence may be bounded (i.e. up to some limit), unbounded, starting from the start (i.e. 2) or above some given value. Organize your function as you wish, in particular, it might resemble a filtering operation, or a sieving operation. If you want to use a ready-made is_prime function, use one from the Primality by trial division page (i.e., add yours there if it isn't there already). Related tasks   count in factors   prime decomposition   factors of an integer   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes
#C.2B.2B
C++
  #include <math.h> #include <iostream> #include <iomanip>   bool isPrime( unsigned u ) { if( u < 4 ) return u > 1; if( /*!( u % 2 ) ||*/ !( u % 3 ) ) return false;   unsigned q = static_cast<unsigned>( sqrt( static_cast<long double>( u ) ) ), c = 5; while( c <= q ) { if( !( u % c ) || !( u % ( c + 2 ) ) ) return false; c += 6; } return true; } int main( int argc, char* argv[] ) { unsigned mx = 100000000, wid = static_cast<unsigned>( log10( static_cast<long double>( mx ) ) ) + 1;   std::cout << "[" << std::setw( wid ) << 2 << " "; unsigned u = 3, p = 1; // <- start computing from 3 while( u < mx ) { if( isPrime( u ) ) { std::cout << std::setw( wid ) << u << " "; p++; } u += 2; } std::cout << "]\n\n Found " << p << " primes.\n\n"; return 0; }