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/Strip_comments_from_a_string
Strip comments from a string
Strip comments from a string You are encouraged to solve this task according to the task description, using any language you may know. The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line. Whitespace debacle:   There is some confusion about whether to remove any whitespace from the input line. As of 2 September 2011, at least 8 languages (C, C++, Java, Perl, Python, Ruby, sed, UNIX Shell) were incorrect, out of 36 total languages, because they did not trim whitespace by 29 March 2011 rules. Some other languages might be incorrect for the same reason. Please discuss this issue at Talk:Strip comments from a string. From 29 March 2011, this task required that: "The comment marker and any whitespace at the beginning or ends of the resultant line should be removed. A line without comments should be trimmed of any leading or trailing whitespace before being produced as a result." The task had 28 languages, which did not all meet this new requirement. From 28 March 2011, this task required that: "Whitespace before the comment marker should be removed." From 30 October 2010, this task did not specify whether or not to remove whitespace. The following examples will be truncated to either "apples, pears " or "apples, pears". (This example has flipped between "apples, pears " and "apples, pears" in the past.) apples, pears # and bananas apples, pears ; and bananas 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
#11l
11l
F remove_comments(line, sep) V? p = line.find(sep) I p != N R line[0.<p].rtrim(‘ ’) R line   print(remove_comments(‘apples ; pears # and bananas’, (‘;’, ‘#’))) print(remove_comments(‘apples ; pears # and bananas’, ‘#’)) print(remove_comments(‘apples ; pears # and bananas’, ‘!’))
http://rosettacode.org/wiki/Strip_block_comments
Strip block comments
A block comment begins with a   beginning delimiter   and ends with a   ending delimiter,   including the delimiters.   These delimiters are often multi-character sequences. Task Strip block comments from program text (of a programming language much like classic C). Your demos should at least handle simple, non-nested and multi-line block comment delimiters. The block comment delimiters are the two-character sequences:     /*     (beginning delimiter)     */     (ending delimiter) Sample text for stripping: /** * Some comments * longer comments here that we can parse. * * Rahoo */ function subroutine() { a = /* inline comment */ b + c ; } /*/ <-- tricky comments */ /** * Another comment. */ function something() { } Extra credit Ensure that the stripping code is not hard-coded to the particular delimiters described above, but instead allows the caller to specify them.   (If your language supports them,   optional parameters   may be useful for this.) 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
#11l
11l
F strip_comments(s, b_delim = ‘/*’, e_delim = ‘*/’) V r = ‘’ V i = 0 L V? p = s.find(b_delim, i) I p == N L.break r ‘’= s[i .< p] V? e = s.find(e_delim, p + b_delim.len) assert(e != N) i = e + e_delim.len r ‘’= s[i..] R r   V text = ‘ /** * Some comments * longer comments here that we can parse. * * Rahoo */ function subroutine() { a = /* inline comment */ b + c ; } /*/ <-- tricky comments */   /** * Another comment. */ function something() { }’   print(strip_comments(text))
http://rosettacode.org/wiki/Sum_to_100
Sum to 100
Task Find solutions to the   sum to one hundred   puzzle. Add (insert) the mathematical operators     +   or   -     (plus or minus)   before any of the digits in the decimal numeric string   123456789   such that the resulting mathematical expression adds up to a particular sum   (in this iconic case,   100). Example: 123 + 4 - 5 + 67 - 89 = 100 Show all output here.   Show all solutions that sum to   100   Show the sum that has the maximum   number   of solutions   (from zero to infinity‡)   Show the lowest positive sum that   can't   be expressed   (has no solutions),   using the rules for this task   Show the ten highest numbers that can be expressed using the rules for this task   (extra credit) ‡   (where   infinity   would be a relatively small   123,456,789) An example of a sum that can't be expressed   (within the rules of this task)   is:   5074 (which,   of course,   isn't the lowest positive sum that can't be expressed).
#Julia
Julia
using Printf, IterTools, DataStructures   expr(p::String...)::String = @sprintf("%s1%s2%s3%s4%s5%s6%s7%s8%s9", p...) function genexpr()::Vector{String} op = ["+", "-", ""] return collect(expr(p...) for (p) in Iterators.product(op, op, op, op, op, op, op, op, op) if p[1] != "+") end   using DataStructures   function allexpr()::Dict{Int,Int} rst = DefaultDict{Int,Int}(0) for e in genexpr() val = eval(Meta.parse(e)) rst[val] += 1 end return rst end   sumto(val::Int)::Vector{String} = filter(e -> eval(Meta.parse(e)) == val, genexpr()) function maxsolve()::Dict{Int,Int} ae = allexpr() vmax = maximum(values(ae)) smax = filter(ae) do (v, f) f == vmax end return smax end function minsolve()::Int ae = keys(allexpr()) for i in 1:typemax(Int) if i ∉ ae return i end end end function highestsums(n::Int)::Vector{Int} sums = collect(keys(allexpr())) return sort!(sums; rev=true)[1:n] end   const solutions = sumto(100) const smax = maxsolve() const smin = minsolve() const hsums = highestsums(10)   println("100 =") foreach(println, solutions)   println("\nMax number of solutions:") for (v, f) in smax @printf("%3i -> %2i\n", v, f) end   println("\nMin number with no solutions: $smin")   println("\nHighest sums representable:") foreach(println, hsums)  
http://rosettacode.org/wiki/Strip_control_codes_and_extended_characters_from_a_string
Strip control codes and extended characters from a string
Task Strip control codes and extended characters from a string. The solution should demonstrate how to achieve each of the following results:   a string with control codes stripped (but extended characters not stripped)   a string with control codes and extended characters stripped In ASCII, the control codes have decimal codes 0 through to 31 and 127. On an ASCII based system, if the control codes are stripped, the resultant string would have all of its characters within the range of 32 to 126 decimal on the ASCII table. On a non-ASCII based system, we consider characters that do not have a corresponding glyph on the ASCII table (within the ASCII range of 32 to 126 decimal) to be an extended character for the purpose of this task. 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
#8086_Assembly
8086 Assembly
.model small .stack 1024 .data StringStrip db "abc",13,10,8,7,"def",90h .code   start:   mov ax,@data mov ds,ax   mov ax,@code mov es,ax     mov ax,03h int 10h ;clear screen   mov si,offset StringStrip call PrintString_PartiallyStripped   call NewLine   mov si,offset StringStrip call PrintString_Stripped   mov ax,4C00h int 21h ;return to DOS   PrintString_Stripped: ;prints a null-terminated string ;all other control codes are stripped. lodsb cmp al,0 jz Terminated ;not equal to zero cmp al,21h ; if (AL < 21h) jb PrintString_Stripped ;skip this character and keep going cmp al,7Fh ; if (AL >= 7Fh) jae PrintString_Stripped ;skip this character and keep going mov ah,02h mov dl,al int 21h ;prints character in DL to screen jmp PrintString_Stripped Terminated: ret PrintString_PartiallyStripped: ;strips control codes but not extended ascii. ;The null terminator isn't stripped of course. lodsb cmp al,0 jz Terminated_PartiallyStripped cmp al,21h jb PrintString_PartiallyStripped cmp al,7Fh je PrintString_PartiallyStripped ;delete counts as a control code mov ah,02h mov dl,al int 21h jmp PrintString_PartiallyStripped Terminated_PartiallyStripped: ret   NewLine: mov ah,02h mov dl,13 ;carriage return int 10h mov ah,02h mov dl,10 ;line feed int 10h ret end start
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5
Sum multiples of 3 and 5
Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
#Emacs_Lisp
Emacs Lisp
(defun sum-3-5 (n) (let ((sum 0)) (dotimes (x n) (when (or (zerop (% x 3)) (zerop (% x 5))) (setq sum (+ sum x)))) sum))
http://rosettacode.org/wiki/Sum_digits_of_an_integer
Sum digits of an integer
Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
#Excel
Excel
digitSum =LAMBDA(s, FOLDROW( LAMBDA(a, LAMBDA(c, a + digitValue(c) ) ) )(0)( CHARSROW(s) ) )     digitValue =LAMBDA(c, LET( ic, UNICODE(MID(c, 1, 1)),   IF(AND(47 < ic, 58 > ic), ic - 48, IF(AND(64 < ic, 91 > ic), 10 + (ic - 65), IF(AND(96 < ic, 123 > ic), 10 + (ic - 97), 0 ) ) ) ) )
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#Fortran
Fortran
real, dimension(1000) :: a = (/ (i, i=1, 1000) /) real, pointer, dimension(:) :: p => a(2:1) ! pointer to zero-length array real :: result, zresult   result = sum(a*a) ! Multiply array by itself to get squares   result = sum(a**2) ! Use exponentiation operator to get squares   zresult = sum(p*p) ! P is zero-length; P*P is valid zero-length array expression; SUM(P*P) == 0.0 as expected
http://rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail
Strip whitespace from a string/Top and tail
Task Demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results: String with leading whitespace removed String with trailing whitespace removed String with both leading and trailing whitespace removed For the purposes of this task whitespace includes non printable characters such as the space character, the tab character, and other such characters that have no corresponding graphical representation. 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
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; with Ada.Strings; use Ada.Strings; with Ada.Strings.Fixed; use Ada.Strings.Fixed; procedure StripDemo is str : String := " Jabberwocky "; begin Put_Line ("'" & Trim (str, Left) & "'"); Put_Line ("'" & Trim (str, Right) & "'"); Put_Line ("'" & Trim (str, Both) & "'"); end StripDemo;
http://rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail
Strip whitespace from a string/Top and tail
Task Demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results: String with leading whitespace removed String with trailing whitespace removed String with both leading and trailing whitespace removed For the purposes of this task whitespace includes non printable characters such as the space character, the tab character, and other such characters that have no corresponding graphical representation. 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
#ALGOL_68
ALGOL 68
# returns "text" with leading non-printing characters removed # PROC trim leading whitespace = ( STRING text )STRING: BEGIN   INT pos := LWB text;   WHILE IF pos > UPB text THEN FALSE ELSE text[ pos ] <= " " FI DO pos +:= 1 OD;   text[ pos : ] END; # trim leading whitespace #   # returns "text" with trailing non-printing characters removed # PROC trim trailing whitespace = ( STRING text )STRING: BEGIN   INT pos := UPB text;   WHILE IF pos < LWB text THEN FALSE ELSE text[ pos ] <= " " FI DO pos -:= 1 OD;   text[ : pos ] END; # trim trailing whitespace #   # returns "text" with leading and trailing non-printing characters removed # PROC trim whitespace = ( STRING text )STRING: BEGIN trim trailing whitespace( trim leading whitespace( text ) ) END; # trim whitespace #     main:( STRING test = " leading and trailing spaces surrounded this text ";   print( ( "trim leading: """ + trim leading whitespace ( test ) + """", newline ) ); print( ( "trim trailing: """ + trim trailing whitespace( test ) + """", newline ) ); print( ( "trim both: """ + trim whitespace ( test ) + """", newline ) ) )
http://rosettacode.org/wiki/Strong_and_weak_primes
Strong and weak primes
Definitions   (as per number theory)   The   prime(p)   is the   pth   prime.   prime(1)   is   2   prime(4)   is   7   A   strong   prime   is when     prime(p)   is   >   [prime(p-1) + prime(p+1)] ÷ 2   A     weak    prime   is when     prime(p)   is   <   [prime(p-1) + prime(p+1)] ÷ 2 Note that the definition for   strong primes   is different when used in the context of   cryptography. Task   Find and display (on one line) the first   36   strong primes.   Find and display the   count   of the strong primes below   1,000,000.   Find and display the   count   of the strong primes below 10,000,000.   Find and display (on one line) the first   37   weak primes.   Find and display the   count   of the weak primes below   1,000,000.   Find and display the   count   of the weak primes below 10,000,000.   (Optional)   display the   counts   and   "below numbers"   with commas. Show all output here. Related Task   Safe primes and unsafe primes. Also see   The OEIS article A051634: strong primes.   The OEIS article A051635: weak primes.
#C.2B.2B
C++
#include <algorithm> #include <iostream> #include <iterator> #include <locale> #include <vector> #include "prime_sieve.hpp"   const int limit1 = 1000000; const int limit2 = 10000000;   class prime_info { public: explicit prime_info(int max) : max_print(max) {} void add_prime(int prime); void print(std::ostream& os, const char* name) const; private: int max_print; int count1 = 0; int count2 = 0; std::vector<int> primes; };   void prime_info::add_prime(int prime) { ++count2; if (prime < limit1) ++count1; if (count2 <= max_print) primes.push_back(prime); }   void prime_info::print(std::ostream& os, const char* name) const { os << "First " << max_print << " " << name << " primes: "; std::copy(primes.begin(), primes.end(), std::ostream_iterator<int>(os, " ")); os << '\n'; os << "Number of " << name << " primes below " << limit1 << ": " << count1 << '\n'; os << "Number of " << name << " primes below " << limit2 << ": " << count2 << '\n'; }   int main() { prime_sieve sieve(limit2 + 100);   // write numbers with groups of digits separated according to the system default locale std::cout.imbue(std::locale(""));   // count and print strong/weak prime numbers prime_info strong_primes(36); prime_info weak_primes(37); int p1 = 2, p2 = 3; for (int p3 = 5; p2 < limit2; ++p3) { if (!sieve.is_prime(p3)) continue; int diff = p1 + p3 - 2 * p2; if (diff < 0) strong_primes.add_prime(p2); else if (diff > 0) weak_primes.add_prime(p2); p1 = p2; p2 = p3; } strong_primes.print(std::cout, "strong"); weak_primes.print(std::cout, "weak"); return 0; }
http://rosettacode.org/wiki/Substring
Substring
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Display a substring:   starting from   n   characters in and of   m   length;   starting from   n   characters in,   up to the end of the string;   whole string minus the last character;   starting from a known   character   within the string and of   m   length;   starting from a known   substring   within the string and of   m   length. If the program uses UTF-8 or UTF-16,   it must work on any valid Unicode code point, whether in the   Basic Multilingual Plane   or above it. The program must reference logical characters (code points),   not 8-bit code units for UTF-8 or 16-bit code units for UTF-16. Programs for other encodings (such as 8-bit ASCII, or EUC-JP) are not required to handle all Unicode characters. 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
#Aime
Aime
text s; data b, d;   s = "The quick brown fox jumps over the lazy dog.";   o_text(cut(s, 4, 15)); o_newline(); o_text(cut(s, 4, length(s))); o_newline(); o_text(delete(s, -1)); o_newline(); o_text(cut(s, index(s, 'q'), 5)); o_newline();   b_cast(b, s); b_cast(d, "brown"); o_text(cut(s, b_find(b, d), 15)); o_newline();
http://rosettacode.org/wiki/Substring
Substring
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Display a substring:   starting from   n   characters in and of   m   length;   starting from   n   characters in,   up to the end of the string;   whole string minus the last character;   starting from a known   character   within the string and of   m   length;   starting from a known   substring   within the string and of   m   length. If the program uses UTF-8 or UTF-16,   it must work on any valid Unicode code point, whether in the   Basic Multilingual Plane   or above it. The program must reference logical characters (code points),   not 8-bit code units for UTF-8 or 16-bit code units for UTF-16. Programs for other encodings (such as 8-bit ASCII, or EUC-JP) are not required to handle all Unicode characters. 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
#ALGOL_68
ALGOL 68
main: ( STRING s = "abcdefgh"; INT n = 2, m = 3; CHAR char = "d"; STRING chars = "cd";   printf(($gl$, s[n:n+m-1])); printf(($gl$, s[n:])); printf(($gl$, s[:UPB s-1]));   INT pos; char in string("d", pos, s); printf(($gl$, s[pos:pos+m-1])); string in string("de", pos, s); printf(($gl$, s[pos:pos+m-1])) )
http://rosettacode.org/wiki/Sudoku
Sudoku
Task Solve a partially filled-in normal   9x9   Sudoku grid   and display the result in a human-readable format. references Algorithmics of Sudoku   may help implement this. Python Sudoku Solver Computerphile video.
#BCPL
BCPL
// This can be run using Cintcode BCPL freely available from www.cl.cam.ac.uk/users/mr10. // Implemented by Martin Richards.   // If you have cintcode BCPL installed on a Linux system you can compile and run this program // execute the following sequence of commands.   // cd $BCPLROOT // cintsys // c bc sudoku // sudoku   // This is a really naive program to solve SuDoku problems. Even so it is usually quite fast.   // SuDoku consists of a 9x9 grid of cells. Each cell should contain // a digit in the range 1..9. Every row, column and major 3x3 // square should contain all the digits 1..9. Some cells have // given values. The problem is to find digits to place in // the unspecified cells satisfying the constraints.   // A typical problem is:   // - - - 6 3 8 - - - // 7 - 6 - - - 3 - 5 // - 1 - - - - - 4 -   // - - 8 7 1 2 4 - - // - 9 - - - - - 5 - // - - 2 5 6 9 1 - -   // - 3 - - - - - 1 - // 1 - 5 - - - 6 - 8 // - - - 1 8 4 - - -   SECTION "sudoku"   GET "libhdr"   GLOBAL { count:ug   // The 9x9 board   a1; a2; a3; a4; a5; a6; a7; a8; a9 b1; b2; b3; b4; b5; b6; b7; b8; b9 c1; c2; c3; c4; c5; c6; c7; c8; c9 d1; d2; d3; d4; d5; d6; d7; d8; d9 e1; e2; e3; e4; e5; e6; e7; e8; e9 f1; f2; f3; f4; f5; f6; f7; f8; f9 g1; g2; g3; g4; g5; g6; g7; g8; g9 h1; h2; h3; h4; h5; h6; h7; h8; h9 i1; i2; i3; i4; i5; i6; i7; i8; i9 }   MANIFEST { N1=1<<0; N2=1<<1; N3=1<<2; N4=1<<3; N5=1<<4; N6=1<<5; N7=1<<6; N8=1<<7; N9=1<<8 }   LET start() = VALOF { count := 0 initboard() prboard() ta1() writef("*n*nTotal number of solutions: %n*n", count) RESULTIS 0 }   AND initboard() BE { a1, a2, a3, a4, a5, a6, a7, a8, a9 := 0, 0, 0, N6,N3,N8, 0, 0, 0 b1, b2, b3, b4, b5, b6, b7, b8, b9 := N7, 0,N6, 0, 0, 0, N3, 0,N5 c1, c2, c3, c4, c5, c6, c7, c8, c9 := 0,N1, 0, 0, 0, 0, 0,N4, 0 d1, d2, d3, d4, d5, d6, d7, d8, d9 := 0, 0,N8, N7,N1,N2, N4, 0, 0 e1, e2, e3, e4, e5, e6, e7, e8, e9 := 0,N9, 0, 0, 0, 0, 0,N5, 0 f1, f2, f3, f4, f5, f6, f7, f8, f9 := 0, 0,N2, N5,N6,N9, N1, 0, 0 g1, g2, g3, g4, g5, g6, g7, g8, g9 := 0,N3, 0, 0, 0, 0, 0,N1, 0 h1, h2, h3, h4, h5, h6, h7, h8, h9 := N1, 0,N5, 0, 0, 0, N6, 0,N8 i1, i2, i3, i4, i5, i6, i7, i8, i9 := 0, 0, 0, N1,N8,N4, 0, 0, 0   // Un-comment the following to test that the backtracking works // giving 184 solutions. //h1, h2, h3, h4, h5, h6, h7, h8, h9 := N1, 0,N5, 0, 0, 0, N6, 0, 0 //i1, i2, i3, i4, i5, i6, i7, i8, i9 := 0, 0, 0, 0, 0, 0, 0, 0, 0 }   AND c(n) = VALOF SWITCHON n INTO { DEFAULT: RESULTIS '?' CASE 0: RESULTIS '-' CASE N1: RESULTIS '1' CASE N2: RESULTIS '2' CASE N3: RESULTIS '3' CASE N4: RESULTIS '4' CASE N5: RESULTIS '5' CASE N6: RESULTIS '6' CASE N7: RESULTIS '7' CASE N8: RESULTIS '8' CASE N9: RESULTIS '9' }   AND prboard() BE { LET form = "%c %c %c  %c %c %c  %c %c %c*n" writef("*ncount = %n*n", count) newline() writef(form, c(a1),c(a2),c(a3),c(a4),c(a5),c(a6),c(a7),c(a8),c(a9)) writef(form, c(b1),c(b2),c(b3),c(b4),c(b5),c(b6),c(b7),c(b8),c(b9)) writef(form, c(c1),c(c2),c(c3),c(c4),c(c5),c(c6),c(c7),c(c8),c(c9)) newline() writef(form, c(d1),c(d2),c(d3),c(d4),c(d5),c(d6),c(d7),c(d8),c(d9)) writef(form, c(e1),c(e2),c(e3),c(e4),c(e5),c(e6),c(e7),c(e8),c(e9)) writef(form, c(f1),c(f2),c(f3),c(f4),c(f5),c(f6),c(f7),c(f8),c(f9)) newline() writef(form, c(g1),c(g2),c(g3),c(g4),c(g5),c(g6),c(g7),c(g8),c(g9)) writef(form, c(h1),c(h2),c(h3),c(h4),c(h5),c(h6),c(h7),c(h8),c(h9)) writef(form, c(i1),c(i2),c(i3),c(i4),c(i5),c(i6),c(i7),c(i8),c(i9))   newline()   //abort(1000) }   AND try(p, f, row, col, sq) BE { LET x = !p TEST x THEN f() ELSE { LET bits = row|col|sq //prboard() // writef("x=%n %b9*n", x, bits) //abort(1000) IF (N1&bits)=0 DO { !p:=N1; f() } IF (N2&bits)=0 DO { !p:=N2; f() } IF (N3&bits)=0 DO { !p:=N3; f() } IF (N4&bits)=0 DO { !p:=N4; f() } IF (N5&bits)=0 DO { !p:=N5; f() } IF (N6&bits)=0 DO { !p:=N6; f() } IF (N7&bits)=0 DO { !p:=N7; f() } IF (N8&bits)=0 DO { !p:=N8; f() } IF (N9&bits)=0 DO { !p:=N9; f() }  !p := 0 } }   AND ta1() BE try(@a1, ta2, a1+a2+a3+a4+a5+a6+a7+a8+a9, a1+b1+c1+d1+e1+f1+g1+h1+i1, a1+a2+a3+b1+b2+b3+c1+c2+c3) AND ta2() BE try(@a2, ta3, a1+a2+a3+a4+a5+a6+a7+a8+a9, a2+b2+c2+d2+e2+f2+g2+h2+i2, a1+a2+a3+b1+b2+b3+c1+c2+c3) AND ta3() BE try(@a3, ta4, a1+a2+a3+a4+a5+a6+a7+a8+a9, a3+b3+c3+d3+e3+f3+g3+h3+i3, a1+a2+a3+b1+b2+b3+c1+c2+c3) AND ta4() BE try(@a4, ta5, a1+a2+a3+a4+a5+a6+a7+a8+a9, a4+b4+c4+d4+e4+f4+g4+h4+i4, a4+a5+a6+b4+b5+b6+c4+c5+c6) AND ta5() BE try(@a5, ta6, a1+a2+a3+a4+a5+a6+a7+a8+a9, a5+b5+c5+d5+e5+f5+g5+h5+i5, a4+a5+a6+b4+b5+b6+c4+c5+c6) AND ta6() BE try(@a6, ta7, a1+a2+a3+a4+a5+a6+a7+a8+a9, a6+b6+c6+d6+e6+f6+g6+h6+i6, a4+a5+a6+b4+b5+b6+c4+c5+c6) AND ta7() BE try(@a7, ta8, a1+a2+a3+a4+a5+a6+a7+a8+a9, a7+b7+c7+d7+e7+f7+g7+h7+i7, a7+a8+a9+b7+b8+b9+c7+c8+c9) AND ta8() BE try(@a8, ta9, a1+a2+a3+a4+a5+a6+a7+a8+a9, a8+b8+c8+d8+e8+f8+g8+h8+i8, a7+a8+a9+b7+b8+b9+c7+c8+c9) AND ta9() BE try(@a9, tb1, a1+a2+a3+a4+a5+a6+a7+a8+a9, a9+b9+c9+d9+e9+f9+g9+h9+i9, a7+a8+a9+b7+b8+b9+c7+c8+c9)   AND tb1() BE try(@b1, tb2, b1+b2+b3+b4+b5+b6+b7+b8+b9, a1+b1+c1+d1+e1+f1+g1+h1+i1, a1+a2+a3+b1+b2+b3+c1+c2+c3) AND tb2() BE try(@b2, tb3, b1+b2+b3+b4+b5+b6+b7+b8+b9, a2+b2+c2+d2+e2+f2+g2+h2+i2, a1+a2+a3+b1+b2+b3+c1+c2+c3) AND tb3() BE try(@b3, tb4, b1+b2+b3+b4+b5+b6+b7+b8+b9, a3+b3+c3+d3+e3+f3+g3+h3+i3, a1+a2+a3+b1+b2+b3+c1+c2+c3) AND tb4() BE try(@b4, tb5, b1+b2+b3+b4+b5+b6+b7+b8+b9, a4+b4+c4+d4+e4+f4+g4+h4+i4, a4+a5+a6+b4+b5+b6+c4+c5+c6) AND tb5() BE try(@b5, tb6, b1+b2+b3+b4+b5+b6+b7+b8+b9, a5+b5+c5+d5+e5+f5+g5+h5+i5, a4+a5+a6+b4+b5+b6+c4+c5+c6) AND tb6() BE try(@b6, tb7, b1+b2+b3+b4+b5+b6+b7+b8+b9, a6+b6+c6+d6+e6+f6+g6+h6+i6, a4+a5+a6+b4+b5+b6+c4+c5+c6) AND tb7() BE try(@b7, tb8, b1+b2+b3+b4+b5+b6+b7+b8+b9, a7+b7+c7+d7+e7+f7+g7+h7+i7, a7+a8+a9+b7+b8+b9+c7+c8+c9) AND tb8() BE try(@b8, tb9, b1+b2+b3+b4+b5+b6+b7+b8+b9, a8+b8+c8+d8+e8+f8+g8+h8+i8, a7+a8+a9+b7+b8+b9+c7+c8+c9) AND tb9() BE try(@b9, tc1, b1+b2+b3+b4+b5+b6+b7+b8+b9, a9+b9+c9+d9+e9+f9+g9+h9+i9, a7+a8+a9+b7+b8+b9+c7+c8+c9)   AND tc1() BE try(@c1, tc2, c1+c2+c3+c4+c5+c6+c7+c8+c9, a1+b1+c1+d1+e1+f1+g1+h1+i1, a1+a2+a3+b1+b2+b3+c1+c2+c3) AND tc2() BE try(@c2, tc3, c1+c2+c3+c4+c5+c6+c7+c8+c9, a2+b2+c2+d2+e2+f2+g2+h2+i2, a1+a2+a3+b1+b2+b3+c1+c2+c3) AND tc3() BE try(@c3, tc4, c1+c2+c3+c4+c5+c6+c7+c8+c9, a3+b3+c3+d3+e3+f3+g3+h3+i3, a1+a2+a3+b1+b2+b3+c1+c2+c3) AND tc4() BE try(@c4, tc5, c1+c2+c3+c4+c5+c6+c7+c8+c9, a4+b4+c4+d4+e4+f4+g4+h4+i4, a4+a5+a6+b4+b5+b6+c4+c5+c6) AND tc5() BE try(@c5, tc6, c1+c2+c3+c4+c5+c6+c7+c8+c9, a5+b5+c5+d5+e5+f5+g5+h5+i5, a4+a5+a6+b4+b5+b6+c4+c5+c6) AND tc6() BE try(@c6, tc7, c1+c2+c3+c4+c5+c6+c7+c8+c9, a6+b6+c6+d6+e6+f6+g6+h6+i6, a4+a5+a6+b4+b5+b6+c4+c5+c6) AND tc7() BE try(@c7, tc8, c1+c2+c3+c4+c5+c6+c7+c8+c9, a7+b7+c7+d7+e7+f7+g7+h7+i7, a7+a8+a9+b7+b8+b9+c7+c8+c9) AND tc8() BE try(@c8, tc9, c1+c2+c3+c4+c5+c6+c7+c8+c9, a8+b8+c8+d8+e8+f8+g8+h8+i8, a7+a8+a9+b7+b8+b9+c7+c8+c9) AND tc9() BE try(@c9, td1, c1+c2+c3+c4+c5+c6+c7+c8+c9, a9+b9+c9+d9+e9+f9+g9+h9+i9, a7+a8+a9+b7+b8+b9+c7+c8+c9)   AND td1() BE try(@d1, td2, d1+d2+d3+d4+d5+d6+d7+d8+d9, a1+b1+c1+d1+e1+f1+g1+h1+i1, d1+d2+d3+e1+e2+e3+f1+f2+f3) AND td2() BE try(@d2, td3, d1+d2+d3+d4+d5+d6+d7+d8+d9, a2+b2+c2+d2+e2+f2+g2+h2+i2, d1+d2+d3+e1+e2+e3+f1+f2+f3) AND td3() BE try(@d3, td4, d1+d2+d3+d4+d5+d6+d7+d8+d9, a3+b3+c3+d3+e3+f3+g3+h3+i3, d1+d2+d3+e1+e2+e3+f1+f2+f3) AND td4() BE try(@d4, td5, d1+d2+d3+d4+d5+d6+d7+d8+d9, a4+b4+c4+d4+e4+f4+g4+h4+i4, d4+d5+d6+e4+e5+e6+f4+f5+f6) AND td5() BE try(@d5, td6, d1+d2+d3+d4+d5+d6+d7+d8+d9, a5+b5+c5+d5+e5+f5+g5+h5+i5, d4+d5+d6+e4+e5+e6+f4+f5+f6) AND td6() BE try(@d6, td7, d1+d2+d3+d4+d5+d6+d7+d8+d9, a6+b6+c6+d6+e6+f6+g6+h6+i6, d4+d5+d6+e4+e5+e6+f4+f5+f6) AND td7() BE try(@d7, td8, d1+d2+d3+d4+d5+d6+d7+d8+d9, a7+b7+c7+d7+e7+f7+g7+h7+i7, d7+d8+d9+e7+e8+e9+f7+f8+f9) AND td8() BE try(@d8, td9, d1+d2+d3+d4+d5+d6+d7+d8+d9, a8+b8+c8+d8+e8+f8+g8+h8+i8, d7+d8+d9+e7+e8+e9+f7+f8+f9) AND td9() BE try(@d9, te1, d1+d2+d3+d4+d5+d6+d7+d8+d9, a9+b9+c9+d9+e9+f9+g9+h9+i9, d7+d8+d9+e7+e8+e9+f7+f8+f9)   AND te1() BE try(@e1, te2, e1+e2+e3+e4+e5+e6+e7+e8+e9, a1+b1+c1+d1+e1+f1+g1+h1+i1, d1+d2+d3+e1+e2+e3+f1+f2+f3) AND te2() BE try(@e2, te3, e1+e2+e3+e4+e5+e6+e7+e8+e9, a2+b2+c2+d2+e2+f2+g2+h2+i2, d1+d2+d3+e1+e2+e3+f1+f2+f3) AND te3() BE try(@e3, te4, e1+e2+e3+e4+e5+e6+e7+e8+e9, a3+b3+c3+d3+e3+f3+g3+h3+i3, d1+d2+d3+e1+e2+e3+f1+f2+f3) AND te4() BE try(@e4, te5, e1+e2+e3+e4+e5+e6+e7+e8+e9, a4+b4+c4+d4+e4+f4+g4+h4+i4, d4+d5+d6+e4+e5+e6+f4+f5+f6) AND te5() BE try(@e5, te6, e1+e2+e3+e4+e5+e6+e7+e8+e9, a5+b5+c5+d5+e5+f5+g5+h5+i5, d4+d5+d6+e4+e5+e6+f4+f5+f6) AND te6() BE try(@e6, te7, e1+e2+e3+e4+e5+e6+e7+e8+e9, a6+b6+c6+d6+e6+f6+g6+h6+i6, d4+d5+d6+e4+e5+e6+f4+f5+f6) AND te7() BE try(@e7, te8, e1+e2+e3+e4+e5+e6+e7+e8+e9, a7+b7+c7+d7+e7+f7+g7+h7+i7, d7+d8+d9+e7+e8+e9+f7+f8+f9) AND te8() BE try(@e8, te9, e1+e2+e3+e4+e5+e6+e7+e8+e9, a8+b8+c8+d8+e8+f8+g8+h8+i8, d7+d8+d9+e7+e8+e9+f7+f8+f9) AND te9() BE try(@e9, tf1, e1+e2+e3+e4+e5+e6+e7+e8+e9, a9+b9+c9+d9+e9+f9+g9+h9+i9, d7+d8+d9+e7+e8+e9+f7+f8+f9)   AND tf1() BE try(@f1, tf2, f1+f2+f3+f4+f5+f6+f7+f8+f9, a1+b1+c1+d1+e1+f1+g1+h1+i1, d1+d2+d3+e1+e2+e3+f1+f2+f3) AND tf2() BE try(@f2, tf3, f1+f2+f3+f4+f5+f6+f7+f8+f9, a2+b2+c2+d2+e2+f2+g2+h2+i2, d1+d2+d3+e1+e2+e3+f1+f2+f3) AND tf3() BE try(@f3, tf4, f1+f2+f3+f4+f5+f6+f7+f8+f9, a3+b3+c3+d3+e3+f3+g3+h3+i3, d1+d2+d3+e1+e2+e3+f1+f2+f3) AND tf4() BE try(@f4, tf5, f1+f2+f3+f4+f5+f6+f7+f8+f9, a4+b4+c4+d4+e4+f4+g4+h4+i4, d4+d5+d6+e4+e5+e6+f4+f5+f6) AND tf5() BE try(@f5, tf6, f1+f2+f3+f4+f5+f6+f7+f8+f9, a5+b5+c5+d5+e5+f5+g5+h5+i5, d4+d5+d6+e4+e5+e6+f4+f5+f6) AND tf6() BE try(@f6, tf7, f1+f2+f3+f4+f5+f6+f7+f8+f9, a6+b6+c6+d6+e6+f6+g6+h6+i6, d4+d5+d6+e4+e5+e6+f4+f5+f6) AND tf7() BE try(@f7, tf8, f1+f2+f3+f4+f5+f6+f7+f8+f9, a7+b7+c7+d7+e7+f7+g7+h7+i7, d7+d8+d9+e7+e8+e9+f7+f8+f9) AND tf8() BE try(@f8, tf9, f1+f2+f3+f4+f5+f6+f7+f8+f9, a8+b8+c8+d8+e8+f8+g8+h8+i8, d7+d8+d9+e7+e8+e9+f7+f8+f9) AND tf9() BE try(@f9, tg1, f1+f2+f3+f4+f5+f6+f7+f8+f9, a9+b9+c9+d9+e9+f9+g9+h9+i9, d7+d8+d9+e7+e8+e9+f7+f8+f9)   AND tg1() BE try(@g1, tg2, g1+g2+g3+g4+g5+g6+g7+g8+g9, a1+b1+c1+d1+e1+f1+g1+h1+i1, g1+g2+g3+h1+h2+h3+i1+i2+i3) AND tg2() BE try(@g2, tg3, g1+g2+g3+g4+g5+g6+g7+g8+g9, a2+b2+c2+d2+e2+f2+g2+h2+i2, g1+g2+g3+h1+h2+h3+i1+i2+i3) AND tg3() BE try(@g3, tg4, g1+g2+g3+g4+g5+g6+g7+g8+g9, a3+b3+c3+d3+e3+f3+g3+h3+i3, g1+g2+g3+h1+h2+h3+i1+i2+i3) AND tg4() BE try(@g4, tg5, g1+g2+g3+g4+g5+g6+g7+g8+g9, a4+b4+c4+d4+e4+f4+g4+h4+i4, g4+g5+g6+h4+h5+h6+i4+i5+i6) AND tg5() BE try(@g5, tg6, g1+g2+g3+g4+g5+g6+g7+g8+g9, a5+b5+c5+d5+e5+f5+g5+h5+i5, g4+g5+g6+h4+h5+h6+i4+i5+i6) AND tg6() BE try(@g6, tg7, g1+g2+g3+g4+g5+g6+g7+g8+g9, a6+b6+c6+d6+e6+f6+g6+h6+i6, g4+g5+g6+h4+h5+h6+i4+i5+i6) AND tg7() BE try(@g7, tg8, g1+g2+g3+g4+g5+g6+g7+g8+g9, a7+b7+c7+d7+e7+f7+g7+h7+i7, g7+g8+g9+h7+h8+h9+i7+i8+i9) AND tg8() BE try(@g8, tg9, g1+g2+g3+g4+g5+g6+g7+g8+g9, a8+b8+c8+d8+e8+f8+g8+h8+i8, g7+g8+g9+h7+h8+h9+i7+i8+i9) AND tg9() BE try(@g9, th1, g1+g2+g3+g4+g5+g6+g7+g8+g9, a9+b9+c9+d9+e9+f9+g9+h9+i9, g7+g8+g9+h7+h8+h9+i7+i8+i9)   AND th1() BE try(@h1, th2, h1+h2+h3+h4+h5+h6+h7+h8+h9, a1+b1+c1+d1+e1+f1+g1+h1+i1, g1+g2+g3+h1+h2+h3+i1+i2+i3) AND th2() BE try(@h2, th3, h1+h2+h3+h4+h5+h6+h7+h8+h9, a2+b2+c2+d2+e2+f2+g2+h2+i2, g1+g2+g3+h1+h2+h3+i1+i2+i3) AND th3() BE try(@h3, th4, h1+h2+h3+h4+h5+h6+h7+h8+h9, a3+b3+c3+d3+e3+f3+g3+h3+i3, g1+g2+g3+h1+h2+h3+i1+i2+i3) AND th4() BE try(@h4, th5, h1+h2+h3+h4+h5+h6+h7+h8+h9, a4+b4+c4+d4+e4+f4+g4+h4+i4, g4+g5+g6+h4+h5+h6+i4+i5+i6) AND th5() BE try(@h5, th6, h1+h2+h3+h4+h5+h6+h7+h8+h9, a5+b5+c5+d5+e5+f5+g5+h5+i5, g4+g5+g6+h4+h5+h6+i4+i5+i6) AND th6() BE try(@h6, th7, h1+h2+h3+h4+h5+h6+h7+h8+h9, a6+b6+c6+d6+e6+f6+g6+h6+i6, g4+g5+g6+h4+h5+h6+i4+i5+i6) AND th7() BE try(@h7, th8, h1+h2+h3+h4+h5+h6+h7+h8+h9, a7+b7+c7+d7+e7+f7+g7+h7+i7, g7+g8+g9+h7+h8+h9+i7+i8+i9) AND th8() BE try(@h8, th9, h1+h2+h3+h4+h5+h6+h7+h8+h9, a8+b8+c8+d8+e8+f8+g8+h8+i8, g7+g8+g9+h7+h8+h9+i7+i8+i9) AND th9() BE try(@h9, ti1, h1+h2+h3+h4+h5+h6+h7+h8+h9, a9+b9+c9+d9+e9+f9+g9+h9+i9, g7+g8+g9+h7+h8+h9+i7+i8+i9)   AND ti1() BE try(@i1, ti2, i1+i2+i3+i4+i5+i6+i7+i8+i9, a1+b1+c1+d1+e1+f1+g1+h1+i1, g1+g2+g3+h1+h2+h3+i1+i2+i3) AND ti2() BE try(@i2, ti3, i1+i2+i3+i4+i5+i6+i7+i8+i9, a2+b2+c2+d2+e2+f2+g2+h2+i2, g1+g2+g3+h1+h2+h3+i1+i2+i3) AND ti3() BE try(@i3, ti4, i1+i2+i3+i4+i5+i6+i7+i8+i9, a3+b3+c3+d3+e3+f3+g3+h3+i3, g1+g2+g3+h1+h2+h3+i1+i2+i3) AND ti4() BE try(@i4, ti5, i1+i2+i3+i4+i5+i6+i7+i8+i9, a4+b4+c4+d4+e4+f4+g4+h4+i4, g4+g5+g6+h4+h5+h6+i4+i5+i6) AND ti5() BE try(@i5, ti6, i1+i2+i3+i4+i5+i6+i7+i8+i9, a5+b5+c5+d5+e5+f5+g5+h5+i5, g4+g5+g6+h4+h5+h6+i4+i5+i6) AND ti6() BE try(@i6, ti7, i1+i2+i3+i4+i5+i6+i7+i8+i9, a6+b6+c6+d6+e6+f6+g6+h6+i6, g4+g5+g6+h4+h5+h6+i4+i5+i6) AND ti7() BE try(@i7, ti8, i1+i2+i3+i4+i5+i6+i7+i8+i9, a7+b7+c7+d7+e7+f7+g7+h7+i7, g7+g8+g9+h7+h8+h9+i7+i8+i9) AND ti8() BE try(@i8, ti9, i1+i2+i3+i4+i5+i6+i7+i8+i9, a8+b8+c8+d8+e8+f8+g8+h8+i8, g7+g8+g9+h7+h8+h9+i7+i8+i9) AND ti9() BE try(@i9, suc, i1+i2+i3+i4+i5+i6+i7+i8+i9, a9+b9+c9+d9+e9+f9+g9+h9+i9, g7+g8+g9+h7+h8+h9+i7+i8+i9)   AND suc() BE { count := count + 1 prboard() }
http://rosettacode.org/wiki/Subleq
Subleq
Subleq is an example of a One-Instruction Set Computer (OISC). It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero. Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory consists of an array of signed integers.   These integers may be interpreted in three ways:   simple numeric values   memory addresses   characters for input or output Any reasonable word size that accommodates all three of the above uses is fine. The program should load the initial contents of the emulated machine's memory, set the instruction pointer to the first address (which is defined to be address 0), and begin emulating the machine, which works as follows:   Let A be the value in the memory location identified by the instruction pointer;   let B and C be the values stored in the next two consecutive addresses in memory.   Advance the instruction pointer three words, to point at the address after the address containing C.   If A is   -1   (negative unity),   then a character is read from the machine's input and its numeric value stored in the address given by B.   C is unused.   If B is   -1   (negative unity),   then the number contained in the address given by A is interpreted as a character and written to the machine's output.   C is unused.   Otherwise, both A and B are treated as addresses.   The number contained in address A is subtracted from the number in address B (and the difference left in address B).   If the result is positive, execution continues uninterrupted; if the result is zero or negative, the number in C becomes the new instruction pointer.   If the instruction pointer becomes negative, execution halts. Your solution may initialize the emulated machine's memory in any convenient manner, but if you accept it as input, it should be a separate input stream from the one fed to the emulated machine once it is running. And if fed as text input, it should be in the form of raw subleq "machine code" - whitespace-separated decimal numbers, with no symbolic names or other assembly-level extensions, to be loaded into memory starting at address   0   (zero). For purposes of this task, show the output of your solution when fed the below   "Hello, world!"   program. As written, this example assumes ASCII or a superset of it, such as any of the Latin-N character sets or Unicode;   you may translate the numbers representing characters (starting with 72=ASCII 'H') into another character set if your implementation runs in a non-ASCII-compatible environment. If 0 is not an appropriate terminator in your character set, the program logic will need some adjustment as well. 15 17 -1 17 -1 -1 16 1 -1 16 3 -1 15 15 0 0 -1 72 101 108 108 111 44 32 119 111 114 108 100 33 10 0 The above "machine code" corresponds to something like this in a hypothetical assembler language for a signed 8-bit version of the machine: start: 0f 11 ff subleq (zero), (message), -1 11 ff ff subleq (message), -1, -1  ; output character at message 10 01 ff subleq (neg1), (start+1), -1 10 03 ff subleq (neg1), (start+3), -1 0f 0f 00 subleq (zero), (zero), start ; useful constants zero: 00 .data 0 neg1: ff .data -1 ; the message to print message: .data "Hello, world!\n\0" 48 65 6c 6c 6f 2c 20 77 6f 72 6c 64 21 0a 00
#ARM_Assembly
ARM Assembly
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@ ARM SUBLEQ for Linux @@@ @@@ Word size is 32 bits. The program is @@@ @@@ given 8 MB (2 Mwords) to run in. @@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ .text .global _start @@@ Linux syscalls .equ exit, 1 .equ read, 3 .equ write, 4 .equ open, 5 _start: pop {r6} @ Retrieve amount of arguments cmp r6,#2 @ There should be exactly 2 (incl program) ldrne r1,=usage @ Otherwise, print usage and stop bne die pop {r0,r1} @ Retrieve filename mov r0,r1 mov r1,#0 @ Try to open the file in read mode mov r2,#0 mov r7,#open swi #0 movs r5,r0 @ File handle in R5 ldrmi r1,=efile @ If the file can't be opened, error bmi die ldr r8,=prog @ R8 = pointer into program mov r6,#0 @ At the beginning, there is no data rdnum: bl fchar @ Skip past whitespace cmp r0,#32 bls rdnum mov r9,#0 @ R9 = current number being read subs r10,r0,#'- @ R10 is zero if number is negative bleq fchar @ And get next character 1: sub r0,r0,#'0 @ Subtract ASCII 0 cmp r0,#9 ldrhi r1,=echar bhi die @ Invalid digit = error mov r1,#10 mla r0,r9,r1,r0 @ Multiply accumulator by 10 and add digit mov r9,r0 bl fchar @ Get next character cmp r0,#32 @ If it isn't whitespace... bhi 1b @ ...then it's the next digit tst r10,r10 @ If the number should be negative, rsbeq r9,r9,#0 @ ...then negate it str r9,[r8],#4 @ Store the number b rdnum @ And get the next number. setup: ldr r0,=prog @ Zero out the rest of program memory sub r0,r8,r0 @ Zero to 8-word (32-byte) boundary orr r0,r0,#31 @ Find address of last byte within add r0,r0,r8 @ current 31-byte block mov r1,#0 @ R1 = zero to write 1: str r1,[r8],#4 @ Write zeroes, cmp r0,r8 @ until boundary reached. blo 1b mov r0,#0 @ 8 words of zeroes in r0-r7 umull r2,r3,r0,r1 @ A trick to produce 2 zero words in one umull r4,r5,r0,r1 @ go: 0*0 = 0, long multiplication umull r6,r7,r0,r1 @ results in 2 words. ldr r9,=mem_end 2: stmia r8!,{r0-r7} @ Write 8 zero words at a time cmp r8,r9 @ Are we at mem_end yet? blo 2b @ If not, keep going ldr r8,=prog @ R8 = IP, starts at beginning ldr r6,=prog @ R6 = base address for memory mov r12,#0xFFFF @ 0x1FFFFF = address mask movt r12,#0x1F instr: ldmia r8!,{r9-r11} @ R9, R10, R11 = A, B, C cmp r9,#-1 @ If A=-1, get character beq rchar cmp r10,#-1 @ Otherwise, if B=-1, write character beq wchar and r9,r9,r12 @ Keep addresses within 2 Mwords and r10,r10,r12 ldr r0,[r6,r9,lsl #2] @ Grab [A] and [B] ldr r1,[r6,r10,lsl #2] subs r1,r1,r0 @ Subtract str r1,[r6,r10,lsl #2] @ Store back in [B] cmpmi r0,r0 @ Set zero flag if negative bne instr @ If result is positive, next instruction lsls r8,r11,#2 @ Otherwise, C becomes the new IP add r8,r8,r6 bpl instr @ If result is positive, keep going mov r0,#0 @ Otherwise, we exit mov r7,#exit swi #0 @@@ Read character into [B] rchar: mov r0,#0 @ STDIN and r10,r10,r12 @ Address of B add r10,r6,r10,lsl #2 @ Kept in R10 out of harm's way mov r1,r10 mov r2,#1 @ Read one character mov r7,#read swi #0 cmp r0,#1 @ We should have received 1 byte movne r1,#-1 @ If not, write -1 ldreqb r1,[r10] @ Otherwise, blank out the top 3 bytes str r1,[r10] b instr @@@ Write character in [A] wchar: mov r0,#1 @ STDIN and r1,r9,r12 @ Address of [A] add r1,r6,r1,lsl #2 mov r2,#1 @ Write one character mov r7,#write swi #0 b instr @@@ Read character from file into R0. Tries to read more @@@ if the buffer is empty (as given by R6). Buffer in R11. fchar: tst r6,r6 @ Any bytes in the buffer? ldrneb r0,[r11],#1 @ If so, return next character from buffer subne r6,r6,#1 bxne lr mov r12,lr @ Save link register mov r0,r5 @ If not, read from file into buffer ldr r1,=fbuf mov r2,#0x400000 mov r7,#read swi #0 movs r6,r0 @ Amount of bytes in r6 beq setup @ If no more bytes, start the program ldr r11,=fbuf @ Otherwise, R11 = start of buffer mov lr,r12 b fchar @@@ Write a zero-terminated string, in [r1], to stdout. print: push {lr} mov r2,r1 1: ldrb r0,[r2],#1 @ Get character and advance pointer tst r0,r0 @ Zero yet? bne 1b @ If not, keep scanning sub r2,r2,r1 @ If so, calculate length mov r0,#1 @ STDOUT mov r7,#write @ Write to STDOUT swi #0 pop {pc} @@@ Print error message in [r1], then end. die: bl print mov r0,#255 mov r7,#exit swi #0 usage: .asciz "Usage: subleq <filename>\n" efile: .asciz "Cannot open file\n" echar: .asciz "Invalid number in file\n" @@@ Memory .bss .align 4 prog: .space 0x400000 @ Lower half of program memory fbuf: .space 0x400000 @ File buffer and top half of program memory mem_end = .
http://rosettacode.org/wiki/Subleq
Subleq
Subleq is an example of a One-Instruction Set Computer (OISC). It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero. Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory consists of an array of signed integers.   These integers may be interpreted in three ways:   simple numeric values   memory addresses   characters for input or output Any reasonable word size that accommodates all three of the above uses is fine. The program should load the initial contents of the emulated machine's memory, set the instruction pointer to the first address (which is defined to be address 0), and begin emulating the machine, which works as follows:   Let A be the value in the memory location identified by the instruction pointer;   let B and C be the values stored in the next two consecutive addresses in memory.   Advance the instruction pointer three words, to point at the address after the address containing C.   If A is   -1   (negative unity),   then a character is read from the machine's input and its numeric value stored in the address given by B.   C is unused.   If B is   -1   (negative unity),   then the number contained in the address given by A is interpreted as a character and written to the machine's output.   C is unused.   Otherwise, both A and B are treated as addresses.   The number contained in address A is subtracted from the number in address B (and the difference left in address B).   If the result is positive, execution continues uninterrupted; if the result is zero or negative, the number in C becomes the new instruction pointer.   If the instruction pointer becomes negative, execution halts. Your solution may initialize the emulated machine's memory in any convenient manner, but if you accept it as input, it should be a separate input stream from the one fed to the emulated machine once it is running. And if fed as text input, it should be in the form of raw subleq "machine code" - whitespace-separated decimal numbers, with no symbolic names or other assembly-level extensions, to be loaded into memory starting at address   0   (zero). For purposes of this task, show the output of your solution when fed the below   "Hello, world!"   program. As written, this example assumes ASCII or a superset of it, such as any of the Latin-N character sets or Unicode;   you may translate the numbers representing characters (starting with 72=ASCII 'H') into another character set if your implementation runs in a non-ASCII-compatible environment. If 0 is not an appropriate terminator in your character set, the program logic will need some adjustment as well. 15 17 -1 17 -1 -1 16 1 -1 16 3 -1 15 15 0 0 -1 72 101 108 108 111 44 32 119 111 114 108 100 33 10 0 The above "machine code" corresponds to something like this in a hypothetical assembler language for a signed 8-bit version of the machine: start: 0f 11 ff subleq (zero), (message), -1 11 ff ff subleq (message), -1, -1  ; output character at message 10 01 ff subleq (neg1), (start+1), -1 10 03 ff subleq (neg1), (start+3), -1 0f 0f 00 subleq (zero), (zero), start ; useful constants zero: 00 .data 0 neg1: ff .data -1 ; the message to print message: .data "Hello, world!\n\0" 48 65 6c 6c 6f 2c 20 77 6f 72 6c 64 21 0a 00
#AWK
AWK
  # syntax: GAWK -f SUBLEQ.AWK SUBLEQ.TXT # converted from Java BEGIN { instruction_pointer = 0 } { printf("%s\n",$0) for (i=1; i<=NF; i++) { if ($i == "*") { ncomments++ break } mem[instruction_pointer++] = $i } } END { if (instruction_pointer == 0) { print("error: nothing to run") exit(1) } printf("input: %d records, %d instructions, %d comments\n\n",NR,instruction_pointer,ncomments) instruction_pointer = 0 do { a = mem[instruction_pointer] b = mem[instruction_pointer+1] if (a == -1) { getline <"con" mem[b] = $1 } else if (b == -1) { printf("%c",mem[a]) } else { mem[b] -= mem[a] if (mem[b] < 1) { instruction_pointer = mem[instruction_pointer+2] continue } } instruction_pointer += 3 } while (instruction_pointer >= 0) exit(0) }  
http://rosettacode.org/wiki/Successive_prime_differences
Successive prime differences
The series of increasing prime numbers begins: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, ... The task applies a filter to the series returning groups of successive primes, (s'primes), that differ from the next by a given value or values. Example 1: Specifying that the difference between s'primes be 2 leads to the groups: (3, 5), (5, 7), (11, 13), (17, 19), (29, 31), ... (Known as Twin primes or Prime pairs) Example 2: Specifying more than one difference between s'primes leads to groups of size one greater than the number of differences. Differences of 2, 4 leads to the groups: (5, 7, 11), (11, 13, 17), (17, 19, 23), (41, 43, 47), .... In the first group 7 is two more than 5 and 11 is four more than 7; as well as 5, 7, and 11 being successive primes. Differences are checked in the order of the values given, (differences of 4, 2 would give different groups entirely). Task In each case use a list of primes less than 1_000_000 For the following Differences show the first and last group, as well as the number of groups found: Differences of 2. Differences of 1. Differences of 2, 2. Differences of 2, 4. Differences of 4, 2. Differences of 6, 4, 2. Show output here. Note: Generation of a list of primes is a secondary aspect of the task. Use of a built in function, well known library, or importing/use of prime generators from other Rosetta Code tasks is encouraged. references https://pdfs.semanticscholar.org/78a1/7349819304863ae061df88dbcb26b4908f03.pdf https://www.primepuzzles.net/puzzles/puzz_011.htm https://matheplanet.de/matheplanet/nuke/html/viewtopic.php?topic=232720&start=0
#Factor
Factor
USING: formatting fry grouping kernel math math.primes math.statistics sequences ; IN: rosetta-code.successive-prime-differences   : seq-diff ( seq diffs -- seq' quot ) dup [ length 1 + <clumps> ] dip '[ differences _ sequence= ]  ; inline   : show ( seq diffs -- ) [ "...for differences %u:\n" printf ] keep seq-diff [ find nip { } like ] [ find-last nip { } like ] [ count ] 2tri "First group: %u\nLast group: %u\nCount: %d\n\n" printf ;   : successive-prime-differences ( -- ) "Groups of successive primes up to one million...\n" printf 1,000,000 primes-upto { { 2 } { 1 } { 2 2 } { 2 4 } { 4 2 } { 6 4 2 } } [ show ] with each ;   MAIN: successive-prime-differences
http://rosettacode.org/wiki/Substring/Top_and_tail
Substring/Top and tail
The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed If the program uses UTF-8 or UTF-16, it must work on any valid Unicode code point, whether in the Basic Multilingual Plane or above it. The program must reference logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16. Programs for other encodings (such as 8-bit ASCII, or EUC-JP) are not required to handle all Unicode characters. 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
#BQN
BQN
str ← "substring" "substring" 1↓str "ubstring" ¯1↓str "substrin" 1↓¯1↓str "ubstrin"
http://rosettacode.org/wiki/Substring/Top_and_tail
Substring/Top and tail
The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed If the program uses UTF-8 or UTF-16, it must work on any valid Unicode code point, whether in the Basic Multilingual Plane or above it. The program must reference logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16. Programs for other encodings (such as 8-bit ASCII, or EUC-JP) are not required to handle all Unicode characters. 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
s$ = "Rosetta Code" PRINT MID$(s$, 2) PRINT LEFT$(s$) PRINT LEFT$(MID$(s$, 2))
http://rosettacode.org/wiki/Subtractive_generator
Subtractive generator
A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence. The formula is r n = r ( n − i ) − r ( n − j ) ( mod m ) {\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod {m}}} for some fixed values of i {\displaystyle i} , j {\displaystyle j} and m {\displaystyle m} , all positive integers. Supposing that i > j {\displaystyle i>j} , then the state of this generator is the list of the previous numbers from r n − i {\displaystyle r_{n-i}} to r n − 1 {\displaystyle r_{n-1}} . Many states generate uniform random integers from 0 {\displaystyle 0} to m − 1 {\displaystyle m-1} , but some states are bad. A state, filled with zeros, generates only zeros. If m {\displaystyle m} is even, then a state, filled with even numbers, generates only even numbers. More generally, if f {\displaystyle f} is a factor of m {\displaystyle m} , then a state, filled with multiples of f {\displaystyle f} , generates only multiples of f {\displaystyle f} . All subtractive generators have some weaknesses. The formula correlates r n {\displaystyle r_{n}} , r ( n − i ) {\displaystyle r_{(n-i)}} and r ( n − j ) {\displaystyle r_{(n-j)}} ; these three numbers are not independent, as true random numbers would be. Anyone who observes i {\displaystyle i} consecutive numbers can predict the next numbers, so the generator is not cryptographically secure. The authors of Freeciv (utility/rand.c) and xpat2 (src/testit2.c) knew another problem: the low bits are less random than the high bits. The subtractive generator has a better reputation than the linear congruential generator, perhaps because it holds more state. A subtractive generator might never multiply numbers: this helps where multiplication is slow. A subtractive generator might also avoid division: the value of r ( n − i ) − r ( n − j ) {\displaystyle r_{(n-i)}-r_{(n-j)}} is always between − m {\displaystyle -m} and m {\displaystyle m} , so a program only needs to add m {\displaystyle m} to negative numbers. The choice of i {\displaystyle i} and j {\displaystyle j} affects the period of the generator. A popular choice is i = 55 {\displaystyle i=55} and j = 24 {\displaystyle j=24} , so the formula is r n = r ( n − 55 ) − r ( n − 24 ) ( mod m ) {\displaystyle r_{n}=r_{(n-55)}-r_{(n-24)}{\pmod {m}}} The subtractive generator from xpat2 uses r n = r ( n − 55 ) − r ( n − 24 ) ( mod 10 9 ) {\displaystyle r_{n}=r_{(n-55)}-r_{(n-24)}{\pmod {10^{9}}}} The implementation is by J. Bentley and comes from program_tools/universal.c of the DIMACS (netflow) archive at Rutgers University. It credits Knuth, TAOCP, Volume 2, Section 3.2.2 (Algorithm A). Bentley uses this clever algorithm to seed the generator. Start with a single s e e d {\displaystyle seed} in range 0 {\displaystyle 0} to 10 9 − 1 {\displaystyle 10^{9}-1} . Set s 0 = s e e d {\displaystyle s_{0}=seed} and s 1 = 1 {\displaystyle s_{1}=1} . The inclusion of s 1 = 1 {\displaystyle s_{1}=1} avoids some bad states (like all zeros, or all multiples of 10). Compute s 2 , s 3 , . . . , s 54 {\displaystyle s_{2},s_{3},...,s_{54}} using the subtractive formula s n = s ( n − 2 ) − s ( n − 1 ) ( mod 10 9 ) {\displaystyle s_{n}=s_{(n-2)}-s_{(n-1)}{\pmod {10^{9}}}} . Reorder these 55 values so r 0 = s 34 {\displaystyle r_{0}=s_{34}} , r 1 = s 13 {\displaystyle r_{1}=s_{13}} , r 2 = s 47 {\displaystyle r_{2}=s_{47}} , ..., r n = s ( 34 ∗ ( n + 1 ) ( mod 55 ) ) {\displaystyle r_{n}=s_{(34*(n+1){\pmod {55}})}} . This is the same order as s 0 = r 54 {\displaystyle s_{0}=r_{54}} , s 1 = r 33 {\displaystyle s_{1}=r_{33}} , s 2 = r 12 {\displaystyle s_{2}=r_{12}} , ..., s n = r ( ( 34 ∗ n ) − 1 ( mod 55 ) ) {\displaystyle s_{n}=r_{((34*n)-1{\pmod {55}})}} . This rearrangement exploits how 34 and 55 are relatively prime. Compute the next 165 values r 55 {\displaystyle r_{55}} to r 219 {\displaystyle r_{219}} . Store the last 55 values. This generator yields the sequence r 220 {\displaystyle r_{220}} , r 221 {\displaystyle r_{221}} , r 222 {\displaystyle r_{222}} and so on. For example, if the seed is 292929, then the sequence begins with r 220 = 467478574 {\displaystyle r_{220}=467478574} , r 221 = 512932792 {\displaystyle r_{221}=512932792} , r 222 = 539453717 {\displaystyle r_{222}=539453717} . By starting at r 220 {\displaystyle r_{220}} , this generator avoids a bias from the first numbers of the sequence. This generator must store the last 55 numbers of the sequence, so to compute the next r n {\displaystyle r_{n}} . Any array or list would work; a ring buffer is ideal but not necessary. Implement a subtractive generator that replicates the sequences from xpat2.
#F.23
F#
[<EntryPoint>] let main argv = let m = 1000000000 let init = Seq.unfold (fun ((i, s2, s1)) -> Some((s2,i), (i+1, s1, (m+s2-s1)%m))) (0, 292929, 1) |> Seq.take 55 |> Seq.sortBy (fun (_,i) -> (34*i+54)%55) |> Seq.map fst let rec r = seq { yield! init yield! Seq.map2 (fun u v -> (m+u-v)%m) r (Seq.skip 31 r) }   r |> Seq.skip 220 |> Seq.take 3 |> Seq.iter (printfn "%d") 0
http://rosettacode.org/wiki/Substitution_cipher
Substitution cipher
Substitution Cipher Implementation - File Encryption/Decryption Task Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypted file into original/decrypted file. This type of Encryption/Decryption scheme is often called a Substitution Cipher. Related tasks Caesar cipher Rot-13 Vigenère Cipher/Cryptanalysis See also Wikipedia: Substitution cipher
#Phixmonti
Phixmonti
include ..\Utilitys.pmt   " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" " VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWobLkESYMTN" "A simple example"   def Encode >ps tps not if >ps swap ps> endif len for >ps tps get swap >ps rot swap find rot swap get ps> swap ps> set endfor ps> not if >ps swap ps> endif enddef   dup ? true Encode dup ? false Encode ?
http://rosettacode.org/wiki/Substitution_cipher
Substitution cipher
Substitution Cipher Implementation - File Encryption/Decryption Task Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypted file into original/decrypted file. This type of Encryption/Decryption scheme is often called a Substitution Cipher. Related tasks Caesar cipher Rot-13 Vigenère Cipher/Cryptanalysis See also Wikipedia: Substitution cipher
#PHP
PHP
<?php   $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $key = 'cPYJpjsBlaOEwRbVZIhQnHDWxMXiCtUToLkFrzdAGymKvgNufeSq';   // Encode input.txt, and save result in output.txt file_put_contents('output.txt', strtr(file_get_contents('input.txt'), $alphabet, $key));   $source = file_get_contents('input.txt'); $encoded = file_get_contents('output.txt'); $decoded = strtr($encoded, $key, $alphabet);   echo '== SOURCE ==', PHP_EOL, $source, PHP_EOL, PHP_EOL, '== ENCODED ==', PHP_EOL, $encoded, PHP_EOL, PHP_EOL, '== DECODED ==', PHP_EOL, $decoded, PHP_EOL, PHP_EOL;
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#Eiffel
Eiffel
  class APPLICATION   create make   feature {NONE}   make local test: ARRAY [INTEGER] do create test.make_empty test := <<5, 1, 9, 7>> io.put_string ("Sum: " + sum (test).out) io.new_line io.put_string ("Product: " + product (test).out) end   sum (ar: ARRAY [INTEGER]): INTEGER -- Sum of the items of the array 'ar'. do across ar.lower |..| ar.upper as c loop Result := Result + ar [c.item] end end   product (ar: ARRAY [INTEGER]): INTEGER -- Product of the items of the array 'ar'. do Result := 1 across ar.lower |..| ar.upper as c loop Result := Result * ar [c.item] end end   end  
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displaystyle S_{n}=\sum _{k=1}^{n}{\frac {1}{k^{2}}}} and compute   S 1000 {\displaystyle S_{1000}} This approximates the   zeta function   for   S=2,   whose exact value ζ ( 2 ) = π 2 6 {\displaystyle \zeta (2)={\pi ^{2} \over 6}} is the solution of the Basel problem.
#DWScript
DWScript
  var s : Float; for var i := 1 to 1000 do s += 1 / Sqr(i);   PrintLn(s);  
http://rosettacode.org/wiki/Strip_comments_from_a_string
Strip comments from a string
Strip comments from a string You are encouraged to solve this task according to the task description, using any language you may know. The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line. Whitespace debacle:   There is some confusion about whether to remove any whitespace from the input line. As of 2 September 2011, at least 8 languages (C, C++, Java, Perl, Python, Ruby, sed, UNIX Shell) were incorrect, out of 36 total languages, because they did not trim whitespace by 29 March 2011 rules. Some other languages might be incorrect for the same reason. Please discuss this issue at Talk:Strip comments from a string. From 29 March 2011, this task required that: "The comment marker and any whitespace at the beginning or ends of the resultant line should be removed. A line without comments should be trimmed of any leading or trailing whitespace before being produced as a result." The task had 28 languages, which did not all meet this new requirement. From 28 March 2011, this task required that: "Whitespace before the comment marker should be removed." From 30 October 2010, this task did not specify whether or not to remove whitespace. The following examples will be truncated to either "apples, pears " or "apples, pears". (This example has flipped between "apples, pears " and "apples, pears" in the past.) apples, pears # and bananas apples, pears ; and bananas 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
#68000_Assembly
68000 Assembly
StripComments: ;prints a string but stops at the comment character ;INPUT: D7 = comment character(s) of choice ;A0 = source address of string ;up to four can be used, each takes up a different 8 bits of the register ;to omit an argument, leave its bits as zero. .loop: MOVE.B (A0)+,D0 CMP.B #0,D0 ;check for null terminator beq .done   CMP.B D7,D0 ;check the first comment char beq .done ROR.L #8,D7   CMP.B D7,D0 ;check the second comment char beq .done ROR.L #8,D7   CMP.B D7,D0 ;check the third comment char beq .done ROR.L #8,D7   CMP.B D7,D0 ;check the fourth comment char beq .done ROR.L #8,D7   CMP.B #' ',D0 BNE dontCheckNext MOVE.B (A0),D1 ;look ahead one character, if that character is a comment char or null terminator, stop here   CMP.B #0,D1 beq .done   CMP.B D7,D1 beq .done ROR.L #8,D7   CMP.B D7,D1 beq .done ROR.L #8,D7   CMP.B D7,D1 beq .done ROR.L #8,D7   CMP.B D7,D1 beq .done ROR.L #8,D7   dontCheckNext: jsr PrintChar bra .loop   .done: rts       TestString: dc.b "apples ; pears # and bananas",0
http://rosettacode.org/wiki/Strip_block_comments
Strip block comments
A block comment begins with a   beginning delimiter   and ends with a   ending delimiter,   including the delimiters.   These delimiters are often multi-character sequences. Task Strip block comments from program text (of a programming language much like classic C). Your demos should at least handle simple, non-nested and multi-line block comment delimiters. The block comment delimiters are the two-character sequences:     /*     (beginning delimiter)     */     (ending delimiter) Sample text for stripping: /** * Some comments * longer comments here that we can parse. * * Rahoo */ function subroutine() { a = /* inline comment */ b + c ; } /*/ <-- tricky comments */ /** * Another comment. */ function something() { } Extra credit Ensure that the stripping code is not hard-coded to the particular delimiters described above, but instead allows the caller to specify them.   (If your language supports them,   optional parameters   may be useful for this.) 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
#Ada
Ada
with Ada.Strings.Fixed; with Ada.Strings.Unbounded; with Ada.Text_IO; with Ada.Command_Line;   procedure Strip is use Ada.Strings.Unbounded; procedure Print_Usage is begin Ada.Text_IO.Put_Line ("Usage:"); Ada.Text_IO.New_Line; Ada.Text_IO.Put_Line (" strip <file> [<opening> [<closing>]]"); Ada.Text_IO.New_Line; Ada.Text_IO.Put_Line (" file: file to strip"); Ada.Text_IO.Put_Line (" opening: string for opening comment"); Ada.Text_IO.Put_Line (" closing: string for closing comment"); Ada.Text_IO.New_Line; end Print_Usage;   Opening_Pattern : Unbounded_String := To_Unbounded_String ("/*"); Closing_Pattern : Unbounded_String := To_Unbounded_String ("*/"); Inside_Comment  : Boolean  := False;   function Strip_Comments (From : String) return String is use Ada.Strings.Fixed; Opening_Index : Natural; Closing_Index : Natural; Start_Index  : Natural := From'First; begin if Inside_Comment then Start_Index := Index (Source => From, Pattern => To_String (Closing_Pattern)); if Start_Index < From'First then return ""; end if; Inside_Comment := False; Start_Index  := Start_Index + Length (Closing_Pattern); end if; Opening_Index := Index (Source => From, Pattern => To_String (Opening_Pattern), From => Start_Index); if Opening_Index < From'First then return From (Start_Index .. From'Last); else Closing_Index := Index (Source => From, Pattern => To_String (Closing_Pattern), From => Opening_Index + Length (Opening_Pattern)); if Closing_Index > 0 then return From (Start_Index .. Opening_Index - 1) & Strip_Comments (From ( Closing_Index + Length (Closing_Pattern) .. From'Last)); else Inside_Comment := True; return From (Start_Index .. Opening_Index - 1); end if; end if; end Strip_Comments;   File : Ada.Text_IO.File_Type; begin if Ada.Command_Line.Argument_Count < 1 or else Ada.Command_Line.Argument_Count > 3 then Print_Usage; return; end if; if Ada.Command_Line.Argument_Count > 1 then Opening_Pattern := To_Unbounded_String (Ada.Command_Line.Argument (2)); if Ada.Command_Line.Argument_Count > 2 then Closing_Pattern := To_Unbounded_String (Ada.Command_Line.Argument (3)); else Closing_Pattern := Opening_Pattern; end if; end if; Ada.Text_IO.Open (File => File, Mode => Ada.Text_IO.In_File, Name => Ada.Command_Line.Argument (1)); while not Ada.Text_IO.End_Of_File (File => File) loop declare Line : constant String := Ada.Text_IO.Get_Line (File); begin Ada.Text_IO.Put_Line (Strip_Comments (Line)); end; end loop; Ada.Text_IO.Close (File => File); end Strip;
http://rosettacode.org/wiki/Sum_to_100
Sum to 100
Task Find solutions to the   sum to one hundred   puzzle. Add (insert) the mathematical operators     +   or   -     (plus or minus)   before any of the digits in the decimal numeric string   123456789   such that the resulting mathematical expression adds up to a particular sum   (in this iconic case,   100). Example: 123 + 4 - 5 + 67 - 89 = 100 Show all output here.   Show all solutions that sum to   100   Show the sum that has the maximum   number   of solutions   (from zero to infinity‡)   Show the lowest positive sum that   can't   be expressed   (has no solutions),   using the rules for this task   Show the ten highest numbers that can be expressed using the rules for this task   (extra credit) ‡   (where   infinity   would be a relatively small   123,456,789) An example of a sum that can't be expressed   (within the rules of this task)   is:   5074 (which,   of course,   isn't the lowest positive sum that can't be expressed).
#Kotlin
Kotlin
// version 1.1.51   class Expression {   private enum class Op { ADD, SUB, JOIN } private val code = Array<Op>(NUMBER_OF_DIGITS) { Op.ADD }   companion object { private const val NUMBER_OF_DIGITS = 9 private const val THREE_POW_4 = 3 * 3 * 3 * 3 private const val FMT = "%9d" const val NUMBER_OF_EXPRESSIONS = 2 * THREE_POW_4 * THREE_POW_4   fun print(givenSum: Int) { var expression = Expression() repeat(Expression.NUMBER_OF_EXPRESSIONS) { if (expression.toInt() == givenSum) println("${FMT.format(givenSum)} = $expression") expression++ } } }   operator fun inc(): Expression { for (i in 0 until code.size) { code[i] = when (code[i]) { Op.ADD -> Op.SUB Op.SUB -> Op.JOIN Op.JOIN -> Op.ADD } if (code[i] != Op.ADD) break } return this }   fun toInt(): Int { var value = 0 var number = 0 var sign = +1 for (digit in 1..9) { when (code[NUMBER_OF_DIGITS - digit]) { Op.ADD -> { value += sign * number; number = digit; sign = +1 } Op.SUB -> { value += sign * number; number = digit; sign = -1 } Op.JOIN -> { number = 10 * number + digit } } } return value + sign * number }   override fun toString(): String { val sb = StringBuilder() for (digit in 1..NUMBER_OF_DIGITS) { when (code[NUMBER_OF_DIGITS - digit]) { Op.ADD -> if (digit > 1) sb.append(" + ") Op.SUB -> sb.append(" - ") Op.JOIN -> {} } sb.append(digit) } return sb.toString().trimStart() } }   class Stat {   val countSum = mutableMapOf<Int, Int>() val sumCount = mutableMapOf<Int, MutableSet<Int>>()   init { var expression = Expression() repeat (Expression.NUMBER_OF_EXPRESSIONS) { val sum = expression.toInt() countSum.put(sum, 1 + (countSum[sum] ?: 0)) expression++ } for ((k, v) in countSum) { val set = if (sumCount.containsKey(v)) sumCount[v]!! else mutableSetOf<Int>() set.add(k) sumCount.put(v, set) } } }   fun main(args: Array<String>) { println("100 has the following solutions:\n") Expression.print(100)   val stat = Stat() val maxCount = stat.sumCount.keys.max() val maxSum = stat.sumCount[maxCount]!!.max() println("\n$maxSum has the maximum number of solutions, namely $maxCount")   var value = 0 while (stat.countSum.containsKey(value)) value++ println("\n$value is the lowest positive number with no solutions")   println("\nThe ten highest numbers that do have solutions are:\n") stat.countSum.keys.toIntArray().sorted().reversed().take(10).forEach { Expression.print(it) } }
http://rosettacode.org/wiki/Strip_a_set_of_characters_from_a_string
Strip a set of characters from a string
Task Create a function that strips a set of characters from a string. The function should take two arguments:   a string to be stripped   a string containing the set of characters to be stripped The returned string should contain the first string, stripped of any characters in the second argument: print stripchars("She was a soul stripper. She took my heart!","aei") Sh ws soul strppr. Sh took my hrt! 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
#11l
11l
F stripchars(s, chars) R s.filter(c -> c !C @chars).join(‘’)   print(stripchars(‘She was a soul stripper. She took my heart!’, ‘aei’))
http://rosettacode.org/wiki/String_prepend
String prepend
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Create a string variable equal to any text value. Prepend the string variable with another string literal. If your language supports any idiomatic ways to do this without referring to the variable twice in one expression, include such solutions. To illustrate the operation, show the content of the variable.
#11l
11l
V s = ‘12345678’ s = ‘0’s print(s)
http://rosettacode.org/wiki/Strip_control_codes_and_extended_characters_from_a_string
Strip control codes and extended characters from a string
Task Strip control codes and extended characters from a string. The solution should demonstrate how to achieve each of the following results:   a string with control codes stripped (but extended characters not stripped)   a string with control codes and extended characters stripped In ASCII, the control codes have decimal codes 0 through to 31 and 127. On an ASCII based system, if the control codes are stripped, the resultant string would have all of its characters within the range of 32 to 126 decimal on the ASCII table. On a non-ASCII based system, we consider characters that do not have a corresponding glyph on the ASCII table (within the ASCII range of 32 to 126 decimal) to be an extended character for the purpose of this task. 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
#Action.21
Action!
BYTE FUNC IsAscii(CHAR c) IF c<32 OR c>124 OR c=96 OR c=123 THEN RETURN (0) FI RETURN (1)   PROC Strip(CHAR ARRAY src,dst) CHAR c BYTE i   dst(0)=0 FOR i=1 TO src(0) DO c=src(i) IF IsAscii(c) THEN dst(0)==+1 dst(dst(0))=c FI OD RETURN   PROC Main() CHAR ARRAY src(20)=[16 0 16 96 123 'a 'b 'c 131 27 30 '1 '2 '3 4 1 20], dst(20)   PrintF("Original string: ""%S""%E",src) Strip(src,dst) PrintF("Stripped string: ""%S""%E",dst) RETURN
http://rosettacode.org/wiki/Strip_control_codes_and_extended_characters_from_a_string
Strip control codes and extended characters from a string
Task Strip control codes and extended characters from a string. The solution should demonstrate how to achieve each of the following results:   a string with control codes stripped (but extended characters not stripped)   a string with control codes and extended characters stripped In ASCII, the control codes have decimal codes 0 through to 31 and 127. On an ASCII based system, if the control codes are stripped, the resultant string would have all of its characters within the range of 32 to 126 decimal on the ASCII table. On a non-ASCII based system, we consider characters that do not have a corresponding glyph on the ASCII table (within the ASCII range of 32 to 126 decimal) to be an extended character for the purpose of this task. 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
#Ada
Ada
with Ada.Text_IO;   procedure Strip_ASCII is   Full: String := 'a' & Character'Val(11) & 'b' & Character'Val(166) & 'c' & Character'Val(127) & Character'Val(203) & Character'Val(202) & "de"; -- 5 ordinary characters ('a' .. 'e') -- 2 control characters (11, 127); note that 11 is the "vertical tab" -- 3 extended characters (166, 203, 202)   function Filter(S: String; From: Character := ' '; To: Character := Character'Val(126); Above: Character := Character'Val(127)) return String is begin if S'Length = 0 then return ""; elsif (S(S'First) >= From and then S(S'First) <= To) or else S(S'First) > Above then return S(S'First) & Filter(S(S'First+1 .. S'Last), From, To, Above); else return Filter(S(S'First+1 .. S'Last), From, To, Above); end if; end Filter;   procedure Put_Line(Text, S: String) is begin Ada.Text_IO.Put_Line(Text & " """ & S & """, Length:" & Integer'Image(S'Length)); end Put_Line;   begin Put_Line("The full string :", Full); Put_Line("No Control Chars:", Filter(Full)); -- default values for From, To, and Above Put_Line("Neither_Extended:", Filter(Full, Above => Character'Last)); -- defaults for From and To end Strip_ASCII;  
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5
Sum multiples of 3 and 5
Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
#Erlang
Erlang
sum_3_5(X) when is_number(X) -> sum_3_5(erlang:round(X)-1, 0). sum_3_5(X, Total) when X < 3 -> Total; sum_3_5(X, Total) when X rem 3 =:= 0 orelse X rem 5 =:= 0 -> sum_3_5(X-1, Total+X); sum_3_5(X, Total) -> sum_3_5(X-1, Total).   io:format("~B~n", [sum_3_5(1000)]).
http://rosettacode.org/wiki/Sum_digits_of_an_integer
Sum digits of an integer
Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
#Ezhil
Ezhil
  # இது ஒரு எழில் தமிழ் நிரலாக்க மொழி உதாரணம்   # sum of digits of a number # எண்ணிக்கையிலான இலக்கங்களின் தொகை   நிரல்பாகம் எண்_கூட்டல்( எண் ) தொகை = 0 @( எண் > 0 ) வரை d = எண்%10; பதிப்பி "digit = ",d எண் = (எண்-d)/10; தொகை = தொகை + d முடி பின்கொடு தொகை முடி     பதிப்பி எண்_கூட்டல்( 1289)#20 பதிப்பி எண்_கூட்டல்( 123456789)# 45  
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Function SumSquares(a() As Double) As Double Dim As Integer length = UBound(a) - LBound(a) + 1 If length = 0 Then Return 0.0 Dim As Double sum = 0.0 For i As Integer = LBound(a) To UBound(a) sum += a(i) * a(i) Next Return sum End Function   Dim a(5) As Double = {1.0, 2.0, 3.0, -1.0, -2.0, -3.0} Dim sum As Double = SumSquares(a()) Print "The sum of the squares is"; sum Print Print "Press any key to quit" Sleep
http://rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail
Strip whitespace from a string/Top and tail
Task Demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results: String with leading whitespace removed String with trailing whitespace removed String with both leading and trailing whitespace removed For the purposes of this task whitespace includes non printable characters such as the space character, the tab character, and other such characters that have no corresponding graphical representation. 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
#AppleScript
AppleScript
use framework "Foundation" -- "OS X" Yosemite onwards, for NSRegularExpression   -- STRIP WHITESPACE ----------------------------------------------------------   -- isSpace :: Char -> Bool on isSpace(c) ((length of c) = 1) and regexTest("\\s", c) end isSpace   -- stripStart :: Text -> Text on stripStart(s) dropWhile(isSpace, s) as text end stripStart   -- stripEnd :: Text -> Text on stripEnd(s) dropWhileEnd(isSpace, s) as text end stripEnd   -- strip :: Text -> Text on strip(s) dropAround(isSpace, s) as text end strip     -- TEST ---------------------------------------------------------------------- on run set strText to " \t\t \n \r Much Ado About Nothing \t \n \r "   script arrowed on |λ|(x) "-->" & x & "<--" end |λ| end script   map(arrowed, [stripStart(strText), stripEnd(strText), strip(strText)])   -- {"-->Much Ado About Nothing -- -- <--", "--> -- -- Much Ado About Nothing<--", "-->Much Ado About Nothing<--"} end run     -- GENERIC FUNCTIONS ---------------------------------------------------------   -- dropAround :: (Char -> Bool) -> [a] -> [a] on dropAround(p, xs) dropWhile(p, dropWhileEnd(p, xs)) end dropAround   -- dropWhile :: (a -> Bool) -> [a] -> [a] on dropWhile(p, xs) tell mReturn(p) set lng to length of xs set i to 1 repeat while i ≤ lng and |λ|(item i of xs) set i to i + 1 end repeat end tell if i ≤ lng then items i thru lng of xs else {} end if end dropWhile   -- dropWhileEnd :: (a -> Bool) -> [a] -> [a] on dropWhileEnd(p, xs) tell mReturn(p) set i to length of xs repeat while i > 0 and |λ|(item i of xs) set i to i - 1 end repeat end tell if i > 0 then items 1 thru i of xs else {} end if end dropWhileEnd   -- map :: (a -> b) -> [a] -> [b] on map(f, 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   -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) if class of f is script then f else script property |λ| : f end script end if end mReturn   -- regexTest :: RegexPattern -> String -> Bool on regexTest(strRegex, str) set ca to current application set oString to ca's NSString's stringWithString:str ((ca's NSRegularExpression's regularExpressionWithPattern:strRegex ¬ options:((ca's NSRegularExpressionAnchorsMatchLines as integer)) ¬ |error|:(missing value))'s firstMatchInString:oString options:0 ¬ range:{location:0, |length|:oString's |length|()}) is not missing value end regexTest
http://rosettacode.org/wiki/Strong_and_weak_primes
Strong and weak primes
Definitions   (as per number theory)   The   prime(p)   is the   pth   prime.   prime(1)   is   2   prime(4)   is   7   A   strong   prime   is when     prime(p)   is   >   [prime(p-1) + prime(p+1)] ÷ 2   A     weak    prime   is when     prime(p)   is   <   [prime(p-1) + prime(p+1)] ÷ 2 Note that the definition for   strong primes   is different when used in the context of   cryptography. Task   Find and display (on one line) the first   36   strong primes.   Find and display the   count   of the strong primes below   1,000,000.   Find and display the   count   of the strong primes below 10,000,000.   Find and display (on one line) the first   37   weak primes.   Find and display the   count   of the weak primes below   1,000,000.   Find and display the   count   of the weak primes below 10,000,000.   (Optional)   display the   counts   and   "below numbers"   with commas. Show all output here. Related Task   Safe primes and unsafe primes. Also see   The OEIS article A051634: strong primes.   The OEIS article A051635: weak primes.
#D
D
import std.algorithm; import std.array; import std.range; import std.stdio;   immutable PRIMES = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733, 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053, 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161, 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243, 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297, 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357, 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473, 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551, 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633, 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687, 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791, 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851, 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917, 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999, 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137, 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209, 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271, 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331, 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391, 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467, 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533, 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583, 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643, 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709, 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779, 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851, 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917, 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989, 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049, 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111, 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177, 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243, 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297, 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391, 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457, 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519, 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597, 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657, 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729, 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799, 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889, 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951, 4957, 4967, 4969, 4973, 4987, 4993, 4999, 5003, 5009, 5011, 5021, 5023, 5039, 5051, 5059, 5077, 5081, 5087, 5099, 5101, 5107, 5113, 5119, 5147, 5153, 5167, 5171, 5179, 5189, 5197, 5209, 5227, 5231, 5233, 5237, 5261, 5273, 5279, 5281, 5297, 5303, 5309, 5323, 5333, 5347, 5351, 5381, 5387, 5393, 5399, 5407, 5413, 5417, 5419, 5431, 5437, 5441, 5443, 5449, 5471, 5477, 5479, 5483, 5501, 5503, 5507, 5519, 5521, 5527, 5531, 5557, 5563, 5569, 5573, 5581, 5591, 5623, 5639, 5641, 5647, 5651, 5653, 5657, 5659, 5669, 5683, 5689, 5693, 5701, 5711, 5717, 5737, 5741, 5743, 5749, 5779, 5783, 5791, 5801, 5807, 5813, 5821, 5827, 5839, 5843, 5849, 5851, 5857, 5861, 5867, 5869, 5879, 5881, 5897, 5903, 5923, 5927, 5939, 5953, 5981, 5987, 6007, 6011, 6029, 6037, 6043, 6047, 6053, 6067, 6073, 6079, 6089, 6091, 6101, 6113, 6121, 6131, 6133, 6143, 6151, 6163, 6173, 6197, 6199, 6203, 6211, 6217, 6221, 6229, 6247, 6257, 6263, 6269, 6271, 6277, 6287, 6299, 6301, 6311, 6317, 6323, 6329, 6337, 6343, 6353, 6359, 6361, 6367, 6373, 6379, 6389, 6397, 6421, 6427, 6449, 6451, 6469, 6473, 6481, 6491, 6521, 6529, 6547, 6551, 6553, 6563, 6569, 6571, 6577, 6581, 6599, 6607, 6619, 6637, 6653, 6659, 6661, 6673, 6679, 6689, 6691, 6701, 6703, 6709, 6719, 6733, 6737, 6761, 6763, 6779, 6781, 6791, 6793, 6803, 6823, 6827, 6829, 6833, 6841, 6857, 6863, 6869, 6871, 6883, 6899, 6907, 6911, 6917, 6947, 6949, 6959, 6961, 6967, 6971, 6977, 6983, 6991, 6997, 7001, 7013, 7019, 7027, 7039, 7043, 7057, 7069, 7079, 7103, 7109, 7121, 7127, 7129, 7151, 7159, 7177, 7187, 7193, 7207, 7211, 7213, 7219, 7229, 7237, 7243, 7247, 7253, 7283, 7297, 7307, 7309, 7321, 7331, 7333, 7349, 7351, 7369, 7393, 7411, 7417, 7433, 7451, 7457, 7459, 7477, 7481, 7487, 7489, 7499, 7507, 7517, 7523, 7529, 7537, 7541, 7547, 7549, 7559, 7561, 7573, 7577, 7583, 7589, 7591, 7603, 7607, 7621, 7639, 7643, 7649, 7669, 7673, 7681, 7687, 7691, 7699, 7703, 7717, 7723, 7727, 7741, 7753, 7757, 7759, 7789, 7793, 7817, 7823, 7829, 7841, 7853, 7867, 7873, 7877, 7879, 7883, 7901, 7907, 7919, 7927, 7933, 7937, 7949, 7951, 7963, 7993, 8009, 8011, 8017, 8039, 8053, 8059, 8069, 8081, 8087, 8089, 8093, 8101, 8111, 8117, 8123, 8147, 8161, 8167, 8171, 8179, 8191, 8209, 8219, 8221, 8231, 8233, 8237, 8243, 8263, 8269, 8273, 8287, 8291, 8293, 8297, 8311, 8317, 8329, 8353, 8363, 8369, 8377, 8387, 8389, 8419, 8423, 8429, 8431, 8443, 8447, 8461, 8467, 8501, 8513, 8521, 8527, 8537, 8539, 8543, 8563, 8573, 8581, 8597, 8599, 8609, 8623, 8627, 8629, 8641, 8647, 8663, 8669, 8677, 8681, 8689, 8693, 8699, 8707, 8713, 8719, 8731, 8737, 8741, 8747, 8753, 8761, 8779, 8783, 8803, 8807, 8819, 8821, 8831, 8837, 8839, 8849, 8861, 8863, 8867, 8887, 8893, 8923, 8929, 8933, 8941, 8951, 8963, 8969, 8971, 8999, 9001, 9007, 9011, 9013, 9029, 9041, 9043, 9049, 9059, 9067, 9091, 9103, 9109, 9127, 9133, 9137, 9151, 9157, 9161, 9173, 9181, 9187, 9199, 9203, 9209, 9221, 9227, 9239, 9241, 9257, 9277, 9281, 9283, 9293, 9311, 9319, 9323, 9337, 9341, 9343, 9349, 9371, 9377, 9391, 9397, 9403, 9413, 9419, 9421, 9431, 9433, 9437, 9439, 9461, 9463, 9467, 9473, 9479, 9491, 9497, 9511, 9521, 9533, 9539, 9547, 9551, 9587, 9601, 9613, 9619, 9623, 9629, 9631, 9643, 9649, 9661, 9677, 9679, 9689, 9697, 9719, 9721, 9733, 9739, 9743, 9749, 9767, 9769, 9781, 9787, 9791, 9803, 9811, 9817, 9829, 9833, 9839, 9851, 9857, 9859, 9871, 9883, 9887, 9901, 9907, 9923, 9929, 9931, 9941, 9949, 9967, 9973, ];   bool isPrime(int n) { if (n < 2) { return false; }   foreach (prime; PRIMES) { if (n == prime) { return true; } if (n % prime == 0) { return false; } if (n < prime * prime) { if (n > PRIMES[$-1] * PRIMES[$-1]) { assert(false, "Out of pre-computed primes."); } break; } }   return true; }   void main() { auto primeList = iota(2, 10_000_100).filter!isPrime.array;   int[] strongPrimes, weakPrimes; foreach (i,p; primeList) { if (i > 0 && i < primeList.length - 1) { if (p > 0.5 * (primeList[i - 1] + primeList[i + 1])) { strongPrimes ~= p; } else if (p < 0.5 * (primeList[i - 1] + primeList[i + 1])) { weakPrimes ~= p; } } }   writeln("First 36 strong primes: ", strongPrimes[0..36]); writefln("There are %d strong primes below 1,000,000", strongPrimes.filter!"a<1_000_000".count); writefln("There are %d strong primes below 10,000,000", strongPrimes.filter!"a<10_000_000".count);   writeln("First 37 weak primes: ", weakPrimes[0..37]); writefln("There are %d weak primes below 1,000,000", weakPrimes.filter!"a<1_000_000".count); writefln("There are %d weak primes below 10,000,000", weakPrimes.filter!"a<10_000_000".count); }
http://rosettacode.org/wiki/Substring
Substring
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Display a substring:   starting from   n   characters in and of   m   length;   starting from   n   characters in,   up to the end of the string;   whole string minus the last character;   starting from a known   character   within the string and of   m   length;   starting from a known   substring   within the string and of   m   length. If the program uses UTF-8 or UTF-16,   it must work on any valid Unicode code point, whether in the   Basic Multilingual Plane   or above it. The program must reference logical characters (code points),   not 8-bit code units for UTF-8 or 16-bit code units for UTF-16. Programs for other encodings (such as 8-bit ASCII, or EUC-JP) are not required to handle all Unicode characters. 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
#Apex
Apex
String x = 'testing123'; //Test1: testing123 System.debug('Test1: ' + x.substring(0,x.length())); //Test2: esting123 System.debug('Test2: ' + x.substring(1,x.length())); //Test3: testing123 System.debug('Test3: ' + x.substring(0)); //Test4: 3 System.debug('Test4: ' + x.substring(x.length()-1)); //Test5: System.debug('Test5: ' + x.substring(1,1)); //Test 6: testing123 System.debug('Test6: ' + x.substring(x.indexOf('testing'))); //Test7: e System.debug('Test7: ' + x.substring(1,2));  
http://rosettacode.org/wiki/Sudoku
Sudoku
Task Solve a partially filled-in normal   9x9   Sudoku grid   and display the result in a human-readable format. references Algorithmics of Sudoku   may help implement this. Python Sudoku Solver Computerphile video.
#Befunge
Befunge
99*>1-:0>:#$"0"\# #~`#$_"0"-\::9%:9+00p3/\9/:99++10p3vv%2g\g01< 2%v|:p+9/9\%9:\p\g02\1p\g01\1:p\g00\1:+8:\p02+*93+*3/<>\20g\g#: v<+>:0\`>v >\::9%:9+00p3/\9/:99++10p3/3*+39*+20p\:8+::00g\g2%\^ v^+^pppp$_:|v<::<_>1-::9%\9/9+g.::9%!\3%+>>#v_>" "v..v,<<<+55<< 03!$v9:_>1v$>9%\v^|:<_v#<%<9<:<<_v#+%*93\!::<,,"|"<\/>:#^_>>>v^ p|<$0.0^!g+:#9/9<^@ ^,>#+5<5_>#!<>#$0"------+-------+-----":#<^ <>v$v1:::0<>"P"`!^>0g#0v#p+9/9\%9:p04:\pg03g021pg03g011pg03g001 ::>^_:#<0#!:p#-\#1:#g0<>30g010g30g020g30g040g:9%\:9/9+\01-\1+0:
http://rosettacode.org/wiki/Subleq
Subleq
Subleq is an example of a One-Instruction Set Computer (OISC). It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero. Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory consists of an array of signed integers.   These integers may be interpreted in three ways:   simple numeric values   memory addresses   characters for input or output Any reasonable word size that accommodates all three of the above uses is fine. The program should load the initial contents of the emulated machine's memory, set the instruction pointer to the first address (which is defined to be address 0), and begin emulating the machine, which works as follows:   Let A be the value in the memory location identified by the instruction pointer;   let B and C be the values stored in the next two consecutive addresses in memory.   Advance the instruction pointer three words, to point at the address after the address containing C.   If A is   -1   (negative unity),   then a character is read from the machine's input and its numeric value stored in the address given by B.   C is unused.   If B is   -1   (negative unity),   then the number contained in the address given by A is interpreted as a character and written to the machine's output.   C is unused.   Otherwise, both A and B are treated as addresses.   The number contained in address A is subtracted from the number in address B (and the difference left in address B).   If the result is positive, execution continues uninterrupted; if the result is zero or negative, the number in C becomes the new instruction pointer.   If the instruction pointer becomes negative, execution halts. Your solution may initialize the emulated machine's memory in any convenient manner, but if you accept it as input, it should be a separate input stream from the one fed to the emulated machine once it is running. And if fed as text input, it should be in the form of raw subleq "machine code" - whitespace-separated decimal numbers, with no symbolic names or other assembly-level extensions, to be loaded into memory starting at address   0   (zero). For purposes of this task, show the output of your solution when fed the below   "Hello, world!"   program. As written, this example assumes ASCII or a superset of it, such as any of the Latin-N character sets or Unicode;   you may translate the numbers representing characters (starting with 72=ASCII 'H') into another character set if your implementation runs in a non-ASCII-compatible environment. If 0 is not an appropriate terminator in your character set, the program logic will need some adjustment as well. 15 17 -1 17 -1 -1 16 1 -1 16 3 -1 15 15 0 0 -1 72 101 108 108 111 44 32 119 111 114 108 100 33 10 0 The above "machine code" corresponds to something like this in a hypothetical assembler language for a signed 8-bit version of the machine: start: 0f 11 ff subleq (zero), (message), -1 11 ff ff subleq (message), -1, -1  ; output character at message 10 01 ff subleq (neg1), (start+1), -1 10 03 ff subleq (neg1), (start+3), -1 0f 0f 00 subleq (zero), (zero), start ; useful constants zero: 00 .data 0 neg1: ff .data -1 ; the message to print message: .data "Hello, world!\n\0" 48 65 6c 6c 6f 2c 20 77 6f 72 6c 64 21 0a 00
#BASIC
BASIC
10 DEFINT A-Z: DIM M(8192) 20 INPUT "Filename";F$ 30 OPEN "I",1,F$ 40 GOTO 70 50 INPUT #1,M(I) 60 I=I+1 70 IF EOF(1) THEN CLOSE(1) ELSE GOTO 50 80 I=0 90 A=M(I): B=M(I+1): C=M(I+2): I=I+3 100 IF A=-1 GOTO 150 ELSE IF B=-1 GOTO 190 120 M(B) = M(B) - M(A) 130 IF M(B)<=0 THEN I=C 140 IF I>=0 GOTO 90 ELSE END 150 A$ = INPUT$(1): PRINT A$; 160 C = ASC(A$): IF C=13 THEN C=10 170 M(B) = C 180 GOTO 90 190 IF M(A)=10 THEN PRINT ELSE PRINT(CHR$(M(A) AND 255)); 200 GOTO 90
http://rosettacode.org/wiki/Successive_prime_differences
Successive prime differences
The series of increasing prime numbers begins: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, ... The task applies a filter to the series returning groups of successive primes, (s'primes), that differ from the next by a given value or values. Example 1: Specifying that the difference between s'primes be 2 leads to the groups: (3, 5), (5, 7), (11, 13), (17, 19), (29, 31), ... (Known as Twin primes or Prime pairs) Example 2: Specifying more than one difference between s'primes leads to groups of size one greater than the number of differences. Differences of 2, 4 leads to the groups: (5, 7, 11), (11, 13, 17), (17, 19, 23), (41, 43, 47), .... In the first group 7 is two more than 5 and 11 is four more than 7; as well as 5, 7, and 11 being successive primes. Differences are checked in the order of the values given, (differences of 4, 2 would give different groups entirely). Task In each case use a list of primes less than 1_000_000 For the following Differences show the first and last group, as well as the number of groups found: Differences of 2. Differences of 1. Differences of 2, 2. Differences of 2, 4. Differences of 4, 2. Differences of 6, 4, 2. Show output here. Note: Generation of a list of primes is a secondary aspect of the task. Use of a built in function, well known library, or importing/use of prime generators from other Rosetta Code tasks is encouraged. references https://pdfs.semanticscholar.org/78a1/7349819304863ae061df88dbcb26b4908f03.pdf https://www.primepuzzles.net/puzzles/puzz_011.htm https://matheplanet.de/matheplanet/nuke/html/viewtopic.php?topic=232720&start=0
#FreeBASIC
FreeBASIC
#include "isprime.bas"   function nextprime( n as uinteger ) as uinteger 'finds the next prime after n if n = 0 then return 2 if n < 3 then return n + 1 dim as integer q = n + 2 while not isprime(q) q+=2 wend return q end function   function spd( byval n as integer, d() as integer ) as boolean if not isprime(n) then return false for i as integer = lbound(d) to ubound(d) if not nextprime(n) = n + d(i) then return false n+=d(i) next i return true end function   sub print_set( byval n as uinteger, d() as uinteger ) print "( ";n;" "; for i as integer = lbound(d) to ubound(d) print n+d(i);" "; n+=d(i) next i print ")" end sub   function count_below( max as uinteger, d() as uinteger ) as uinteger dim as uinteger c = 0, last = 0 for n as uinteger = 2 to max-d(ubound(d)) if spd(n, d()) then c+=1 if c=1 then print_set( n, d() ) last = n end if next n print_set(last, d()) return c end function   dim as integer n, c   'example 1, differences of 2 redim as uinteger d(0) d(0) = 2 print "Differences of 2 (the twin primes)" c = count_below(1000000, d()) print "Number of occurrences: ", c   'example 2, difference of 1 d(0) = 1 print print "Differences of 1" c = count_below(1000000, d()) print "Number of occurrences: ", c   'example 3, differences of 2,2 redim as uinteger d(1) d(0) = 2 : d(1) = 2 print print "Differences of 2, 2" c = count_below(1000000, d()) print "Number of occurrences: ", c   'example 4, differences of 2,4 d(1) = 4 print print "Differences of 2, 4" c = count_below(1000000, d()) print "Number of occurrences: ", c   'example 5, differences of 2,2 d(0) = 4 : d(1) = 2 print print "Differences of 4, 2" c = count_below(1000000, d()) print "Number of occurrences: ", c   'example 6, differences of 6,4,2 redim as uinteger d(2) d(0) = 6 : d(1) = 4 : d(2) = 2 print print "Differences of 6, 4, 2" c = count_below(1000000, d()) print "Number of occurrences: ", c
http://rosettacode.org/wiki/Substring/Top_and_tail
Substring/Top and tail
The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed If the program uses UTF-8 or UTF-16, it must work on any valid Unicode code point, whether in the Basic Multilingual Plane or above it. The program must reference logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16. Programs for other encodings (such as 8-bit ASCII, or EUC-JP) are not required to handle all Unicode characters. 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
#Bracmat
Bracmat
(substringUTF-8= @( Δημοτική  : (%?a&utf$!a) ?"String with first character removed" ) & @( Δημοτική  : ?"String with last character removed" (?z&utf$!z) ) & @( Δημοτική  : (%?a&utf$!a)  ?"String with both the first and last characters removed" (?z&utf$!z) ) & out $ ("String with first character removed:" !"String with first character removed") & out $ ("String with last character removed:" !"String with last character removed") & out $ ( "String with both the first and last characters removed:"  !"String with both the first and last characters removed" ));
http://rosettacode.org/wiki/Subtractive_generator
Subtractive generator
A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence. The formula is r n = r ( n − i ) − r ( n − j ) ( mod m ) {\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod {m}}} for some fixed values of i {\displaystyle i} , j {\displaystyle j} and m {\displaystyle m} , all positive integers. Supposing that i > j {\displaystyle i>j} , then the state of this generator is the list of the previous numbers from r n − i {\displaystyle r_{n-i}} to r n − 1 {\displaystyle r_{n-1}} . Many states generate uniform random integers from 0 {\displaystyle 0} to m − 1 {\displaystyle m-1} , but some states are bad. A state, filled with zeros, generates only zeros. If m {\displaystyle m} is even, then a state, filled with even numbers, generates only even numbers. More generally, if f {\displaystyle f} is a factor of m {\displaystyle m} , then a state, filled with multiples of f {\displaystyle f} , generates only multiples of f {\displaystyle f} . All subtractive generators have some weaknesses. The formula correlates r n {\displaystyle r_{n}} , r ( n − i ) {\displaystyle r_{(n-i)}} and r ( n − j ) {\displaystyle r_{(n-j)}} ; these three numbers are not independent, as true random numbers would be. Anyone who observes i {\displaystyle i} consecutive numbers can predict the next numbers, so the generator is not cryptographically secure. The authors of Freeciv (utility/rand.c) and xpat2 (src/testit2.c) knew another problem: the low bits are less random than the high bits. The subtractive generator has a better reputation than the linear congruential generator, perhaps because it holds more state. A subtractive generator might never multiply numbers: this helps where multiplication is slow. A subtractive generator might also avoid division: the value of r ( n − i ) − r ( n − j ) {\displaystyle r_{(n-i)}-r_{(n-j)}} is always between − m {\displaystyle -m} and m {\displaystyle m} , so a program only needs to add m {\displaystyle m} to negative numbers. The choice of i {\displaystyle i} and j {\displaystyle j} affects the period of the generator. A popular choice is i = 55 {\displaystyle i=55} and j = 24 {\displaystyle j=24} , so the formula is r n = r ( n − 55 ) − r ( n − 24 ) ( mod m ) {\displaystyle r_{n}=r_{(n-55)}-r_{(n-24)}{\pmod {m}}} The subtractive generator from xpat2 uses r n = r ( n − 55 ) − r ( n − 24 ) ( mod 10 9 ) {\displaystyle r_{n}=r_{(n-55)}-r_{(n-24)}{\pmod {10^{9}}}} The implementation is by J. Bentley and comes from program_tools/universal.c of the DIMACS (netflow) archive at Rutgers University. It credits Knuth, TAOCP, Volume 2, Section 3.2.2 (Algorithm A). Bentley uses this clever algorithm to seed the generator. Start with a single s e e d {\displaystyle seed} in range 0 {\displaystyle 0} to 10 9 − 1 {\displaystyle 10^{9}-1} . Set s 0 = s e e d {\displaystyle s_{0}=seed} and s 1 = 1 {\displaystyle s_{1}=1} . The inclusion of s 1 = 1 {\displaystyle s_{1}=1} avoids some bad states (like all zeros, or all multiples of 10). Compute s 2 , s 3 , . . . , s 54 {\displaystyle s_{2},s_{3},...,s_{54}} using the subtractive formula s n = s ( n − 2 ) − s ( n − 1 ) ( mod 10 9 ) {\displaystyle s_{n}=s_{(n-2)}-s_{(n-1)}{\pmod {10^{9}}}} . Reorder these 55 values so r 0 = s 34 {\displaystyle r_{0}=s_{34}} , r 1 = s 13 {\displaystyle r_{1}=s_{13}} , r 2 = s 47 {\displaystyle r_{2}=s_{47}} , ..., r n = s ( 34 ∗ ( n + 1 ) ( mod 55 ) ) {\displaystyle r_{n}=s_{(34*(n+1){\pmod {55}})}} . This is the same order as s 0 = r 54 {\displaystyle s_{0}=r_{54}} , s 1 = r 33 {\displaystyle s_{1}=r_{33}} , s 2 = r 12 {\displaystyle s_{2}=r_{12}} , ..., s n = r ( ( 34 ∗ n ) − 1 ( mod 55 ) ) {\displaystyle s_{n}=r_{((34*n)-1{\pmod {55}})}} . This rearrangement exploits how 34 and 55 are relatively prime. Compute the next 165 values r 55 {\displaystyle r_{55}} to r 219 {\displaystyle r_{219}} . Store the last 55 values. This generator yields the sequence r 220 {\displaystyle r_{220}} , r 221 {\displaystyle r_{221}} , r 222 {\displaystyle r_{222}} and so on. For example, if the seed is 292929, then the sequence begins with r 220 = 467478574 {\displaystyle r_{220}=467478574} , r 221 = 512932792 {\displaystyle r_{221}=512932792} , r 222 = 539453717 {\displaystyle r_{222}=539453717} . By starting at r 220 {\displaystyle r_{220}} , this generator avoids a bias from the first numbers of the sequence. This generator must store the last 55 numbers of the sequence, so to compute the next r n {\displaystyle r_{n}} . Any array or list would work; a ring buffer is ideal but not necessary. Implement a subtractive generator that replicates the sequences from xpat2.
#Fortran
Fortran
module subgenerator implicit none   integer, parameter :: modulus = 1000000000 integer :: s(0:54), r(0:54)   contains   subroutine initgen(seed) integer :: seed integer :: n, rnum   s(0) = seed s(1) = 1   do n = 2, 54 s(n) = mod(s(n-2) - s(n-1), modulus) if (s(n) < 0) s(n) = s(n) + modulus end do   do n = 0, 54 r(n) = s(mod(34*(n+1), 55)) end do   do n = 1, 165 rnum = subrand() end do   end subroutine initgen   integer function subrand() integer, save :: p1 = 0 integer, save :: p2 = 31   r(p1) = mod(r(p1) - r(p2), modulus) if (r(p1) < 0) r(p1) = r(p1) + modulus subrand = r(p1) p1 = mod(p1 + 1, 55) p2 = mod(p2 + 1, 55)   end function subrand end module subgenerator   program subgen_test use subgenerator implicit none   integer :: seed = 292929 integer :: i   call initgen(seed) do i = 1, 10 write(*,*) subrand() end do   end program
http://rosettacode.org/wiki/Substitution_cipher
Substitution cipher
Substitution Cipher Implementation - File Encryption/Decryption Task Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypted file into original/decrypted file. This type of Encryption/Decryption scheme is often called a Substitution Cipher. Related tasks Caesar cipher Rot-13 Vigenère Cipher/Cryptanalysis See also Wikipedia: Substitution cipher
#Picat
Picat
main => S = "The quick brown fox jumped over the lazy dog", cypher(S,E),  % encrypt println(E),   cypher(D, E), % decrypt println(D),   S == D, println(ok).   cypher(O, S) :- nonvar(O), var(S), sub_chars(O,S). cypher(O, S) :- nonvar(S), var(O), sub_chars(O,S).   base("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz "). subs("VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWob LkESYMTN").   sub_chars(Original,Subbed) :- base(Base), subs(Subs), maplist($sub_char(Base,Subs),Original,Subbed).   sub_char([Co|_],[Cs|_],Co,Cs) :- !. sub_char([_|To],[_|Ts], Co, Cs) :- sub_char(To,Ts,Co,Cs).   maplist(Goal, List1, List2) :- maplist_(List1, List2, Goal).   maplist_([], X, _) :- X = []. maplist_([Elem1|Tail1], [Elem2|Tail2], Goal) :- call(Goal, Elem1, Elem2), maplist_(Tail1, Tail2, Goal).
http://rosettacode.org/wiki/Substitution_cipher
Substitution cipher
Substitution Cipher Implementation - File Encryption/Decryption Task Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypted file into original/decrypted file. This type of Encryption/Decryption scheme is often called a Substitution Cipher. Related tasks Caesar cipher Rot-13 Vigenère Cipher/Cryptanalysis See also Wikipedia: Substitution cipher
#PicoLisp
PicoLisp
(setq *A (chop "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")) (setq *K (chop "VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWobLkESYMTN"))   (de cipher (Str D) (let (K *K A *A) (and D (xchg 'A 'K)) (pack (mapcar '((N) (or (pick '((A K) (and (= A N) K)) A K ) N ) ) (chop Str) ) ) ) ) (and (println 'encode (cipher "The quick brown fox jumped over the lazy dog's back")) (println 'decode (cipher @ T)) )
http://rosettacode.org/wiki/Substitution_cipher
Substitution cipher
Substitution Cipher Implementation - File Encryption/Decryption Task Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypted file into original/decrypted file. This type of Encryption/Decryption scheme is often called a Substitution Cipher. Related tasks Caesar cipher Rot-13 Vigenère Cipher/Cryptanalysis See also Wikipedia: Substitution cipher
#Pike
Pike
string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; string key = "VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWobLkESYMTN"; mapping key_mapping = mkmapping(alphabet/1, key/1); object c = Crypto.Substitution()->set_key(key_mapping);   string msg = "The quick brown fox jumped over the lazy dogs"; string msg_enc = c->encrypt(msg); string msg_dec = c->decrypt(msg_enc);   write("Encrypted: %s\n", msg_enc); write("Decrypted: %s\n", msg_dec);
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#Elena
Elena
import system'routines; import extensions;   public program() { var list := new int[]{1, 2, 3, 4, 5 };   var sum := list.summarize(new Integer()); var product := list.accumulate(new Integer(1), (var,val => var * val)); }
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#Elixir
Elixir
iex(26)> Enum.reduce([1,2,3,4,5], 0, fn x,acc -> x+acc end) 15 iex(27)> Enum.reduce([1,2,3,4,5], 1, fn x,acc -> x*acc end) 120 iex(28)> Enum.reduce([1,2,3,4,5], fn x,acc -> x+acc end) 15 iex(29)> Enum.reduce([1,2,3,4,5], fn x,acc -> x*acc end) 120 iex(30)> Enum.reduce([], 0, fn x,acc -> x+acc end) 0 iex(31)> Enum.reduce([], 1, fn x,acc -> x*acc end) 1 iex(32)> Enum.reduce([], fn x,acc -> x+acc end) ** (Enum.EmptyError) empty error (elixir) lib/enum.ex:1287: Enum.reduce/2 iex(32)> Enum.reduce([], fn x,acc -> x*acc end) ** (Enum.EmptyError) empty error (elixir) lib/enum.ex:1287: Enum.reduce/2
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displaystyle S_{n}=\sum _{k=1}^{n}{\frac {1}{k^{2}}}} and compute   S 1000 {\displaystyle S_{1000}} This approximates the   zeta function   for   S=2,   whose exact value ζ ( 2 ) = π 2 6 {\displaystyle \zeta (2)={\pi ^{2} \over 6}} is the solution of the Basel problem.
#Dyalect
Dyalect
func Integer.SumSeries() { var ret = 0   for i in 1..this { ret += 1 / pow(Float(i), 2) }   ret }   var x = 1000 print(x.SumSeries())
http://rosettacode.org/wiki/Strip_comments_from_a_string
Strip comments from a string
Strip comments from a string You are encouraged to solve this task according to the task description, using any language you may know. The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line. Whitespace debacle:   There is some confusion about whether to remove any whitespace from the input line. As of 2 September 2011, at least 8 languages (C, C++, Java, Perl, Python, Ruby, sed, UNIX Shell) were incorrect, out of 36 total languages, because they did not trim whitespace by 29 March 2011 rules. Some other languages might be incorrect for the same reason. Please discuss this issue at Talk:Strip comments from a string. From 29 March 2011, this task required that: "The comment marker and any whitespace at the beginning or ends of the resultant line should be removed. A line without comments should be trimmed of any leading or trailing whitespace before being produced as a result." The task had 28 languages, which did not all meet this new requirement. From 28 March 2011, this task required that: "Whitespace before the comment marker should be removed." From 30 October 2010, this task did not specify whether or not to remove whitespace. The following examples will be truncated to either "apples, pears " or "apples, pears". (This example has flipped between "apples, pears " and "apples, pears" in the past.) apples, pears # and bananas apples, pears ; and bananas 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
#Action.21
Action!
PROC Strip(CHAR ARRAY text,chars,result) BYTE i,j,pos,found   pos=text(0) FOR i=1 TO text(0) DO found=0 FOR j=1 TO chars(0) DO IF text(i)=chars(j) THEN found=1 EXIT FI OD IF found THEN pos=i-1 EXIT FI OD WHILE pos>0 AND text(pos)=' DO pos==-1 OD SCopyS(result,text,1,pos) RETURN   PROC Test(CHAR ARRAY text,chars) CHAR ARRAY result(255)   Strip(text,chars,result) PrintF("""%S"", ""%S"" -> ""%S""%E%E",text,chars,result) RETURN   PROC Main() Test("apples, pears # and bananas","#;") Test("apples, pears ; and bananas","#;") Test("qwerty # asdfg ; zxcvb","#") Test("qwerty # asdfg ; zxcvb",";") Test("  ;this is a comment","#;") Test("#this is a comment","#;") Test(" ",";") Test("","#") RETURN
http://rosettacode.org/wiki/Strip_comments_from_a_string
Strip comments from a string
Strip comments from a string You are encouraged to solve this task according to the task description, using any language you may know. The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line. Whitespace debacle:   There is some confusion about whether to remove any whitespace from the input line. As of 2 September 2011, at least 8 languages (C, C++, Java, Perl, Python, Ruby, sed, UNIX Shell) were incorrect, out of 36 total languages, because they did not trim whitespace by 29 March 2011 rules. Some other languages might be incorrect for the same reason. Please discuss this issue at Talk:Strip comments from a string. From 29 March 2011, this task required that: "The comment marker and any whitespace at the beginning or ends of the resultant line should be removed. A line without comments should be trimmed of any leading or trailing whitespace before being produced as a result." The task had 28 languages, which did not all meet this new requirement. From 28 March 2011, this task required that: "Whitespace before the comment marker should be removed." From 30 October 2010, this task did not specify whether or not to remove whitespace. The following examples will be truncated to either "apples, pears " or "apples, pears". (This example has flipped between "apples, pears " and "apples, pears" in the past.) apples, pears # and bananas apples, pears ; and bananas 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
#Ada
Ada
with Ada.Text_IO; procedure Program is Comment_Characters : String := "#;"; begin loop declare Line : String := Ada.Text_IO.Get_Line; begin exit when Line'Length = 0; Outer_Loop : for I in Line'Range loop for J in Comment_Characters'Range loop if Comment_Characters(J) = Line(I) then Ada.Text_IO.Put_Line(Line(Line'First .. I - 1)); exit Outer_Loop; end if; end loop; end loop Outer_Loop; end; end loop; end Program;
http://rosettacode.org/wiki/Strip_block_comments
Strip block comments
A block comment begins with a   beginning delimiter   and ends with a   ending delimiter,   including the delimiters.   These delimiters are often multi-character sequences. Task Strip block comments from program text (of a programming language much like classic C). Your demos should at least handle simple, non-nested and multi-line block comment delimiters. The block comment delimiters are the two-character sequences:     /*     (beginning delimiter)     */     (ending delimiter) Sample text for stripping: /** * Some comments * longer comments here that we can parse. * * Rahoo */ function subroutine() { a = /* inline comment */ b + c ; } /*/ <-- tricky comments */ /** * Another comment. */ function something() { } Extra credit Ensure that the stripping code is not hard-coded to the particular delimiters described above, but instead allows the caller to specify them.   (If your language supports them,   optional parameters   may be useful for this.) 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
#ALGOL_W
ALGOL W
begin  % strips block comments from a source  %  % the source is read from standard input and the result written to  %  % standard output, The comment start text is in cStart and the ending  %  % is in cEnd.  %  % As strings are fixed length in Algol W, the first space in cStart/cEnd  %  % is assumed to terminate the delimiter, i.e. the comment start/end  %  % delimiters cannot contain spaces.  %  % If non-blank, quote1 and quote2 are the string quote characters.  %  % If escape is non-blank it indicates that quotes can be embedded in  %  % string literals by preceding them with escape (as in C, java, etc.).  % procedure stripBlockComments( string(32) value cStart, cEnd  ; string(1) value quote1, quote2, escape ) ; begin integer columnNumber, lineWidth; string(256) line; string(1) currChar; string(1) newlineChar;  % gets the next source character  % procedure nextChar ; begin if columnNumber = lineWidth then begin currChar  := newlineChar; columnNumber := columnNumber + 1 end else if columnNumber > lineWidth then begin readcard( line ); lineWidth := 256; while lineWidth > 0 and line( lineWidth - 1 // 1 ) = " " do lineWidth := lineWidth - 1; columnNumber := 1; currChar  := line( 0 // 1 ) end else begin currChar  := line( columnNumber // 1 ); columnNumber := columnNumber + 1 end end nextChar ;  % copy the current character and get the next  % procedure copyAndNext ; begin if currChar = newlineChar then write() else writeon( currChar ); nextChar end copyAndNext ;  % skips the current character and gets the next  % procedure skipAndNext ; begin if currChar not = newlineChar then currChar := " "; copyAndNext end skipAndNext ;  % handle a string literal  % procedure stringLiteral( string(1) value quote, escape ) ; begin copyAndNext; while currChar not = quote and not XCPNOTED(ENDFILE) do begin if escape <> " " and currChar = escape then copyAndNext; if not XCPNOTED(ENDFILE) then copyAndNext end while_have_more_string ; if currChar = quote then copyAndNext end stringLiteral ;  % returns true if the line continues with the specified text  %  % false if not.  % logical procedure remainingLineStartsWith ( string(32) value text ) ; begin logical haveText; integer lPos, wPos; haveText := currChar = text( 0 // 1 ); lPos  := columnNumber; wPos  := 1; while haveText and wPos <= 32 and text( wPos // 1 ) not = " " do begin if lPos >= lineWidth then begin  % past the end of the line  % haveText := false end else begin  % still have text on the line  % haveText := line( lPos // 1 ) = text( wPos // 1 ); wPos  := wPos + 1; lPos  := lPos + 1; end if_past_end_of_line_ end while_have_text_and_more_text ; haveText end remainingLineStartsWith ;  % skips the number of leading non-blank characters in the delimiter  % procedure skipDelimiter( string(32) value delimiter ) ; begin integer dPos; dPos := 0; while dPos < 32 and not XCPNOTED(ENDFILE) and delimiter( dPos // 1 ) not = " " do begin dPos := dPos + 1; skipAndNext end while_not_at_end_of_delimiter end skipDelimiter ; newlineChar  := code( 10 ); lineWidth  := 0; columnNumber := lineWidth + 1; currChar  := " ";  % allow the program to continue after reaching end-of-file % ENDFILE  := EXCEPTION( false, 1, 0, false, "EOF" );  % get the first source character  % nextChar;  % strip the comments  % while not XCPNOTED(ENDFILE) do begin if currChar = " " then copyAndNext else if remainingLineStartsWith( cStart ) then begin  % have a comment  % skipDelimiter( cStart ); while not remainingLineStartsWith( cEnd ) and not XCPNOTED(ENDFILE) do skipAndNext; skipDelimiter( cEnd ) end else if currChar = quote1 then stringLiteral( quote1, escape ) else if currChar = quote2 then stringLiteral( quote2, escape ) else copyAndNext end while_not_at_eof end stripBlockComments ;  % text stripBlockComments for C-style source  % stripBlockComments( "/*", "*/", """", "'", "\" ) end.
http://rosettacode.org/wiki/Strip_block_comments
Strip block comments
A block comment begins with a   beginning delimiter   and ends with a   ending delimiter,   including the delimiters.   These delimiters are often multi-character sequences. Task Strip block comments from program text (of a programming language much like classic C). Your demos should at least handle simple, non-nested and multi-line block comment delimiters. The block comment delimiters are the two-character sequences:     /*     (beginning delimiter)     */     (ending delimiter) Sample text for stripping: /** * Some comments * longer comments here that we can parse. * * Rahoo */ function subroutine() { a = /* inline comment */ b + c ; } /*/ <-- tricky comments */ /** * Another comment. */ function something() { } Extra credit Ensure that the stripping code is not hard-coded to the particular delimiters described above, but instead allows the caller to specify them.   (If your language supports them,   optional parameters   may be useful for this.) 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
code = ( /** * Some comments * longer comments here that we can parse. * * Rahoo */ function subroutine() { a = /* inline comment */ b + c ; } /*/ <-- tricky comments */   /** * Another comment. */ function something() { } ) ;Open-Close Comment delimiters openC:="/*" closeC:="*/" ;Make it "Regex-Safe" openC:=RegExReplace(openC,"(\*|\^|\?|\\|\+|\.|\!|\{|\}|\[|\]|\$|\|)","\$0") closeC:=RegExReplace(closeC,"(\*|\^|\?|\\|\+|\.|\!|\{|\}|\[|\]|\$|\|)","\$0") ;Display final result MsgBox % sCode := RegExReplace(code,"s)(" . openC . ").*?(" . closeC . ")")
http://rosettacode.org/wiki/Sum_to_100
Sum to 100
Task Find solutions to the   sum to one hundred   puzzle. Add (insert) the mathematical operators     +   or   -     (plus or minus)   before any of the digits in the decimal numeric string   123456789   such that the resulting mathematical expression adds up to a particular sum   (in this iconic case,   100). Example: 123 + 4 - 5 + 67 - 89 = 100 Show all output here.   Show all solutions that sum to   100   Show the sum that has the maximum   number   of solutions   (from zero to infinity‡)   Show the lowest positive sum that   can't   be expressed   (has no solutions),   using the rules for this task   Show the ten highest numbers that can be expressed using the rules for this task   (extra credit) ‡   (where   infinity   would be a relatively small   123,456,789) An example of a sum that can't be expressed   (within the rules of this task)   is:   5074 (which,   of course,   isn't the lowest positive sum that can't be expressed).
#Lua
Lua
local expressionsLength = 0 function compareExpressionBySum(a, b) return a.sum - b.sum end   local countSumsLength = 0 function compareCountSumsByCount(a, b) return a.counts - b.counts end   function evaluate(code) local value = 0 local number = 0 local power = 1 for k=9,1,-1 do number = power*k + number local mod = code % 3 if mod == 0 then -- ADD value = value + number number = 0 power = 1 elseif mod == 1 then -- SUB value = value - number number = 0 power = 1 elseif mod == 2 then -- JOIN power = 10 * power else print("This should not happen.") end code = math.floor(code / 3) end return value end   function printCode(code) local a = 19683 local b = 6561 local s = "" for k=1,9 do local temp = math.floor((code % a) / b) if temp == 0 then -- ADD if k>1 then s = s .. '+' end elseif temp == 1 then -- SUB s = s .. '-' end a = b b = math.floor(b/3) s = s .. tostring(k) end print("\t"..evaluate(code).." = "..s) end   -- Main local nexpr = 13122   print("Show all solutions that sum to 100") for i=0,nexpr-1 do if evaluate(i) == 100 then printCode(i) end end print()   print("Show the sum that has the maximum number of solutions") local nbest = -1 for i=0,nexpr-1 do local test = evaluate(i) if test>0 then local ntest = 0 for j=0,nexpr-1 do if evaluate(j) == test then ntest = ntest + 1 end if ntest > nbest then best = test nbest = ntest end end end end print(best.." has "..nbest.." solutions\n")   print("Show the lowest positive number that can't be expressed") local code = -1 for i=0,123456789 do for j=0,nexpr-1 do if evaluate(j) == i then code = j break end end if evaluate(code) ~= i then code = i break end end print(code.."\n")   print("Show the ten highest numbers that can be expressed") local limit = 123456789 + 1 for i=1,10 do local best=0 for j=0,nexpr-1 do local test = evaluate(j) if (test<limit) and (test>best) then best = test end end for j=0,nexpr-1 do if evaluate(j) == best then printCode(j) end end limit = best end
http://rosettacode.org/wiki/Strip_a_set_of_characters_from_a_string
Strip a set of characters from a string
Task Create a function that strips a set of characters from a string. The function should take two arguments:   a string to be stripped   a string containing the set of characters to be stripped The returned string should contain the first string, stripped of any characters in the second argument: print stripchars("She was a soul stripper. She took my heart!","aei") Sh ws soul strppr. Sh took my hrt! 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
#360_Assembly
360 Assembly
* Strip a set of characters from a string 07/07/2016 STRIPCH CSECT USING STRIPCH,R13 base register B 72(R15) skip savearea DC 17F'0' savearea STM R14,R12,12(R13) prolog ST R13,4(R15) " <- ST R15,8(R13) " -> LR R13,R15 " addressability LA R1,PARMLIST parameter list BAL R14,STRIPCHR c3=stripchr(c1,c2) LA R2,PG @pg LH R3,C3 length(c3) LA R4,C3+2 @c3 LR R5,R3 length(c3) MVCL R2,R4 pg=c3 XPRNT PG,80 print buffer L R13,4(0,R13) epilog LM R14,R12,12(R13) " restore XR R15,R15 " rc=0 BR R14 exit PARMLIST DC A(C3) @c3 DC A(C1) @c1 DC A(C2) @c2 C1 DC H'43',CL62'She was a soul stripper. She took my heart!' C2 DC H'3',CL14'aei' c2 [varchar(14)] C3 DS H,CL62 c3 [varchar(62)] PG DC CL80' ' buffer [char(80)] *------- stripchr ----------------------------------------------------- STRIPCHR L R9,0(R1) @parm1 L R2,4(R1) @parm2 L R3,8(R1) @parm3 MVC PHRASE(64),0(R2) phrase=parm2 MVC REMOVE(16),0(R3) remove=parm3 SR R8,R8 k=0 LA R6,1 i=1 LOOPI CH R6,PHRASE do i=1 to length(phrase) BH ELOOPI " LA R4,PHRASE+1 @phrase AR R4,R6 +i MVC CI(1),0(R4) ci=substr(phrase,i,1) MVI OK,X'01' ok='1'B LA R7,1 j=1 LOOPJ CH R7,REMOVE do j=1 to length(remove) BH ELOOPJ " LA R4,REMOVE+1 @remove AR R4,R7 +j MVC CJ,0(R4) cj=substr(remove,j,1) CLC CI,CJ if ci=cj BNE CINECJ then MVI OK,X'00' ok='0'B B ELOOPJ leave j CINECJ LA R7,1(R7) j=j+1 B LOOPJ end do j ELOOPJ CLI OK,X'01' if ok BNE NOTOK then LA R8,1(R8) k=k+1 LA R4,RESULT+1 @result AR R4,R8 +k MVC 0(1,R4),CI substr(result,k,1)=ci NOTOK LA R6,1(R6) i=i+1 B LOOPI end do i ELOOPI STH R8,RESULT length(result)=k MVC 0(64,R9),RESULT return(result) BR R14 return to caller CI DS CL1 ci [char(1)] CJ DS CL1 cj [char(1)] OK DS X ok [boolean] PHRASE DS H,CL62 phrase [varchar(62)] REMOVE DS H,CL14 remove [varchar(14)] RESULT DS H,CL62 result [varchar(62)] * ---- ------------------------------------------------------- YREGS END STRIPCH
http://rosettacode.org/wiki/Strip_a_set_of_characters_from_a_string
Strip a set of characters from a string
Task Create a function that strips a set of characters from a string. The function should take two arguments:   a string to be stripped   a string containing the set of characters to be stripped The returned string should contain the first string, stripped of any characters in the second argument: print stripchars("She was a soul stripper. She took my heart!","aei") Sh ws soul strppr. Sh took my hrt! 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
#8080_Assembly
8080 Assembly
org 100h jmp demo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Strip a set of chracters from a string, in place. ;;; Input: ;;; DE = $-terminated string to be stripped ;;; HL = $-terminated string containing characters to strip stripchars: push h ; Store characters to strip on stack. mov b,d ; Copy input string pointer to BC. This will be mov c,e ; the target pointer. stripchr: ldax d ; Copy current character from [DE] to [BC] stax b cpi '$' ; Done? jz stripdone pop h ; Get string of characters to strip. push h stripsrch: mvi a,'$' ; At the end? cmp m jz srchdone ldax d ; Does it match the character in the input? cmp m jz srchfound inx h ; Look at next character to strip jmp stripsrch srchfound: dcx b ; Found: copy next character over it later. srchdone: inx b ; Increment both pointers inx d jmp stripchr stripdone: pop h ; Remove temporary variable from stack ret ; Done ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; demo: lxi d,string ; Strip from the string, lxi h,remove ; the characters to remove. call stripchars lxi d,string ; Print the result. mvi c,9 jmp 5 string: db 'She was a soul stripper. She took my heart!$' remove: db 'aei$'
http://rosettacode.org/wiki/String_prepend
String prepend
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Create a string variable equal to any text value. Prepend the string variable with another string literal. If your language supports any idiomatic ways to do this without referring to the variable twice in one expression, include such solutions. To illustrate the operation, show the content of the variable.
#360_Assembly
360 Assembly
* String prepend - 14/04/2020 PREPEND CSECT USING PREPEND,13 base register B 72(15) skip savearea DC 17F'0' savearea SAVE (14,12) save previous context ST 13,4(15) link backward ST 15,8(13) link forward LR 13,15 set addressability MVC C+L'B(L'A),A c=a MVC C(L'B),B c=b+c (prepend) XPRNT C,L'C print buffer L 13,4(0,13) restore previous savearea pointer RETURN (14,12),RC=0 restore registers from calling sav A DC C'world!' a B DC C'Hello ' b C DC CL80' ' c END PREPEND
http://rosettacode.org/wiki/String_prepend
String prepend
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Create a string variable equal to any text value. Prepend the string variable with another string literal. If your language supports any idiomatic ways to do this without referring to the variable twice in one expression, include such solutions. To illustrate the operation, show the content of the variable.
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program appendstr64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64.inc"   /*******************************************/ /* Initialized data */ /*******************************************/ .data szMessString: .asciz "British Museum.\n" szComplement: .skip 80 szStringStart: .asciz "The rosetta stone is at " szCarriageReturn: .asciz "\n" /*******************************************/ /* UnInitialized data */ /*******************************************/ .bss /*******************************************/ /* code section */ /*******************************************/ .text .global main main:   ldr x0,qAdrszMessString // display message bl affichageMess   ldr x0,qAdrszMessString ldr x1,qAdrszStringStart bl prepend // append sting2 to string1 ldr x0,qAdrszMessString bl affichageMess   ldr x0,qAdrszCarriageReturn bl affichageMess     100: // standard end of the program mov x0,0 // return code mov x8,EXIT // request to exit program svc 0 // perform system call qAdrszMessString: .quad szMessString qAdrszStringStart: .quad szStringStart qAdrszCarriageReturn: .quad szCarriageReturn /**************************************************/ /* append two strings */ /**************************************************/ /* x0 contains the address of the string1 */ /* x1 contains the address of the string2 */ prepend: stp x1,lr,[sp,-16]! // save registers mov x3,#0 // length counter 1: // compute length of string 1 ldrb w4,[x0,x3] cmp w4,#0 cinc x3,x3,ne // increment to one if not equal bne 1b // loop if not equal mov x5,#0 // length counter insertion string 2: // compute length of insertion string ldrb w4,[x1,x5] cmp x4,#0 cinc x5,x5,ne // increment to one if not equal bne 2b cmp x5,#0 beq 99f // string empty -> error add x3,x3,x5 // add 2 length add x3,x3,#1 // +1 for final zero mov x6,x0 // save address string 1 mov x0,#0 // allocation place heap mov x8,BRK // call system 'brk' svc #0 mov x5,x0 // save address heap for output string add x0,x0,x3 // reservation place x3 length mov x8,BRK // call system 'brk' svc #0 cmp x0,#-1 // allocation error beq 99f mov x4,#0 // counter byte string 2 3: ldrb w3,[x1,x4] // load byte string 2 cbz x3,4f // zero final ? strb w3,[x5,x4] // store byte string 2 in heap add x4,x4,1 // increment counter 1 b 3b // no -> loop 4: mov x2,#0 // counter byte string 1 5: ldrb w3,[x6,x2] // load byte string 1 strb w3,[x5,x4] // store byte string in heap cbz x3,6f // zero final ? add x2,x2,1 // no -> increment counter 1 add x4,x4,1 // no -> increment counter 2 b 5b // no -> loop 6: // recopie heap in string 1 mov x2,#0 // counter byte string 7: ldrb w3,[x5,x2] // load byte string in heap strb w3,[x6,x2] // store byte string 1 cbz x3,100f // zero final ? add x2,x2,1 // no -> increment counter 1 b 7b // no -> loop 100:   ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 /********************************************************/ /* File Include fonctions */ /********************************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeARM64.inc"  
http://rosettacode.org/wiki/String_prepend
String prepend
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Create a string variable equal to any text value. Prepend the string variable with another string literal. If your language supports any idiomatic ways to do this without referring to the variable twice in one expression, include such solutions. To illustrate the operation, show the content of the variable.
#Action.21
Action!
PROC Append(CHAR ARRAY text,suffix) BYTE POINTER srcPtr,dstPtr BYTE len   len=suffix(0) IF text(0)+len>255 THEN len=255-text(0) FI IF len THEN srcPtr=suffix+1 dstPtr=text+text(0)+1 MoveBlock(dstPtr,srcPtr,len) text(0)==+suffix(0) FI RETURN   PROC Prepend(CHAR ARRAY text,prefix) CHAR ARRAY tmp(256)   SCopy(tmp,text) SCopy(text,prefix) Append(text,tmp) RETURN   PROC TestPrepend(CHAR ARRAY text,preffix) PrintF("Source ""%S"" at address %H%E",text,text) PrintF("Prepend ""%S""%E",preffix) Prepend(text,preffix) PrintF("Result ""%S"" at address %H%E",text,text) PutE() RETURN   PROC Main() CHAR ARRAY text(256)   text(0)=0 TestPrepend(text,"World!") TestPrepend(text,"Hello ") RETURN
http://rosettacode.org/wiki/Strip_control_codes_and_extended_characters_from_a_string
Strip control codes and extended characters from a string
Task Strip control codes and extended characters from a string. The solution should demonstrate how to achieve each of the following results:   a string with control codes stripped (but extended characters not stripped)   a string with control codes and extended characters stripped In ASCII, the control codes have decimal codes 0 through to 31 and 127. On an ASCII based system, if the control codes are stripped, the resultant string would have all of its characters within the range of 32 to 126 decimal on the ASCII table. On a non-ASCII based system, we consider characters that do not have a corresponding glyph on the ASCII table (within the ASCII range of 32 to 126 decimal) to be an extended character for the purpose of this task. 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
#ALGOL_68
ALGOL 68
# remove control characters and optionally extended characters from the string text # # assums ASCII is the character set # PROC strip characters = ( STRING text, BOOL strip extended )STRING: BEGIN # we build the result in a []CHAR and convert back to a string at the end # INT text start = LWB text; INT text max = UPB text; [ text start : text max ]CHAR result; INT result pos := text start; FOR text pos FROM text start TO text max DO INT ch := ABS text[ text pos ]; IF ( ch >= 0 AND ch <= 31 ) OR ch = 127 THEN # control character # SKIP ELIF strip extended AND ( ch > 126 OR ch < 0 ) THEN # extened character and we don't want them # SKIP ELSE # include this character # result[ result pos ] := REPR ch; result pos +:= 1 FI OD; result[ text start : result pos - 1 ] END # strip characters # ;   # test the control/extended character stripping procedure # STRING t = REPR 2 + "abc" + REPR 10 + REPR 160 + "def~" + REPR 127 + REPR 10 + REPR 150 + REPR 152 + "!"; print( ( "<<" + t + ">> - without control characters: <<" + strip characters( t, FALSE ) + ">>", newline ) ); print( ( "<<" + t + ">> - without control or extended characters: <<" + strip characters( t, TRUE ) + ">>", newline ) )
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5
Sum multiples of 3 and 5
Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
#F.23
F#
  let sum35 n = Seq.init n (id) |> Seq.reduce (fun sum i -> if i % 3 = 0 || i % 5 = 0 then sum + i else sum)   printfn "%d" (sum35 1000) printfn "----------"   let sumUpTo (n : bigint) = n * (n + 1I) / 2I   let sumMultsBelow k n = k * (sumUpTo ((n-1I)/k))   let sum35fast n = (sumMultsBelow 3I n) + (sumMultsBelow 5I n) - (sumMultsBelow 15I n)   [for i = 0 to 30 do yield i] |> List.iter (fun i -> printfn "%A" (sum35fast (bigint.Pow(10I, i))))
http://rosettacode.org/wiki/Sum_digits_of_an_integer
Sum digits of an integer
Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
#F.23
F#
open System   let digsum b n = let rec loop acc = function | n when n > 0 -> let m, r = Math.DivRem(n, b) loop (acc + r) m | _ -> acc loop 0 n   [<EntryPoint>] let main argv = let rec show = function | n :: b :: r -> printf " %d" (digsum b n); show r | _ -> ()   show [1; 10; 1234; 10; 0xFE; 16; 0xF0E; 16] // -> 1 10 29 29 0
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#Frink
Frink
  f = {|x| x^2} // Anonymous function which squares its argument a = [1,2,3,5,7] println[sum[map[f,a], 0]]  
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#F.C5.8Drmul.C3.A6
Fōrmulæ
# Just multiplying a vector by itself yields the sum of squares (it's an inner product) # It's necessary to check for the empty vector though SumSq := function(v) if Size(v) = 0 then return 0; else return v*v; fi; end;
http://rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail
Strip whitespace from a string/Top and tail
Task Demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results: String with leading whitespace removed String with trailing whitespace removed String with both leading and trailing whitespace removed For the purposes of this task whitespace includes non printable characters such as the space character, the tab character, and other such characters that have no corresponding graphical representation. 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
str: " Hello World "   print [pad "strip all:" 15 ">" strip str "<"] print [pad "strip leading:" 15 ">" strip.start str "<"] print [pad "strip trailing:" 15 ">" strip.end str "<"]
http://rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail
Strip whitespace from a string/Top and tail
Task Demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results: String with leading whitespace removed String with trailing whitespace removed String with both leading and trailing whitespace removed For the purposes of this task whitespace includes non printable characters such as the space character, the tab character, and other such characters that have no corresponding graphical representation. 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
string := " abc " MsgBox % clipboard := "<" LTrim(string) ">`n<" RTrim(string) ">`n<" . Trim(string) ">"
http://rosettacode.org/wiki/Strong_and_weak_primes
Strong and weak primes
Definitions   (as per number theory)   The   prime(p)   is the   pth   prime.   prime(1)   is   2   prime(4)   is   7   A   strong   prime   is when     prime(p)   is   >   [prime(p-1) + prime(p+1)] ÷ 2   A     weak    prime   is when     prime(p)   is   <   [prime(p-1) + prime(p+1)] ÷ 2 Note that the definition for   strong primes   is different when used in the context of   cryptography. Task   Find and display (on one line) the first   36   strong primes.   Find and display the   count   of the strong primes below   1,000,000.   Find and display the   count   of the strong primes below 10,000,000.   Find and display (on one line) the first   37   weak primes.   Find and display the   count   of the weak primes below   1,000,000.   Find and display the   count   of the weak primes below 10,000,000.   (Optional)   display the   counts   and   "below numbers"   with commas. Show all output here. Related Task   Safe primes and unsafe primes. Also see   The OEIS article A051634: strong primes.   The OEIS article A051635: weak primes.
#Factor
Factor
USING: formatting grouping kernel math math.primes sequences tools.memory.private ; IN: rosetta-code.strong-primes   : fn ( p-1 p p+1 -- p sum ) rot + 2 / ; : strong? ( p-1 p p+1 -- ? ) fn > ; : weak? ( p-1 p p+1 -- ? ) fn < ;   : swprimes ( seq quot -- seq ) [ 3 <clumps> ] dip [ first3 ] prepose filter [ second ] map  ; inline   : stats ( seq n -- firstn count1 count2 ) [ head ] [ drop [ 1e6 < ] filter length ] [ drop length ] 2tri [ commas ] bi@ ;   10,000,019 primes-upto [ strong? ] over [ weak? ] [ swprimes ] 2bi@ [ 36 ] [ 37 ] bi* [ stats ] 2bi@   "First 36 strong primes:\n%[%d, %] %s strong primes below 1,000,000 %s strong primes below 10,000,000\n First 37 weak primes:\n%[%d, %] %s weak primes below 1,000,000 %s weak primes below 10,000,000\n" printf
http://rosettacode.org/wiki/Strong_and_weak_primes
Strong and weak primes
Definitions   (as per number theory)   The   prime(p)   is the   pth   prime.   prime(1)   is   2   prime(4)   is   7   A   strong   prime   is when     prime(p)   is   >   [prime(p-1) + prime(p+1)] ÷ 2   A     weak    prime   is when     prime(p)   is   <   [prime(p-1) + prime(p+1)] ÷ 2 Note that the definition for   strong primes   is different when used in the context of   cryptography. Task   Find and display (on one line) the first   36   strong primes.   Find and display the   count   of the strong primes below   1,000,000.   Find and display the   count   of the strong primes below 10,000,000.   Find and display (on one line) the first   37   weak primes.   Find and display the   count   of the weak primes below   1,000,000.   Find and display the   count   of the weak primes below 10,000,000.   (Optional)   display the   counts   and   "below numbers"   with commas. Show all output here. Related Task   Safe primes and unsafe primes. Also see   The OEIS article A051634: strong primes.   The OEIS article A051635: weak primes.
#FreeBASIC
FreeBASIC
  #include "isprime.bas"   function nextprime( n as uinteger ) as uinteger 'finds the next prime after n, excluding n if it happens to be prime itself if n = 0 then return 2 if n < 3 then return n + 1 dim as integer q = n + 2 while not isprime(q) q+=2 wend return q end function   function lastprime( n as uinteger ) as uinteger 'finds the last prime before n, excluding n if it happens to be prime itself if n = 2 then return 0 'zero isn't prime, but it is a good sentinel value :) if n = 3 then return 2 dim as integer q = n - 2 while not isprime(q) q-=2 wend return q end function   function isstrong( p as integer ) as boolean if nextprime(p) + lastprime(p) >= 2*p then return false else return true end function   function isweak( p as integer ) as boolean if nextprime(p) + lastprime(p) <= 2*p then return false else return true end function   print "The first 36 strong primes are: " dim as uinteger c, p=3 while p < 10000000 if isprime(p) andalso isstrong(p) then c += 1 if c <= 36 then print p;" "; if c=37 then print end if if p = 1000001 then print "There are ";c;" strong primes below one million" p+=2 wend print "There are ";c;" strong primes below ten million" print   print "The first 37 weak primes are: " p=3 : c=0 while p < 10000000 if isprime(p) andalso isweak(p) then c += 1 if c <= 37 then print p;" "; if c=38 then print end if   if p = 1000001 then print "There are ";c;" weak primes below one million" p+=2 wend print "There are ";c;" weak primes below ten million" print
http://rosettacode.org/wiki/Substring
Substring
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Display a substring:   starting from   n   characters in and of   m   length;   starting from   n   characters in,   up to the end of the string;   whole string minus the last character;   starting from a known   character   within the string and of   m   length;   starting from a known   substring   within the string and of   m   length. If the program uses UTF-8 or UTF-16,   it must work on any valid Unicode code point, whether in the   Basic Multilingual Plane   or above it. The program must reference logical characters (code points),   not 8-bit code units for UTF-8 or 16-bit code units for UTF-16. Programs for other encodings (such as 8-bit ASCII, or EUC-JP) are not required to handle all Unicode characters. 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
#AppleScript
AppleScript
-- SUBSTRINGS -----------------------------------------------------------------   -- take :: Int -> Text -> Text on take(n, s) text 1 thru n of s end take   -- drop :: Int -> Text -> Text on drop(n, s) text (n + 1) thru -1 of s end drop   -- breakOn :: Text -> Text -> (Text, Text) on breakOn(strPattern, s) set {dlm, my text item delimiters} to {my text item delimiters, strPattern} set lstParts to text items of s set my text item delimiters to dlm {item 1 of lstParts, strPattern & (item 2 of lstParts)} end breakOn   -- init :: Text -> Text on init(s) if length of s > 0 then text 1 thru -2 of s else missing value end if end init     -- TEST ----------------------------------------------------------------------- on run set str to "一二三四五六七八九十"   set legends to {¬ "from n in, of n length", ¬ "from n in, up to end", ¬ "all but last", ¬ "from matching char, of m length", ¬ "from matching string, of m length"}   set parts to {¬ take(3, drop(4, str)), ¬ drop(3, str), ¬ init(str), ¬ take(3, item 2 of breakOn("五", str)), ¬ take(4, item 2 of breakOn("六七", str))}   script tabulate property strPad : " "   on |λ|(l, r) l & drop(length of l, strPad) & r end |λ| end script   linefeed & intercalate(linefeed, ¬ zipWith(tabulate, ¬ legends, parts)) & linefeed end run   -- GENERIC FUNCTIONS FOR TEST -------------------------------------------------   -- intercalate :: Text -> [Text] -> Text on intercalate(strText, lstText) set {dlm, my text item delimiters} to {my text item delimiters, strText} set strJoined to lstText as text set my text item delimiters to dlm return strJoined end intercalate   -- min :: Ord a => a -> a -> a on min(x, y) if y < x then y else x end if end min   -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) if class of f is script then f else script property |λ| : f end script end if end mReturn   -- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] on zipWith(f, xs, ys) set lng to min(length of xs, length of ys) set lst to {} tell mReturn(f) repeat with i from 1 to lng set end of lst to |λ|(item i of xs, item i of ys) end repeat return lst end tell end zipWith
http://rosettacode.org/wiki/Sudoku
Sudoku
Task Solve a partially filled-in normal   9x9   Sudoku grid   and display the result in a human-readable format. references Algorithmics of Sudoku   may help implement this. Python Sudoku Solver Computerphile video.
#Bracmat
Bracmat
{sudokuSolver.bra   Solves any 9x9 sudoku, using backtracking. Not a simple brute force algorithm!}   sudokuSolver= ( sudoku = ( new = create . ( create = a .  !arg:%(<3:?a) ?arg & ( !a .  !arg: & 1 2 3 4 5 6 7 8 9 | create$!arg ) create$(!a+1 !arg) | ) & create$(0 0 0 0):?(its.Tree) & ( init = cell remainingCells remainingRows x y .  !arg  : ( ?y . ?x . (.%?cell ?remainingCells) ?remainingRows ) & (  !cell:# & ( !cell . mod$(!x,3) div$(!x,3) mod$(!y,3) div$(!y,3) ) | ) (  !remainingCells: & init$(!y+1.0.!remainingRows) | init $ ( !y . !x+1 . (.!remainingCells) !remainingRows ) ) | ) & out$!arg & (its.Set)$(!(its.Tree).init$(0.0.!arg))  : ?(its.Tree) ) ( Display = val . put$(str$("|~~~|~~~|~~~|" \n)) &  !(its.Tree)  :  ? ( ? .  ? ( ?&put$"|" .  ? ( ? .  ? ( ( ? .  ?val & !val:% % & put$"-" |  !val: & put$" " | put$!val ) & ~ )  ? | ?&put$"|"&~ )  ? | ?&put$\n&~ )  ? |  ? & put$(str$("|~~~|~~~|~~~|" \n)) & ~ )  ? | ) ( Set = update certainValue a b c d , tree branch todo DOING loop dcba minlen len minp . ( update = path rempath value tr , k z x y trc p v branch s n .  !arg:(?path.?value.?tr.?trc) & (  !path:%?path ?rempath & `(  !tr  : ?k (!path:?p.?branch) ?z & `( update$(!rempath.!value.!branch.!p !trc)  : ?s & update $ (!path !rempath.!value.!z.!trc)  : ?n & !k (!p.!s) !n ) | !tr ) | !DOING:(?.!trc)&!value |  !tr:?x !value ?y & `( !x !y  : ( ~:@ & (  !todo:? (?v.!trc) ? & ( !v:!x !y | out $ (mismatch v !v "<>" x y !x !y) & get' ) | (!x !y.!trc) !todo:?todo ) | % % | &!DOING:(?.!trc) ) ) | !tr ) ) & !arg:(?tree.?todo) & ( loop =  !todo: |  !todo  : ((?certainValue.%?d %?c %?b %?a):?DOING) ?todo & update$(!a ? !c ?.!certainValue.!tree.)  : ?tree & update$(!a !b <>!c ?.!certainValue.!tree.)  : ?tree & update$(<>!a ? !c !d.!certainValue.!tree.)  : ?tree & !loop ) & !loop & ( ~( !tree  :  ? (?.? (?.? (?.? (?.% %) ?) ?) ?)  ? ) | 9:?minlen & :?minp & ( len = .  !arg:% %?arg&1+len$!arg | 1 ) & (  !tree  :  ? ( ?a .  ? ( ?b .  ? ( ?c .  ? ( ?d .  % %:?p & len$!p:<!minlen:?minlen & !d !c !b !a:?dcba & !p:?:?minp & ~ )  ? )  ? )  ? )  ? |  !minp  :  ? ( %@?n & (its.Set)$(!tree.!n.!dcba):?tree )  ? ) ) & !tree ) (Tree=) ) ( new = puzzle . new$((its.sudoku),!arg):?puzzle & (puzzle..Display)$ );
http://rosettacode.org/wiki/Subleq
Subleq
Subleq is an example of a One-Instruction Set Computer (OISC). It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero. Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory consists of an array of signed integers.   These integers may be interpreted in three ways:   simple numeric values   memory addresses   characters for input or output Any reasonable word size that accommodates all three of the above uses is fine. The program should load the initial contents of the emulated machine's memory, set the instruction pointer to the first address (which is defined to be address 0), and begin emulating the machine, which works as follows:   Let A be the value in the memory location identified by the instruction pointer;   let B and C be the values stored in the next two consecutive addresses in memory.   Advance the instruction pointer three words, to point at the address after the address containing C.   If A is   -1   (negative unity),   then a character is read from the machine's input and its numeric value stored in the address given by B.   C is unused.   If B is   -1   (negative unity),   then the number contained in the address given by A is interpreted as a character and written to the machine's output.   C is unused.   Otherwise, both A and B are treated as addresses.   The number contained in address A is subtracted from the number in address B (and the difference left in address B).   If the result is positive, execution continues uninterrupted; if the result is zero or negative, the number in C becomes the new instruction pointer.   If the instruction pointer becomes negative, execution halts. Your solution may initialize the emulated machine's memory in any convenient manner, but if you accept it as input, it should be a separate input stream from the one fed to the emulated machine once it is running. And if fed as text input, it should be in the form of raw subleq "machine code" - whitespace-separated decimal numbers, with no symbolic names or other assembly-level extensions, to be loaded into memory starting at address   0   (zero). For purposes of this task, show the output of your solution when fed the below   "Hello, world!"   program. As written, this example assumes ASCII or a superset of it, such as any of the Latin-N character sets or Unicode;   you may translate the numbers representing characters (starting with 72=ASCII 'H') into another character set if your implementation runs in a non-ASCII-compatible environment. If 0 is not an appropriate terminator in your character set, the program logic will need some adjustment as well. 15 17 -1 17 -1 -1 16 1 -1 16 3 -1 15 15 0 0 -1 72 101 108 108 111 44 32 119 111 114 108 100 33 10 0 The above "machine code" corresponds to something like this in a hypothetical assembler language for a signed 8-bit version of the machine: start: 0f 11 ff subleq (zero), (message), -1 11 ff ff subleq (message), -1, -1  ; output character at message 10 01 ff subleq (neg1), (start+1), -1 10 03 ff subleq (neg1), (start+3), -1 0f 0f 00 subleq (zero), (zero), start ; useful constants zero: 00 .data 0 neg1: ff .data -1 ; the message to print message: .data "Hello, world!\n\0" 48 65 6c 6c 6f 2c 20 77 6f 72 6c 64 21 0a 00
#BBC_BASIC
BBC BASIC
REM >subleq DIM memory%(255) counter% = 0 INPUT "SUBLEQ> " program$ WHILE INSTR(program$, " ") memory%(counter%) = VAL(LEFT$(program$, INSTR(program$, " ") - 1)) program$ = MID$(program$, INSTR(program$, " ") + 1) counter% += 1 ENDWHILE memory%(counter%) = VAL(program$) counter% = 0 REPEAT a% = memory%(counter%) b% = memory%(counter% + 1) c% = memory%(counter% + 2) counter% += 3 IF a% = -1 THEN INPUT "SUBLEQ> " character$ memory%(b%) = ASC(character$) ELSE IF b% = -1 THEN PRINT CHR$(memory%(a%)); ELSE memory%(b%) = memory%(b%) - memory%(a%) IF memory%(b%) <= 0 THEN counter% = c% ENDIF ENDIF UNTIL counter% < 0
http://rosettacode.org/wiki/Subleq
Subleq
Subleq is an example of a One-Instruction Set Computer (OISC). It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero. Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory consists of an array of signed integers.   These integers may be interpreted in three ways:   simple numeric values   memory addresses   characters for input or output Any reasonable word size that accommodates all three of the above uses is fine. The program should load the initial contents of the emulated machine's memory, set the instruction pointer to the first address (which is defined to be address 0), and begin emulating the machine, which works as follows:   Let A be the value in the memory location identified by the instruction pointer;   let B and C be the values stored in the next two consecutive addresses in memory.   Advance the instruction pointer three words, to point at the address after the address containing C.   If A is   -1   (negative unity),   then a character is read from the machine's input and its numeric value stored in the address given by B.   C is unused.   If B is   -1   (negative unity),   then the number contained in the address given by A is interpreted as a character and written to the machine's output.   C is unused.   Otherwise, both A and B are treated as addresses.   The number contained in address A is subtracted from the number in address B (and the difference left in address B).   If the result is positive, execution continues uninterrupted; if the result is zero or negative, the number in C becomes the new instruction pointer.   If the instruction pointer becomes negative, execution halts. Your solution may initialize the emulated machine's memory in any convenient manner, but if you accept it as input, it should be a separate input stream from the one fed to the emulated machine once it is running. And if fed as text input, it should be in the form of raw subleq "machine code" - whitespace-separated decimal numbers, with no symbolic names or other assembly-level extensions, to be loaded into memory starting at address   0   (zero). For purposes of this task, show the output of your solution when fed the below   "Hello, world!"   program. As written, this example assumes ASCII or a superset of it, such as any of the Latin-N character sets or Unicode;   you may translate the numbers representing characters (starting with 72=ASCII 'H') into another character set if your implementation runs in a non-ASCII-compatible environment. If 0 is not an appropriate terminator in your character set, the program logic will need some adjustment as well. 15 17 -1 17 -1 -1 16 1 -1 16 3 -1 15 15 0 0 -1 72 101 108 108 111 44 32 119 111 114 108 100 33 10 0 The above "machine code" corresponds to something like this in a hypothetical assembler language for a signed 8-bit version of the machine: start: 0f 11 ff subleq (zero), (message), -1 11 ff ff subleq (message), -1, -1  ; output character at message 10 01 ff subleq (neg1), (start+1), -1 10 03 ff subleq (neg1), (start+3), -1 0f 0f 00 subleq (zero), (zero), start ; useful constants zero: 00 .data 0 neg1: ff .data -1 ; the message to print message: .data "Hello, world!\n\0" 48 65 6c 6c 6f 2c 20 77 6f 72 6c 64 21 0a 00
#BCPL
BCPL
get "libhdr"   // Read a string let reads(v) be $( let ch = ? v%0 := 0 ch := rdch() until ch = '*N' do $( v%0 := v%0 + 1 v%(v%0) := ch ch := rdch() $) $)   // Try to read a number, fail on EOF // (Alas, the included READN just returns 0 and that's a valid number) let readnum(n) = valof $( let neg, ch = false, ?  !n := 0 $( ch := rdch() if ch = endstreamch then resultis false $) repeatuntil ch = '-' | '0' <= ch <= '9' if ch = '-' then $( neg := true ch := rdch() $) while '0' <= ch <= '9' do $(  !n := !n * 10 + ch - '0' ch := rdch() $) if neg then !n := -!n resultis true $)   // Read SUBLEQ code let readfile(file, v) = valof $( let i, oldin = 0, input() selectinput(file) while readnum(v+i) do i := i + 1 endread() selectinput(oldin) resultis i $)   // Run SUBLEQ code let run(v) be $( let ip = 0 until ip < 0 do $( let a, b, c = v!ip, v!(ip+1), v!(ip+2) ip := ip + 3 test a=-1 then v!b := rdch() else test b=-1 then wrch(v!a) else $( v!b := v!b - v!a if v!b <= 0 then ip := c $) $) $)   let start() be $( let filename = vec 64 let file = ?   writes("Filename? ") reads(filename) file := findinput(filename) test file = 0 then writes("Cannot open file.*N") else $( let top = maxvec() let mem = getvec(top) let progtop = readfile(file, mem) for i = progtop to top do mem!i := 0 run(mem) freevec(mem) $) $)
http://rosettacode.org/wiki/Successive_prime_differences
Successive prime differences
The series of increasing prime numbers begins: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, ... The task applies a filter to the series returning groups of successive primes, (s'primes), that differ from the next by a given value or values. Example 1: Specifying that the difference between s'primes be 2 leads to the groups: (3, 5), (5, 7), (11, 13), (17, 19), (29, 31), ... (Known as Twin primes or Prime pairs) Example 2: Specifying more than one difference between s'primes leads to groups of size one greater than the number of differences. Differences of 2, 4 leads to the groups: (5, 7, 11), (11, 13, 17), (17, 19, 23), (41, 43, 47), .... In the first group 7 is two more than 5 and 11 is four more than 7; as well as 5, 7, and 11 being successive primes. Differences are checked in the order of the values given, (differences of 4, 2 would give different groups entirely). Task In each case use a list of primes less than 1_000_000 For the following Differences show the first and last group, as well as the number of groups found: Differences of 2. Differences of 1. Differences of 2, 2. Differences of 2, 4. Differences of 4, 2. Differences of 6, 4, 2. Show output here. Note: Generation of a list of primes is a secondary aspect of the task. Use of a built in function, well known library, or importing/use of prime generators from other Rosetta Code tasks is encouraged. references https://pdfs.semanticscholar.org/78a1/7349819304863ae061df88dbcb26b4908f03.pdf https://www.primepuzzles.net/puzzles/puzz_011.htm https://matheplanet.de/matheplanet/nuke/html/viewtopic.php?topic=232720&start=0
#Go
Go
package main   import "fmt"   func sieve(limit int) []int { primes := []int{2} c := make([]bool, limit+1) // composite = true // no need to process even numbers > 2 p := 3 for { p2 := p * p if p2 > limit { break } for i := p2; i <= limit; i += 2 * p { c[i] = true } for { p += 2 if !c[p] { break } } } for i := 3; i <= limit; i += 2 { if !c[i] { primes = append(primes, i) } } return primes }   func successivePrimes(primes, diffs []int) [][]int { var results [][]int dl := len(diffs) outer: for i := 0; i < len(primes)-dl; i++ { group := make([]int, dl+1) group[0] = primes[i] for j := i; j < i+dl; j++ { if primes[j+1]-primes[j] != diffs[j-i] { group = nil continue outer } group[j-i+1] = primes[j+1] } results = append(results, group) group = nil } return results }   func main() { primes := sieve(999999) diffsList := [][]int{{2}, {1}, {2, 2}, {2, 4}, {4, 2}, {6, 4, 2}} fmt.Println("For primes less than 1,000,000:-\n") for _, diffs := range diffsList { fmt.Println(" For differences of", diffs, "->") sp := successivePrimes(primes, diffs) if len(sp) == 0 { fmt.Println(" No groups found") continue } fmt.Println(" First group = ", sp[0]) fmt.Println(" Last group = ", sp[len(sp)-1]) fmt.Println(" Number found = ", len(sp)) fmt.Println() } }
http://rosettacode.org/wiki/Substring/Top_and_tail
Substring/Top and tail
The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed If the program uses UTF-8 or UTF-16, it must work on any valid Unicode code point, whether in the Basic Multilingual Plane or above it. The program must reference logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16. Programs for other encodings (such as 8-bit ASCII, or EUC-JP) are not required to handle all Unicode characters. 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
#Burlesque
Burlesque
  blsq ) "RosettaCode"[- "osettaCode" blsq ) "RosettaCode"-] 'R blsq ) "RosettaCode"~] "RosettaCod" blsq ) "RosettaCode"[~ 'e blsq ) "RosettaCode"~- "osettaCod"  
http://rosettacode.org/wiki/Substring/Top_and_tail
Substring/Top and tail
The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed If the program uses UTF-8 or UTF-16, it must work on any valid Unicode code point, whether in the Basic Multilingual Plane or above it. The program must reference logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16. Programs for other encodings (such as 8-bit ASCII, or EUC-JP) are not required to handle all Unicode characters. 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
#C
C
#include <string.h> #include <stdlib.h> #include <stdio.h>   int main( int argc, char ** argv ){ const char * str_a = "knight"; const char * str_b = "socks"; const char * str_c = "brooms";   char * new_a = malloc( strlen( str_a ) - 1 ); char * new_b = malloc( strlen( str_b ) - 1 ); char * new_c = malloc( strlen( str_c ) - 2 );   strcpy( new_a, str_a + 1 ); strncpy( new_b, str_b, strlen( str_b ) - 1 ); strncpy( new_c, str_c + 1, strlen( str_c ) - 2 );   printf( "%s\n%s\n%s\n", new_a, new_b, new_c );   free( new_a ); free( new_b ); free( new_c );   return 0; }
http://rosettacode.org/wiki/Subtractive_generator
Subtractive generator
A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence. The formula is r n = r ( n − i ) − r ( n − j ) ( mod m ) {\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod {m}}} for some fixed values of i {\displaystyle i} , j {\displaystyle j} and m {\displaystyle m} , all positive integers. Supposing that i > j {\displaystyle i>j} , then the state of this generator is the list of the previous numbers from r n − i {\displaystyle r_{n-i}} to r n − 1 {\displaystyle r_{n-1}} . Many states generate uniform random integers from 0 {\displaystyle 0} to m − 1 {\displaystyle m-1} , but some states are bad. A state, filled with zeros, generates only zeros. If m {\displaystyle m} is even, then a state, filled with even numbers, generates only even numbers. More generally, if f {\displaystyle f} is a factor of m {\displaystyle m} , then a state, filled with multiples of f {\displaystyle f} , generates only multiples of f {\displaystyle f} . All subtractive generators have some weaknesses. The formula correlates r n {\displaystyle r_{n}} , r ( n − i ) {\displaystyle r_{(n-i)}} and r ( n − j ) {\displaystyle r_{(n-j)}} ; these three numbers are not independent, as true random numbers would be. Anyone who observes i {\displaystyle i} consecutive numbers can predict the next numbers, so the generator is not cryptographically secure. The authors of Freeciv (utility/rand.c) and xpat2 (src/testit2.c) knew another problem: the low bits are less random than the high bits. The subtractive generator has a better reputation than the linear congruential generator, perhaps because it holds more state. A subtractive generator might never multiply numbers: this helps where multiplication is slow. A subtractive generator might also avoid division: the value of r ( n − i ) − r ( n − j ) {\displaystyle r_{(n-i)}-r_{(n-j)}} is always between − m {\displaystyle -m} and m {\displaystyle m} , so a program only needs to add m {\displaystyle m} to negative numbers. The choice of i {\displaystyle i} and j {\displaystyle j} affects the period of the generator. A popular choice is i = 55 {\displaystyle i=55} and j = 24 {\displaystyle j=24} , so the formula is r n = r ( n − 55 ) − r ( n − 24 ) ( mod m ) {\displaystyle r_{n}=r_{(n-55)}-r_{(n-24)}{\pmod {m}}} The subtractive generator from xpat2 uses r n = r ( n − 55 ) − r ( n − 24 ) ( mod 10 9 ) {\displaystyle r_{n}=r_{(n-55)}-r_{(n-24)}{\pmod {10^{9}}}} The implementation is by J. Bentley and comes from program_tools/universal.c of the DIMACS (netflow) archive at Rutgers University. It credits Knuth, TAOCP, Volume 2, Section 3.2.2 (Algorithm A). Bentley uses this clever algorithm to seed the generator. Start with a single s e e d {\displaystyle seed} in range 0 {\displaystyle 0} to 10 9 − 1 {\displaystyle 10^{9}-1} . Set s 0 = s e e d {\displaystyle s_{0}=seed} and s 1 = 1 {\displaystyle s_{1}=1} . The inclusion of s 1 = 1 {\displaystyle s_{1}=1} avoids some bad states (like all zeros, or all multiples of 10). Compute s 2 , s 3 , . . . , s 54 {\displaystyle s_{2},s_{3},...,s_{54}} using the subtractive formula s n = s ( n − 2 ) − s ( n − 1 ) ( mod 10 9 ) {\displaystyle s_{n}=s_{(n-2)}-s_{(n-1)}{\pmod {10^{9}}}} . Reorder these 55 values so r 0 = s 34 {\displaystyle r_{0}=s_{34}} , r 1 = s 13 {\displaystyle r_{1}=s_{13}} , r 2 = s 47 {\displaystyle r_{2}=s_{47}} , ..., r n = s ( 34 ∗ ( n + 1 ) ( mod 55 ) ) {\displaystyle r_{n}=s_{(34*(n+1){\pmod {55}})}} . This is the same order as s 0 = r 54 {\displaystyle s_{0}=r_{54}} , s 1 = r 33 {\displaystyle s_{1}=r_{33}} , s 2 = r 12 {\displaystyle s_{2}=r_{12}} , ..., s n = r ( ( 34 ∗ n ) − 1 ( mod 55 ) ) {\displaystyle s_{n}=r_{((34*n)-1{\pmod {55}})}} . This rearrangement exploits how 34 and 55 are relatively prime. Compute the next 165 values r 55 {\displaystyle r_{55}} to r 219 {\displaystyle r_{219}} . Store the last 55 values. This generator yields the sequence r 220 {\displaystyle r_{220}} , r 221 {\displaystyle r_{221}} , r 222 {\displaystyle r_{222}} and so on. For example, if the seed is 292929, then the sequence begins with r 220 = 467478574 {\displaystyle r_{220}=467478574} , r 221 = 512932792 {\displaystyle r_{221}=512932792} , r 222 = 539453717 {\displaystyle r_{222}=539453717} . By starting at r 220 {\displaystyle r_{220}} , this generator avoids a bias from the first numbers of the sequence. This generator must store the last 55 numbers of the sequence, so to compute the next r n {\displaystyle r_{n}} . Any array or list would work; a ring buffer is ideal but not necessary. Implement a subtractive generator that replicates the sequences from xpat2.
#Go
Go
package main   import ( "fmt" "os" )   // A fairly close port of the Bentley code, but parameterized to better // conform to the algorithm description in the task, which didn't assume // constants for i, j, m, and seed. also parameterized here are k, // the reordering factor, and s, the number of intial numbers to discard, // as these are dependant on i. func newSG(i, j, k, s, m, seed int) func() int { // check parameters for range and mutual consistency assert(i > 0, "i must be > 0") assert(j > 0, "j must be > 0") assert(i > j, "i must be > j") assert(k > 0, "k must be > 0") p, q := i, k if p < q { p, q = q, p } for q > 0 { p, q = q, p%q } assert(p == 1, "k, i must be relatively prime") assert(s >= i, "s must be >= i") assert(m > 0, "m must be > 0") assert(seed >= 0, "seed must be >= 0") // variables for closure f arr := make([]int, i) a := 0 b := j // f is Bently RNG lprand f := func() int { if a == 0 { a = i } a-- if b == 0 { b = i } b-- t := arr[a] - arr[b] if t < 0 { t += m } arr[a] = t return t } // Bentley seed algorithm sprand last := seed arr[0] = last next := 1 for i0 := 1; i0 < i; i0++ { ii := k * i0 % i arr[ii] = next next = last - next if next < 0 { next += m } last = arr[ii] } for i0 := i; i0 < s; i0++ { f() } // return the fully initialized RNG return f }   func assert(p bool, m string) { if !p { fmt.Println(m) os.Exit(1) } }   func main() { // 1st test case included in program_tools/universal.c. // (2nd test case fails. A single digit is missing, indicating a typo.) ptTest(0, 1, []int{921674862, 250065336, 377506581})   // reproduce 3 values given in task description skip := 220 sg := newSG(55, 24, 21, skip, 1e9, 292929) for n := skip; n <= 222; n++ { fmt.Printf("r(%d) = %d\n", n, sg()) } }   func ptTest(nd, s int, rs []int) { sg := newSG(55, 24, 21, 220+nd, 1e9, s) for _, r := range rs { a := sg() if r != a { fmt.Println("Fail") os.Exit(1) } } }
http://rosettacode.org/wiki/Substitution_cipher
Substitution cipher
Substitution Cipher Implementation - File Encryption/Decryption Task Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypted file into original/decrypted file. This type of Encryption/Decryption scheme is often called a Substitution Cipher. Related tasks Caesar cipher Rot-13 Vigenère Cipher/Cryptanalysis See also Wikipedia: Substitution cipher
#Prolog
Prolog
cypher(O, S) :- nonvar(O), var(S), atom_chars(O,Oc), sub_chars(Oc,Sc), atom_chars(S,Sc). cypher(O, S) :- nonvar(S), var(O), atom_chars(S,Sc), sub_chars(Oc,Sc), atom_chars(O,Oc).   % mapping based on ADA implementation but have added space character base(['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,' ']). subs(['V',s,c,i,'B',j,e,d,g,r,z,y,'H',a,l,v,'X','Z','K',t,'U','P',u,m,'G',f,'I',w,'J',x,q,'O','C','F','R','A',p,n,'D',h,'Q','W',o,b,' ','L',k,'E','S','Y','M','T','N']).   sub_chars(Original,Subbed) :- base(Base), subs(Subs), maplist(sub_char(Base,Subs),Original,Subbed).   sub_char([Co|_],[Cs|_],Co,Cs) :- !. sub_char([_|To],[_|Ts], Co, Cs) :- sub_char(To,Ts,Co,Cs).
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#Emacs_Lisp
Emacs Lisp
(let ((array [1 2 3 4 5])) (apply #'+ (append array nil)) (apply #'* (append array nil)))
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displaystyle S_{n}=\sum _{k=1}^{n}{\frac {1}{k^{2}}}} and compute   S 1000 {\displaystyle S_{1000}} This approximates the   zeta function   for   S=2,   whose exact value ζ ( 2 ) = π 2 6 {\displaystyle \zeta (2)={\pi ^{2} \over 6}} is the solution of the Basel problem.
#E
E
pragma.enable("accumulator") accum 0 for x in 1..1000 { _ + 1 / x ** 2 }
http://rosettacode.org/wiki/Strip_comments_from_a_string
Strip comments from a string
Strip comments from a string You are encouraged to solve this task according to the task description, using any language you may know. The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line. Whitespace debacle:   There is some confusion about whether to remove any whitespace from the input line. As of 2 September 2011, at least 8 languages (C, C++, Java, Perl, Python, Ruby, sed, UNIX Shell) were incorrect, out of 36 total languages, because they did not trim whitespace by 29 March 2011 rules. Some other languages might be incorrect for the same reason. Please discuss this issue at Talk:Strip comments from a string. From 29 March 2011, this task required that: "The comment marker and any whitespace at the beginning or ends of the resultant line should be removed. A line without comments should be trimmed of any leading or trailing whitespace before being produced as a result." The task had 28 languages, which did not all meet this new requirement. From 28 March 2011, this task required that: "Whitespace before the comment marker should be removed." From 30 October 2010, this task did not specify whether or not to remove whitespace. The following examples will be truncated to either "apples, pears " or "apples, pears". (This example has flipped between "apples, pears " and "apples, pears" in the past.) apples, pears # and bananas apples, pears ; and bananas 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
#Aime
Aime
strip_comments(data b) { b.size(b.look(0, ";#")).bf_drop(" \t").bb_drop(" \t"); }   main(void) { for (, text n in list("apples, pears # and bananas", "apples, pears ; and bananas")) { o_(strip_comments(n), "\n"); }   0; }
http://rosettacode.org/wiki/Strip_comments_from_a_string
Strip comments from a string
Strip comments from a string You are encouraged to solve this task according to the task description, using any language you may know. The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line. Whitespace debacle:   There is some confusion about whether to remove any whitespace from the input line. As of 2 September 2011, at least 8 languages (C, C++, Java, Perl, Python, Ruby, sed, UNIX Shell) were incorrect, out of 36 total languages, because they did not trim whitespace by 29 March 2011 rules. Some other languages might be incorrect for the same reason. Please discuss this issue at Talk:Strip comments from a string. From 29 March 2011, this task required that: "The comment marker and any whitespace at the beginning or ends of the resultant line should be removed. A line without comments should be trimmed of any leading or trailing whitespace before being produced as a result." The task had 28 languages, which did not all meet this new requirement. From 28 March 2011, this task required that: "Whitespace before the comment marker should be removed." From 30 October 2010, this task did not specify whether or not to remove whitespace. The following examples will be truncated to either "apples, pears " or "apples, pears". (This example has flipped between "apples, pears " and "apples, pears" in the past.) apples, pears # and bananas apples, pears ; and bananas 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
#ALGOL_68
ALGOL 68
#!/usr/local/bin/a68g --script #   PROC trim comment = (STRING line, CHAR marker)STRING:( INT index := UPB line+1; char in string(marker, index, line); FOR i FROM index-1 BY -1 TO LWB line WHILE line[i]=" " DO index := i OD; line[:index-1] );   CHAR q = """";   print(( q, trim comment("apples, pears # and bananas", "#"), q, new line, q, trim comment("apples, pears ; and bananas", ";"), q, new line, q, trim comment("apples, pears and bananas ", ";"), q, new line, q, trim comment(" ", ";"), q, new line, # blank string # q, trim comment("", ";"), q, new line # empty string # ))   CO Alternatively Algol68g has available "grep" ;STRING re marker := " *#", line := "apples, pears # and bananas"; INT index := UPB line; grep in string(re marker, line, index, NIL); print((q, line[:index-1], q, new line)) END CO
http://rosettacode.org/wiki/Strip_block_comments
Strip block comments
A block comment begins with a   beginning delimiter   and ends with a   ending delimiter,   including the delimiters.   These delimiters are often multi-character sequences. Task Strip block comments from program text (of a programming language much like classic C). Your demos should at least handle simple, non-nested and multi-line block comment delimiters. The block comment delimiters are the two-character sequences:     /*     (beginning delimiter)     */     (ending delimiter) Sample text for stripping: /** * Some comments * longer comments here that we can parse. * * Rahoo */ function subroutine() { a = /* inline comment */ b + c ; } /*/ <-- tricky comments */ /** * Another comment. */ function something() { } Extra credit Ensure that the stripping code is not hard-coded to the particular delimiters described above, but instead allows the caller to specify them.   (If your language supports them,   optional parameters   may be useful for this.) 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 STRIP_BLOCK_COMMENTS.AWK filename # source: https://www.gnu.org/software/gawk/manual/gawk.html#Plain-Getline # Remove text between /* and */, inclusive { while ((start = index($0,"/*")) != 0) { out = substr($0,1,start-1) # leading part of the string rest = substr($0,start+2) # ... */ ... while ((end = index(rest,"*/")) == 0) { # is */ in trailing part? if (getline <= 0) { # get more text printf("unexpected EOF or error: %s\n",ERRNO) >"/dev/stderr" exit } rest = rest $0 # build up the line using string concatenation } rest = substr(rest,end+2) # remove comment $0 = out rest # build up the output line using string concatenation } printf("%s\n",$0) } END { exit(0) }  
http://rosettacode.org/wiki/Strip_block_comments
Strip block comments
A block comment begins with a   beginning delimiter   and ends with a   ending delimiter,   including the delimiters.   These delimiters are often multi-character sequences. Task Strip block comments from program text (of a programming language much like classic C). Your demos should at least handle simple, non-nested and multi-line block comment delimiters. The block comment delimiters are the two-character sequences:     /*     (beginning delimiter)     */     (ending delimiter) Sample text for stripping: /** * Some comments * longer comments here that we can parse. * * Rahoo */ function subroutine() { a = /* inline comment */ b + c ; } /*/ <-- tricky comments */ /** * Another comment. */ function something() { } Extra credit Ensure that the stripping code is not hard-coded to the particular delimiters described above, but instead allows the caller to specify them.   (If your language supports them,   optional parameters   may be useful for this.) 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
infile$ = "C:\sample.c" outfile$ = "C:\stripped.c"   PROCstripblockcomments(infile$, outfile$, "/*", "*/") END   DEF PROCstripblockcomments(infile$, outfile$, start$, finish$) LOCAL infile%, outfile%, comment%, test%, A$   infile% = OPENIN(infile$) IF infile%=0 ERROR 100, "Could not open input file" outfile% = OPENOUT(outfile$) IF outfile%=0 ERROR 100, "Could not open output file"   WHILE NOT EOF#infile% A$ = GET$#infile% TO 10 REPEAT IF comment% THEN test% = INSTR(A$, finish$) IF test% THEN A$ = MID$(A$, test% + LEN(finish$)) comment% = FALSE ENDIF ELSE test% = INSTR(A$, start$) IF test% THEN BPUT#outfile%, LEFT$(A$, test%-1); A$ = MID$(A$, test% + LEN(start$)) comment% = TRUE ENDIF ENDIF UNTIL test%=0 IF NOT comment% BPUT#outfile%, A$ ENDWHILE   CLOSE #infile% CLOSE #outfile% ENDPROC
http://rosettacode.org/wiki/Sum_to_100
Sum to 100
Task Find solutions to the   sum to one hundred   puzzle. Add (insert) the mathematical operators     +   or   -     (plus or minus)   before any of the digits in the decimal numeric string   123456789   such that the resulting mathematical expression adds up to a particular sum   (in this iconic case,   100). Example: 123 + 4 - 5 + 67 - 89 = 100 Show all output here.   Show all solutions that sum to   100   Show the sum that has the maximum   number   of solutions   (from zero to infinity‡)   Show the lowest positive sum that   can't   be expressed   (has no solutions),   using the rules for this task   Show the ten highest numbers that can be expressed using the rules for this task   (extra credit) ‡   (where   infinity   would be a relatively small   123,456,789) An example of a sum that can't be expressed   (within the rules of this task)   is:   5074 (which,   of course,   isn't the lowest positive sum that can't be expressed).
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
operations = DeleteCases[Tuples[{"+", "-", ""}, 9], {x_, y__} /; x == "+"]; sums = Map[StringJoin[Riffle[#, CharacterRange["1", "9"]]] &, operations];
http://rosettacode.org/wiki/Strip_a_set_of_characters_from_a_string
Strip a set of characters from a string
Task Create a function that strips a set of characters from a string. The function should take two arguments:   a string to be stripped   a string containing the set of characters to be stripped The returned string should contain the first string, stripped of any characters in the second argument: print stripchars("She was a soul stripper. She took my heart!","aei") Sh ws soul strppr. Sh took my hrt! 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
#8086_Assembly
8086 Assembly
bits 16 cpu 8086 section .text org 100h jmp demo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Strip a set of characters from a string, in place. ;;; Input: ;;; DS:DI = $-terminated string to be stripped. ;;; DS:SI = $-terminated string containing chars to strip stripchars: mov bx,di ; Copy string ptr to use as target ptr mov dx,si ; Copy ptr to characters to strip .char: mov al,[di] ; Copy character mov [bx],al cmp al,'$' ; Done? je .done mov si,dx ; See if character should be stripped .search: mov ah,[si] cmp ah,'$' ; End of characters to strip? je .srchdone cmp ah,al ; Does it match the current character? je .srchfound inc si ; Try next character jmp .search .srchfound: dec bx ; Found - decrement target pointer .srchdone: inc bx ; Increment both pointers inc di jmp .char .done: ret ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; demo: mov di,string ; Strip from the string, mov si,remove ; the characters to remove. call stripchars mov dx,string ; Print the result mov ah,9 int 21h ret section .data string: db 'She was a soul stripper. She took my heart!$' remove: db 'aei$'
http://rosettacode.org/wiki/String_prepend
String prepend
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Create a string variable equal to any text value. Prepend the string variable with another string literal. If your language supports any idiomatic ways to do this without referring to the variable twice in one expression, include such solutions. To illustrate the operation, show the content of the variable.
#Ada
Ada
with Ada.Text_IO; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;   procedure Prepend_String is S: Unbounded_String := To_Unbounded_String("World!"); begin S := "Hello " & S;-- this is the operation to prepend "Hello " to S. Ada.Text_IO.Put_Line(To_String(S)); end Prepend_String;
http://rosettacode.org/wiki/String_prepend
String prepend
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Create a string variable equal to any text value. Prepend the string variable with another string literal. If your language supports any idiomatic ways to do this without referring to the variable twice in one expression, include such solutions. To illustrate the operation, show the content of the variable.
#ALGOL_68
ALGOL 68
#!/usr/bin/a68g --script # # -*- coding: utf-8 -*- #   STRING str := "12345678"; "0" +=: str; print(str)
http://rosettacode.org/wiki/Strip_control_codes_and_extended_characters_from_a_string
Strip control codes and extended characters from a string
Task Strip control codes and extended characters from a string. The solution should demonstrate how to achieve each of the following results:   a string with control codes stripped (but extended characters not stripped)   a string with control codes and extended characters stripped In ASCII, the control codes have decimal codes 0 through to 31 and 127. On an ASCII based system, if the control codes are stripped, the resultant string would have all of its characters within the range of 32 to 126 decimal on the ASCII table. On a non-ASCII based system, we consider characters that do not have a corresponding glyph on the ASCII table (within the ASCII range of 32 to 126 decimal) to be an extended character for the purpose of this task. 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
str: {string of ☺☻♥♦⌂, may include control characters and other ♫☼§►↔◄░▒▓█┌┴┐±÷²¬└┬┘ilk.}   print "with extended characters" print join select split str 'x -> not? in? to :integer to :char x (0..31)++127   print "without extended characters" print join select split str 'x -> and? ascii? x not? in? to :integer to :char x (0..31)++127
http://rosettacode.org/wiki/Strip_control_codes_and_extended_characters_from_a_string
Strip control codes and extended characters from a string
Task Strip control codes and extended characters from a string. The solution should demonstrate how to achieve each of the following results:   a string with control codes stripped (but extended characters not stripped)   a string with control codes and extended characters stripped In ASCII, the control codes have decimal codes 0 through to 31 and 127. On an ASCII based system, if the control codes are stripped, the resultant string would have all of its characters within the range of 32 to 126 decimal on the ASCII table. On a non-ASCII based system, we consider characters that do not have a corresponding glyph on the ASCII table (within the ASCII range of 32 to 126 decimal) to be an extended character for the purpose of this task. 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
Stripped(x){ Loop Parse, x if Asc(A_LoopField) > 31 and Asc(A_LoopField) < 128 r .= A_LoopField return r } MsgBox % stripped("`ba" Chr(00) "b`n`rc`fd" Chr(0xc3))
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5
Sum multiples of 3 and 5
Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
#Factor
Factor
USING: kernel math prettyprint ;   : sum-multiples ( m n upto -- sum ) >integer 1 - [ 2dup * ] dip [ 2dup swap [ mod - + ] [ /i * 2/ ] 2bi ] curry tri@ [ + ] [ - ] bi* ;   3 5 1000 sum-multiples . 3 5 1e20 sum-multiples .
http://rosettacode.org/wiki/Sum_digits_of_an_integer
Sum digits of an integer
Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
#Factor
Factor
: sum-digits ( base n -- sum ) 0 swap [ dup zero? ] [ pick /mod swapd + swap ] until drop nip ;   { 10 10 16 16 } { 1 1234 0xfe 0xf0e } [ sum-digits ] 2each
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#GAP
GAP
# Just multiplying a vector by itself yields the sum of squares (it's an inner product) # It's necessary to check for the empty vector though SumSq := function(v) if Size(v) = 0 then return 0; else return v*v; fi; end;
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#GEORGE
GEORGE
read (n) print ; 0 1, n rep (i) read print dup mult + ] print
http://rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail
Strip whitespace from a string/Top and tail
Task Demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results: String with leading whitespace removed String with trailing whitespace removed String with both leading and trailing whitespace removed For the purposes of this task whitespace includes non printable characters such as the space character, the tab character, and other such characters that have no corresponding graphical representation. 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
function trimleft(str ,c, out, arr) { c = split(str, arr, "") for ( i = match(str, /[[:graph:]]/); i <= c; i++) out = out arr[i] return out }   function reverse(str ,n, tmp, j, out) { n = split(str, tmp, "") for (j = n; j > 0; j--) out = out tmp[j] return out }   function trimright(str) { return reverse(trimleft(reverse(str))) }   function trim(str) { return trimright(trimleft(str)) }   BEGIN { str = " \x0B\t\r\n \xA0 Hellö \xA0\x0B\t\r\n " print "string = |" str "|" print "left = |" trimleft(str) "|" print "right = |" trimright(str) "|" print "both = |" trim(str) "|" }
http://rosettacode.org/wiki/Strong_and_weak_primes
Strong and weak primes
Definitions   (as per number theory)   The   prime(p)   is the   pth   prime.   prime(1)   is   2   prime(4)   is   7   A   strong   prime   is when     prime(p)   is   >   [prime(p-1) + prime(p+1)] ÷ 2   A     weak    prime   is when     prime(p)   is   <   [prime(p-1) + prime(p+1)] ÷ 2 Note that the definition for   strong primes   is different when used in the context of   cryptography. Task   Find and display (on one line) the first   36   strong primes.   Find and display the   count   of the strong primes below   1,000,000.   Find and display the   count   of the strong primes below 10,000,000.   Find and display (on one line) the first   37   weak primes.   Find and display the   count   of the weak primes below   1,000,000.   Find and display the   count   of the weak primes below 10,000,000.   (Optional)   display the   counts   and   "below numbers"   with commas. Show all output here. Related Task   Safe primes and unsafe primes. Also see   The OEIS article A051634: strong primes.   The OEIS article A051635: weak primes.
#Frink
Frink
  strongPrimes[end=undef] := select[primes[3,end], {|p| p > (previousPrime[p] + nextPrime[p])/2 }] weakPrimes[end=undef]  := select[primes[3,end], {|p| p < (previousPrime[p] + nextPrime[p])/2 }]   println["First 36 strong primes: " + first[strongPrimes[], 36]] println["Strong primes below 1,000,000: " + length[strongPrimes[1_000_000]]] println["Strong primes below 10,000,000: " + length[strongPrimes[10_000_000]]]   println["First 37 weak primes: " + first[weakPrimes[], 37]] println["Weak primes below 1,000,000: " + length[weakPrimes[1_000_000]]] println["Weak primes below 10,000,000: " + length[weakPrimes[10_000_000]]]  
http://rosettacode.org/wiki/Strong_and_weak_primes
Strong and weak primes
Definitions   (as per number theory)   The   prime(p)   is the   pth   prime.   prime(1)   is   2   prime(4)   is   7   A   strong   prime   is when     prime(p)   is   >   [prime(p-1) + prime(p+1)] ÷ 2   A     weak    prime   is when     prime(p)   is   <   [prime(p-1) + prime(p+1)] ÷ 2 Note that the definition for   strong primes   is different when used in the context of   cryptography. Task   Find and display (on one line) the first   36   strong primes.   Find and display the   count   of the strong primes below   1,000,000.   Find and display the   count   of the strong primes below 10,000,000.   Find and display (on one line) the first   37   weak primes.   Find and display the   count   of the weak primes below   1,000,000.   Find and display the   count   of the weak primes below 10,000,000.   (Optional)   display the   counts   and   "below numbers"   with commas. Show all output here. Related Task   Safe primes and unsafe primes. Also see   The OEIS article A051634: strong primes.   The OEIS article A051635: weak primes.
#Go
Go
package main   import "fmt"   func sieve(limit int) []bool { limit++ // True denotes composite, false denotes prime. // Don't bother marking even numbers >= 4 as composite. c := make([]bool, limit) c[0] = true c[1] = true   p := 3 // start from 3 for { p2 := p * p if p2 >= limit { break } for i := p2; i < limit; i += 2 * p { c[i] = true } for { p += 2 if !c[p] { break } } } return c }   func commatize(n int) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } return s }   func main() { // sieve up to 10,000,019 - the first prime after 10 million const limit = 1e7 + 19 sieved := sieve(limit) // extract primes var primes = []int{2} for i := 3; i <= limit; i += 2 { if !sieved[i] { primes = append(primes, i) } } // extract strong and weak primes var strong []int var weak = []int{3} // so can use integer division for rest for i := 2; i < len(primes)-1; i++ { // start from 5 if primes[i] > (primes[i-1]+primes[i+1])/2 { strong = append(strong, primes[i]) } else if primes[i] < (primes[i-1]+primes[i+1])/2 { weak = append(weak, primes[i]) } }   fmt.Println("The first 36 strong primes are:") fmt.Println(strong[:36]) count := 0 for _, p := range strong { if p >= 1e6 { break } count++ } fmt.Println("\nThe number of strong primes below 1,000,000 is", commatize(count)) fmt.Println("\nThe number of strong primes below 10,000,000 is", commatize(len(strong)))   fmt.Println("\nThe first 37 weak primes are:") fmt.Println(weak[:37]) count = 0 for _, p := range weak { if p >= 1e6 { break } count++ } fmt.Println("\nThe number of weak primes below 1,000,000 is", commatize(count)) fmt.Println("\nThe number of weak primes below 10,000,000 is", commatize(len(weak))) }
http://rosettacode.org/wiki/Substring
Substring
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Display a substring:   starting from   n   characters in and of   m   length;   starting from   n   characters in,   up to the end of the string;   whole string minus the last character;   starting from a known   character   within the string and of   m   length;   starting from a known   substring   within the string and of   m   length. If the program uses UTF-8 or UTF-16,   it must work on any valid Unicode code point, whether in the   Basic Multilingual Plane   or above it. The program must reference logical characters (code points),   not 8-bit code units for UTF-8 or 16-bit code units for UTF-16. Programs for other encodings (such as 8-bit ASCII, or EUC-JP) are not required to handle all Unicode characters. 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
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */ /* program substring.s */   /* Constantes */ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 @ Linux syscall   .equ BUFFERSIZE, 100   /* Initialized data */ .data szMessString: .asciz "Result : " szString1: .asciz "abcdefghijklmnopqrstuvwxyz" szStringStart: .asciz "abcdefg" szCarriageReturn: .asciz "\n"   /* UnInitialized data */ .bss szSubString: .skip 500 @ buffer result     /* code section */ .text .global main main:   ldr r0,iAdrszString1 @ address input string ldr r1,iAdrszSubString @ address output string mov r2,#22 @ location mov r3,#4 @ length bl subStringNbChar @ starting from n characters in and of m length ldr r0,iAdrszMessString @ display message bl affichageMess ldr r0,iAdrszSubString @ display substring result bl affichageMess ldr r0,iAdrszCarriageReturn @ display line return bl affichageMess @ ldr r0,iAdrszString1 ldr r1,iAdrszSubString mov r2,#15 @ location bl subStringEnd @starting from n characters in, up to the end of the string ldr r0,iAdrszMessString @ display message bl affichageMess ldr r0,iAdrszSubString bl affichageMess ldr r0,iAdrszCarriageReturn @ display line return bl affichageMess @ ldr r0,iAdrszString1 ldr r1,iAdrszSubString bl subStringMinus @ whole string minus last character ldr r0,iAdrszMessString @ display message bl affichageMess ldr r0,iAdrszSubString bl affichageMess ldr r0,iAdrszCarriageReturn @ display line return bl affichageMess @ ldr r0,iAdrszString1 ldr r1,iAdrszSubString mov r2,#'c' @ start character mov r3,#5 @ length bl subStringStChar @starting from a known character within the string and of m length cmp r0,#-1 @ error ? beq 2f ldr r0,iAdrszMessString @ display message bl affichageMess ldr r0,iAdrszSubString bl affichageMess ldr r0,iAdrszCarriageReturn @ display line return bl affichageMess @ 2: ldr r0,iAdrszString1 ldr r1,iAdrszSubString ldr r2,iAdrszStringStart @ sub string to start mov r3,#10 @ length bl subStringStString @ starting from a known substring within the string and of m length cmp r0,#-1 @ error ? beq 3f ldr r0,iAdrszMessString @ display message bl affichageMess ldr r0,iAdrszSubString bl affichageMess ldr r0,iAdrszCarriageReturn @ display line return bl affichageMess 3: 100: @ standard end of the program mov r0, #0 @ return code mov r7, #EXIT @ request to exit program svc 0 @ perform system call iAdrszMessString: .int szMessString iAdrszString1: .int szString1 iAdrszSubString: .int szSubString iAdrszStringStart: .int szStringStart iAdrszCarriageReturn: .int szCarriageReturn /******************************************************************/ /* sub strings index start number of characters */ /******************************************************************/ /* r0 contains the address of the input string */ /* r1 contains the address of the output string */ /* r2 contains the start index */ /* r3 contains numbers of characters to extract */ /* r0 returns number of characters or -1 if error */ subStringNbChar: push {r1-r5,lr} @ save registers mov r4,#0 @ counter byte output string 1: ldrb r5,[r0,r2] @ load byte string input cmp r5,#0 @ zero final ? beq 2f strb r5,[r1,r4] @ store byte output string add r2,#1 @ increment counter add r4,#1 cmp r4,r3 @ end ? blt 1b @ no -> loop 2: mov r5,#0 strb r5,[r1,r4] @ load byte string 2 mov r0,r4 100: pop {r1-r5,lr} @ restaur registers bx lr @ return /******************************************************************/ /* sub strings index start at end of string */ /******************************************************************/ /* r0 contains the address of the input string */ /* r1 contains the address of the output string */ /* r2 contains the start index */ /* r0 returns number of characters or -1 if error */ subStringEnd: push {r1-r5,lr} @ save registers mov r4,#0 @ counter byte output string 1: ldrb r5,[r0,r2] @ load byte string 1 cmp r5,#0 @ zero final ? beq 2f strb r5,[r1,r4] add r2,#1 add r4,#1 b 1b @ loop 2: mov r5,#0 strb r5,[r1,r4] @ load byte string 2 mov r0,r4 100: pop {r1-r5,lr} @ restaur registers bx lr /******************************************************************/ /* whole string minus last character */ /******************************************************************/ /* r0 contains the address of the input string */ /* r1 contains the address of the output string */ /* r0 returns number of characters or -1 if error */ subStringMinus: push {r1-r5,lr} @ save registers mov r2,#0 @ counter byte input string mov r4,#0 @ counter byte output string 1: ldrb r5,[r0,r2] @ load byte string cmp r5,#0 @ zero final ? beq 2f strb r5,[r1,r4] add r2,#1 add r4,#1 b 1b @ loop 2: sub r4,#1 mov r5,#0 strb r5,[r1,r4] @ load byte string 2 mov r0,r4 100: pop {r1-r5,lr} @ restaur registers bx lr /******************************************************************/ /* starting from a known character within the string and of m length */ /******************************************************************/ /* r0 contains the address of the input string */ /* r1 contains the address of the output string */ /* r2 contains the character */ /* r3 contains the length /* r0 returns number of characters or -1 if error */ subStringStChar: push {r1-r5,lr} @ save registers mov r6,#0 @ counter byte input string mov r4,#0 @ counter byte output string   1: ldrb r5,[r0,r6] @ load byte string cmp r5,#0 @ zero final ? streqb r5,[r1,r4] moveq r0,#-1 beq 100f cmp r5,r2 beq 2f add r6,#1 b 1b @ loop 2: strb r5,[r1,r4] add r6,#1 add r4,#1 cmp r4,r3 bge 3f ldrb r5,[r0,r6] @ load byte string cmp r5,#0 bne 2b 3: mov r5,#0 strb r5,[r1,r4] @ load byte string 2 mov r0,r4 100: pop {r1-r5,lr} @ restaur registers bx lr   /******************************************************************/ /* starting from a known substring within the string and of m length */ /******************************************************************/ /* r0 contains the address of the input string */ /* r1 contains the address of the output string */ /* r2 contains the address of string to start */ /* r3 contains the length /* r0 returns number of characters or -1 if error */ subStringStString: push {r1-r8,lr} @ save registers mov r7,r0 @ save address mov r8,r1 @ counter byte string mov r1,r2 bl searchSubString cmp r0,#-1 beq 100f mov r6,r0 @ counter byte input string mov r4,#0 1: ldrb r5,[r7,r6] @ load byte string strb r5,[r8,r4] cmp r5,#0 @ zero final ? moveq r0,r4 beq 100f add r4,#1 cmp r4,r3 addlt r6,#1 blt 1b @ loop mov r5,#0 strb r5,[r8,r4] mov r0,r4 100: pop {r1-r8,lr} @ restaur registers bx lr   /******************************************************************/ /* search a substring in the string */ /******************************************************************/ /* r0 contains the address of the input string */ /* r1 contains the address of substring */ /* r0 returns index of substring in string or -1 if not found */ searchSubString: push {r1-r6,lr} @ save registers mov r2,#0 @ counter byte input string mov r3,#0 @ counter byte string mov r6,#-1 @ index found ldrb r4,[r1,r3] 1: ldrb r5,[r0,r2] @ load byte string cmp r5,#0 @ zero final ? moveq r0,#-1 @ yes returns error beq 100f cmp r5,r4 @ compare character beq 2f mov r6,#-1 @ no equals - > raz index mov r3,#0 @ and raz counter byte add r2,#1 @ and increment counter byte b 1b @ and loop 2: @ characters equals cmp r6,#-1 @ first characters equals ? moveq r6,r2 @ yes -> index begin in r6 add r3,#1 @ increment counter substring ldrb r4,[r1,r3] @ and load next byte cmp r4,#0 @ zero final ? beq 3f @ yes -> end search add r2,#1 @ else increment counter string b 1b @ and loop 3: mov r0,r6 100: pop {r1-r6,lr} @ restaur registers bx lr   /******************************************************************/ /* display text with size calculation */ /******************************************************************/ /* r0 contains the address of the message */ affichageMess: push {r0,r1,r2,r7,lr} @ save registers mov r2,#0 @ counter length */ 1: @ loop length calculation ldrb r1,[r0,r2] @ read octet start position + index cmp r1,#0 @ if 0 its over addne r2,r2,#1 @ else add 1 in the length bne 1b @ and loop @ so here r2 contains the length of the message mov r1,r0 @ address message in r1 mov r0,#STDOUT @ code to write to the standard output Linux mov r7, #WRITE @ code call system "write" svc #0 @ call system pop {r0,r1,r2,r7,lr} @ restaur registers bx lr @ return      
http://rosettacode.org/wiki/Sudoku
Sudoku
Task Solve a partially filled-in normal   9x9   Sudoku grid   and display the result in a human-readable format. references Algorithmics of Sudoku   may help implement this. Python Sudoku Solver Computerphile video.
#C
C
#include <stdio.h>   void show(int *x) { int i, j; for (i = 0; i < 9; i++) { if (!(i % 3)) putchar('\n'); for (j = 0; j < 9; j++) printf(j % 3 ? "%2d" : "%3d", *x++); putchar('\n'); } }   int trycell(int *x, int pos) { int row = pos / 9; int col = pos % 9; int i, j, used = 0;   if (pos == 81) return 1; if (x[pos]) return trycell(x, pos + 1);   for (i = 0; i < 9; i++) used |= 1 << (x[i * 9 + col] - 1);   for (j = 0; j < 9; j++) used |= 1 << (x[row * 9 + j] - 1);   row = row / 3 * 3; col = col / 3 * 3; for (i = row; i < row + 3; i++) for (j = col; j < col + 3; j++) used |= 1 << (x[i * 9 + j] - 1);   for (x[pos] = 1; x[pos] <= 9; x[pos]++, used >>= 1) if (!(used & 1) && trycell(x, pos + 1)) return 1;   x[pos] = 0; return 0; }   void solve(const char *s) { int i, x[81]; for (i = 0; i < 81; i++) x[i] = s[i] >= '1' && s[i] <= '9' ? s[i] - '0' : 0;   if (trycell(x, 0)) show(x); else puts("no solution"); }   int main(void) { solve( "5x..7...." "6..195..." ".98....6." "8...6...3" "4..8.3..1" "7...2...6" ".6....28." "...419..5" "....8..79" );   return 0; }
http://rosettacode.org/wiki/Subleq
Subleq
Subleq is an example of a One-Instruction Set Computer (OISC). It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero. Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory consists of an array of signed integers.   These integers may be interpreted in three ways:   simple numeric values   memory addresses   characters for input or output Any reasonable word size that accommodates all three of the above uses is fine. The program should load the initial contents of the emulated machine's memory, set the instruction pointer to the first address (which is defined to be address 0), and begin emulating the machine, which works as follows:   Let A be the value in the memory location identified by the instruction pointer;   let B and C be the values stored in the next two consecutive addresses in memory.   Advance the instruction pointer three words, to point at the address after the address containing C.   If A is   -1   (negative unity),   then a character is read from the machine's input and its numeric value stored in the address given by B.   C is unused.   If B is   -1   (negative unity),   then the number contained in the address given by A is interpreted as a character and written to the machine's output.   C is unused.   Otherwise, both A and B are treated as addresses.   The number contained in address A is subtracted from the number in address B (and the difference left in address B).   If the result is positive, execution continues uninterrupted; if the result is zero or negative, the number in C becomes the new instruction pointer.   If the instruction pointer becomes negative, execution halts. Your solution may initialize the emulated machine's memory in any convenient manner, but if you accept it as input, it should be a separate input stream from the one fed to the emulated machine once it is running. And if fed as text input, it should be in the form of raw subleq "machine code" - whitespace-separated decimal numbers, with no symbolic names or other assembly-level extensions, to be loaded into memory starting at address   0   (zero). For purposes of this task, show the output of your solution when fed the below   "Hello, world!"   program. As written, this example assumes ASCII or a superset of it, such as any of the Latin-N character sets or Unicode;   you may translate the numbers representing characters (starting with 72=ASCII 'H') into another character set if your implementation runs in a non-ASCII-compatible environment. If 0 is not an appropriate terminator in your character set, the program logic will need some adjustment as well. 15 17 -1 17 -1 -1 16 1 -1 16 3 -1 15 15 0 0 -1 72 101 108 108 111 44 32 119 111 114 108 100 33 10 0 The above "machine code" corresponds to something like this in a hypothetical assembler language for a signed 8-bit version of the machine: start: 0f 11 ff subleq (zero), (message), -1 11 ff ff subleq (message), -1, -1  ; output character at message 10 01 ff subleq (neg1), (start+1), -1 10 03 ff subleq (neg1), (start+3), -1 0f 0f 00 subleq (zero), (zero), start ; useful constants zero: 00 .data 0 neg1: ff .data -1 ; the message to print message: .data "Hello, world!\n\0" 48 65 6c 6c 6f 2c 20 77 6f 72 6c 64 21 0a 00
#Befunge
Befunge
01-00p00g:0`*2/00p010p0>$~>:4v4:-1g02p+5/"P"\%"P":p01+1:g01+g00*p02+1_v#!`"/":< \0_v#-"-":\1_v#!`\*84:_^#- *8< >\#%"P"/#:5#<+g00g-\1+:"P"%\"P"v>5+#\*#<+"0"-~>^ <~0>#<$#-0#\<>$0>:3+\::"P"%\"P"/5+g00g-:1+#^_$:~>00gvv0gp03:+5/"P"\p02:%"P":< ^ >>>>>> , >>>>>> ^$p+5/"P"\%"P":-g00g+5/"P"\%"P":+1\+<>0g-\-:0v>5+g00g-:1+>>#^_$ -:0\`#@_^<<<<<_1#`-#0:#p2#g5#08#3*#g*#0%#2\#+2#g5#08#<**/5+g00g
http://rosettacode.org/wiki/Subleq
Subleq
Subleq is an example of a One-Instruction Set Computer (OISC). It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero. Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory consists of an array of signed integers.   These integers may be interpreted in three ways:   simple numeric values   memory addresses   characters for input or output Any reasonable word size that accommodates all three of the above uses is fine. The program should load the initial contents of the emulated machine's memory, set the instruction pointer to the first address (which is defined to be address 0), and begin emulating the machine, which works as follows:   Let A be the value in the memory location identified by the instruction pointer;   let B and C be the values stored in the next two consecutive addresses in memory.   Advance the instruction pointer three words, to point at the address after the address containing C.   If A is   -1   (negative unity),   then a character is read from the machine's input and its numeric value stored in the address given by B.   C is unused.   If B is   -1   (negative unity),   then the number contained in the address given by A is interpreted as a character and written to the machine's output.   C is unused.   Otherwise, both A and B are treated as addresses.   The number contained in address A is subtracted from the number in address B (and the difference left in address B).   If the result is positive, execution continues uninterrupted; if the result is zero or negative, the number in C becomes the new instruction pointer.   If the instruction pointer becomes negative, execution halts. Your solution may initialize the emulated machine's memory in any convenient manner, but if you accept it as input, it should be a separate input stream from the one fed to the emulated machine once it is running. And if fed as text input, it should be in the form of raw subleq "machine code" - whitespace-separated decimal numbers, with no symbolic names or other assembly-level extensions, to be loaded into memory starting at address   0   (zero). For purposes of this task, show the output of your solution when fed the below   "Hello, world!"   program. As written, this example assumes ASCII or a superset of it, such as any of the Latin-N character sets or Unicode;   you may translate the numbers representing characters (starting with 72=ASCII 'H') into another character set if your implementation runs in a non-ASCII-compatible environment. If 0 is not an appropriate terminator in your character set, the program logic will need some adjustment as well. 15 17 -1 17 -1 -1 16 1 -1 16 3 -1 15 15 0 0 -1 72 101 108 108 111 44 32 119 111 114 108 100 33 10 0 The above "machine code" corresponds to something like this in a hypothetical assembler language for a signed 8-bit version of the machine: start: 0f 11 ff subleq (zero), (message), -1 11 ff ff subleq (message), -1, -1  ; output character at message 10 01 ff subleq (neg1), (start+1), -1 10 03 ff subleq (neg1), (start+3), -1 0f 0f 00 subleq (zero), (zero), start ; useful constants zero: 00 .data 0 neg1: ff .data -1 ; the message to print message: .data "Hello, world!\n\0" 48 65 6c 6c 6f 2c 20 77 6f 72 6c 64 21 0a 00
#BQN
BQN
  # Helpers _while_ ← {𝔽⍟𝔾∘𝔽_𝕣_𝔾∘𝔽⍟𝔾𝕩} ToNum ← {neg ← '-'=⊑𝕩 ⋄ (¯1⋆neg)×10⊸×⊸+˜´·⌽-⟜'0'neg↓𝕩}   Subleq ← { 𝕊 memory: { 𝕊 ip‿mem: { ¯1‿b‿·: ⟨ip+3, (@-˜•term.CharB@)⌾(b⊸⊑) mem⟩; a‿¯1‿·: •Out @+a⊑mem, ⟨ip+3, mem⟩; a‿b‿c : d ← b-○(⊑⟜mem)a, ⟨(0<d)⊑⟨c, ip+3⟩, d⌾(b⊸⊑) mem⟩ } mem⊏˜ip+↕3 } _while_ {𝕊 ip‿mem: ip≥0} 0‿memory }   Subleq ToNum¨•args
http://rosettacode.org/wiki/Successive_prime_differences
Successive prime differences
The series of increasing prime numbers begins: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, ... The task applies a filter to the series returning groups of successive primes, (s'primes), that differ from the next by a given value or values. Example 1: Specifying that the difference between s'primes be 2 leads to the groups: (3, 5), (5, 7), (11, 13), (17, 19), (29, 31), ... (Known as Twin primes or Prime pairs) Example 2: Specifying more than one difference between s'primes leads to groups of size one greater than the number of differences. Differences of 2, 4 leads to the groups: (5, 7, 11), (11, 13, 17), (17, 19, 23), (41, 43, 47), .... In the first group 7 is two more than 5 and 11 is four more than 7; as well as 5, 7, and 11 being successive primes. Differences are checked in the order of the values given, (differences of 4, 2 would give different groups entirely). Task In each case use a list of primes less than 1_000_000 For the following Differences show the first and last group, as well as the number of groups found: Differences of 2. Differences of 1. Differences of 2, 2. Differences of 2, 4. Differences of 4, 2. Differences of 6, 4, 2. Show output here. Note: Generation of a list of primes is a secondary aspect of the task. Use of a built in function, well known library, or importing/use of prime generators from other Rosetta Code tasks is encouraged. references https://pdfs.semanticscholar.org/78a1/7349819304863ae061df88dbcb26b4908f03.pdf https://www.primepuzzles.net/puzzles/puzz_011.htm https://matheplanet.de/matheplanet/nuke/html/viewtopic.php?topic=232720&start=0
#Haskell
Haskell
{-# LANGUAGE NumericUnderscores #-} import Data.Numbers.Primes (primes)   type Result = [(String, [Int])]   oneMillionPrimes :: Integral p => [p] oneMillionPrimes = takeWhile (<1_000_000) primes   getGroups :: [Int] -> Result getGroups [] = [] getGroups ps@(n:x:y:z:xs) | x-n == 6 && y-x == 4 && z-y == 2 = ("(6 4 2)", [n, x, y, z])  : getGroups (tail ps) | x-n == 4 && y-x == 2 = ("(4 2)", [n, x, y])  : getGroups (tail ps) | x-n == 2 && y-x == 4 = ("(2 4)", [n, x, y]) : ("2", [n, x]) : getGroups (tail ps) | x-n == 2 && y-x == 2 = ("(2 2)", [n, x, y]) : ("2", [n, x]) : getGroups (tail ps) | x-n == 2 = ("2", [n, x])  : getGroups (tail ps) | x-n == 1 = ("1", [n, x])  : getGroups (tail ps) | otherwise = getGroups (tail ps) getGroups (x:xs) = getGroups xs   groups :: Result groups = getGroups oneMillionPrimes   showGroup :: String -> IO () showGroup group = do putStrLn $ "Differences of " ++ group ++ ": " ++ show (length r) putStrLn $ "First: " ++ show (head r) ++ "\nLast: " ++ show (last r) ++ "\n" where r = foldr (\(a, b) c -> if a == group then b : c else c) [] groups   main :: IO () main = showGroup "2" >> showGroup "1" >> showGroup "(2 2)" >> showGroup "(2 4)" >> showGroup "(4 2)" >> showGroup "(6 4 2)"
http://rosettacode.org/wiki/Substring/Top_and_tail
Substring/Top and tail
The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed If the program uses UTF-8 or UTF-16, it must work on any valid Unicode code point, whether in the Basic Multilingual Plane or above it. The program must reference logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16. Programs for other encodings (such as 8-bit ASCII, or EUC-JP) are not required to handle all Unicode characters. 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
#C.23
C#
  using System;   class Program { static void Main(string[] args) { string testString = "test"; Console.WriteLine(testString.Substring(1)); Console.WriteLine(testString.Substring(0, testString.Length - 1)); Console.WriteLine(testString.Substring(1, testString.Length - 2)); } }