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/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.
#C
C
#include<stdio.h> #include<string.h> #include<stdlib.h>   int main() { char str[100]="my String"; char *cstr="Changed "; char *dup; sprintf(str,"%s%s",cstr,(dup=strdup(str))); free(dup); printf("%s\n",str); return 0; }
http://rosettacode.org/wiki/String_comparison
String comparison
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 Demonstrate how to compare two strings from within the language and how to achieve a lexical comparison. The task should demonstrate: Comparing two strings for exact equality Comparing two strings for inequality (i.e., the inverse of exact equality) Comparing two strings to see if one is lexically ordered before than the other Comparing two strings to see if one is lexically ordered after than the other How to achieve both case sensitive comparisons and case insensitive comparisons within the language How the language handles comparison of numeric strings if these are not treated lexically Demonstrate any other kinds of string comparisons that the language provides, particularly as it relates to your type system. For example, you might demonstrate the difference between generic/polymorphic comparison and coercive/allomorphic comparison if your language supports such a distinction. Here "generic/polymorphic" comparison means that the function or operator you're using doesn't always do string comparison, but bends the actual semantics of the comparison depending on the types one or both arguments; with such an operator, you achieve string comparison only if the arguments are sufficiently string-like in type or appearance. In contrast, a "coercive/allomorphic" comparison function or operator has fixed string-comparison semantics regardless of the argument type;   instead of the operator bending, it's the arguments that are forced to bend instead and behave like strings if they can,   and the operator simply fails if the arguments cannot be viewed somehow as strings.   A language may have one or both of these kinds of operators;   see the Raku entry for an example of a language with both kinds of operators. 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 compare(a, b) I a < b {print(‘'#.' is strictly less than '#.'’.format(a, b))} I a <= b {print(‘'#.' is less than or equal to '#.'’.format(a, b))} I a > b {print(‘'#.' is strictly greater than '#.'’.format(a, b))} I a >= b {print(‘'#.' is greater than or equal to '#.'’.format(a, b))} I a == b {print(‘'#.' is equal to '#.'’.format(a, b))} I a != b {print(‘'#.' is not equal to '#.'’.format(a, b))}   compare(‘YUP’, ‘YUP’) compare(‘BALL’, ‘BELL’) compare(‘24’, ‘123’)
http://rosettacode.org/wiki/String_case
String case
Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is not reversable. Show any additional case conversion functions   (e.g. swapping case, capitalizing the first letter, etc.)   that may be included in the library of your language. 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
V s = ‘alphaBETA’ print(s.uppercase()) print(s.lowercase())
http://rosettacode.org/wiki/String_matching
String matching
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 Given two strings, demonstrate the following three types of string matching:   Determining if the first string starts with second string   Determining if the first string contains the second string at any location   Determining if the first string ends with the second string Optional requirements:   Print the location of the match for part 2   Handle multiple occurrences of a string for part 2. 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 FindS(CHAR ARRAY text,sub BYTE start) BYTE i,j,found   i=start WHILE i<=text(0)-sub(0)+1 DO found=0 FOR j=1 TO sub(0) DO IF text(i+j-1)#sub(j) THEN found=0 EXIT ELSE found=1 FI OD IF found THEN RETURN (i) FI i==+1 OD RETURN (0)   BYTE FUNC StartsWith(CHAR ARRAY text,sub) BYTE pos   pos=FindS(text,sub,1) IF pos=1 THEN RETURN (1) FI RETURN (0)   BYTE FUNC EndsWith(CHAR ARRAY text,sub) BYTE pos,start   IF sub(0)>text(0) THEN RETURN (0) FI start=text(0)-sub(0)+1 pos=FindS(text,sub,start) IF pos=start THEN RETURN (1) FI RETURN (0)   BYTE FUNC Contains(CHAR ARRAY text,sub BYTE ARRAY positions) BYTE pos,count   pos=1 count=0 WHILE pos<=text(0) DO pos=FindS(text,sub,pos) IF pos>0 THEN positions(count)=pos count==+1 pos==+1 ELSE EXIT FI OD RETURN (count)   PROC TestStartsWith(CHAR ARRAY text,sub) IF StartsWith(text,sub) THEN PrintF("""%S"" starts with ""%S"".%E",text,sub) ELSE PrintF("""%S"" does not start with ""%S"".%E",text,sub) FI RETURN   PROC TestEndsWith(CHAR ARRAY text,sub) IF EndsWith(text,sub) THEN PrintF("""%S"" ends with ""%S"".%E",text,sub) ELSE PrintF("""%S"" does not end with ""%S"".%E",text,sub) FI RETURN   PROC TestContains(CHAR ARRAY text,sub) BYTE ARRAY positions(20) BYTE i,count   count=Contains(text,sub,positions) IF count>0 THEN PrintF("""%S"" contains %B ""%S"" at positions:",text,count,sub) FOR i=0 TO count-1 DO PrintB(positions(i)) IF i<count-1 THEN Print(", ") ELSE PrintE(".") FI OD ELSE PrintF("""%S"" does not contain ""%S"".%E",text,sub) FI RETURN   PROC Main() TestStartsWith("1234abc","123") TestStartsWith("1234abc","234") PutE() TestContains("abbaabab","ab") TestContains("abbaabab","ba") TestContains("abbaabab","xyz") PutE() TestEndsWith("1234abc","abc") TestEndsWith("1234abc","ab") RETURN
http://rosettacode.org/wiki/String_matching
String matching
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 Given two strings, demonstrate the following three types of string matching:   Determining if the first string starts with second string   Determining if the first string contains the second string at any location   Determining if the first string ends with the second string Optional requirements:   Print the location of the match for part 2   Handle multiple occurrences of a string for part 2. 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; use Ada.Strings.Fixed; with Ada.Text_IO; use Ada.Text_IO;   procedure Match_Strings is S1 : constant String := "abcd"; S2 : constant String := "abab"; S3 : constant String := "ab"; begin if S1'Length >= S3'Length and then S1 (S1'First..S1'First + S3'Length - 1) = S3 then Put_Line (''' & S1 & "' starts with '" & S3 & '''); end if; if S2'Length >= S3'Length and then S2 (S2'Last - S3'Length + 1..S2'Last) = S3 then Put_Line (''' & S2 & "' ends with '" & S3 & '''); end if; Put_Line (''' & S3 & "' first appears in '" & S1 & "' at" & Integer'Image (Index (S1, S3))); Put_Line ( ''' & S3 & "' appears in '" & S2 & ''' & Integer'Image (Ada.Strings.Fixed.Count (S2, S3)) & " times" ); end Match_Strings;  
http://rosettacode.org/wiki/String_length
String length
Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme containing combining characters. For example, the character length of "møøse" is 5 but the byte length is 7 in UTF-8 and 10 in UTF-16. Non-BMP code points (those between 0x10000 and 0x10FFFF) must also be handled correctly: answers should produce actual character counts in code points, not in code unit counts. Therefore a string like "𝔘𝔫𝔦𝔠𝔬𝔡𝔢" (consisting of the 7 Unicode characters U+1D518 U+1D52B U+1D526 U+1D520 U+1D52C U+1D521 U+1D522) is 7 characters long, not 14 UTF-16 code units; and it is 28 bytes long whether encoded in UTF-8 or in UTF-16. Please mark your examples with ===Character Length=== or ===Byte Length===. If your language is capable of providing the string length in graphemes, mark those examples with ===Grapheme Length===. For example, the string "J̲o̲s̲é̲" ("J\x{332}o\x{332}s\x{332}e\x{301}\x{332}") has 4 user-visible graphemes, 9 characters (code points), and 14 bytes when encoded in UTF-8. 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
;INPUT: DS:SI = BASE ADDR. OF STRING ;TYPICALLY, MS-DOS USES $ TO TERMINATE STRINGS. GetStringLength: xor cx,cx ;this takes fewer bytes to encode than "mov cx,0" cld ;makes string functions post-inc rather than post-dec.   loop_GetStringLength: lodsb ;equivalent of "mov al,[ds:si],inc si" except this doesn't alter the flags. cmp '$' je done ;if equal, we're finished. inc cx ;add 1 to length counter. A null string will have a length of zero. jmp loop_GetStringLength   done: ret
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
#C
C
#include <stdlib.h> #include <stdio.h> #include <string.h>   #define MAXBUF 256 /* limit */ #define STR_SZ 100 /* string size */     /* function prototypes */ int ascii (const unsigned char c);   int ascii_ext (const unsigned char c);   unsigned char* strip(unsigned char* str, const size_t n, int ext );     /* check a character return 1 for true 0 for false */ int ascii (const unsigned char c) { unsigned char min = 32; /* <space> */ unsigned char max = 126; /* ~ tilde */   if ( c>=min && c<=max ) return 1;   return 0; }     /* check if extended character return 1 for true 0 for false */ int ascii_ext (const unsigned char c) { unsigned char min_ext = 128; unsigned char max_ext = 255;   if ( c>=min_ext && c<=max_ext ) return 1;   return 0; }     /* fill buffer with only ASCII valid characters then rewrite string from buffer limit to n < MAX chars */   unsigned char* strip( unsigned char* str, const size_t n, int ext) {   unsigned char buffer[MAXBUF] = {'\0'};   size_t i = 0; // source index size_t j = 0; // dest index   size_t max = (n<MAXBUF)? n : MAXBUF -1; // limit size   while (i < max ) { if ( (ext && ascii_ext(str[i]) ) || (ascii(str[i]) ) ) // check { buffer[j++] = str[i]; // assign } i++; }   memset(str, '\0', max); // wipe string   i = 0; // reset count   while( i < j) { str[i] = buffer[i]; // copy back i++; }   str[j] = '\0'; // terminate properly   return str; }   /* try it out */ int main( int argc, char** argv) { enum {ASCII=0, EXT=1}; /* enumeration makes easier reading */   unsigned int seed = 134529; // RNG seed value   /* variables and storage */ unsigned char badstring[STR_SZ] = {'\0'}; unsigned char bs_2[STR_SZ] = {'\0'};   unsigned char* goodstring = NULL; unsigned char* goodstring_ext = NULL;   size_t i = 0;   srand(seed); /* seed RNG */   fprintf(stdout, "Original:\t" );   /* generate a random string */ for (i = 0; i < STR_SZ; i++) { badstring[i] = (unsigned char) ( rand () & (unsigned char)0xFF ); fprintf(stdout, "%c", badstring[i] ); } fprintf(stdout, "\n");     memcpy(bs_2, badstring, STR_SZ * sizeof(unsigned char) ); /* copy string */   goodstring_ext = strip( badstring, STR_SZ, EXT); /* remove non-extended and non-ascii */   fprintf(stdout, "\nEXT:\t%s\n" , goodstring_ext );   goodstring = strip( bs_2, STR_SZ, ASCII); /* remove all non-ascii */   fprintf(stdout, "\nASCII:\t%s\n" , goodstring );   return 0; }
http://rosettacode.org/wiki/String_concatenation
String concatenation
String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string literal. To illustrate the operation, show the content of the variables. 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 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 Concatenate(CHAR ARRAY text,left,right) SCopy(text,left) Append(text,right) RETURN   PROC TestConcatenate(CHAR ARRAY left,right) CHAR ARRAY text(256)   Concatenate(text,left,right) PrintF("""%S""+""%S""=""%S""%E",left,right,text) RETURN   PROC Main() TestConcatenate("Hello", " World!") RETURN
http://rosettacode.org/wiki/String_concatenation
String concatenation
String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string literal. To illustrate the operation, show the content of the variables. 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
#ActionScript
ActionScript
package { public class Str { public static function main():void { var s:String = "hello"; trace(s + " literal"); var s2:String = s + " literal"; trace(s2); } } }
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.
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Function sum35 (n As UInteger) As UInteger If n = 0 Then Return 0 Dim As UInteger i, sum = 0 For i = 1 To n If (i Mod 3 = 0) OrElse (i Mod 5 = 0) Then sum += i Next Return sum End Function   Print "Sum of positive integers below 1000 divisible by 3 or 5 is : "; sum35(999) Print Print "Press any key to quit" Sleep
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
#Frink
Frink
sumDigits[n, base=10] := sum[integerDigits[n, base]]
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
#Icon_and_Unicon
Icon and Unicon
procedure main() local lst lst := [] #Construct a simple list and pass it to getsum every put(lst,seq()\2) write(getsum(lst)) end   procedure getsum(lst) local total total := 0 every total +:= !lst ^ 2 return total 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
#IDL
IDL
print,total(array^2)
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
#Burlesque
Burlesque
  blsq ) " this is a string "t[ "this is a string " blsq ) " this is a string "t] " this is a string" blsq ) " this is a string "tt "this is a string"  
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
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h>   char *rtrim(const char *s) { while( isspace(*s) || !isprint(*s) ) ++s; return strdup(s); }   char *ltrim(const char *s) { char *r = strdup(s); if (r != NULL) { char *fr = r + strlen(s) - 1; while( (isspace(*fr) || !isprint(*fr) || *fr == 0) && fr >= r) --fr; *++fr = 0; } return r; }   char *trim(const char *s) { char *r = rtrim(s); char *f = ltrim(r); free(r); return f; }   const char *a = " this is a string ";   int main() { char *b = rtrim(a); char *c = ltrim(a); char *d = trim(a);   printf("'%s'\n'%s'\n'%s'\n", b, c, d);   free(b); free(c); free(d); return 0; }
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.
#Ksh
Ksh
  #!/bin/ksh   # Strong and weak primes # # 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. ???   # # A strong prime is when prime[p] > (prime[p-1] + prime[p+1]) ÷ 2 # # A weak prime is when prime[p] < (prime[p-1] + prime[p+1]) ÷ 2 # # Balanced prime is when prime[p] = (prime[p-1] + prime[p+1]) ÷ 2   # # Variables: # integer NUM_STRONG=36 NUM_WEAK=37 GOAL1=1000000 MAX_INT=10000000   # # Functions: # # # Function _isprime(n) return 1 for prime, 0 for not prime # function _isprime { typeset _n ; integer _n=$1 typeset _i ; integer _i   (( _n < 2 )) && return 0 for (( _i=2 ; _i*_i<=_n ; _i++ )); do (( ! ( _n % _i ) )) && return 0 done return 1 }   # # Function _strength(prime[n], prime[n-1], prime[n+1]) return 1 for strong # function _strength { typeset _pri ; integer _pri=$1 # PRIme number under consideration typeset _pre ; integer _pre=$2 # PREvious prime number typeset _nex ; integer _nex=$3 # NEXt prime number typeset _result ; typeset -F1 _result   (( _result = (_pre + _nex) / 2.0 )) (( _pri > _result )) && echo STRONG && return 0 (( _pri < _result )) && echo WEAK && return 1 echo BALANCED && return 99 }   ##### # main # ######   integer spcnt=0 wpcnt=0 bpcnt=0 sflg=0 wflg=0 i j k goal1_strong goal1_weak typeset -C prime # prime[].val prime[].typ typeset -a prime.val typeset -a prime.typ prime.typ[0]='NA' ; prime.typ[1]='NA'   for (( i=2; i<MAX_INT; i++ )); do _isprime ${i} ; (( ! $? )) && continue prime.val+=( ${i} ) (( ${#prime.val[*]} <= 2 )) && continue   (( j = ${#prime.val[*]} - 2 )) ; (( k = j - 1 )) prime.typ+=( $(_strength ${prime.val[${j}]} ${prime.val[k]} ${prime.val[-1]}) ) case $? in 0) (( spcnt++ )) (( spcnt <= NUM_STRONG )) && strbuff+="${prime.val[j]}, " (( i >= GOAL1 )) && (( ! sflg )) && (( goal1_strong = spcnt - 1 )) && (( sflg = 1 ))  ;;   1) (( wpcnt++ )) (( wpcnt <= NUM_WEAK )) && weabuff+="${prime.val[j]}, " (( i >= GOAL1 )) && (( ! wflg )) && (( goal1_weak = wpcnt - 1 )) && (( wflg = 1 ))  ;;   99) (( bpcnt++ ))  ;; esac done   printf "Total primes under %d = %d\n\n" $MAX_INT ${#prime.val[*]} printf "First %d Strong Primes are: %s\n\n" $NUM_STRONG "${strbuff%,*}" printf "Number of Strong Primes under %d is: %d\n" $GOAL1 ${goal1_strong} printf "Number of Strong Primes under %d is: %d\n\n\n" $MAX_INT ${spcnt} printf "First %d Weak Primes are: %s\n\n" $NUM_WEAK "${weabuff%,*}" printf "Number of Weak Primes under %d is: %d\n" $GOAL1 ${goal1_weak} printf "Number of Weak Primes under %d is: %d\n\n\n" $MAX_INT ${wpcnt} printf "Number of Balanced Primes under %d is: %d\n\n\n" $MAX_INT ${bpcnt}
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.
#Lua
Lua
-- Return a table of the primes up to n, then one more function primeList (n) local function isPrime (x) for d = 3, math.sqrt(x), 2 do if x % d == 0 then return false end end return true end local pTable, j = {2, 3} for i = 5, n, 2 do if isPrime(i) then table.insert(pTable, i) end j = i end repeat j = j + 2 until isPrime(j) table.insert(pTable, j) return pTable end   -- Return a boolean indicating whether prime p is strong function isStrong (p) if p == 1 or p == #prime then return false end return prime[p] > (prime[p-1] + prime[p+1]) / 2 end   -- Return a boolean indicating whether prime p is weak function isWeak (p) if p == 1 or p == #prime then return false end return prime[p] < (prime[p-1] + prime[p+1]) / 2 end   -- Main procedure prime = primeList(1e7) local strong, weak, sCount, wCount = {}, {}, 0, 0 for k, v in pairs(prime) do if isStrong(k) then table.insert(strong, v) if v < 1e6 then sCount = sCount + 1 end end if isWeak(k) then table.insert(weak, v) if v < 1e6 then wCount = wCount + 1 end end end print("The first 36 strong primes are:") for i = 1, 36 do io.write(strong[i] .. " ") end print("\n\nThere are " .. sCount .. " strong primes below one million.") print("\nThere are " .. #strong .. " strong primes below ten million.") print("\nThe first 37 weak primes are:") for i = 1, 37 do io.write(weak[i] .. " ") end print("\n\nThere are " .. wCount .. " weak primes below one million.") print("\nThere are " .. #weak .. " weak primes below ten million.")
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
#BASIC
BASIC
DIM baseString AS STRING, subString AS STRING, findString AS STRING DIM m AS INTEGER, n AS INTEGER   baseString = "abcdefghijklmnopqrstuvwxyz" n = 12 m = 5   ' starting from n characters in and of m length; subString = MID$(baseString, n, m) PRINT subString   ' starting from n characters in, up to the end of the string; subString = MID$(baseString, n) PRINT subString   ' whole string minus last character; subString = LEFT$(baseString, LEN(baseString) - 1) PRINT subString   ' starting from a known character within the string and of m length; subString = MID$(baseString, INSTR(baseString, "b"), m) PRINT subString   ' starting from a known substring within the string and of m length. findString = "pq" subString = MID$(baseString, INSTR(baseString, findString), m) PRINT subString  
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.
#Common_Lisp
Common Lisp
(defun row-neighbors (row column grid &aux (neighbors '())) (dotimes (i 9 neighbors) (let ((x (aref grid row i))) (unless (or (eq '_ x) (= i column)) (push x neighbors)))))   (defun column-neighbors (row column grid &aux (neighbors '())) (dotimes (i 9 neighbors) (let ((x (aref grid i column))) (unless (or (eq x '_) (= i row)) (push x neighbors)))))   (defun square-neighbors (row column grid &aux (neighbors '())) (let* ((rmin (* 3 (floor row 3))) (rmax (+ rmin 3)) (cmin (* 3 (floor column 3))) (cmax (+ cmin 3))) (do ((r rmin (1+ r))) ((= r rmax) neighbors) (do ((c cmin (1+ c))) ((= c cmax)) (let ((x (aref grid r c))) (unless (or (eq x '_) (= r row) (= c column)) (push x neighbors)))))))   (defun choices (row column grid) (nset-difference (list 1 2 3 4 5 6 7 8 9) (nconc (row-neighbors row column grid) (column-neighbors row column grid) (square-neighbors row column grid))))   (defun solve (grid &optional (row 0) (column 0)) (cond ((= row 9) grid) ((= column 9) (solve grid (1+ row) 0)) ((not (eq '_ (aref grid row column))) (solve grid row (1+ column))) (t (dolist (choice (choices row column grid) (setf (aref grid row column) '_)) (setf (aref grid row column) choice) (when (eq grid (solve grid row (1+ column))) (return grid))))))
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
#CLU
CLU
% Read numbers from a stream read_nums = iter (s: stream) yields (int) while true do c: char := stream$getc(s) while c~='-' & ~(c>='0' & c<='9') do c := stream$getc(s) end acc: int := 0 neg: bool if c='-' then neg := true c := stream$getc(s) else neg := false end while c>='0' & c<='9' do acc := acc*10 + char$c2i(c) - char$c2i('0') c := stream$getc(s) except when end_of_file: break end end if neg then acc := -acc end yield(acc) end except when end_of_file: end end read_nums   % Auto-resizing array mem = cluster is new, load, fetch, store rep = array[int]   new = proc () returns (cvt) return(rep$predict(0,2**9)) end new   fill_to = proc (a: rep, lim: int) while rep$high(a) < lim do rep$addh(a,0) end end fill_to   fetch = proc (a: cvt, n: int) returns (int) signals (bounds) fill_to(a,n) return(a[n]) resignal bounds end fetch   store = proc (a: cvt, n: int, v: int) signals (bounds) fill_to(a,n) a[n] := v resignal bounds end store   load = proc (a: cvt, s: stream) i: int := 0 for n: int in read_nums(s) do up(a)[i] := n i := i + 1 end end load end mem   % Run a Subleq program subleq = proc (m: mem, si, so: stream) ip: int := 0 while ip >= 0 do a: int := m[ip] b: int := m[ip+1] c: int := m[ip+2] ip := ip + 3 if a=-1 then m[b] := char$c2i(stream$getc(si)) elseif b=-1 then stream$putc(so,char$i2c(m[a] // 256)) else m[b] := m[b] - m[a] if m[b] <= 0 then ip := c end end end end subleq   start_up = proc () pi: stream := stream$primary_input() po: stream := stream$primary_output()   args: sequence[string] := get_argv() if sequence[string]$size(args) ~= 1 then stream$putl(stream$error_output(), "Usage: subleq file_name") return end   fname: file_name := file_name$parse(sequence[string]$bottom(args)) file: stream := stream$open(fname, "read") m: mem := mem$new() mem$load(m, file) stream$close(file) subleq(m, pi, po) end start_up
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
#COBOL
COBOL
identification division. program-id. subleq-program. data division. working-storage section. 01 subleq-source-code. 05 source-string pic x(2000). 01 subleq-virtual-machine. 05 memory-table. 10 memory pic s9999 occurs 500 times. 05 a pic s9999. 05 b pic s9999. 05 c pic s9999. 05 instruction-pointer pic s9999. 05 input-output-character pic x. 01 working-variables. 05 loop-counter pic 9999. 05 instruction-counter pic 9999. 05 string-pointer pic 9999. 05 adjusted-index-a pic 9999. 05 adjusted-index-b pic 9999. 05 output-character-code pic 9999. procedure division. read-source-paragraph. accept source-string from console. display 'READING SUBLEQ PROGRAM... ' with no advancing. move 1 to string-pointer. move 0 to instruction-counter. perform split-source-paragraph varying loop-counter from 1 by 1 until loop-counter is greater than 500 or string-pointer is greater than 2000. display instruction-counter with no advancing. display ' WORDS READ.'. execute-paragraph. move 1 to instruction-pointer. move 0 to instruction-counter. display 'BEGINNING RUN... '. display ''. perform execute-instruction-paragraph until instruction-pointer is negative. display ''. display 'HALTED AFTER ' instruction-counter ' INSTRUCTIONS.'. stop run. execute-instruction-paragraph. add 1 to instruction-counter. move memory(instruction-pointer) to a. add 1 to instruction-pointer. move memory(instruction-pointer) to b. add 1 to instruction-pointer. move memory(instruction-pointer) to c. add 1 to instruction-pointer. if a is equal to -1 then perform input-paragraph. if b is equal to -1 then perform output-paragraph. if a is not equal to -1 and b is not equal to -1 then perform subtraction-paragraph. split-source-paragraph. unstring source-string delimited by all spaces into memory(loop-counter) with pointer string-pointer. add 1 to instruction-counter. input-paragraph. display '> ' with no advancing. accept input-output-character from console. add 1 to b giving adjusted-index-b. move function ord(input-output-character) to memory(adjusted-index-b). subtract 1 from memory(adjusted-index-b). output-paragraph. add 1 to a giving adjusted-index-a. add 1 to memory(adjusted-index-a) giving output-character-code. move function char(output-character-code) to input-output-character. display input-output-character with no advancing. subtraction-paragraph. add 1 to c. add 1 to a giving adjusted-index-a. add 1 to b giving adjusted-index-b. subtract memory(adjusted-index-a) from memory(adjusted-index-b). if memory(adjusted-index-b) is equal to zero or memory(adjusted-index-b) is negative then move c to instruction-pointer.
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
#Julia
Julia
using Primes   function filterdifferences(deltas, N) allprimes = primes(N) differences = map(i -> allprimes[i + 1] - allprimes[i], 1:length(allprimes) - 1) println("Diff Sequence Count First Last") for delt in deltas ret = trues(length(allprimes) - length(delt)) for j in 1:length(ret) for (i, d) in enumerate(delt) if differences[j - 1 + i] != d ret[j] = false break end end end count, p1, pn, n = sum(ret), findfirst(ret), findlast(ret), length(delt) println(rpad(string(delt), 16), lpad(count, 4), lpad(string(allprimes[p1:p1 + n]), 18), "...", rpad(allprimes[pn:pn+n], 15)) end end   filterdifferences([[2], [1], [2, 2], [2, 4], [4, 2], [6, 4, 2]], 1000000)  
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
#Common_Lisp
Common Lisp
> (defvar *str* "∀Ꮺ✤Л◒") *STR* > (subseq *str* 1) ; remove first character "Ꮺ✤Л◒" > (subseq *str* 0 (1- (length *str*))) ; remove last character "∀Ꮺ✤Л" > (subseq *str* 1 (1- (length *str*))) ; remove first and last character "Ꮺ✤Л"
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.
#Julia
Julia
i,j,m,d,seed = 55,24,10^9,34,292929 # parameters s = Array{Int32}(undef,i); r = similar(s) s[1:2] = [seed,1] # table initialization for n = 3:i; (s[n] = s[n-2]-s[n-1]) < 0 && (s[n] += m) end t = 1; for u=1:i; (global t+=d)>i && (t-=i); r[u]=s[t] end # permutation, r = s[(d*(1:i) .% i).+1]   u,v,n = i,i-j,i-1 while (n += 1) > 0 (global u += 1) > i && (u = 1) # circular indexing: u,v = ((n,n-j) .% i).+1 (global v += 1) > i && (v = 1) (r[u] -= r[v]) < 0 && (r[u] += m) # table update n < 220 && continue # 165 silent values print((n,r[u])) # show (index,value) of next pseudorandom number x = readline(stdin) # wait until the ENTER key is pressed length(x) > 0 && break # any other key before ENTER => exit end
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.
#Kotlin
Kotlin
// version 1.1.51   const val MOD = 1_000_000_000   val state = IntArray(55) var si = 0 var sj = 0   fun subrandSeed(p: Int) { var p1 = p var p2 = 1 state[0] = p1 % MOD var j = 21 for (i in 1..54) { if (j >=55) j -= 55 state[j] = p2 p2 = p1 - p2 if (p2 < 0) p2 += MOD p1 = state[j] j += 21 } si = 0 sj = 24 repeat(165) { subrand() } }   fun subrand(): Int { if (si == sj) subrandSeed(0) if (si-- == 0) si = 54 if (sj-- == 0) sj = 54 var x = state[si] - state[sj] if (x < 0) x += MOD state[si] = x return x }   fun main(args: Array<String>) { subrandSeed(292_929) for (i in 0..9) println("r[${i + 220}] = ${subrand()}") }
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
#Ring
Ring
  # Project : Substitution Cipher   plaintext = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ciphertext = "ZEBRASCDFGHIJKLMNOPQTUVWXY" test = "flee at once. we are discovered!" encrypt = "SIAA ZQ LKBA. VA ZOA RFPBLUAOAR!"   see "Plaintext : " + plaintext + nl see "Ciphertext : " + ciphertext + nl see "Test : " + test + nl see "Encoded : " encodetext = encode(test) see encodetext + nl see "Decoded : " decodetext = decode(encodetext) see decodetext + nl   func encode(test) str = "" for n = 1 to len(test) pos = substr(plaintext, upper(test[n])) if test[n] = " " str = str + " " elseif test[n] = "!" str = str + "!" elseif test[n] = "." str = str + "." else str = str + substr(ciphertext, pos, 1) ok next return str   func decode(test) str = "" for n = 1 to len(encodetext) pos = substr(ciphertext, upper(encodetext[n])) if test[n] = " " str = str + " " elseif test[n] = "!" str = str + "!" elseif test[n] = "." str = str + "." else str = str + lower(substr(plaintext, pos, 1)) ok next return str  
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
#Ruby
Ruby
Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" Key = "VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWobLkESYMTN"   def encrypt(str) = str.tr(Alphabet, Key) def decrypt(str) = str.tr(Key, Alphabet)   str = 'All is lost, he thought. Everything is ruined. It’s ten past three.' p encrypted = encrypt(str) p decrypt(encrypted)  
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
#Scala
Scala
object SubstitutionCipher extends App { private val key = "]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\"v*N" + "[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ" private val text = """"It was still dark, in the early morning hours of the twenty-second of December | 1946, on the second floor of the house at Schilderskade 66 in our town, | when the hero of this story, Frits van Egters, awoke."""".stripMargin   val enc = encode(text) println("Encoded: " + enc) println("Decoded: " + decode(enc))   private def encode(s: String) = { val sb = new StringBuilder(s.length) s.map { case c if (' ' to '~').contains(c) => sb.append(key(c.toInt - 32)) case _ => } sb.toString }   private def decode(s: String) = { val sb = new StringBuilder(s.length) s.map { case c if (' ' to '~').contains(c) => sb.append((key.indexOf(c.toInt) + 32).toChar) case _ => } sb.toString } }
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.
#Fermat
Fermat
  [a]:=[(1,1,2,3,5,8,13)]; !!Sigma<i=1,7>[a[i]]; !!Prod<i=1,7>[a[i]];  
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.
#Forth
Forth
: third ( a b c -- a b c a ) 2 pick ; : reduce ( xt n addr cnt -- n' ) \ where xt ( a b -- n ) cells bounds do i @ third execute cell +loop nip ;   create a 1 , 2 , 3 , 4 , 5 ,   ' + 0 a 5 reduce . \ 15 ' * 1 a 5 reduce . \ 120
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.
#Elixir
Elixir
iex(1)> Enum.reduce(1..1000, 0, fn x,sum -> sum + 1/(x*x) end) 1.6439345666815615
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
#Bracmat
Bracmat
( " apples, pears # and bananas oranges, mangos ; and a durian"  : ?text & :?newText & ( non-blank = %@:~(" "|\t|\r|\n) ) & ( cleanUp = . @(!arg:?arg ("#"|";") ?) & @(rev$!arg:? (!non-blank ?:?arg)) & @(rev$!arg:? (!non-blank ?:?arg)) & !arg {You could write & "[" !arg "]" to prove that the blanks are stripped.} ) & whl ' ( @(!text:?line (\r|\n) ?text) & !newText \n cleanUp$!line:?newText ) & !newText \n cleanUp$!text:?newText & out$(str$!newText) );
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
#C
C
#include<stdio.h>   int main() { char ch, str[100]; int i;   do{ printf("\nEnter the string :"); fgets(str,100,stdin); for(i=0;str[i]!=00;i++) { if(str[i]=='#'||str[i]==';') { str[i]=00; break; } } printf("\nThe modified string is : %s",str); printf("\nDo you want to repeat (y/n): "); scanf("%c",&ch); fflush(stdin); }while(ch=='y'||ch=='Y');   return 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
#Delphi
Delphi
  program Strip_block_comments;   {$APPTYPE CONSOLE}   uses System.SysUtils;   function BlockCommentStrip(commentStart, commentEnd, sampleText: string): string; begin while ((sampleText.IndexOf(commentStart) > -1) and (sampleText.IndexOf(commentEnd, sampleText.IndexOf(commentStart) + commentStart.Length) > -1)) do begin var start := sampleText.IndexOf(commentStart); var _end := sampleText.IndexOf(commentEnd, start + commentStart.Length); sampleText := sampleText.Remove(start, (_end + commentEnd.Length) - start); end; Result := sampleText; end;   const test = '/**' + #10 + '* Some comments' + #10 + '* longer comments here that we can parse.' + #10 + '*' + #10 + '* Rahoo ' + #10 + '*/' + #10 + 'function subroutine() {' + #10 + 'a = /* inline comment */ b + c ;' + #10 + '}' + #10 + '/*/ <-- tricky comments */' + #10 + '' + #10 + '/**' + #10 + '* Another comment.' + #10 + '*/' + #10 + 'function something() {' + #10 + '}';   begin   writeln(BlockCommentStrip('/*', '*/', test)); readln; end.
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).
#Phix
Phix
with javascript_semantics enum SUB=-1, NOP=0, ADD=1 function evaluate(sequence s) integer res = 0, tmp = 0, op = ADD for i=1 to length(s) do if s[i]=NOP then tmp = tmp*10+i else res += op*tmp tmp = i op = s[i] end if end for return res + op*tmp end function procedure show(sequence s) string res = "" for i=1 to length(s) do if s[i]!=NOP then res &= ','-s[i] end if res &= '0'+i end for printf(1,"%s = %d\n",{res,evaluate(s)}) end procedure -- Logically this intersperses -/nop/+ between each digit, but you do not actually need the digit. sequence s = repeat(SUB,9) -- (==> ..nop+add*8) bool done = false integer maxl = 0, maxr integer count = 0 while not done do count += 1 integer r = evaluate(s), k = getd_index(r) sequence solns = iff(k=0?{}:deep_copy(getd_by_index(k))) solns = append(solns,deep_copy(s)) setd(r,solns) if r>0 and maxl<length(solns) then maxl = length(solns) maxr = r end if for i=length(s) to 1 by -1 do if i=1 and s[i]=NOP then done = true exit elsif s[i]!=ADD then s[i] += 1 exit end if s[i] = SUB end for end while printf(1,"%d solutions considered (dictionary size: %d)\n",{count,dict_size()}) sequence s100 = getd(100) printf(1,"There are %d sums to 100:\n",{length(s100)}) papply(s100,show) printf(1,"The positive sum of %d has the maximum number of solutions: %d\n",{maxr,maxl}) integer prev = 0 function missing(integer key, sequence /*data*/, integer /*pkey*/, object /*user_data=-2*/) if key!=prev+1 then return 0 end if prev = key return 1 end function traverse_dict_partial_key(missing,1) printf(1,"The lowest positive sum that cannot be expressed: %d\n",{prev+1}) sequence highest = {} function top10(integer key, sequence /*data*/, object /*user_data*/) highest &= key return length(highest)<10 end function --DEV named params on builtins need pre-loading...: --traverse_dict(top10,rev:=1) traverse_dict(top10,0,1,true) printf(1,"The 10 highest sums: %v\n",{highest})
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
#Applesoft_BASIC
Applesoft BASIC
100 LET S$ = "SHE WAS A SOUL STRIPPER. SHE TOOK MY HEART!" 110 LET RM$ = "AEI" 120 GOSUB 200STRIPCHARS 130 PRINT SC$ 190 END 200 REM 210 REM STRIPCHARS 220 REM 230 LET SC$ = "" 240 LET SL = LEN (S$) 250 IF SL = 0 THEN RETURN 260 FOR SI = 1 TO SL 270 LET SM$ = MID$ (S$,SI,1) 280 FOR SJ = 1 TO LEN (RM$) 290 LET SR$ = MID$ (RM$,SJ,1) 300 LET ST = SR$ < > SM$ 310 IF ST THEN NEXT SJ 320 IF ST THEN SC$ = SC$ + SM$ 330 NEXT SI 340 RETURN  
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
#Arturo
Arturo
stripChars: function [str, chars]-> join select split str => [not? in? & split chars]   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.
#C.23
C#
using System;   namespace PrependString { class Program { static void Main(string[] args) { string str = "World"; str = "Hello " + str; Console.WriteLine(str); Console.ReadKey(); } } }
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.
#C.2B.2B
C++
include <vector> #include <algorithm> #include <string> #include <iostream>   int main( ) { std::vector<std::string> myStrings { "prepended to" , "my string" } ; std::string prepended = std::accumulate( myStrings.begin( ) , myStrings.end( ) , std::string( "" ) , []( std::string a , std::string b ) { return a + b ; } ) ; std::cout << prepended << std::endl ; return 0 ; }
http://rosettacode.org/wiki/String_comparison
String comparison
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 Demonstrate how to compare two strings from within the language and how to achieve a lexical comparison. The task should demonstrate: Comparing two strings for exact equality Comparing two strings for inequality (i.e., the inverse of exact equality) Comparing two strings to see if one is lexically ordered before than the other Comparing two strings to see if one is lexically ordered after than the other How to achieve both case sensitive comparisons and case insensitive comparisons within the language How the language handles comparison of numeric strings if these are not treated lexically Demonstrate any other kinds of string comparisons that the language provides, particularly as it relates to your type system. For example, you might demonstrate the difference between generic/polymorphic comparison and coercive/allomorphic comparison if your language supports such a distinction. Here "generic/polymorphic" comparison means that the function or operator you're using doesn't always do string comparison, but bends the actual semantics of the comparison depending on the types one or both arguments; with such an operator, you achieve string comparison only if the arguments are sufficiently string-like in type or appearance. In contrast, a "coercive/allomorphic" comparison function or operator has fixed string-comparison semantics regardless of the argument type;   instead of the operator bending, it's the arguments that are forced to bend instead and behave like strings if they can,   and the operator simply fails if the arguments cannot be viewed somehow as strings.   A language may have one or both of these kinds of operators;   see the Raku entry for an example of a language with both kinds of operators. 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
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program comparString64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64.inc" /*******************************************/ /* Initialized data */ /*******************************************/ .data szMessStringEqu: .asciz "The strings are equals.\n" szMessStringNotEqu: .asciz "The strings are not equals.\n" szCarriageReturn: .asciz "\n"   szString1: .asciz "ABCDE" szString2: .asciz "ABCDE" szString3: .asciz "ABCFG" szString4: .asciz "ABC" szString5: .asciz "abcde" /*******************************************/ /* UnInitialized data / /*******************************************/ .bss /*******************************************/ /* code section */ /*******************************************/ .text .global main main: // entry of program   ldr x0,qAdrszString1 ldr x1,qAdrszString2 bl Comparaison   ldr x0,qAdrszString1 ldr x1,qAdrszString3 bl Comparaison   ldr x0,qAdrszString1 ldr x1,qAdrszString4 bl Comparaison // case sensitive comparisons ABCDE et abcde ldr x0,qAdrszString1 ldr x1,qAdrszString5 bl Comparaison // case insensitive comparisons ABCDE et abcde ldr x0,qAdrszString1 ldr x1,qAdrszString5 bl comparStringsInsensitive cbnz x0,1f ldr x0,qAdrszMessStringEqu bl affichageMess b 2f 1: ldr x0,qAdrszMessStringNotEqu bl affichageMess   2:   100: // standard end of the program mov x0,0 // return code mov x8,EXIT // request to exit program svc 0 // perform the system call qAdrszString1: .quad szString1 qAdrszString2: .quad szString2 qAdrszString3: .quad szString3 qAdrszString4: .quad szString4 qAdrszString5: .quad szString5 qAdrszMessStringEqu: .quad szMessStringEqu qAdrszMessStringNotEqu: .quad szMessStringNotEqu qAdrszCarriageReturn: .quad szCarriageReturn /*********************************************/ /* comparaison */ /*********************************************/ /* x0 contains address String 1 */ /* x1 contains address String 2 */ Comparaison: stp x1,lr,[sp,-16]! // save registers bl comparStrings cbnz x0,1f ldr x0,qAdrszMessStringEqu bl affichageMess b 2f 1: ldr x0,qAdrszMessStringNotEqu bl affichageMess   2: ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30   /************************************/ /* Strings case sensitive comparisons */ /************************************/ /* x0 et x1 contains the address of strings */ /* return 0 in x0 if equals */ /* return -1 if string x0 < string x1 */ /* return 1 if string x0 > string x1 */ comparStrings: stp x1,lr,[sp,-16]! // save registers stp x2,x3,[sp,-16]! // save registers stp x4,x5,[sp,-16]! // save registers mov x2,#0 // counter 1: ldrb w3,[x0,x2] // byte string 1 ldrb w4,[x1,x2] // byte string 2 cmp x3,x4 blt 2f bgt 3f cbz x3,4f // 0 end string add x2,x2,1 // else add 1 in counter b 1b // and loop */ 2: mov x0,-1 // lower b 100f 3: mov x0,1 // higher b 100f 4: mov x0,0 // equal 100: ldp x4,x5,[sp],16 // restaur 2 registers ldp x2,x3,[sp],16 // restaur 2 registers ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 /************************************/ /* Strings case insensitive comparisons */ /************************************/ /* x0 et x1 contains the address of strings */ /* return 0 in x0 if equals */ /* return -1 if string x0 < string x1 */ /* return 1 if string x0 > string x1 */ comparStringsInsensitive: stp x1,lr,[sp,-16]! // save registers stp x2,x3,[sp,-16]! // save registers stp x4,x5,[sp,-16]! // save registers mov x2,#0 // counter   1: ldrb w3,[x0,x2] // byte string 1 ldrb w4,[x1,x2] // byte string 2 // majuscules --> minuscules byte 1 cmp x3,65 blt 2f cmp x3,90 bgt 2f add x3,x3,32 2: // majuscules --> minuscules byte 2 cmp x4,65 blt 3f cmp x4,90 bgt 3f add x4,x4,32 3: cmp x3,x4 blt 4f bgt 5f cbz x3,6f // 0 end string add x2,x2,1 // else add 1 in counter b 1b // and loop 4: mov x0,-1 // lower b 100f 5: mov x0,1 // higher b 100f 6: mov x0,0 // equal 100: ldp x4,x5,[sp],16 // restaur 2 registers ldp x2,x3,[sp],16 // restaur 2 registers ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 /********************************************************/ /* File Include fonctions */ /********************************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeARM64.inc"  
http://rosettacode.org/wiki/String_comparison
String comparison
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 Demonstrate how to compare two strings from within the language and how to achieve a lexical comparison. The task should demonstrate: Comparing two strings for exact equality Comparing two strings for inequality (i.e., the inverse of exact equality) Comparing two strings to see if one is lexically ordered before than the other Comparing two strings to see if one is lexically ordered after than the other How to achieve both case sensitive comparisons and case insensitive comparisons within the language How the language handles comparison of numeric strings if these are not treated lexically Demonstrate any other kinds of string comparisons that the language provides, particularly as it relates to your type system. For example, you might demonstrate the difference between generic/polymorphic comparison and coercive/allomorphic comparison if your language supports such a distinction. Here "generic/polymorphic" comparison means that the function or operator you're using doesn't always do string comparison, but bends the actual semantics of the comparison depending on the types one or both arguments; with such an operator, you achieve string comparison only if the arguments are sufficiently string-like in type or appearance. In contrast, a "coercive/allomorphic" comparison function or operator has fixed string-comparison semantics regardless of the argument type;   instead of the operator bending, it's the arguments that are forced to bend instead and behave like strings if they can,   and the operator simply fails if the arguments cannot be viewed somehow as strings.   A language may have one or both of these kinds of operators;   see the Raku entry for an example of a language with both kinds of operators. 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 TestEqual(CHAR ARRAY s1,s2) INT res   PrintF("""%S"" and ""%S"" are equal: ",s1,s2) IF SCompare(s1,s2)=0 THEN PrintE("True") ELSE PrintE("False") FI RETURN   PROC TestInequal(CHAR ARRAY s1,s2) INT res   PrintF("""%S"" and ""%S"" are inequal: ",s1,s2) IF SCompare(s1,s2)#0 THEN PrintE("True") ELSE PrintE("False") FI RETURN   PROC TestBefore(CHAR ARRAY s1,s2) INT res   PrintF("""%S"" is before ""%S"": ",s1,s2) IF SCompare(s1,s2)<0 THEN PrintE("True") ELSE PrintE("False") FI RETURN   PROC TestAfter(CHAR ARRAY s1,s2) INT res   PrintF("""%S"" is after ""%S"": ",s1,s2) IF SCompare(s1,s2)>0 THEN PrintE("True") ELSE PrintE("False") FI RETURN   PROC TestNumEqual(CHAR ARRAY s1,s2) INT v1,v2   PrintF("""%S"" and ""%S"" are equal: ",s1,s2) v1=ValI(s1) v2=ValI(s2) IF v1=v2 THEN PrintE("True") ELSE PrintE("False") FI RETURN   PROC TestNumInequal(CHAR ARRAY s1,s2) INT v1,v2   PrintF("""%S"" and ""%S"" are inequal: ",s1,s2) v1=ValI(s1) v2=ValI(s2) IF v1#v2 THEN PrintE("True") ELSE PrintE("False") FI RETURN   PROC TestNumBefore(CHAR ARRAY s1,s2) INT v1,v2   PrintF("""%S"" is before ""%S"": ",s1,s2) v1=ValI(s1) v2=ValI(s2) IF v1<v2 THEN PrintE("True") ELSE PrintE("False") FI RETURN   PROC TestNumAfter(CHAR ARRAY s1,s2) INT v1,v2   PrintF("""%S"" is after ""%S"": ",s1,s2) v1=ValI(s1) v2=ValI(s2) IF v1>v2 THEN PrintE("True") ELSE PrintE("False") FI RETURN   PROC Main() PrintE("Lexical comparison:") TestEqual("abcd","Abcd") TestInequal("abcd","Abcd") TestBefore("abcd","Abcd") TestAfter("abcd","Abcd") PutE()   PrintE("Numerical comparison:") TestNumEqual("1234","99876") TestNumInequal("1234","99876") TestNumBefore("1234","99876") TestNumAfter("1234","99876") RETURN
http://rosettacode.org/wiki/String_case
String case
Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is not reversable. Show any additional case conversion functions   (e.g. swapping case, capitalizing the first letter, etc.)   that may be included in the library of your language. 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
UCASE CSECT USING UCASE,R15 MVC UC,PG MVC LC,PG OC UC,=16C' ' or X'40' uppercase NC LC,=16X'BF' and X'BF' lowercase XPRNT PG,L'PG print original XPRNT UC,L'UC print uc XPRNT LC,L'LC print lc BR R14 PG DC CL9'alphaBETA' UC DS CL(L'PG) LC DS CL(L'PG) YREGS END UCASE
http://rosettacode.org/wiki/String_case
String case
Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is not reversable. Show any additional case conversion functions   (e.g. swapping case, capitalizing the first letter, etc.)   that may be included in the library of your language. 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
#4D
4D
$string:="alphaBETA" $uppercase:=Uppercase($string) $lowercase:=Lowercase($string)
http://rosettacode.org/wiki/String_matching
String matching
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 Given two strings, demonstrate the following three types of string matching:   Determining if the first string starts with second string   Determining if the first string contains the second string at any location   Determining if the first string ends with the second string Optional requirements:   Print the location of the match for part 2   Handle multiple occurrences of a string for part 2. 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 t; data b;   b = "Bangkok";   t = "Bang";   o_form("starts with, embeds, ends with \"~\": ~, ~, ~\n", t, b.seek(t) == 0, b.seek(t) != -1, b.seek(t) != -1 && b.seek(t) + ~t == ~b);   t = "ok";   o_form("starts with, embeds, ends with \"~\": ~, ~, ~\n", t, b.seek(t) == 0, b.seek(t) != -1, b.seek(t) != -1 && b.seek(t) + ~t == ~b);   t = "Summer";   o_form("starts with, embeds, ends with \"~\": ~, ~, ~\n", t, b.seek(t) == 0, b.seek(t) != -1, b.seek(t) != -1 && b.seek(t) + ~t == ~b);
http://rosettacode.org/wiki/String_length
String length
Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme containing combining characters. For example, the character length of "møøse" is 5 but the byte length is 7 in UTF-8 and 10 in UTF-16. Non-BMP code points (those between 0x10000 and 0x10FFFF) must also be handled correctly: answers should produce actual character counts in code points, not in code unit counts. Therefore a string like "𝔘𝔫𝔦𝔠𝔬𝔡𝔢" (consisting of the 7 Unicode characters U+1D518 U+1D52B U+1D526 U+1D520 U+1D52C U+1D521 U+1D522) is 7 characters long, not 14 UTF-16 code units; and it is 28 bytes long whether encoded in UTF-8 or in UTF-16. Please mark your examples with ===Character Length=== or ===Byte Length===. If your language is capable of providing the string length in graphemes, mark those examples with ===Grapheme Length===. For example, the string "J̲o̲s̲é̲" ("J\x{332}o\x{332}s\x{332}e\x{301}\x{332}") has 4 user-visible graphemes, 9 characters (code points), and 14 bytes when encoded in UTF-8. 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
#4D
4D
$length:=Length("Hello, world!")
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
#C.23
C#
  using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;   namespace RosettaCode { class Program { static void Main(string[] args) { string test = "string of ☺☻♥♦⌂, may include control characters and other ilk.♫☼§►↔◄"; Console.WriteLine("Original: {0}", test); Console.WriteLine("Stripped of control codes: {0}", StripControlChars(test)); Console.WriteLine("Stripped of extended: {0}", StripExtended(test)); }   static string StripControlChars(string arg) { char[] arrForm = arg.ToCharArray(); StringBuilder buffer = new StringBuilder(arg.Length);//This many chars at most   foreach(char ch in arrForm) if (!Char.IsControl(ch)) buffer.Append(ch);//Only add to buffer if not a control char   return buffer.ToString(); }   static string StripExtended(string arg) { StringBuilder buffer = new StringBuilder(arg.Length); //Max length foreach(char ch in arg) { UInt16 num = Convert.ToUInt16(ch);//In .NET, chars are UTF-16 //The basic characters have the same code points as ASCII, and the extended characters are bigger if((num >= 32u) && (num <= 126u)) buffer.Append(ch); } return buffer.ToString(); } } }  
http://rosettacode.org/wiki/String_concatenation
String concatenation
String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string literal. To illustrate the operation, show the content of the variables. 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;   procedure String_Concatenation is S1 : constant String := "Hello"; S2 : constant String := S1 & " literal"; begin Put_Line (S1); Put_Line (S2); end String_Concatenation;
http://rosettacode.org/wiki/String_concatenation
String concatenation
String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string literal. To illustrate the operation, show the content of the variables. 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, v;   s = "Hello"; o_(s, "\n"); v = s + ", World!"; o_(v, "\n");
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.
#Frink
Frink
  sum999 = sum[select[1 to 999, {|n| n mod 3 == 0 or n mod 5 == 0}]]   sumdiv[n, d] := { m = floor[n/d] m(m + 1)/2 d }   sum35big[n] := sumdiv[n, 3] + sumdiv[n, 5] - sumdiv[n, 15]   println["The sum of all the multiples of 3 or 5 below 1000 is $sum999"] println["The sum of all multiples less than 1e20 is " + sum35big[1_00000_00000_00000_00000 - 1]]  
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.C5.8Drmul.C3.A6
Fōrmulæ
// File digit.go   package digit   import ( "math/big" "strconv" )   func SumString(n string, base int) (int, error) { i, ok := new(big.Int).SetString(n, base) if !ok { return 0, strconv.ErrSyntax } if i.Sign() < 0 { return 0, strconv.ErrRange } if i.BitLen() <= 64 { return Sum(i.Uint64(), base), nil } return SumBig(i, base), nil }   func Sum(i uint64, base int) (sum int) { b64 := uint64(base) for ; i > 0; i /= b64 { sum += int(i % b64) } return }   func SumBig(n *big.Int, base int) (sum int) { i := new(big.Int).Set(n) b := new(big.Int).SetUint64(uint64(base)) r := new(big.Int) for i.BitLen() > 0 { i.DivMod(i, b, r) sum += int(r.Uint64()) } return }
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
#Inform_7
Inform 7
Sum Of Squares is a room.   To decide which number is the sum of (N - number) and (M - number) (this is summing): decide on N + M.   To decide which number is (N - number) squared (this is squaring): decide on N * N.   To decide which number is the sum of squares of (L - list of numbers): decide on the summing reduction of squaring applied to L.   When play begins: say the sum of squares of {}; say line break; say the sum of squares of {1, 2, 3}; end the story.
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
#Io
Io
list(3,1,4,1,5,9) map(squared) sum
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
#C.23
C#
using System;   public class TrimExample { public static void Main(String[] args) { const string toTrim = " Trim me "; Console.WriteLine(Wrap(toTrim.TrimStart())); Console.WriteLine(Wrap(toTrim.TrimEnd())); Console.WriteLine(Wrap(toTrim.Trim())); }   private static string Wrap(string s) { return "'" + s + "'"; } }
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
#C.2B.2B
C++
#include <boost/algorithm/string.hpp> #include <string> #include <iostream>   int main( ) { std::string testphrase( " There are unwanted blanks here! " ) ; std::string lefttrimmed = boost::trim_left_copy( testphrase ) ; std::string righttrimmed = boost::trim_right_copy( testphrase ) ; std::cout << "The test phrase is :" << testphrase << "\n" ; std::cout << "Trimmed on the left side :" << lefttrimmed << "\n" ; std::cout << "Trimmed on the right side :" << righttrimmed << "\n" ; boost::trim( testphrase ) ; std::cout << "Trimmed on both sides :" << testphrase << "\n" ; return 0 ; }
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.
#Maple
Maple
isStrong := proc(n::posint) local holder; holder := false; if isprime(n) and 1/2*prevprime(n) + 1/2*nextprime(n) < n then holder := true; end if; return holder; end proc:   isWeak := proc(n::posint) local holder; holder := false; if isprime(n) and n < 1/2*prevprime(n) + 1/2*nextprime(n) then holder := true; end if; return holder; end proc   findStrong := proc(n::posint) local count, list, k; count := 0; list := []; for k from 3 while count < n do if isStrong(k) then count := count + 1; list := [op(list), k]; end if; end do; return list; end proc:   findWeak := proc(n::posint) local count, list, k; count := 0; list := []; for k from 3 while count < n do if isWeak(k) then count := count + 1; list := [op(list), k]; end if; end do; return list; end proc:   findStrong(36) findWeak(37) countStrong(1000000) countStrong(10000000) countWeak(1000000) countWeak(10000000)
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
p = Prime[Range[PrimePi[10^3]]]; SequenceCases[p, ({a_, b_, c_}) /; (a + c < 2 b) :> b, 36, Overlaps -> True] SequenceCases[p, ({a_, b_, c_}) /; (a + c > 2 b) :> b, 37, Overlaps -> True] p = Prime[Range[PrimePi[10^6] + 1]]; Length[Select[Partition[p, 3, 1], #[[3]] + #[[1]] < 2 #[[2]] &]] Length[Select[Partition[p, 3, 1], #[[3]] + #[[1]] > 2 #[[2]] &]] p = Prime[Range[PrimePi[10^7] + 1]]; Length[Select[Partition[p, 3, 1], #[[3]] + #[[1]] < 2 #[[2]] &]] Length[Select[Partition[p, 3, 1], #[[3]] + #[[1]] > 2 #[[2]] &]]
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
#BQN
BQN
5↑3↓"Marshmallow" "shmal" 3↓"Marshmallow" "shmallow" ¯1↓"Marshmallow" "Marshmallo" (⊑∘/'m'⊸=)⊸↓"Marshmallow" "mallow" (⊑∘/"sh"⊸⍷)⊸↓"Marshmallow" "shmallow"
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
#Bracmat
Bracmat
( (basestring = "The five boxing wizards jump quickly") & (n = 10) & (m = 5)   { starting from n characters in and of m length: } & @(!basestring:? [(!n+-1) ?substring [(!n+!m+-1) ?) & out$!substring   { starting from n characters in, up to the end of the string: } & @(!basestring:? [(!n+-1) ?substring) & out$!substring   { whole string minus last character: } & @(!basestring:?substring [-2 ?) & out$!substring   { starting from a known character within the string and of m length: } & (char = "w") & @(!basestring:? ([?p !char ?: ?substring [(!p+!m) ?)) & out$!substring   { starting from a known substring within the string and of m length: } & (find = "iz") & @(!basestring:? ([?p !find ?: ?substring [(!p+!m) ?)) & out$!substring & )
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.
#Crystal
Crystal
GRID_SIZE = 9   def isNumberInRow(board, number, row) board[row].includes?(number) end def isNumberInColumn(board, number, column) board.any?{|row| row[column] == number } end def isNumberInBox(board, number, row, column) localBoxRow = row - row % 3 localBoxColumn = column - column % 3 (localBoxRow...(localBoxRow+3)).each do |i| (localBoxColumn...(localBoxColumn+3)).each do |j| return true if board[i][j] == number end end false end   def isValidPlacement(board, number, row, column) return !isNumberInRow(board, number, row) &&  !isNumberInColumn(board, number, column) &&  !isNumberInBox(board, number, row, column) end   def solveBoard(board) board.each_with_index do |row, i| row.each_with_index do |cell, j| if(cell == 0) (1..GRID_SIZE).each do |n| if(isValidPlacement(board,n,i,j)) board[i][j]=n if(solveBoard(board)) return true else board[i][j]=0 end end end return false end end end return true end   def printBoard(board) board.each_with_index do |row, i| row.each_with_index do |cell, j| print cell print '|' if j == 2 || j == 5 print '\n' if j == 8 end print "-"*11 + '\n' if i == 2 || i == 5 end print '\n' end   board = [ [7, 0, 2, 0, 5, 0, 6, 0, 0], [0, 0, 0, 0, 0, 3, 0, 0, 0], [1, 0, 0, 0, 0, 9, 5, 0, 0], [8, 0, 0, 0, 0, 0, 0, 9, 0], [0, 4, 3, 0, 0, 0, 7, 5, 0], [0, 9, 0, 0, 0, 0, 0, 0, 8], [0, 0, 9, 7, 0, 0, 0, 0, 5], [0, 0, 0, 2, 0, 0, 0, 0, 0], [0, 0, 7, 0, 4, 0, 2, 0, 3]]   printBoard(board) if(solveBoard(board)) printBoard(board) 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
#Common_Lisp
Common Lisp
(defun run (memory) (loop for pc = 0 then next-pc until (minusp pc) for a = (aref memory pc) for b = (aref memory (+ pc 1)) for c = (aref memory (+ pc 2)) for next-pc = (cond ((minusp a) (setf (aref memory b) (char-code (read-char))) (+ pc 3)) ((minusp b) (write-char (code-char (aref memory a))) (+ pc 3)) ((plusp (setf (aref memory b) (- (aref memory b) (aref memory a)))) (+ pc 3)) (t c))))   (defun main () (let ((memory (vector 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))) (run memory)))
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
#Lua
Lua
function findspds(primelist, diffs) local results = {} for i = 1, #primelist-#diffs do result = {primelist[i]} for j = 1, #diffs do if primelist[i+j] - primelist[i+j-1] == diffs[j] then result[j+1] = primelist[i+j] else result = nil break end end results[#results+1] = result end return results end   primegen:generate(nil, 1000000) for _,diffs in ipairs{{2}, {1}, {2,2}, {2,4}, {4,2}, {6,4,2}} do spdlist = findspds(primegen.primelist, diffs) print("DIFFS: ["..table.concat(diffs," ").."]") print("COUNT: "..#spdlist) print("FIRST: ["..table.concat(spdlist[1]," ").."]") print("LAST : ["..table.concat(spdlist[#spdlist]," ").."]") print() end
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
#D
D
import std.stdio;   void main() { // strip first character writeln("knight"[1 .. $]);   // strip last character writeln("socks"[0 .. $ - 1]);   // strip both first and last characters writeln("brooms"[1 .. $ - 1]); }
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
#Delphi
Delphi
program TopAndTail;   {$APPTYPE CONSOLE}   const TEST_STRING = '1234567890'; begin Writeln(TEST_STRING); // full string Writeln(Copy(TEST_STRING, 2, Length(TEST_STRING))); // first character removed Writeln(Copy(TEST_STRING, 1, Length(TEST_STRING) - 1)); // last character removed Writeln(Copy(TEST_STRING, 2, Length(TEST_STRING) - 2)); // first and last characters removed   Readln; end.
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.
#Lua
Lua
function SubGen(seed) local n, r, s = 54, {}, { [0]=seed, 1 } for n = 2,54 do s[n] = (s[n-2] - s[n-1]) % 1e9 end for n = 0,54 do r[n] = s[(34*(n+1))%55] end local next = function() n = (n+1) % 55 r[n] = (r[(n-55)%55] - r[(n-24)%55]) % 1e9 return r[n] end for n = 55,219 do next() end return next end subgen = SubGen(292929) for n = 220,229 do print(n,subgen()) end
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
#Sidef
Sidef
module SubstitutionCipher {   const key = %c"]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\"v*N[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ"   func encode(String s) { var r = "" s.each {|c| r += key[c.ord - 32] } return r }   func decode(String s) { var r = "" s.each {|c| r += (key.first_index { _ == c } + 32 -> chr) } return r } }     with ("The quick brown fox jumps over the lazy dog, who barks VERY loudly!") { |s| var enc = SubstitutionCipher::encode(s) var dec = SubstitutionCipher::decode(enc) say("Original: ", s, "\n -> Encoded: ", enc, "\n -> Decoded: ", dec) }
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
#Tcl
Tcl
oo::class create SubCipher { variable Alphabet variable Key variable EncMap variable DecMap constructor {{alphabet abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ} {cipherbet ""}} { set Alphabet $alphabet if {$cipherbet eq ""} { my key [my RandomKey] } else { my key $cipherbet } } method key args { if {$args eq ""} { return $Key } elseif {[llength $args] > 1} { throw {TCL WRONGARGS} "Expected \"[self class] key\" or \"[self class]\" key keystring" } lassign $args s   set size [string length $Alphabet] if {[string length $s] != $size} { return -code error "Key must be $size chars long!" } set encmap {} set decmap {} foreach c [split $Alphabet {}] e [split $s {}] { dict set encmap $c $e dict set decmap $e $c } if {[dict size $encmap] != $size} { return -code error "Alphabet has repeating characters!" } if {[dict size $decmap] != $size} { return -code error "Key has repeating characters!" } set Key $s set EncMap $encmap set DecMap $decmap } method RandomKey {} { set chars $Alphabet set key {} for {set n [string length $chars]} {$n > 0} {incr n -1} { set i [expr {int(rand()*$n)}] append key [string index $chars $i] set chars [string range $chars 0 $i-1][string range $chars $i+1 end] } return $key }   method enc {s} { string map $EncMap $s } method dec {s} { string map $DecMap $s } }
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.
#Fortran
Fortran
integer, dimension(10) :: a = (/ (i, i=1, 10) /) integer :: sresult, presult   sresult = sum(a) presult = product(a)
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.
#Emacs_Lisp
Emacs Lisp
(defun series (n) (when (<= n 0) (user-error "n must be positive")) (apply #'+ (mapcar (lambda (k) (/ 1.0 (* k k))) (number-sequence 1 n))))   (format "%.10f" (series 1000)) ;=> "1.6439345667"
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
#C.23
C#
  using System.Text.RegularExpressions;   string RemoveComments(string str, string delimiter) { //regular expression to find a character (delimiter) and // replace it and everything following it with an empty string. //.Trim() will remove all beginning and ending white space. return Regex.Replace(str, delimiter + ".+", string.Empty).Trim(); }  
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
#C.2B.2B
C++
#include <iostream> #include <string>   std::string strip_white(const std::string& input) { size_t b = input.find_first_not_of(' '); if (b == std::string::npos) b = 0; return input.substr(b, input.find_last_not_of(' ') + 1 - b); }   std::string strip_comments(const std::string& input, const std::string& delimiters) { return strip_white(input.substr(0, input.find_first_of(delimiters))); }   int main( ) { std::string input; std::string delimiters("#;"); while ( getline(std::cin, input) && !input.empty() ) { std::cout << strip_comments(input, delimiters) << std::endl ; } return 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
#F.23
F#
open System open System.Text.RegularExpressions   let balancedComments opening closing = new Regex( String.Format(""" {0} # An outer opening delimiter (?> # efficiency: no backtracking here {0} (?<LEVEL>) # An opening delimiter, one level down | {1} (?<-LEVEL>) # A closing delimiter, one level up | (?! {0} | {1} ) . # With negative lookahead: Anything but delimiters )* # As many times as we see these (?(LEVEL)(?!)) # Fail, unless on level 0 here {1} # Outer closing delimiter """, Regex.Escape(opening), Regex.Escape(closing)), RegexOptions.IgnorePatternWhitespace ||| RegexOptions.Singleline)   [<EntryPoint>] let main args = let sample = """ /** * Some comments * longer comments here that we can parse. * * Rahoo */ function subroutine() { a = /* inline comment */ b + c ; } /*/ <-- tricky comments */   /** * Another comment. * /* nested balanced */ */ function something() { } """ let balancedC = balancedComments "/*" "*/" printfn "%s" (balancedC.Replace(sample, "")) 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
#Factor
Factor
  : strip-block-comments ( string -- string ) R/ /\*.*?\*\// "" re-replace ;  
http://rosettacode.org/wiki/String_interpolation_(included)
String interpolation (included)
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 Given a string and defined variables or values, string interpolation is the replacement of defined character sequences in the string by values or variable values. For example, given an original string of "Mary had a X lamb.", a value of "big", and if the language replaces X in its interpolation routine, then the result of its interpolation would be the string "Mary had a big lamb". (Languages usually include an infrequently used character or sequence of characters to indicate what is to be replaced such as "%", or "#" rather than "X"). Task Use your languages inbuilt string interpolation abilities to interpolate a string missing the text "little" which is held in a variable, to produce the output string "Mary had a little lamb". If possible, give links to further documentation on your languages string interpolation features. Note: The task is not to create a string interpolation routine, but to show a language's built-in capability. 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
V extra = ‘little’ print(‘Mary had a ’extra‘ lamb.’) print(‘Mary had a #. lamb.’.format(extra)) print(f:‘Mary had a {extra} lamb.’)
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).
#Picat
Picat
main => L = "23456789", gen(L,Str), Exp = parse_term(['1'|Str]), Exp =:= 100, println(['1'|Str]).   gen(L@[_],Str) => Str = L. gen([D|Ds],Str) ?=> Str = [D|StrR], gen(Ds,StrR).  % no operator gen([D|Ds],Str) ?=> Str = ['+',D|StrR], gen(Ds,StrR). % insert + gen([D|Ds],Str) => Str = ['-',D|StrR], gen(Ds,StrR).  % insert -  
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
#Asymptote
Asymptote
string text = "She was a soul stripper. She took my heart!"; string[][] remove = {{"a",""},{"e",""},{"i",""}};   for(var i : remove) text = replace(text, remove); } write(text);
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
#AutoHotkey
AutoHotkey
MsgBox % stripchars("She was a soul stripper. She took my heart!","aei")   StripChars(string, charsToStrip){ Loop Parse, charsToStrip StringReplace, string, string, % A_LoopField, , All return 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.
#Clojure
Clojure
  (defn str-prepend [a-string, to-prepend] (str to-prepend a-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.
#COBOL
COBOL
identification division. program-id. prepend. data division. working-storage section. 1 str pic x(30) value "World!". 1 binary. 2 len pic 9(4) value 0. 2 scratch pic 9(4) value 0. procedure division. begin. perform rev-sub-str move function reverse ("Hello ") to str (len + 1:) perform rev-sub-str display str stop run .   rev-sub-str. move 0 to len scratch inspect function reverse (str) tallying scratch for leading spaces len for characters after space move function reverse (str (1:len)) to str . end program prepend.
http://rosettacode.org/wiki/String_comparison
String comparison
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 Demonstrate how to compare two strings from within the language and how to achieve a lexical comparison. The task should demonstrate: Comparing two strings for exact equality Comparing two strings for inequality (i.e., the inverse of exact equality) Comparing two strings to see if one is lexically ordered before than the other Comparing two strings to see if one is lexically ordered after than the other How to achieve both case sensitive comparisons and case insensitive comparisons within the language How the language handles comparison of numeric strings if these are not treated lexically Demonstrate any other kinds of string comparisons that the language provides, particularly as it relates to your type system. For example, you might demonstrate the difference between generic/polymorphic comparison and coercive/allomorphic comparison if your language supports such a distinction. Here "generic/polymorphic" comparison means that the function or operator you're using doesn't always do string comparison, but bends the actual semantics of the comparison depending on the types one or both arguments; with such an operator, you achieve string comparison only if the arguments are sufficiently string-like in type or appearance. In contrast, a "coercive/allomorphic" comparison function or operator has fixed string-comparison semantics regardless of the argument type;   instead of the operator bending, it's the arguments that are forced to bend instead and behave like strings if they can,   and the operator simply fails if the arguments cannot be viewed somehow as strings.   A language may have one or both of these kinds of operators;   see the Raku entry for an example of a language with both kinds of operators. 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, Ada.Strings.Equal_Case_Insensitive;   procedure String_Compare is   procedure Print_Comparison (A, B : String) is begin Ada.Text_IO.Put_Line ("""" & A & """ and """ & B & """: " & (if A = B then "equal, " elsif Ada.Strings.Equal_Case_Insensitive (A, B) then "case-insensitive-equal, " else "not equal at all, ") & (if A /= B then "/=, " else "") & (if A < B then "before, " else "") & (if A > B then "after, " else "") & (if A <= B then "<=, " else "(not <=), ") & (if A >= B then ">=. " else "(not >=).")); end Print_Comparison; begin Print_Comparison ("this", "that"); Print_Comparison ("that", "this"); Print_Comparison ("THAT", "That"); Print_Comparison ("this", "This"); Print_Comparison ("this", "this"); Print_Comparison ("the", "there"); Print_Comparison ("there", "the"); end String_Compare;
http://rosettacode.org/wiki/String_case
String case
Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is not reversable. Show any additional case conversion functions   (e.g. swapping case, capitalizing the first letter, etc.)   that may be included in the library of your language. 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
#6502_Assembly
6502 Assembly
.lf case6502.lst .cr 6502 .tf case6502.obj,ap1 ;------------------------------------------------------ ; String Case for the 6502 by barrym95838 2013.04.07 ; Thanks to sbprojects.com for a very nice assembler! ; The target for this assembly is an Apple II with ; mixed-case output capabilities. Apple IIs like to ; work in '+128' ascii, so this version leaves bit 7 ; alone, and can be used with either flavor. ; 6502s work best with data structures < 256 bytes; ; several instructions would have to be added to ; properly deal with longer strings. ; Tested and verified on AppleWin 1.20.0.0 ;------------------------------------------------------ ; Constant Section ; StrPtr = $6 ;0-page temp pointer (2 bytes) Low = $8 ;0-page temp low bound High = $9 ;0-page temp high bound CharOut = $fded ;Specific to the Apple II BigA = "A" ;'A' for normal ascii BigZ = "Z" ;'Z' " " " LittleA = "a" ;'a' " " " LittleZ = "z" ;'z' " " " ;====================================================== .or $0f00 ;------------------------------------------------------ ; The main program ; main ldx #sTest ;Point to the test string lda /sTest jsr puts ;print it to stdout jsr toUpper ;convert to UPPER-case jsr puts ;print it jsr toLower ;convert to lower-case jmp puts ;print it and return to caller ;------------------------------------------------------ toUpper ldy #LittleA sty Low ;set up the flip range ldy #LittleZ bne toLow2 ;return via toLower's tail ;------------------------------------------------------ toLower ldy #BigA sty Low ;set up the flip range ldy #BigZ toLow2 sty High ; ;return via fall-thru to flip ;------------------------------------------------------ ; Given a NUL-terminated string at A:X, flip the case ; of any chars in the range [Low..High], inclusive; ; only works on the first 256 bytes of a long string ; Uses: StrPtr, Low, High ; Preserves: A, X ; Trashes: Y ; flip stx StrPtr ;init string pointer sta StrPtr+1 ldy #0 pha ;save A flip2 lda (StrPtr),y ;get string char beq flip5 ;done if NUL cmp Low bcc flip4 ;if Low <= char <= High cmp High beq flip3 bcs flip4 flip3 eor #$20 ; then flip the case sta (StrPtr),y flip4 iny ;point to next char bne flip2 ;loop up to 255 times flip5 pla ;restore A rts ;return ;------------------------------------------------------ ; Output NUL-terminated string @ A:X; strings longer ; than 256 bytes are truncated there ; Uses: StrPtr ; Preserves: A, X ; Trashes: Y ; puts stx StrPtr ;init string pointer sta StrPtr+1 ldy #0 pha ;save A puts2 lda (StrPtr),y ;get string char beq puts3 ;done if NUL jsr CharOut ;output the char iny ;point to next char bne puts2 ;loop up to 255 times puts3 pla ;restore A rts ;return ;------------------------------------------------------ ; Test String (in '+128' ascii, Apple II style) ; sTest .as -"Alpha, BETA, gamma, {[(<123@_>)]}." .az -#13 ;------------------------------------------------------ .en
http://rosettacode.org/wiki/String_matching
String matching
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 Given two strings, demonstrate the following three types of string matching:   Determining if the first string starts with second string   Determining if the first string contains the second string at any location   Determining if the first string ends with the second string Optional requirements:   Print the location of the match for part 2   Handle multiple occurrences of a string for part 2. 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
# define some appropriate OPerators # PRIO STARTSWITH = 5, ENDSWITH = 5; OP STARTSWITH = (STRING str, prefix)BOOL: # assuming LWB = 1 # IF UPB str < UPB prefix THEN FALSE ELSE str[:UPB prefix]=prefix FI; OP ENDSWITH = (STRING str, suffix)BOOL: # assuming LWB = 1 # IF UPB str < UPB suffix THEN FALSE ELSE str[UPB str-UPB suffix+1:]=suffix FI;   INT loc, loc2;   print(( "abcd" STARTSWITH "ab", # returns TRUE # "abcd" ENDSWITH "zn", # returns FALSE # string in string("bb",loc,"abab"), # returns FALSE # string in string("ab",loc,"abab"), # returns TRUE # (string in string("bb",loc,"abab")|loc|-1), # returns -1 # (string in string("ab",loc,"abab")|loc|-1), # returns +1 # (string in string("ab",loc2,"abab"[loc+1:])|loc+loc2|-1) # returns +3 # ))
http://rosettacode.org/wiki/String_length
String length
Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme containing combining characters. For example, the character length of "møøse" is 5 but the byte length is 7 in UTF-8 and 10 in UTF-16. Non-BMP code points (those between 0x10000 and 0x10FFFF) must also be handled correctly: answers should produce actual character counts in code points, not in code unit counts. Therefore a string like "𝔘𝔫𝔦𝔠𝔬𝔡𝔢" (consisting of the 7 Unicode characters U+1D518 U+1D52B U+1D526 U+1D520 U+1D52C U+1D521 U+1D522) is 7 characters long, not 14 UTF-16 code units; and it is 28 bytes long whether encoded in UTF-8 or in UTF-16. Please mark your examples with ===Character Length=== or ===Byte Length===. If your language is capable of providing the string length in graphemes, mark those examples with ===Grapheme Length===. For example, the string "J̲o̲s̲é̲" ("J\x{332}o\x{332}s\x{332}e\x{301}\x{332}") has 4 user-visible graphemes, 9 characters (code points), and 14 bytes when encoded in UTF-8. 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
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program stringLength64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64.inc"   /*********************************/ /* Initialized data */ /*********************************/ .data sMessResultByte: .asciz "===Byte Length=== : @ \n" sMessResultChar: .asciz "===Character Length=== : @ \n" szString1: .asciz "møøse€" szCarriageReturn: .asciz "\n"   /*********************************/ /* UnInitialized data */ /*********************************/ .bss sZoneConv: .skip 24 /*********************************/ /* code section */ /*********************************/ .text .global main main: // entry of program ldr x0,qAdrszString1 bl affichageMess // display string ldr x0,qAdrszCarriageReturn bl affichageMess   ldr x0,qAdrszString1 mov x1,#0 1: // loop compute length bytes ldrb w2,[x0,x1] cmp w2,#0 cinc x1,x1,ne bne 1b   mov x0,x1 // result display ldr x1,qAdrsZoneConv bl conversion10 // call decimal conversion ldr x0,qAdrsMessResultByte ldr x1,qAdrsZoneConv // insert conversion in message bl strInsertAtCharInc bl affichageMess   ldr x0,qAdrszString1 mov x1,#0 mov x3,#0 2: // loop compute length characters ldrb w2,[x0,x1] cmp w2,#0 beq 6f and x2,x2,#0b11100000 // 3 bytes ? cmp x2,#0b11100000 bne 3f add x3,x3,#1 add x1,x1,#3 b 2b 3: and x2,x2,#0b11000000 // 2 bytes ? cmp x2,#0b11000000 bne 4f add x3,x3,#1 add x1,x1,#2 b 2b 4: // else 1 byte add x3,x3,#1 add x1,x1,#1 b 2b   6: mov x0,x3 ldr x1,qAdrsZoneConv bl conversion10 // call decimal conversion ldr x0,qAdrsMessResultChar ldr x1,qAdrsZoneConv // insert conversion in message bl strInsertAtCharInc bl affichageMess 100: // standard end of the program mov x0,0 // return code mov x8,EXIT // request to exit program svc 0 // perform the system call   qAdrszCarriageReturn: .quad szCarriageReturn qAdrsMessResultByte: .quad sMessResultByte qAdrsMessResultChar: .quad sMessResultChar qAdrszString1: .quad szString1 qAdrsZoneConv: .quad sZoneConv /********************************************************/ /* File Include fonctions */ /********************************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeARM64.inc"  
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
#C.2B.2B
C++
#include <string> #include <iostream> #include <algorithm> #include <boost/lambda/lambda.hpp> #include <boost/lambda/casts.hpp> #include <ctime> #include <cstdlib> using namespace boost::lambda ;   struct MyRandomizer { char operator( )( ) { return static_cast<char>( rand( ) % 256 ) ; } } ;   std::string deleteControls ( std::string startstring ) { std::string noControls( " " ) ;//creating space for //the standard algorithm remove_copy_if std::remove_copy_if( startstring.begin( ) , startstring.end( ) , noControls.begin( ) , ll_static_cast<int>( _1 ) < 32 && ll_static_cast<int>( _1 ) == 127 ) ; return noControls ; }   std::string deleteExtended( std::string startstring ) { std::string noExtended ( " " ) ;//same as above std::remove_copy_if( startstring.begin( ) , startstring.end( ) , noExtended.begin( ) , ll_static_cast<int>( _1 ) > 127 || ll_static_cast<int>( _1 ) < 32 ) ; return noExtended ; }   int main( ) { std::string my_extended_string ; for ( int i = 0 ; i < 40 ; i++ ) //we want the extended string to be 40 characters long my_extended_string.append( " " ) ; srand( time( 0 ) ) ; std::generate_n( my_extended_string.begin( ) , 40 , MyRandomizer( ) ) ; std::string no_controls( deleteControls( my_extended_string ) ) ; std::string no_extended ( deleteExtended( my_extended_string ) ) ; std::cout << "string with all characters: " << my_extended_string << std::endl ; std::cout << "string without control characters: " << no_controls << std::endl ; std::cout << "string without extended characters: " << no_extended << std::endl ; return 0 ; }
http://rosettacode.org/wiki/String_concatenation
String concatenation
String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string literal. To illustrate the operation, show the content of the variables. 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
STRING s := "hello"; print ((s + " literal", new line)); STRING s1 := s + " literal"; print ((s1, new line))
http://rosettacode.org/wiki/String_concatenation
String concatenation
String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string literal. To illustrate the operation, show the content of the variables. 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-M
ALGOL-M
  begin   comment The string concatenation operator is ||, and the default string length is 10 characters unless a longer length (up to 255) is explicitly declared;   string(20) s1, s2;   s1 := "Hello"; write (s1 || ", world");   s2 := s1 || ", world"; write (s2);   end  
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.
#Go
Go
package main   import "fmt"   func main() { fmt.Println(s35(1000)) }   func s35(n int) int { n-- threes := n / 3 fives := n / 5 fifteen := n / 15   threes = 3 * threes * (threes + 1) fives = 5 * fives * (fives + 1) fifteen = 15 * fifteen * (fifteen + 1)   n = (threes + fives - fifteen) / 2   return n }
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
#Go
Go
// File digit.go   package digit   import ( "math/big" "strconv" )   func SumString(n string, base int) (int, error) { i, ok := new(big.Int).SetString(n, base) if !ok { return 0, strconv.ErrSyntax } if i.Sign() < 0 { return 0, strconv.ErrRange } if i.BitLen() <= 64 { return Sum(i.Uint64(), base), nil } return SumBig(i, base), nil }   func Sum(i uint64, base int) (sum int) { b64 := uint64(base) for ; i > 0; i /= b64 { sum += int(i % b64) } return }   func SumBig(n *big.Int, base int) (sum int) { i := new(big.Int).Set(n) b := new(big.Int).SetUint64(uint64(base)) r := new(big.Int) for i.BitLen() > 0 { i.DivMod(i, b, r) sum += int(r.Uint64()) } return }
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
#J
J
ss=: +/ @: *:
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
#Java
Java
public class SumSquares { public static void main(final String[] args) { double sum = 0; int[] nums = {1,2,3,4,5}; for (int i : nums) sum += i * i; System.out.println("The sum of the squares is: " + sum); } }
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
#Clojure
Clojure
  (use 'clojure.string) (triml " my string ") => "my string " (trimr " my string ") => " my string" (trim " \t\r\n my string \t\r\n ") => "my string"  
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
#COBOL
COBOL
DISPLAY "'" FUNCTION TRIM(str, LEADING) "'" DISPLAY "'" FUNCTION TRIM(str, TRAILING) "'" DISPLAY "'" FUNCTION 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.
#Nim
Nim
import math, strutils   const M = 10_000_000 N = M + 19 # Maximum value for sieve.   # Fill sieve of Erathosthenes. var comp: array[2..N, bool] # True means composite; default is prime. for n in countup(3, sqrt(N.toFloat).int, 2): if not comp[n]: for k in countup(n * n, N, 2 * n): comp[k] = true   # Build list of primes. var primes = @[2] for n in countup(3, N, 2): if not comp[n]: primes.add n if primes[^1] < M: quit "Not enough primes: please, increase value of N."   # Build lists of strong and weak primes. var strongPrimes, weakPrimes: seq[int] for i in 1..<primes.high: let p = primes[i] if p shl 1 > primes[i - 1] + primes[i + 1]: strongPrimes.add p elif p shl 1 < primes[i - 1] + primes[i + 1]: weakPrimes.add p     when isMainModule:   proc count(list: seq[int]; max: int): int = ## Return the count of values less than "max". for p in list: if p >= max: break inc result   echo "First 36 strong primes:" echo " ", strongPrimes[0..35].join(" ") echo "Count of strong primes below 1_000_000: ", strongPrimes.count(1_000_000) echo "Count of strong primes below 10_000_000: ", strongPrimes.count(10_000_000) echo()   echo "First 37 weak primes:" echo " ", weakPrimes[0..36].join(" ") echo "Count of weak primes below 1_000_000: ", weakPrimes.count(1_000_000) echo "Count of weak primes below 10_000_000: ", weakPrimes.count(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.
#Pascal
Pascal
program WeakPrim; {$IFNDEF FPC} {$AppType CONSOLE} {$ENDIF} const PrimeLimit = 1000*1000*1000;//must be >= 2*3; type tLimit = 0..(PrimeLimit-1) DIV 2; tPrimCnt = 0..51*1000*1000; tWeakStrong = record strong, balanced, weak : NativeUint; end; var primes: array [tLimit] of byte; //always initialized with 0 at startup delta : array [tPrimCnt] of byte; cntWS : tWeakStrong; deltaCnt :NativeUint;   procedure sieveprimes; //Only odd numbers, minimal count of strikes var spIdx,sieveprime,sievePos,fact :NativeUInt; begin spIdx := 1; repeat if primes[spIdx]=0 then begin sieveprime := 2*spIdx+1; fact := PrimeLimit DIV sieveprime; if Not(odd(fact)) then dec(fact); IF fact < sieveprime then BREAK; sievePos := ((fact*sieveprime)-1) DIV 2; fact := (fact-1) DIV 2; repeat primes[sievePos] := 1; repeat dec(fact); dec(sievePos,sieveprime); until primes[fact]= 0; until fact < spIdx; end; inc(spIdx); until false; end; { Not neccessary for this small primes. procedure EmergencyStop(i:NativeInt); Begin Writeln( 'STOP at ',i,'.th prime'); HALT(i); end; } function GetDeltas:NativeUint; //Converting prime positions into distance var i,j,last : NativeInt; Begin j :=0; i := 1; last :=1; For i := 1 to High(primes) do if primes[i] = 0 then Begin //IF i-last > 255 {aka delta prim > 512} then EmergencyStop (j); delta[j] := i-last; last := i; inc(j); end; GetDeltas := j; end;   procedure OutHeader; Begin writeln('Limit':12,'Strong':10,'balanced':12,'weak':10); end;   procedure OutcntWS (const cntWS : tWeakStrong;Lmt:NativeInt); Begin with cntWS do writeln(lmt:12,Strong:10,balanced:12,weak:10); end;   procedure CntWeakStrong10(var Out:tWeakStrong); // Output a table of values for strang/balanced/weak for 10^n var idx,diff,prime,lmt :NativeInt; begin OutHeader; lmt := 10; fillchar(Out,SizeOf(Out),#0); idx := 0; prime:=3; repeat dec(prime,2*delta[idx]); while idx < deltaCnt do Begin inc(prime,2*delta[idx]); IF prime > lmt then BREAK;   diff := delta[idx] - delta[idx+1]; if diff>0 then inc(Out.strong) else if diff< 0 then inc(Out.weak) else inc(Out.balanced);   inc(idx); end; OutcntWS(Out,Lmt); lmt := lmt*10; until Lmt > PrimeLimit; end;   procedure WeakOut(cnt:NativeInt); var idx,prime : NativeInt; begin Writeln('The first ',cnt,' weak primes'); prime:=3; idx := 0; repeat inc(prime,2*delta[idx]); if delta[idx] - delta[idx+1]< 0 then Begin write(prime,' '); dec(cnt); IF cnt <=0 then BREAK; end; inc(idx); until idx >= deltaCnt; Writeln; end;   procedure StrongOut(cnt:NativeInt); var idx,prime : NativeInt; begin Writeln('The first ',cnt,' strong primes'); prime:=3; idx := 0; repeat inc(prime,2*delta[idx]); if delta[idx] - delta[idx+1]> 0 then Begin write(prime,' '); dec(cnt); IF cnt <=0 then BREAK; end; inc(idx); until idx >= deltaCnt; Writeln; end;   begin sieveprimes; deltaCnt := GetDeltas;   StrongOut(36); WeakOut(37); CntWeakStrong10(CntWs); end.
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
#Burlesque
Burlesque
  blsq ) "RosettaCode"5.+ "Roset" blsq ) "RosettaCode"5.+2.- "set" blsq ) "RosettaCode""set"ss 2 blsq ) "RosettaCode"J"set"ss.- "settaCode" blsq ) "RosettaCode"~] "RosettaCod" blsq ) "RosettaCode"[- "osettaCode"  
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
#C
C
/* * RosettaCode: Substring, C89 * * In this 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 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. * * This example program DOES NOT make substrings. The program simply displays * certain parts of the input string. * */ #define _CRT_SECURE_NO_WARNINGS /* MSVS compilers need this */ #include <stdio.h> #include <stdlib.h> #include <string.h>   /* * Put no more than m characters from string to standard output. * * It is worth noting that printf("%*s",width,string) does not limit the number * of characters to be printed. * * @param string null terminated string * @param m number of characters to display */ void putm(char* string, size_t m) { while(*string && m--) putchar(*string++); }   int main(void) {   char string[] = "Programs for other encodings (such as 8-bit ASCII, or EUC-JP)."   int n = 3; int m = 4; char knownCharacter = '('; char knownSubstring[] = "encodings";   putm(string+n-1, m ); putchar('\n'); puts(string+n+1); putchar('\n'); putm(string, strlen(string)-1); putchar('\n'); putm(strchr(string, knownCharacter), m ); putchar('\n'); putm(strstr(string, knownSubstring), m ); putchar('\n');   return EXIT_SUCCESS; }
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.
#Curry
Curry
----------------------------------------------------------------------------- --- Solving Su Doku puzzles in Curry with FD constraints --- --- @author Michael Hanus --- @version December 2005 -----------------------------------------------------------------------------   import CLPFD import List   -- Solving a Su Doku puzzle represented as a matrix of numbers (possibly free -- variables): sudoku :: [[Int]] -> Success sudoku m = domain (concat m) 1 9 & -- define domain of all digits foldr1 (&) (map allDifferent m) & -- all rows contain different digits foldr1 (&) (map allDifferent (transpose m)) & -- all columns have different digits foldr1 (&) (map allDifferent (squaresOfNine m)) & -- all 3x3 squares are different labeling [FirstFailConstrained] (concat m)   -- translate a matrix into a list of small 3x3 squares squaresOfNine :: [[a]] -> [[a]] squaresOfNine [] = [] squaresOfNine (l1:l2:l3:ls) = group3Rows [l1,l2,l3] ++ squaresOfNine ls   group3Rows l123 = if null (head l123) then [] else concatMap (take 3) l123 : group3Rows (map (drop 3) l123)   -- read a Su Doku specification written as a list of strings containing digits -- and spaces readSudoku :: [String] -> [[Int]] readSudoku s = map (map transDigit) s where transDigit c = if c==' ' then x else ord c - ord '0' where x free   -- show a solved Su Doku matrix showSudoku :: [[Int]] -> String showSudoku = unlines . map (concatMap (\i->[chr (i + ord '0'),' ']))   -- the main function, e.g., evaluate (main s1): main s | sudoku m = putStrLn (showSudoku m) where m = readSudoku s   s1 = ["9 2 5 ", " 4 6 3 ", " 3 6", " 9 2 ", " 5 8 ", " 7 4 3", "7 1 ", " 5 2 4 ", " 1 6 9"]   s2 = ["819 5 ", " 2 75 ", " 371 4 6 ", "4 59 1 ", "7 3 8 2", " 3 62 7", " 5 7 921 ", " 64 9 ", " 2 438"]
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
#D
D
import std.stdio;   void main() { int[] mem = [ 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 ];   int instructionPointer = 0;   do { int a = mem[instructionPointer]; int b = mem[instructionPointer + 1];   if (a == -1) { int input; readf!" %d"(input); mem[b] = input; } else if (b == -1) { write(cast(char) mem[a]); } else { mem[b] -= mem[a]; if (mem[b] < 1) { instructionPointer = mem[instructionPointer + 2]; continue; } }   instructionPointer += 3; } while (instructionPointer >= 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
#Kotlin
Kotlin
private fun sieve(limit: Int): Array<Int> { val primes = mutableListOf<Int>() primes.add(2) val c = BooleanArray(limit + 1) // composite = true // no need to process even numbers > 2 var p = 3 while (true) { val p2 = p * p if (p2 > limit) { break } var i = p2 while (i <= limit) { c[i] = true i += 2 * p } do { p += 2 } while (c[p]) } var i = 3 while (i <= limit) { if (!c[i]) { primes.add(i) } i += 2 } return primes.toTypedArray() }   private fun successivePrimes(primes: Array<Int>, diffs: Array<Int>): List<List<Int>> { val results = mutableListOf<List<Int>>() val dl = diffs.size outer@ for (i in 0 until primes.size - dl) { val group = IntArray(dl + 1) group[0] = primes[i] for (j in i until i + dl) { if (primes[j + 1] - primes[j] != diffs[j - i]) { continue@outer } group[j - i + 1] = primes[j + 1] } results.add(group.toList()) } return results }   fun main() { val primes = sieve(999999) val diffsList = arrayOf( arrayOf(2), arrayOf(1), arrayOf(2, 2), arrayOf(2, 4), arrayOf(4, 2), arrayOf(6, 4, 2) ) println("For primes less than 1,000,000:-\n") for (diffs in diffsList) { println(" For differences of ${diffs.contentToString()} ->") val sp = successivePrimes(primes, diffs) if (sp.isEmpty()) { println(" No groups found") continue } println(" First group = ${sp[0].toTypedArray().contentToString()}") println(" Last group = ${sp[sp.size - 1].toTypedArray().contentToString()}") println(" Number found = ${sp.size}") 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
#Eero
Eero
#import <Foundation/Foundation.h>   int main() autoreleasepool   s := 'knight' Log( '%@', s[1 .. s.length-1] ) // strip first character   s = 'socks' Log( '%@', s[0 .. s.length-2] ) // strip last character   s = 'brooms' Log( '%@', s[1 .. s.length-2] ) // strip both first and last characters   s = 'Δημοτική' Log( '%@', s[1 .. s.length-2] ) // strip both first and last characters   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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
initialize[n_] := Module[{buffer}, buffer = Join[Nest[Flatten@{#, Mod[Subtract @@ #[[-2 ;;]], 10^9]} &, {n, 1}, 53][[1 + Mod[34 Range@54, 55]]], {n}]; Nest[nextValue, buffer, 165]]   nextValue[buffer_] := Flatten@{Rest@buffer, Mod[Subtract @@ buffer[[{1, 32}]], 10^9]}