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/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.
| #Haskell | Haskell | subtractgen :: Int -> [Int]
subtractgen seed = drop 220 out
where
out = mmod $ r <> zipWith (-) out (drop 31 out)
where
r = take 55 $ shuffle $ cycle $ take 55 s
shuffle x = (:) . head <*> shuffle $ drop 34 x
s = mmod $ seed : 1 : zipWith (-) s (tail s)
mmod = fmap (`mod` 10 ^ 9)
main :: IO ()
main = mapM_ print $ take 10 $ subtractgen 292929 |
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
| #Python | Python |
from string import printable
import random
EXAMPLE_KEY = ''.join(sorted(printable, key=lambda _:random.random()))
def encode(plaintext, key):
return ''.join(key[printable.index(char)] for char in plaintext)
def decode(plaintext, key):
return ''.join(printable[key.index(char)] for char in plaintext)
original = "A simple example."
encoded = encode(original, EXAMPLE_KEY)
decoded = decode(encoded, EXAMPLE_KEY)
print("""The original is: {}
Encoding it with the key: {}
Gives: {}
Decoding it by the same key gives: {}""".format(
original, EXAMPLE_KEY, encoded, decoded)) |
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.
| #Erlang | Erlang | % create the list:
L = lists:seq(1, 10).
% and compute its sum:
S = lists:sum(L).
P = lists:foldl(fun (X, P) -> X * P end, 1, L). |
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.
| #EchoLisp | EchoLisp |
(lib 'math) ;; for (sigma f(n) nfrom nto) function
(Σ (λ(n) (// (* n n))) 1 1000)
;; or
(sigma (lambda(n) (// (* n n))) 1 1000)
→ 1.6439345666815615
(// (* PI PI) 6)
→ 1.6449340668482264
|
http://rosettacode.org/wiki/Strip_comments_from_a_string | Strip comments from a string | Strip comments from a string
You are encouraged to solve this task according to the task description, using any language you may know.
The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line.
Whitespace debacle: There is some confusion about whether to remove any whitespace from the input line.
As of 2 September 2011, at least 8 languages (C, C++, Java, Perl, Python, Ruby, sed, UNIX Shell) were incorrect, out of 36 total languages, because they did not trim whitespace by 29 March 2011 rules. Some other languages might be incorrect for the same reason.
Please discuss this issue at Talk:Strip comments from a string.
From 29 March 2011, this task required that: "The comment marker and any whitespace at the beginning or ends of the resultant line should be removed. A line without comments should be trimmed of any leading or trailing whitespace before being produced as a result." The task had 28 languages, which did not all meet this new requirement.
From 28 March 2011, this task required that: "Whitespace before the comment marker should be removed."
From 30 October 2010, this task did not specify whether or not to remove whitespace.
The following examples will be truncated to either "apples, pears " or "apples, pears".
(This example has flipped between "apples, pears " and "apples, pears" in the past.)
apples, pears # and bananas
apples, pears ; and bananas
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #ALGOL_W | ALGOL W | begin
% determines the non-comment portion of the string s, startPos and endPos are %
% returned set to the beginning and ending character positions (indexed from 0) %
% of the non-comment text in s. If there is no non-comment text in s, startPos %
% will be greater than endPos %
% note that in Algol W, strings can be at most 256 characters long %
procedure stripComments ( string(256) value s; integer result startPos, endPos ) ;
begin
integer MAX_LENGTH;
MAX_LENGTH := 256;
startPos := 0;
endPos := -1;
% find the first non-blank character in s %
while startPos < MAX_LENGTH and s( startPos // 1 ) = " " do startPos := startPos + 1;
if startPos < MAX_LENGTH then begin
% have a non-blank character in the string %
if s( startPos // 1 ) not = "#" and s( startPos // 1 ) not = ";" then begin
% the non-blank character is not a comment delimiter %
integer cPos;
cPos := endPos := startPos;
while cPos < MAX_LENGTH and s( cPos // 1 ) not = "#" and s( cPos // 1 ) not = ";" do begin
if s( cPos // 1 ) not = " " then endPos := cPos;
cPos := cPos + 1
end while_not_a_comment
end if_not_a_comment
end if_startPos_lt_MAX_LENGTH
end stripComments ;
% tests the stripComments procedure %
procedure testStripComments( string(256) value s ) ;
begin
integer startPos, endPos;
stripComments( s, startPos, endPos );
write( """" );
for cPos := startPos until endPos do writeon( s( cPos // 1 ) );
writeon( """" )
end testStripComments ;
begin % test cases - should all print "apples, pears" %
testStripComments( "apples, pears # and bananas" );
testStripComments( "apples, pears ; and bananas" );
testStripComments( "apples, pears " );
testStripComments( " apples, pears" )
end
end. |
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
| #Applesoft_BASIC | Applesoft BASIC | 10 LET C$ = ";#"
20 S$(1)="APPLES, PEARS # AND BANANAS"
30 S$(2)="APPLES, PEARS ; AND BANANAS"
40 FOR Q = 1 TO 2
50 LET S$ = S$(Q)
60 GOSUB 100"STRIP COMMENTS
70 PRINT S$
80 NEXT Q
90 END
100 IF S$ = "" THEN RETURN
110 FOR I = 1 TO LEN(S$)
120 LET A$ = MID$(S$, I, 1)
130 FOR J = 1 TO LEN(C$)
140 LET F$ = MID$(C$, J, 1)
150 IF A$ <> F$ THEN NEXT J
160 IF A$ = F$ THEN 200
170 NEXT I
200 LET I = I - 1
210 GOSUB 260"STRIP
220 IF S$ = "" THEN RETURN
230 FOR I = I TO 0 STEP -1
240 LET A$ = MID$(S$, I, 1)
250 IF A$ = " " THEN NEXT I
260 LET S$ = MID$(S$, 1, I)
270 RETURN |
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
| #C | C | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
const char *ca = "/*", *cb = "*/";
int al = 2, bl = 2;
char *loadfile(const char *fn) {
FILE *f = fopen(fn, "rb");
int l;
char *s;
if (f != NULL) {
fseek(f, 0, SEEK_END);
l = ftell(f);
s = malloc(l+1);
rewind(f);
if (s)
fread(s, 1, l, f);
fclose(f);
}
return s;
}
void stripcomments(char *s) {
char *a, *b;
int len = strlen(s) + 1;
while ((a = strstr(s, ca)) != NULL) {
b = strstr(a+al, cb);
if (b == NULL)
break;
b += bl;
memmove(a, b, len-(b-a));
}
}
int main(int argc, char **argv) {
const char *fn = "input.txt";
char *s;
if (argc >= 2)
fn = argv[1];
s = loadfile(fn);
if (argc == 4) {
al = strlen(ca = argv[2]);
bl = strlen(cb = argv[3]);
}
stripcomments(s);
puts(s);
free(s);
return 0;
} |
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).
| #Modula-2 | Modula-2 | MODULE SumTo100;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
PROCEDURE Evaluate(code : INTEGER) : INTEGER;
VAR
value,number,power,k : INTEGER;
BEGIN
value := 0;
number := 0;
power := 1;
FOR k:=9 TO 1 BY -1 DO
number := power * k + number;
IF code MOD 3 = 0 THEN
(* ADD *)
value := value + number;
number := 0;
power := 1
ELSIF code MOD 3 = 1 THEN
(* SUB *)
value := value - number;
number := 0;
power := 1
ELSE
(* CAT *)
power := power * 10
END;
code := code / 3
END;
RETURN value
END Evaluate;
PROCEDURE Print(code : INTEGER);
VAR
expr,buf : ARRAY[0..63] OF CHAR;
a,b,k,p : INTEGER;
BEGIN
a := 19683;
b := 6561;
p := 0;
FOR k:=1 TO 9 DO
IF (code MOD a) / b = 0 THEN
IF k > 1 THEN
expr[p] := '+';
INC(p)
END
ELSIF (code MOD a) / b = 1 THEN
expr[p] := '-';
INC(p)
END;
a := b;
b := b / 3;
expr[p] := CHR(k + 30H);
INC(p)
END;
expr[p] := 0C;
FormatString("%9i = %s\n", buf, Evaluate(code), expr);
WriteString(buf)
END Print;
(* Main *)
CONST nexpr = 13122;
VAR
i,j : INTEGER;
best,nbest,test,ntest,limit : INTEGER;
buf : ARRAY[0..63] OF CHAR;
BEGIN
WriteString("Show all solution that sum to 100");
WriteLn;
FOR i:=0 TO nexpr-1 DO
IF Evaluate(i) = 100 THEN
Print(i)
END
END;
WriteLn;
WriteString("Show the sum that has the maximum number of solutions");
WriteLn;
nbest := -1;
FOR i:=0 TO nexpr-1 DO
test := Evaluate(i);
IF test > 0 THEN
ntest := 0;
FOR j:=0 TO nexpr-1 DO
IF Evaluate(j) = test THEN
INC(ntest)
END;
IF ntest > nbest THEN
best := test;
nbest := ntest
END
END
END
END;
FormatString("%i has %i solutions\n\n", buf, best, nbest);
WriteString(buf);
WriteString("Show the lowest positive number that can't be expressed");
WriteLn;
FOR i:=0 TO 123456789 DO
FOR j:=0 TO nexpr-1 DO
IF i = Evaluate(j) THEN
BREAK
END
END;
IF i # Evaluate(j) THEN
BREAK
END
END;
FormatString("%i\n\n", buf, i);
WriteString(buf);
WriteString("Show the ten highest numbers that can be expressed");
WriteLn;
limit := 123456789 + 1;
FOR i:=1 TO 10 DO
best := 0;
FOR j:=0 TO nexpr-1 DO
test := Evaluate(j);
IF (test < limit) AND (test > best) THEN
best := test
END
END;
FOR j:=0 TO nexpr-1 DO
IF Evaluate(j) = best THEN
Print(j)
END
END;
limit := best
END;
ReadChar
END SumTo100. |
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
| #Action.21 | Action! | PROC Strip(CHAR ARRAY text,chars,res)
BYTE i,j,size,found
CHAR c
size=0
FOR i=1 TO text(0)
DO
c=text(i) found=0
FOR j=1 TO chars(0)
DO
IF c=chars(j) THEN
found=1 EXIT
FI
OD
IF found=0 THEN
size==+1
res(size)=c
FI
OD
res(0)=size
RETURN
PROC Main()
CHAR ARRAY
text="She was a soul stripper. She took my heart!",
chars="aei", result(255)
Strip(text,chars,result)
PrintE("String to be stripped:")
PrintF("""%S""%E%E",text)
PrintE("Characters to be stripped:")
PrintF("""%S""%E%E",chars)
PrintE("Stripped string:")
PrintF("""%S""%E%E",result)
RETURN |
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.
| #AppleScript | AppleScript | set aVariable to "world!"
set aVariable to "Hello " & aVariable
return aVariable |
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.
| #Arturo | Arturo | a: "World"
a: "Hello" ++ a
print a
b: "World"
b: append "Hello" b
print a
c: "World"
prefix 'c "Hello"
print c
d: "World"
print prefix d "Hello" |
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
| #11l | 11l | print(‘abcd’.starts_with(‘ab’))
print(‘abcd’.ends_with(‘zn’))
print(‘bb’ C ‘abab’)
print(‘ab’ C ‘abab’)
print(‘abab’.find(‘bb’) ? -1)
print(‘abab’.find(‘ab’) ? -1) |
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
| #360_Assembly | 360 Assembly | * String length 06/07/2016
LEN CSECT
USING LEN,15 base register
LA 1,L'C length of C
XDECO 1,PG
XPRNT PG,12
LA 1,L'H length of H
XDECO 1,PG
XPRNT PG,12
LA 1,L'F length of F
XDECO 1,PG
XPRNT PG,12
LA 1,L'D length of D
XDECO 1,PG
XPRNT PG,12
LA 1,L'PG length of PG
XDECO 1,PG
XPRNT PG,12
BR 14 exit length
C DS C character 1
H DS H half word 2
F DS F full word 4
D DS D double word 8
PG DS CL12 string 12
END LEN |
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
| #AWK | AWK |
# syntax: GAWK -f STRIP_CONTROL_CODES_AND_EXTENDED_CHARACTERS.AWK
BEGIN {
s = "ab\xA2\x09z" # a b cent tab z
printf("original string: %s (length %d)\n",s,length(s))
gsub(/[\x00-\x1F\x7F]/,"",s); printf("control characters stripped: %s (length %d)\n",s,length(s))
gsub(/[\x80-\xFF]/,"",s); printf("control and extended stripped: %s (length %d)\n",s,length(s))
exit(0)
}
|
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.
| #FBSL | FBSL | #APPTYPE CONSOLE
FUNCTION sumOfThreeFiveMultiples(n AS INTEGER)
DIM sum AS INTEGER
FOR DIM i = 1 TO n - 1
IF (NOT (i MOD 3)) OR (NOT (i MOD 5)) THEN
INCR(sum, i)
END IF
NEXT
RETURN sum
END FUNCTION
PRINT sumOfThreeFiveMultiples(1000)
PAUSE
|
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
| #Forth | Forth | : sum_int 0 begin over while swap base @ /mod swap rot + repeat nip ;
2 base ! 11110 sum_int decimal . cr
10 base ! 12345 sum_int decimal . cr
16 base ! f0e sum_int decimal . cr |
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
| #Go | Go | package main
import "fmt"
var v = []float32{1, 2, .5}
func main() {
var sum float32
for _, x := range v {
sum += x * x
}
fmt.Println(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
| #BaCon | BaCon |
'---Remove leading whitespace
PRINT CHOP$(" String with spaces "," ",1)
'---Remove trailing whitespace
PRINT CHOP$(" String with spaces "," ",2)
'---Remove both leading and trailing whitespace
PRINT CHOP$(" String with spaces "," ",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.
| #Haskell | Haskell | import Text.Printf (printf)
import Data.Numbers.Primes (primes)
xPrimes :: (Real a, Fractional b) => (b -> b -> Bool) -> [a] -> [a]
xPrimes op ps@(p1:p2:p3:xs)
| realToFrac p2 `op` (realToFrac (p1 + p3) / 2) = p2 : xPrimes op (tail ps)
| otherwise = xPrimes op (tail ps)
main :: IO ()
main = do
printf "First 36 strong primes: %s\n" . show . take 36 $ strongPrimes
printf "Strong primes below 1,000,000: %d\n" . length . takeWhile (<1000000) $ strongPrimes
printf "Strong primes below 10,000,000: %d\n\n" . length . takeWhile (<10000000) $ strongPrimes
printf "First 37 weak primes: %s\n" . show . take 37 $ weakPrimes
printf "Weak primes below 1,000,000: %d\n" . length . takeWhile (<1000000) $ weakPrimes
printf "Weak primes below 10,000,000: %d\n\n" . length . takeWhile (<10000000) $ weakPrimes
where strongPrimes = xPrimes (>) primes
weakPrimes = xPrimes (<) primes |
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
| #Arturo | Arturo | str: "abcdefgh"
n: 2
m: 3
; starting from n=2 characters in and m=3 in length
print slice str n-1 n+m-2
; starting from n characters in, up to the end of the string
print slice str n-1 (size str)-1
; whole string minus last character
print slice str 0 (size str)-2
; starting from a known character char="d"
; within the string and of m length
print slice str index str "d" m+(index str "d")-1
; starting from a known substring chars="cd"
; within the string and of m length
print slice str index str "cd" m+(index str "cd")-1 |
http://rosettacode.org/wiki/Sudoku | Sudoku | Task
Solve a partially filled-in normal 9x9 Sudoku grid and display the result in a human-readable format.
references
Algorithmics of Sudoku may help implement this.
Python Sudoku Solver Computerphile video.
| #C.23 | C# | using System;
class SudokuSolver
{
private int[] grid;
public SudokuSolver(String s)
{
grid = new int[81];
for (int i = 0; i < s.Length; i++)
{
grid[i] = int.Parse(s[i].ToString());
}
}
public void solve()
{
try
{
placeNumber(0);
Console.WriteLine("Unsolvable!");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(this);
}
}
public void placeNumber(int pos)
{
if (pos == 81)
{
throw new Exception("Finished!");
}
if (grid[pos] > 0)
{
placeNumber(pos + 1);
return;
}
for (int n = 1; n <= 9; n++)
{
if (checkValidity(n, pos % 9, pos / 9))
{
grid[pos] = n;
placeNumber(pos + 1);
grid[pos] = 0;
}
}
}
public bool checkValidity(int val, int x, int y)
{
for (int i = 0; i < 9; i++)
{
if (grid[y * 9 + i] == val || grid[i * 9 + x] == val)
return false;
}
int startX = (x / 3) * 3;
int startY = (y / 3) * 3;
for (int i = startY; i < startY + 3; i++)
{
for (int j = startX; j < startX + 3; j++)
{
if (grid[i * 9 + j] == val)
return false;
}
}
return true;
}
public override string ToString()
{
string sb = "";
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
sb += (grid[i * 9 + j] + " ");
if (j == 2 || j == 5)
sb += ("| ");
}
sb += ('\n');
if (i == 2 || i == 5)
sb += ("------+-------+------\n");
}
return sb;
}
public static void Main(String[] args)
{
new SudokuSolver("850002400" +
"720000009" +
"004000000" +
"000107002" +
"305000900" +
"040000000" +
"000080070" +
"017000000" +
"000036040").solve();
Console.Read();
}
} |
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
| #C | C | #include <stdlib.h>
#include <stdio.h>
void
subleq(int *code)
{
int ip = 0, a, b, c, nextIP;
char ch;
while(0 <= ip) {
nextIP = ip + 3;
a = code[ip];
b = code[ip + 1];
c = code[ip + 2];
if(a == -1) {
scanf("%c", &ch);
code[b] = (int)ch;
} else if(b == -1) {
printf("%c", (char)code[a]);
} else {
code[b] -= code[a];
if(code[b] <= 0)
nextIP = c;
}
ip = nextIP;
}
}
void
processFile(char *fileName)
{
int *dataSet, i, num;
FILE *fp = fopen(fileName, "r");
fscanf(fp, "%d", &num);
dataSet = (int *)malloc(num * sizeof(int));
for(i = 0; i < num; i++)
fscanf(fp, "%d", &dataSet[i]);
fclose(fp);
subleq(dataSet);
}
int
main(int argC, char *argV[])
{
if(argC != 2)
printf("Usage : %s <subleq code file>\n", argV[0]);
else
processFile(argV[1]);
return 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 | #J | J |
primes_less_than=: i.&.:(p:inv)
assert 2 3 5 -: primes_less_than 7
Primes=: primes_less_than 1e6
NB. Insert minus `-/' into the length two infixes `\'.
NB. Passive `~' swaps the arguments producing the positive differences.
Successive_Differences=: 2 -~/\ Primes
assert 8169 -: +/ 2 = Successive_Differences NB. twin prime tally
Groups=: 2 ; 1 ; 2 2 ; 2 4 ; 4 2 ; 6 4 2
group_index=: [: I. E.
end_groups=: Primes {~ ({. , {:)@] +/ 0,#\@[
Header=: <;._2 'Group;Count;First/Last groups;'
Header ,> Groups ([ ([ ; #@] ; end_groups) group_index)&.> <Successive_Differences
┌─────┬─────┬───────────────────────────┐
│Group│Count│First/Last groups │
├─────┼─────┼───────────────────────────┤
│2 │8169 │ 3 5 │
│ │ │999959 999961 │
├─────┼─────┼───────────────────────────┤
│1 │1 │2 3 │
│ │ │2 3 │
├─────┼─────┼───────────────────────────┤
│2 2 │1 │3 5 7 │
│ │ │3 5 7 │
├─────┼─────┼───────────────────────────┤
│2 4 │1393 │ 5 7 11 │
│ │ │999431 999433 999437 │
├─────┼─────┼───────────────────────────┤
│4 2 │1444 │ 7 11 13 │
│ │ │997807 997811 997813 │
├─────┼─────┼───────────────────────────┤
│6 4 2│306 │ 31 37 41 43│
│ │ │997141 997147 997151 997153│
└─────┴─────┴───────────────────────────┘ |
http://rosettacode.org/wiki/Substring/Top_and_tail | Substring/Top and tail | The task is to demonstrate how to remove the first and last characters from a string.
The solution should demonstrate how to obtain the following results:
String with first character removed
String with last character removed
String with both the first and last characters removed
If the program uses UTF-8 or UTF-16, it must work on any valid Unicode code point, whether in the Basic Multilingual Plane or above it.
The program must reference logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16.
Programs for other encodings (such as 8-bit ASCII, or EUC-JP) are not required to handle all Unicode characters.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #C.2B.2B | C++ | #include <string>
#include <iostream>
int main( ) {
std::string word( "Premier League" ) ;
std::cout << "Without first letter: " << word.substr( 1 ) << " !\n" ;
std::cout << "Without last letter: " << word.substr( 0 , word.length( ) - 1 ) << " !\n" ;
std::cout << "Without first and last letter: " << word.substr( 1 , word.length( ) - 2 ) << " !\n" ;
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.
| #Icon_and_Unicon | Icon and Unicon | procedure main()
every 1 to 10 do
write(rand_sub(292929))
end
procedure rand_sub(x)
static ring,m
if /ring then {
m := 10^9
every (seed | ring) := list(55)
seed[1] := \x | ?(m-1)
seed[2] := 1
every seed[n := 3 to 55] := (seed[n-2]-seed[n-1])%m
every ring[(n := 0 to 54) + 1] := seed[1 + (34 * (n + 1)%55)]
every n := *ring to 219 do {
ring[1] -:= ring[-24]
ring[1] %= m
put(ring,get(ring))
}
}
ring[1] -:= ring[-24]
ring[1] %:= m
if ring[1] < 0 then ring[1] +:= m
put(ring,get(ring))
return ring[-1]
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
| #Quackery | Quackery | [ stack ] is encryption ( --> s )
[ stack ] is decryption ( --> s )
[ [] 95 times [ i^ join ]
shuffle encryption put ] is makeencrypt ( --> )
[ encryption share
0 95 of swap
witheach
[ i^ unrot poke ]
decryption put ] is makedecrypt ( --> )
[ makeencrypt makedecrypt ] is makekeys ( --> )
[ witheach [ char ! + emit ] ] is echokey ( s --> )
[ encryption release
decryption release ] is releasekeys ( --> )
[ [] swap witheach
[ dup char ! char ~ 1+
within if
[ char ! -
encryption share
swap peek char ! + ]
join ] ] is encrypt ( $ --> $ )
[ [] swap witheach
[ dup char ! char ~ 1+
within if
[ char ! -
decryption share
swap peek char ! + ]
join ] ] is decrypt ( $ --> $ )
randomise
makekeys
say "Encryption key is: " encryption share echokey cr
say "Decryption key is: " decryption share echokey cr
cr
$ "Encryption matters, and it is not just for spies and philanderers."
say "Plaintext: " dup echo$ cr
say "Encrypted: " encrypt dup echo$ cr
say "Decrypted: " decrypt echo$ cr
releasekeys |
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
| #Racket | Racket | #lang racket/base
(require racket/list racket/function racket/file)
(define abc "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")
;; Used to generate my-key for examples
(define (random-key (alphabet abc))
(list->string (shuffle (string->list alphabet))))
(define (cypher/decypher key (alphabet abc))
;; alist is fine, hashes are better over 40 chars... so alist for
;; abc, hash for ASCII.
(define ab-chars (string->list alphabet))
(define ky-chars (string->list key))
(define cypher-alist (map cons ab-chars ky-chars))
(define decypher-alist (map cons ky-chars ab-chars))
(define ((subst-map alist) str)
(list->string (map (lambda (c) (cond [(assoc c alist) => cdr] [else c]))
(string->list str))))
(values (subst-map cypher-alist)
(subst-map decypher-alist)))
(define (cypher/decypher-files key (alphabet abc))
(define-values (cypher decypher) (cypher/decypher key alphabet))
(define ((convert-file f) in out #:exists (exists-flag 'error))
(curry with-output-to-file out #:exists exists-flag
(lambda () (display (f (file->string in))))))
(values (convert-file cypher)
(convert-file decypher)))
(module+ test
(require rackunit)
(define my-key "LXRWzUrIYPJiVQyMwKudbAaDjSEefvhlqmOkGcBZCFsNpxHTgton")
(define-values (cypher decypher) (cypher/decypher my-key abc))
(define in-text #<<T
The quick brown fox...
.. jumped over
the lazy dog!
T
)
(define cypher-text (cypher in-text))
(define plain-text (decypher cypher-text))
(displayln cypher-text)
(check-equal? plain-text in-text)
(define-values (file-cypher file-decypher) (cypher/decypher-files my-key abc))
(file-cypher "data/substitution.in.txt" "data/substitution.crypt.txt" #:exists 'replace)
(file-decypher "data/substitution.crypt.txt" "data/substitution.plain.txt" #:exists 'replace)
(displayln "---")
(displayln (file->string "data/substitution.crypt.txt"))
(check-equal? (file->string "data/substitution.in.txt")
(file->string "data/substitution.plain.txt"))) |
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.
| #Euphoria | Euphoria | sequence array
integer sum,prod
array = { 1, 2, 3, 4, 5 }
sum = 0
prod = 1
for i = 1 to length(array) do
sum += array[i]
prod *= array[i]
end for
printf(1,"sum is %d\n",sum)
printf(1,"prod is %d\n",prod) |
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.
| #EDSAC_order_code | EDSAC order code |
[Sum of a series, Rosetta Code website.
EDSAC program, Initial Orders 2.]
..PZ [blank tape and terminator]
[Library subroutine D6 - Division, accurate, fast.
36 locations, working positons 6D and 8D.
C(0D) := C(0D)/C(4D), where C(4D) <> 0, -1.]
T56K
GKA3FT34@S4DE13@T4DSDTDE2@T4DADLDTDA4DLDE8@RDU4DLDA35@
T6DE25@U8DN8DA6DT6DH6DS6DN4DA4DYFG21@SDVDTDEFW1526D
[Library subroutine P1 - Print positive number, no formatting or round-off.
Prints number in 0D to n places of decimals, where n is specified by 'P n F'
pseudo-order after subroutine call. 21 locations.]
T92K
GKA18@U17@S20@T5@H19@PFT5@VDUFOFFFSFL4FTDA5@A2FG6@EFU3FJFM1F
[Custom subroutine to calculate 1/k^2 for a 17-bit integer k > 1.
Input: 0F = k (with the usual scaling; actually k/(2^16).
Output: 0D = 1/k^2.]
T120K GK
A3F T11@ [set up return to caller as usual]
HF [multiply register := k/(2^16)]
VF [acc := k/(2^16) squared]
[At this point acc =(k^2)/(2^32). Now we switch to 35-bit
arithmetic, in which integers are scaled by 2^(-34)]
R1F [shift acc 2 right to adjust scaling]
T4D [4D := k^2]
TD [set 0D := 0; clears "sandwich bit" between 0F and 1F]
A12@ TF [set 0D := 1 by setting 0F := 1]
A9@ G56F [call EDSAC library subroutine for division]
[11] ZF [overwritten by jump back to caller]
[12] PD [short constant 1]
[Main program]
T200K GK [load at even address because of long variable at 0]
[0] PF PF [build sum here]
[2] PD [short constant 1]
[3] P500F [short constant 1000]
[4] K2048F #F !F @F &F [letters, figures, space, CR, LF]
[9] HF IF LF [letters H, I, L (in letters mode)]
[12] QF MF [digit 1, dot (in figures mode)]
[14] PF [variable k]
[15] T#@ A2@ T14@ [sum := 0, k := 1]
[18] TF A14@ A2@ U14@ TF [inc k; pass new k to function in 0F]
A23@ G120F [call function; places 1/k^2 at 0D]
AD A#@ T#@ [add 1/k^2 into sum]
A14@ S3@ G18@ [test for k = maximum, loop back if not]
O4@ O11@ O89@ O6@ O15@ O89@ O6@ O9@ O10@ O6@ [print 'LO TO HI ']
O5@ O12@ O13@ [print '1.']
A#@ TD A46@ G92F [call subroutine to print decimal part]
P10F [parameter for print subroutine; 10 decimal places]
O7@ O8@ [print CR, LF]
[Sum in reverse order to confirm that the result is identical on EDSAC.
Not much different from the above, so given in condensed form.]
TFT#@A3@T14@TFA14@TFA58@G120FADA#@T#@A14@S2@U14@S2FE55@TDA#@TD
O4@O9@O10@O6@O15@O89@O6@O11@O89@O6@O5@O12@O13@A84@G92FP10FO7@O8@
[89] O5@ ZF [flush teleprinter buffer; stop]
E15Z PF [define entry point; enter with acc = 0]
|
http://rosettacode.org/wiki/Strip_comments_from_a_string | Strip comments from a string | Strip comments from a string
You are encouraged to solve this task according to the task description, using any language you may know.
The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line.
Whitespace debacle: There is some confusion about whether to remove any whitespace from the input line.
As of 2 September 2011, at least 8 languages (C, C++, Java, Perl, Python, Ruby, sed, UNIX Shell) were incorrect, out of 36 total languages, because they did not trim whitespace by 29 March 2011 rules. Some other languages might be incorrect for the same reason.
Please discuss this issue at Talk:Strip comments from a string.
From 29 March 2011, this task required that: "The comment marker and any whitespace at the beginning or ends of the resultant line should be removed. A line without comments should be trimmed of any leading or trailing whitespace before being produced as a result." The task had 28 languages, which did not all meet this new requirement.
From 28 March 2011, this task required that: "Whitespace before the comment marker should be removed."
From 30 October 2010, this task did not specify whether or not to remove whitespace.
The following examples will be truncated to either "apples, pears " or "apples, pears".
(This example has flipped between "apples, pears " and "apples, pears" in the past.)
apples, pears # and bananas
apples, pears ; and bananas
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Arturo | Arturo | stripComments: function [str][
strip replace str {/[#;].+/} ""
]
loop ["apples, pears # and bananas", "apples, pears ; and bananas"] 'str [
print [str "->" stripComments str]
] |
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
| #AutoHotkey | AutoHotkey | Delims := "#;"
str := "apples, pears # and bananas"
str2:= "apples, pears, `; and bananas" ; needed to escape the ; since that is AHK's comment marker
msgbox % StripComments(Str,Delims)
msgbox % StripComments(Str2,Delims)
; The % forces expression mode.
StripComments(String1,Delims){
Loop, parse, delims
{
If Instr(String1,A_LoopField)
EndPosition := InStr(String1,A_LoopField) - 1
Else
EndPosition := StrLen(String1)
StringLeft, String1, String1, EndPosition
}
return String1
} |
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
| #C.23 | C# | using System;
class Program
{
private static string BlockCommentStrip(string commentStart, string commentEnd, string sampleText)
{
while (sampleText.IndexOf(commentStart) > -1 && sampleText.IndexOf(commentEnd, sampleText.IndexOf(commentStart) + commentStart.Length) > -1)
{
int start = sampleText.IndexOf(commentStart);
int end = sampleText.IndexOf(commentEnd, start + commentStart.Length);
sampleText = sampleText.Remove(
start,
(end + commentEnd.Length) - start
);
}
return sampleText;
}
} |
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
| #C.2B.2B | C++ | #include <string>
#include <iostream>
#include <iterator>
#include <fstream>
#include <boost/regex.hpp>
int main( ) {
std::ifstream codeFile( "samplecode.txt" ) ;
if ( codeFile ) {
boost::regex commentre( "/\\*.*?\\*/" ) ;//comment start and end, and as few characters in between as possible
std::string my_erase( "" ) ; //erase them
std::string stripped ;
std::string code( (std::istreambuf_iterator<char>( codeFile ) ) ,
std::istreambuf_iterator<char>( ) ) ;
codeFile.close( ) ;
stripped = boost::regex_replace( code , commentre , my_erase ) ;
std::cout << "Code unstripped:\n" << stripped << std::endl ;
return 0 ;
}
else {
std::cout << "Could not find code file!" << std::endl ;
return 1 ;
}
} |
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).
| #Nim | Nim | import algorithm, parseutils, sequtils, strutils, tables
type Expression = string
proc buildExprs(start: Natural = 0): seq[Expression] =
let item = if start == 0: "" else: $start
if start == 9: return @[item]
for expr in buildExprs(start + 1):
result.add item & expr
result.add item & '-' & expr
if start != 0: result.add item & '+' & expr
proc evaluate(expr: Expression): int =
var idx = 0
var val: int
while idx < expr.len:
let n = expr.parseInt(val, idx)
inc idx, n
result += val
let exprs = buildExprs()
var counts: CountTable[int]
echo "The solutions for 100 are:"
for expr in exprs:
let sum = evaluate(expr)
if sum == 100: echo expr
if sum > 0: counts.inc(sum)
let (n, count) = counts.largest()
echo "\nThe maximum count of positive solutions is $1 for number $2.".format(count, n)
var s = 1
while true:
if s notin counts:
echo "\nThe smallest number than cannot be expressed is: $1.".format(s)
break
inc s
echo "\nThe ten highest numbers than can be expressed are:"
let numbers = sorted(toSeq(counts.keys), Descending)
echo numbers[0..9].join(", ") |
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
| #Ada | Ada | with Ada.Text_IO;
procedure Strip_Characters_From_String is
function Strip(The_String: String; The_Characters: String)
return String is
Keep: array (Character) of Boolean := (others => True);
Result: String(The_String'Range);
Last: Natural := Result'First-1;
begin
for I in The_Characters'Range loop
Keep(The_Characters(I)) := False;
end loop;
for J in The_String'Range loop
if Keep(The_String(J)) then
Last := Last+1;
Result(Last) := The_String(J);
end if;
end loop;
return Result(Result'First .. Last);
end Strip;
S: String := "She was a soul stripper. She took my heart!";
begin -- main
Ada.Text_IO.Put_Line(Strip(S, "aei"));
end Strip_Characters_From_String; |
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
| #Aime | Aime | text
stripchars1(data b, text w)
{
integer p;
p = b.look(0, w);
while (p < ~b) {
b.delete(p);
p += b.look(p, w);
}
b;
}
text
stripchars2(data b, text w)
{
b.drop(w);
}
integer
main(void)
{
o_text(stripchars1("She was a soul stripper. She took my heart!", "aei"));
o_newline();
o_text(stripchars2("She was a soul stripper. She took my heart!", "aei"));
o_newline();
return 0;
} |
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.
| #Asymptote | Asymptote | string s1 = " World!";
write("Hello" + s1);
write("Hello", s1);
string s2 = "Hello" + s1;
write(s2); |
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.
| #AutoHotkey | AutoHotkey | s := "foo"
s := s "bar"
Msgbox % s |
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
| #360_Assembly | 360 Assembly | * String matching 04/04/2017
STRMATCH CSECT
USING STRMATCH,R15
XPRNT SS,L'SS
*
CLC SS(L'S1),S1
BNE NOT1
XPRNT =C'-- STARTS WITH',14
XPRNT S1,L'S1
NOT1 EQU *
*
CLC SS+L'SS-L'S2(L'S2),S2
BNE NOT2
XPRNT =C'-- ENDS WITH',12
XPRNT S2,L'S2
NOT2 EQU *
*
LA R0,L'SS-L'S3+1
LA R1,SS
LOOP CLC 0(L'S3,R1),S3
BNE NOT3
XPRNT =C'-- CONTAINS',11
XPRNT S3,L'S3
NOT3 LA R1,1(R1)
BCT R0,LOOP
*
BR R14
SS DC CL6'ABCDEF'
S1 DC CL2'AB'
S2 DC CL2'EF'
S3 DC CL2'CD'
PG DC CL80' '
YREGS
END STRMATCH |
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
| #6502_Assembly | 6502 Assembly | GetStringLength: ;$00 and $01 make up the pointer to the string's base address.
;(Of course, any two consecutive zero-page memory locations can fulfill this role.)
LDY #0 ;Y is both the index into the string and the length counter.
loop_getStringLength:
LDA ($00),y
BEQ exit
INY
JMP loop_getStringLength
exit:
RTS ;string length is now loaded into Y. |
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
| #BASIC | BASIC | DECLARE FUNCTION strip$ (what AS STRING)
DECLARE FUNCTION strip2$ (what AS STRING)
DIM x AS STRING, y AS STRING, z AS STRING
' tab c+cedilla eof
x = CHR$(9) + "Fran" + CHR$(135) + "ais" + CHR$(26)
y = strip(x)
z = strip2(x)
PRINT "x:"; x
PRINT "y:"; y
PRINT "z:"; z
FUNCTION strip$ (what AS STRING)
DIM outP AS STRING, L0 AS INTEGER, tmp AS STRING
FOR L0 = 1 TO LEN(what)
tmp = MID$(what, L0, 1)
SELECT CASE ASC(tmp)
CASE 32 TO 126
outP = outP + tmp
END SELECT
NEXT
strip$ = outP
END FUNCTION
FUNCTION strip2$ (what AS STRING)
DIM outP AS STRING, L1 AS INTEGER, tmp AS STRING
FOR L1 = 1 TO LEN(what)
tmp = MID$(what, L1, 1)
SELECT CASE ASC(tmp)
'normal accented various greek, math, etc.
CASE 32 TO 126, 128 TO 168, 171 TO 175, 224 TO 253
outP = outP + tmp
END SELECT
NEXT
strip2$ = outP
END FUNCTION |
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
| #11l | 11l | V s1 = ‘hello’
print(s1‘ world’)
V s2 = s1‘ world’
print(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.
| #Forth | Forth | : main ( n -- )
0 swap
3 do
i 3 mod 0= if
i +
else i 5 mod 0= if
i +
then then
loop
. ;
1000 main \ 233168 ok |
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
| #Fortran | Fortran |
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Fri Jun 7 21:00:12
!
!a=./f && make $a && $a
!gfortran -std=f2008 -Wall -fopenmp -ffree-form -fall-intrinsics -fimplicit-none f.f08 -o f
!f.f08:57.29:
!
! subroutine process1(fmt,s,b)
! 1
!Warning: Unused dummy argument 'b' at (1)
!digit sum n
! 1 1
! 10 1234
! 29 fe
! 29 f0e
! sum of digits of n expressed in base is...
! n base sum
! 1 10 1
! 1234 10 10
! 254 16 29
! 3854 16 29
!
!Compilation finished at Fri Jun 7 21:00:12
module base_mod
private :: reverse
contains
subroutine reverse(a)
integer, dimension(:), intent(inout) :: a
integer :: i, j, t
do i=1,size(a)/2
j = size(a) - i + 1
t = a(i)
a(i) = a(j)
a(j) = t
end do
end subroutine reverse
function antibase(b, n) result(a)
integer, intent(in) :: b,n
integer, dimension(32) :: a
integer :: m, i
a = 0
m = n
i = 1
do while (m .ne. 0)
a(i) = mod(m, b)
m = m/b
i = i+1
end do
call reverse(a)
end function antibase
end module base_mod
program digit_sum
use base_mod
call still
call confused
contains
subroutine still
character(len=6),parameter :: fmt = '(i9,a)'
print'(a9,a8)','digit sum','n'
call process1(fmt,'1',10)
call process1(fmt,'1234',10)
call process1(fmt,'fe',16)
call process1(fmt,'f0e',16)
end subroutine still
subroutine process1(fmt,s,b)
character(len=*), intent(in) :: fmt, s
integer, intent(in), optional :: b
integer :: i
print fmt,sum((/(index('123456789abcdef',s(i:i)),i=1,len(s))/)),' '//s
end subroutine process1
subroutine confused
character(len=5),parameter :: fmt = '(3i7)'
print*,'sum of digits of n expressed in base is...'
print'(3a7)','n','base','sum'
call process0(10,1,fmt)
call process0(10,1234,fmt)
call process0(16,254,fmt)
call process0(16,3854,fmt)
end subroutine confused
subroutine process0(b,n,fmt)
integer, intent(in) :: b, n
character(len=*), intent(in) :: fmt
print fmt,n,b,sum(antibase(b, n))
end subroutine process0
end program digit_sum
|
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
| #Golfscript | Golfscript | {0\{.*+}%}:sqsum;
# usage example
[1 2 3]sqsum puts |
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
| #Groovy | Groovy | def array = 1..3
// square via multiplication
def sumSq = array.collect { it * it }.sum()
println sumSq
// square via exponentiation
sumSq = array.collect { it ** 2 }.sum()
println sumSq |
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
| #BASIC | BASIC | mystring$=ltrim(mystring$) ' remove leading whitespace
mystring$=rtrim(mystring$) ' remove trailing whitespace
mystring$=ltrim(rtrim(mystring$)) ' remove both leading and trailing whitespace |
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
| #BBC_BASIC | BBC BASIC | REM Remove leading whitespace:
WHILE ASC(A$)<=32 A$ = MID$(A$,2) : ENDWHILE
REM Remove trailing whitespace:
WHILE ASC(RIGHT$(A$))<=32 A$ = LEFT$(A$) : ENDWHILE
REM Remove both leading and trailing whitespace:
WHILE ASC(A$)<=32 A$ = MID$(A$,2) : ENDWHILE
WHILE ASC(RIGHT$(A$))<=32 A$ = LEFT$(A$) : ENDWHILE |
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.
| #J | J | Filter =: (#~`)(`:6)
average =: +/ % #
NB. vector of primes from 2 to 10000019
PRIMES=:i.@>:&.(p:inv) 10000000
strongQ =: 1&{ > [: average {. , {:
STRONG_PRIMES=: (0, 0,~ 3&(strongQ\))Filter PRIMES
NB. first 36 strong primes
36 {. STRONG_PRIMES
11 17 29 37 41 59 67 71 79 97 101 107 127 137 149 163 179 191 197 223 227 239 251 269 277 281 307 311 331 347 367 379 397 419 431 439
NB. tally of strong primes less than one and ten million
+/ STRONG_PRIMES </ 1e6 * 1 10
37723 320991
weakQ =: 1&{ < [: average {. , {:
weaklings =: (0, 0,~ 3&(weakQ\))Filter PRIMES
NB. first 37 weak primes
37 {. weaklings
3 7 13 19 23 31 43 47 61 73 83 89 103 109 113 131 139 151 167 181 193 199 229 233 241 271 283 293 313 317 337 349 353 359 383 389 401
NB. tally of weak primes less than one and ten million
+/ weaklings </ 1e6 * 1 10
37780 321750
|
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.
| #Java | Java |
public class StrongAndWeakPrimes {
private static int MAX = 10_000_000 + 1000;
private static boolean[] primes = new boolean[MAX];
public static void main(String[] args) {
sieve();
System.out.println("First 36 strong primes:");
displayStrongPrimes(36);
for ( int n : new int[] {1_000_000, 10_000_000}) {
System.out.printf("Number of strong primes below %,d = %,d%n", n, strongPrimesBelow(n));
}
System.out.println("First 37 weak primes:");
displayWeakPrimes(37);
for ( int n : new int[] {1_000_000, 10_000_000}) {
System.out.printf("Number of weak primes below %,d = %,d%n", n, weakPrimesBelow(n));
}
}
private static int weakPrimesBelow(int maxPrime) {
int priorPrime = 2;
int currentPrime = 3;
int count = 0;
while ( currentPrime < maxPrime ) {
int nextPrime = getNextPrime(currentPrime);
if ( currentPrime * 2 < priorPrime + nextPrime ) {
count++;
}
priorPrime = currentPrime;
currentPrime = nextPrime;
}
return count;
}
private static void displayWeakPrimes(int maxCount) {
int priorPrime = 2;
int currentPrime = 3;
int count = 0;
while ( count < maxCount ) {
int nextPrime = getNextPrime(currentPrime);
if ( currentPrime * 2 < priorPrime + nextPrime) {
count++;
System.out.printf("%d ", currentPrime);
}
priorPrime = currentPrime;
currentPrime = nextPrime;
}
System.out.println();
}
private static int getNextPrime(int currentPrime) {
int nextPrime = currentPrime + 2;
while ( ! primes[nextPrime] ) {
nextPrime += 2;
}
return nextPrime;
}
private static int strongPrimesBelow(int maxPrime) {
int priorPrime = 2;
int currentPrime = 3;
int count = 0;
while ( currentPrime < maxPrime ) {
int nextPrime = getNextPrime(currentPrime);
if ( currentPrime * 2 > priorPrime + nextPrime ) {
count++;
}
priorPrime = currentPrime;
currentPrime = nextPrime;
}
return count;
}
private static void displayStrongPrimes(int maxCount) {
int priorPrime = 2;
int currentPrime = 3;
int count = 0;
while ( count < maxCount ) {
int nextPrime = getNextPrime(currentPrime);
if ( currentPrime * 2 > priorPrime + nextPrime) {
count++;
System.out.printf("%d ", currentPrime);
}
priorPrime = currentPrime;
currentPrime = nextPrime;
}
System.out.println();
}
private static final void sieve() {
// primes
for ( int i = 2 ; i < MAX ; i++ ) {
primes[i] = true;
}
for ( int i = 2 ; i < MAX ; i++ ) {
if ( primes[i] ) {
for ( int j = 2*i ; j < MAX ; j += i ) {
primes[j] = false;
}
}
}
}
}
|
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
| #AutoHotkey | AutoHotkey | String := "abcdefghijklmnopqrstuvwxyz"
; also: String = abcdefghijklmnopqrstuvwxyz
n := 12
m := 5
; starting from n characters in and of m length;
subString := SubStr(String, n, m)
; alternative: StringMid, subString, String, n, m
MsgBox % subString
; starting from n characters in, up to the end of the string;
subString := SubStr(String, n)
; alternative: StringMid, subString, String, n
MsgBox % subString
; whole string minus last character;
StringTrimRight, subString, String, 1
; alternatives: subString := SubStr(String, 1, StrLen(String) - 1)
; StringMid, subString, String, 1, StrLen(String) - 1
MsgBox % subString
; starting from a known character within the string and of m length;
findChar := "q"
subString := SubStr(String, InStr(String, findChar), m)
; alternatives: RegExMatch(String, findChar . ".{" . m - 1 . "}", subString)
; StringMid, subString, String, InStr(String, findChar), m
MsgBox % subString
; starting from a known character within the string and of m length;
findString := "pq"
subString := SubStr(String, InStr(String, findString), m)
; alternatives: RegExMatch(String, findString . ".{" . m - StrLen(findString) . "}", subString)
; StringMid, subString, String, InStr(String, findString), m
MsgBox % 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.
| #C.2B.2B | C++ | #include <iostream>
using namespace std;
class SudokuSolver {
private:
int grid[81];
public:
SudokuSolver(string s) {
for (unsigned int i = 0; i < s.length(); i++) {
grid[i] = (int) (s[i] - '0');
}
}
void solve() {
try {
placeNumber(0);
cout << "Unsolvable!" << endl;
} catch (char* ex) {
cout << ex << endl;
cout << this->toString() << endl;
}
}
void placeNumber(int pos) {
if (pos == 81) {
throw (char*) "Finished!";
}
if (grid[pos] > 0) {
placeNumber(pos + 1);
return;
}
for (int n = 1; n <= 9; n++) {
if (checkValidity(n, pos % 9, pos / 9)) {
grid[pos] = n;
placeNumber(pos + 1);
grid[pos] = 0;
}
}
}
bool checkValidity(int val, int x, int y) {
for (int i = 0; i < 9; i++) {
if (grid[y * 9 + i] == val || grid[i * 9 + x] == val)
return false;
}
int startX = (x / 3) * 3;
int startY = (y / 3) * 3;
for (int i = startY; i < startY + 3; i++) {
for (int j = startX; j < startX + 3; j++) {
if (grid[i * 9 + j] == val)
return false;
}
}
return true;
}
string toString() {
string sb;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
char c[2];
c[0] = grid[i * 9 + j] + '0';
c[1] = '\0';
sb.append(c);
sb.append(" ");
if (j == 2 || j == 5)
sb.append("| ");
}
sb.append("\n");
if (i == 2 || i == 5)
sb.append("------+-------+------\n");
}
return sb;
}
};
int main() {
SudokuSolver ss("850002400"
"720000009"
"004000000"
"000107002"
"305000900"
"040000000"
"000080070"
"017000000"
"000036040");
ss.solve();
return EXIT_SUCCESS;
} |
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
| #C.23 | C# | using System;
namespace Subleq {
class Program {
static void Main(string[] args) {
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) {
mem[b] = Console.Read();
}
else if (b == -1) {
Console.Write((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 | #Java | Java | import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SuccessivePrimeDifferences {
private static Integer[] sieve(int limit) {
List<Integer> primes = new ArrayList<>();
primes.add(2);
boolean[] c = new boolean[limit + 1];// composite = true
// no need to process even numbers > 2
int p = 3;
while (true) {
int p2 = p * p;
if (p2 > limit) {
break;
}
for (int i = p2; i <= limit; i += 2 * p) {
c[i] = true;
}
do {
p += 2;
} while (c[p]);
}
for (int i = 3; i <= limit; i += 2) {
if (!c[i]) {
primes.add(i);
}
}
return primes.toArray(new Integer[0]);
}
private static List<List<Integer>> successivePrimes(Integer[] primes, Integer[] diffs) {
List<List<Integer>> results = new ArrayList<>();
int dl = diffs.length;
outer:
for (int i = 0; i < primes.length - dl; i++) {
Integer[] group = new Integer[dl + 1];
group[0] = primes[i];
for (int j = i; j < i + dl; ++j) {
if (primes[j + 1] - primes[j] != diffs[j - i]) {
continue outer;
}
group[j - i + 1] = primes[j + 1];
}
results.add(Arrays.asList(group));
}
return results;
}
public static void main(String[] args) {
Integer[] primes = sieve(999999);
Integer[][] diffsList = {{2}, {1}, {2, 2}, {2, 4}, {4, 2}, {6, 4, 2}};
System.out.println("For primes less than 1,000,000:-\n");
for (Integer[] diffs : diffsList) {
System.out.printf(" For differences of %s ->\n", Arrays.toString(diffs));
List<List<Integer>> sp = successivePrimes(primes, diffs);
if (sp.isEmpty()) {
System.out.println(" No groups found");
continue;
}
System.out.printf(" First group = %s\n", Arrays.toString(sp.get(0).toArray(new Integer[0])));
System.out.printf(" Last group = %s\n", Arrays.toString(sp.get(sp.size() - 1).toArray(new Integer[0])));
System.out.printf(" Number found = %d\n", sp.size());
System.out.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
| #Clojure | Clojure | ; using substring:
user=> (subs "knight" 1)
"night"
user=> (subs "socks" 0 4)
"sock"
user=> (.substring "brooms" 1 5)
"room"
; using rest and drop-last:
user=> (apply str (rest "knight"))
"night"
user=> (apply str (drop-last "socks"))
"sock"
user=> (apply str (rest (drop-last "brooms")))
"room" |
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.
| #J | J | came_from_locale_sg_=: coname''
cocurrent'sg' NB. install the state of rng sg into locale sg
SEED=: 292929
'I J M first_Bentley_number B2'=: 55 24 1e9 34 165
SG=: 1 : 'M&|@:-/@:(m&{)'
r=: (I|(first_Bentley_number*>:i.I)) { (, _2 _1 SG)^:(I-2) 1,~SEED
sg=: 3 : 0
t=. (, (-I,J)SG)^:y r
r=: y }. t
t {.~ -y
)
discard=. sg B2
cocurrent came_from_locale NB. return to previous locale
sg=: sg_sg_ NB. make a local name for sg in locale sg
|
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.
| #Java | Java | import java.util.function.IntSupplier;
import static java.util.stream.IntStream.generate;
public class SubtractiveGenerator implements IntSupplier {
static final int MOD = 1_000_000_000;
private int[] state = new int[55];
private int si, sj;
public SubtractiveGenerator(int p1) {
subrandSeed(p1);
}
void subrandSeed(int p1) {
int p2 = 1;
state[0] = p1 % MOD;
for (int i = 1, j = 21; i < 55; i++, j += 21) {
if (j >= 55)
j -= 55;
state[j] = p2;
if ((p2 = p1 - p2) < 0)
p2 += MOD;
p1 = state[j];
}
si = 0;
sj = 24;
for (int i = 0; i < 165; i++)
getAsInt();
}
@Override
public int getAsInt() {
if (si == sj)
subrandSeed(0);
if (si-- == 0)
si = 54;
if (sj-- == 0)
sj = 54;
int x = state[si] - state[sj];
if (x < 0)
x += MOD;
return state[si] = x;
}
public static void main(String[] args) {
generate(new SubtractiveGenerator(292_929)).limit(10)
.forEach(System.out::println);
}
} |
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
| #Raku | Raku | my $chr = (' ' .. '}').join('');
my $key = $chr.comb.pick(*).join('');
# Be very boring and use the same key every time to fit task reqs.
$key = q☃3#}^",dLs*>tPMcZR!fmC rEKhlw1v4AOgj7Q]YI+|pDB82a&XFV9yzuH<WT%N;iS.0e:`G\n['6@_{bk)=-5qx(/?$JoU☃;
sub MAIN ($action = 'encode', $file = '') {
die 'Only options are encode or decode.' unless $action ~~ any 'encode'|'decode';
my $text = qq:to/END/;
Here we have to do is there will be a input/source file in which
we are going to Encrypt the 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.
END
$text = $file.IO.slurp if $file;
say "Key = $key\n";
if $file {
say &::($action)($text);
} else {
my $encoded;
say "Encoded text: \n {$encoded = encode $text}";
say "Decoded text: \n {decode $encoded}";
}
}
sub encode ($text) { $text.trans($chr => $key) }
sub decode ($text) { $text.trans($key => $chr) } |
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.
| #F.23 | F# |
let numbers = [| 1..10 |]
let sum = numbers |> Array.sum
let product = numbers |> Array.reduce (*)
|
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.
| #Factor | Factor | 1 5 1 <range> [ sum . ] [ product . ] bi
15 120
{ 1 2 3 4 } [ sum ] [ product ] bi
10 24 |
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.
| #Eiffel | Eiffel |
note
description: "Compute the n-th term of a series"
class
SUM_OF_SERIES_EXAMPLE
inherit
MATH_CONST
create
make
feature -- Initialization
make
local
approximated, known: REAL_64
do
known := Pi^2 / 6
approximated := sum_until (agent g, 1001)
print ("%Nzeta function exact value: %N")
print (known)
print ("%Nzeta function approximated value: %N")
print (approximated)
end
feature -- Access
g (k: INTEGER): REAL_64
-- 'k'-th term of the serie
require
k_positive: k > 0
do
Result := 1 / (k * k)
end
sum_until (s: FUNCTION [ANY, TUPLE [INTEGER], REAL_64]; n: INTEGER): REAL_64
-- sum of the 'n' first terms of 's'
require
n_positive: n > 0
one_parameter: s.open_count = 1
do
Result := 0
across 1 |..| n as it loop
Result := Result + s.item ([it.item])
end
end
end
|
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
| #AutoIt | AutoIt |
Dim $Line1 = "apples, pears # and bananas"
Dim $Line2 = "apples, pears ; and bananas"
_StripAtMarker($Line1)
_StripAtMarker($Line2)
Func _StripAtMarker($_Line, $sMarker='# ;')
Local $aMarker = StringSplit($sMarker, ' ')
Local $iPos
For $i = 1 To $aMarker[0]
$iPos = StringInStr($_Line, $aMarker[$i])
If $iPos Then
ConsoleWrite($_Line & @CRLF)
ConsoleWrite( StringStripWS( StringLeft($_Line, $iPos -1), 2) & @CRLF)
EndIf
Next
EndFunc ;==>_StripAtMarker
|
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
| #Clojure | Clojure | (defn comment-strip [txt & args]
(let [args (conj {:delim ["/*" "*/"]} (apply hash-map args)) ; This is the standard way of doing keyword/optional arguments in Clojure
[opener closer] (:delim args)]
(loop [out "", txt txt, delim-count 0] ; delim-count is needed to handle nested comments
(let [[hdtxt resttxt] (split-at (count opener) txt)] ; This splits "/* blah blah */" into hdtxt="/*" and restxt="blah blah */"
(printf "hdtxt=%8s resttxt=%8s out=%8s txt=%16s delim-count=%s\n" (apply str hdtxt) (apply str resttxt) out (apply str txt) delim-count)
(cond
(empty? hdtxt) (str out (apply str txt))
(= (apply str hdtxt) opener) (recur out resttxt (inc delim-count))
(= (apply str hdtxt) closer) (recur out resttxt (dec delim-count))
(= delim-count 0)(recur (str out (first txt)) (rest txt) delim-count)
true (recur out (rest txt) delim-count)))))) |
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).
| #Pascal | Pascal | { RossetaCode: Sum to 100, Pascal.
Find solutions to the "sum to one hundred" puzzle.
We don't use arrays, but recompute all values again and again.
It is a little surprise that the time efficiency is quite acceptable. }
program sumto100;
const
ADD = 0; SUB = 1; JOIN = 2; { opcodes inserted between digits }
NEXPR = 13122; { the total number of expressions }
var
i, j: integer;
loop: boolean;
test, ntest, best, nbest, limit: integer;
function evaluate(code: integer): integer;
var
k: integer;
value, number, power: integer;
begin
value := 0;
number := 0;
power := 1;
for k := 9 downto 1 do
begin
number := power * k + number;
case code mod 3 of
ADD: begin value := value + number; number := 0; power := 1; end;
SUB: begin value := value - number; number := 0; power := 1; end;
JOIN: power := power * 10
end;
code := code div 3
end;
evaluate := value
end;
procedure print(code: integer);
var
k: integer;
a, b: integer;
begin
a := 19683;
b := 6561;
write( evaluate(code):9 );
write(' = ');
for k := 1 to 9 do
begin
case ((code mod a) div b) of
ADD: if k > 1 then write('+');
SUB: { always } write('-');
end;
a := b;
b := b div 3;
write( k:1 )
end;
writeln
end;
begin
writeln;
writeln('Show all solutions that sum to 100');
writeln;
for i := 0 to NEXPR - 1 do
if evaluate(i) = 100 then
print(i);
writeln;
writeln('Show the sum that has the maximum number of solutions');
writeln;
nbest := (-1);
for i := 0 to NEXPR - 1 do
begin
test := evaluate(i);
if test > 0 then
begin
ntest := 0;
for j := 0 to NEXPR - 1 do
if evaluate(j) = test then
ntest := ntest + 1;
if ntest > nbest then
begin
best := test;
nbest := ntest;
end
end
end;
writeln(best, ' has ', nbest, ' solutions');
writeln;
writeln('Show the lowest positive number that can''t be expressed');
writeln;
i := 0;
loop := TRUE;
while (i <= 123456789) and loop do
begin
j := 0;
while (j < NEXPR - 1) and (i <> evaluate(j)) do
j := j + 1;
if i <> evaluate(j) then
loop := FALSE
else
i := i + 1;
end;
writeln(i);
writeln;
writeln('Show the ten highest numbers that can be expressed');
writeln;
limit := 123456789 + 1;
for i := 1 to 10 do
begin
best := 0;
for j := 0 to NEXPR - 1 do
begin
test := evaluate(j);
if (test < limit) and (test > best) then
best := test;
end;
for j := 0 to NEXPR - 1 do
if evaluate(j) = best then
print(j);
limit := best;
end
end. |
http://rosettacode.org/wiki/Strip_a_set_of_characters_from_a_string | Strip a set of characters from a string | Task
Create a function that strips a set of characters from a string.
The function should take two arguments:
a string to be stripped
a string containing the set of characters to be stripped
The returned string should contain the first string, stripped of any characters in the second argument:
print stripchars("She was a soul stripper. She took my heart!","aei")
Sh ws soul strppr. Sh took my hrt!
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #ALGOL_68 | ALGOL 68 | #!/usr/local/bin/a68g --script #
PROC strip chars = (STRING mine, ore)STRING: (
STRING out := "";
FOR i FROM LWB mine TO UPB mine DO
IF NOT char in string(mine[i], LOC INT, ore) THEN
out +:= mine[i]
FI
OD;
out[@LWB mine]
);
printf(($gl$,stripchars("She was a soul stripper. She took my heart!","aei"))) |
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
| #ALGOL_W | ALGOL W | begin
% returns s with the characters in remove removed %
% as all strings in Algol W are fixed length, the length of remove %
% must be specified in removeLength %
string(256) procedure stripCharacters( string(256) value s, remove
; integer value removeLength
) ;
begin
string(256) resultText;
integer tPos;
resultText := " ";
tPos := 0;
for sPos := 0 until 255 do begin
logical keepCharacter;
string(1) c;
c := s( sPos // 1 );
keepCharacter := true;
for rPos := 0 until removeLength - 1 do begin
if remove( rPos // 1 ) = c then begin
% have a character that should be removed %
keepCharacter := false;
goto endSearch
end if_have_a_character_to_remove ;
end for_rPos ;
endSearch:
if keepCharacter then begin
resultText( tPos // 1 ) := c;
tPos := tPos + 1
end if_keepCharacter
end for_sPos ;
resultText
end stripCharacters ;
% task test case %
begin
string(256) ex, stripped;
ex := "She was a soul stripper. She took my heart!";
stripped := stripCharacters( ex, "aei", 3 );
write( "text: ", ex( 0 // 64 ) );
write( " ->: ", stripped( 0 // 64 ) )
end
end. |
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.
| #AWK | AWK |
# syntax: GAWK -f STRING_PREPEND.AWK
BEGIN {
s = "bar"
s = "foo" s
print(s)
exit(0)
}
|
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.
| #BaCon | BaCon | s$ = "prepend"
s$ = "String " & s$
PRINT s$ |
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.
| #BASIC | BASIC | S$ = " World!"
S$ = "Hello" + S$
PRINT S$
|
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
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program strMatching64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*******************************************/
/* Initialized data */
/*******************************************/
.data
szMessFound: .asciz "String found. \n"
szMessNotFound: .asciz "String not found. \n"
szString: .asciz "abcdefghijklmnopqrstuvwxyz"
szString2: .asciz "abc"
szStringStart: .asciz "abcd"
szStringEnd: .asciz "xyz"
szStringStart2: .asciz "abcd"
szStringEnd2: .asciz "xabc"
szCarriageReturn: .asciz "\n"
/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
/*******************************************/
/* code section */
/*******************************************/
.text
.global main
main:
ldr x0,qAdrszString // address input string
ldr x1,qAdrszStringStart // address search string
bl searchStringDeb // Determining if the first string starts with second string
cmp x0,0
ble 1f
ldr x0,qAdrszMessFound // display message
bl affichageMess
b 2f
1:
ldr x0,qAdrszMessNotFound
bl affichageMess
2:
ldr x0,qAdrszString // address input string
ldr x1,qAdrszStringEnd // address search string
bl searchStringFin // Determining if the first string ends with the second string
cmp x0,0
ble 3f
ldr x0,qAdrszMessFound // display message
bl affichageMess
b 4f
3:
ldr x0,qAdrszMessNotFound
bl affichageMess
4:
ldr x0,qAdrszString2 // address input string
ldr x1,qAdrszStringStart2 // address search string
bl searchStringDeb //
cmp x0,0
ble 5f
ldr x0,qAdrszMessFound // display message
bl affichageMess
b 6f
5:
ldr x0,qAdrszMessNotFound
bl affichageMess
6:
ldr x0,qAdrszString2 // address input string
ldr x1,qAdrszStringEnd2 // address search string
bl searchStringFin
cmp x0,0
ble 7f
ldr x0,qAdrszMessFound // display message
bl affichageMess
b 8f
7:
ldr x0,qAdrszMessNotFound
bl affichageMess
8:
ldr x0,qAdrszString // address input string
ldr x1,qAdrszStringEnd // address search string
bl searchSubString // Determining if the first string contains the second string at any location
cmp x0,0
ble 9f
ldr x0,qAdrszMessFound // display message
bl affichageMess
b 10f
9:
ldr x0,qAdrszMessNotFound // display substring result
bl affichageMess
10:
100: // standard end of the program
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform system call
qAdrszMessFound: .quad szMessFound
qAdrszMessNotFound: .quad szMessNotFound
qAdrszString: .quad szString
qAdrszString2: .quad szString2
qAdrszStringStart: .quad szStringStart
qAdrszStringEnd: .quad szStringEnd
qAdrszStringStart2: .quad szStringStart2
qAdrszStringEnd2: .quad szStringEnd2
qAdrszCarriageReturn: .quad szCarriageReturn
/******************************************************************/
/* search substring at begin of input string */
/******************************************************************/
/* x0 contains the address of the input string */
/* x1 contains the address of substring */
/* x0 returns 1 if find or 0 if not or -1 if error */
searchStringDeb:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
mov x3,0 // counter byte string
ldrb w4,[x1,x3] // load first byte of substring
cbz x4,99f // empty string ?
1:
ldrb w2,[x0,x3] // load byte string input
cbz x2,98f // zero final ?
cmp x4,x2 // bytes equals ?
bne 98f // no not find
add x3,x3,1 // increment counter
ldrb w4,[x1,x3] // and load next byte of substring
cbnz x4,1b // zero final ?
mov x0,1 // yes is ok
b 100f
98:
mov x0,0 // not find
b 100f
99:
mov x0,-1 // error
100:
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* search substring at end of input string */
/******************************************************************/
/* x0 contains the address of the input string */
/* x1 contains the address of substring */
/* x0 returns 1 if find or 0 if not or -1 if error */
searchStringFin:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
mov x3,0 // counter byte string
// search the last character of substring
1:
ldrb w4,[x1,x3] // load byte of substring
cmp x4,#0 // zero final ?
add x2,x3,1
csel x3,x2,x3,ne // no increment counter
//addne x3,#1 // no increment counter
bne 1b // and loop
cbz x3,99f // empty string ?
sub x3,x3,1 // index of last byte
ldrb w4,[x1,x3] // load last byte of substring
// search the last character of string
mov x2,0 // index last character
2:
ldrb w5,[x0,x2] // load first byte of substring
cmp x5,0 // zero final ?
add x5,x2,1 // no -> increment counter
csel x2,x5,x2,ne
//addne x2,#1 // no -> increment counter
bne 2b // and loop
cbz x2,98f // empty input string ?
sub x2,x2,1 // index last character
3:
ldrb w5,[x0,x2] // load byte string input
cmp x4,x5 // bytes equals ?
bne 98f // no -> not found
subs x3,x3,1 // decrement counter
blt 97f // ok found
subs x2,x2,1 // decrement counter input string
blt 98f // if zero -> not found
ldrb w4,[x1,x3] // load previous byte of substring
b 3b // and loop
97:
mov x0,1 // yes is ok
b 100f
98:
mov x0,0 // not found
b 100f
99:
mov x0,-1 // error
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
/******************************************************************/
/* search a substring in the string */
/******************************************************************/
/* x0 contains the address of the input string */
/* x1 contains the address of substring */
/* x0 returns index of substring in string or -1 if not found */
searchSubString:
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 byte input string
mov x3,0 // counter byte string
mov x6,-1 // index found
ldrb w4,[x1,x3]
1:
ldrb w5,[x0,x2] // load byte string
cbz x5,99f // zero final ?
cmp x5,x4 // compare character
beq 2f
mov x6,-1 // no equals - > raz index
mov x3,0 // and raz counter byte
add x2,x2,1 // and increment counter byte
b 1b // and loop
2: // characters equals
cmp x6,-1 // first characters equals ?
csel x6,x2,x6,eq // yes -> index begin in x6
//moveq x6,x2 // yes -> index begin in x6
add x3,x3,1 // increment counter substring
ldrb w4,[x1,x3] // and load next byte
cmp x4,0 // zero final ?
beq 3f // yes -> end search
add x2,x2,1 // else increment counter string
b 1b // and loop
3:
mov x0,x6
b 100f
98:
mov x0,0 // not found
b 100f
99:
mov x0,-1 // error
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_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
| #68000_Assembly | 68000 Assembly | GetStringLength:
; INPUT: A3 = BASE ADDRESS OF STRING
; RETURNS LENGTH IN D1 (MEASURED IN BYTES)
MOVE.L #0,D1
loop_getStringLength:
MOVE.B (A3)+,D0
CMP #0,D0
BEQ done
ADDQ.L #1,D1
BRA loop_getStringLength
done:
RTS |
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
| #BBC_BASIC | BBC BASIC | test$ = CHR$(9) + "Fran" + CHR$(231) + "ais." + CHR$(127)
PRINT "Original ISO-8859-1 string: " test$ " (length " ; LEN(test$) ")"
test$ = FNstripcontrol(test$)
PRINT "Control characters stripped: " test$ " (length " ; LEN(test$) ")"
test$ = FNstripextended(test$)
PRINT "Control & extended stripped: " test$ " (length " ; LEN(test$) ")"
END
DEF FNstripcontrol(A$) : REM CHR$(127) is a 'control' code
LOCAL I%
WHILE I%<LEN(A$)
I% += 1
IF ASCMID$(A$,I%)<32 OR ASCMID$(A$,I%)=127 THEN
A$ = LEFT$(A$,I%-1) + MID$(A$,I%+1)
ENDIF
ENDWHILE
= A$
DEF FNstripextended(A$)
LOCAL I%
WHILE I%<LEN(A$)
I% += 1
IF ASCMID$(A$,I%)>127 THEN
A$ = LEFT$(A$,I%-1) + MID$(A$,I%+1)
ENDIF
ENDWHILE
= A$ |
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
| #Bracmat | Bracmat | ( "string of ☺☻♥♦⌂, may include control
characters and other ilk.\L\D§►↔◄
Rødgrød med fløde"
: ?string1
: ?string2
& :?newString
& whl
' ( @(!string1:?clean (%@:<" ") ?string1)
& !newString !clean:?newString
)
& !newString !string1:?newString
& out$(str$("Control characters stripped:
" str$!newString))
& :?newString
& whl
' ( @(!string2:?clean (%@:(<" "|>"~")) ?string2)
& !newString !clean:?newString
)
& !newString !string2:?newString
& out
$ ( str
$ ( "
Control characters and extended characters stripped:
"
str$!newString
)
)
& ); |
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
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program concatStr64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*******************************************/
/* Initialized data */
/*******************************************/
.data
szMessFinal: .asciz "The final string is \n"
szString: .asciz "Hello "
szString1: .asciz " the world. \n"
/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
szFinalString: .skip 255
/*******************************************/
/* code section */
/*******************************************/
.text
.global main
main:
// load string
ldr x1,qAdrszString
ldr x2,qAdrszFinalString
mov x4,0
1:
ldrb w0,[x1,x4] // load byte of string
strb w0,[x2,x4]
cmp x0,0 // compar with zero ?
add x3,x4,1
csel x4,x3,x4,ne // if x0 <> 0 x4 = x4 +1 sinon x4
bne 1b
ldr x1,qAdrszString1
mov x3,0
2:
ldrb w0,[x1,x3] // load byte of string 1
strb w0,[x2,x4]
cmp x0,0 // compar with zero ?
add x5,x4,1
csel x4,x5,x4,ne
add x5,x3,1
csel x3,x5,x3,ne
bne 2b
mov x0,x2 // display final string
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
qAdrszString: .quad szString
qAdrszString1: .quad szString1
qAdrszFinalString: .quad szFinalString
qAdrszMessFinal: .quad szMessFinal
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
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
| #ABAP | ABAP | DATA: s1 TYPE string,
s2 TYPE string.
s1 = 'Hello'.
CONCATENATE s1 ' literal' INTO s2 RESPECTING BLANKS.
WRITE: / s1.
WRITE: / 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.
| #Fortran | Fortran |
INTEGER*8 FUNCTION SUMI(N) !Sums the integers 1 to N inclusive.
Calculates as per the young Gauss: N*(N + 1)/2 = 1 + 2 + 3 + ... + N.
INTEGER*8 N !The number. Possibly large.
IF (MOD(N,2).EQ.0) THEN !So, I'm worried about overflow with N*(N + 1)
SUMI = N/2*(N + 1) !But since N is even, N/2 is good.
ELSE !Otherwise, if N is odd,
SUMI = (N + 1)/2*N !(N + 1) must be even.
END IF !Either way, the /2 reduces the result.
END FUNCTION SUMI !So overflow of intermediate results is avoided.
INTEGER*8 FUNCTION SUMF(N,F) !Sum of numbers up to N divisible by F.
INTEGER*8 N,F !The selection.
INTEGER*8 L !The last in range. N itself is excluded.
INTEGER*8 SUMI !Known type of the function.
L = (N - 1)/F !Truncates fractional parts.
SUMF = F*SUMI(L) !3 + 6 + 9 + ... = 3(1 + 2 + 3 + ...)
END FUNCTION SUMF !Could just put SUMF = F*SUMI((N - 1)/F).
INTEGER*8 FUNCTION SUMBFI(N) !Brute force and ignorance summation.
INTEGER*8 N !The number.
INTEGER*8 I,S !Stepper and counter.
S = 0 !So, here we go.
DO I = 3,N - 1 !N itself is not a candidate.
IF (MOD(I,3).EQ.0 .OR. MOD(I,5).EQ.0) S = S + I !Whee!
END DO !On to the next.
SUMBFI = S !The result.
END FUNCTION SUMBFI !Oh well, computers are fast these days.
INTEGER*8 SUMF,SUMBFI !Known type of the function.
INTEGER*8 N !The number.
WRITE (6,*) "Sum multiples of 3 and 5 up to N"
10 WRITE (6,11) !Ask nicely.
11 FORMAT ("Specify N: ",$) !Obviously, the $ says 'stay on this line'.
READ (5,*) N !If blank input is given, further input will be requested.
IF (N.LE.0) STOP !Good enough.
WRITE (6,*) "By Gauss:",SUMF(N,3) + SUMF(N,5) - SUMF(N,15)
WRITE (6,*) "BFI sum :",SUMBFI(N) !This could be a bit slow.
GO TO 10 !Have another go.
END !So much for that.
|
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
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Function SumDigits(number As Integer, nBase As Integer) As Integer
If number < 0 Then number = -number ' convert negative numbers to positive
If nBase < 2 Then nBase = 2 ' nBase can't be less than 2
Dim As Integer sum = 0
While number > 0
sum += number Mod nBase
number \= nBase
Wend
Return sum
End Function
Print "The sums of the digits are:"
Print
Print "1 base 10 :"; SumDigits(1, 10)
Print "1234 base 10 :"; SumDigits(1234, 10)
Print "fe base 16 :"; SumDigits(&Hfe, 16)
Print "f0e base 16 :"; SumDigits(&Hf0e, 16)
Print
Print "Press any key to quit the program"
Sleep |
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
| #Haskell | Haskell | versions :: [[Int] -> Int]
versions =
[ sum . fmap (^ 2) -- ver 1
, sum . ((^ 2) <$>) -- ver 2
, foldr ((+) . (^ 2)) 0 -- ver 3
]
main :: IO ()
main =
mapM_ print ((`fmap` [[3, 1, 4, 1, 5, 9], [1 .. 6], [], [1]]) <$> versions) |
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
| #BQN | BQN | ws ← @+⟨9, 10, 11, 12, 13, 32, 133, 160,
5760, 8192, 8193, 8194, 8195, 8196, 8197, 8198,
8199, 8200, 8201, 8202, 8232, 8233, 8239, 8287,
12288⟩
Lead ← (¬·∧`∊⟜ws)⊸/
Trail ← (¬·⌽·∧`·∊⟜ws⌽)⊸/
•Show Lead " fs df"
•Show Trail "fdsf asd "
•Show Lead∘Trail " white space " |
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
| #Bracmat | Bracmat | ( ( ltrim
= s
. @( !arg
: ?
( ( %@
: ~( " "
| \a
| \b
| \n
| \r
| \t
| \v
)
)
?
: ?s
)
)
& !s
)
& (rtrim=.rev$(ltrim$(rev$!arg)))
& (trim=.rev$(ltrim$(rev$(ltrim$!arg))))
& (string=" \a Hear
the sound?
\v
\r
")
& out$(str$("Input:[" !string "]"))
& out$(str$("ltrim:[" ltrim$!string "]"))
& out$(str$("rtrim:[" rtrim$!string "]"))
& out$(str$("trim :[" trim$!string "]"))
&
); |
http://rosettacode.org/wiki/Strong_and_weak_primes | Strong and weak primes |
Definitions (as per number theory)
The prime(p) is the pth prime.
prime(1) is 2
prime(4) is 7
A strong prime is when prime(p) is > [prime(p-1) + prime(p+1)] ÷ 2
A weak prime is when prime(p) is < [prime(p-1) + prime(p+1)] ÷ 2
Note that the definition for strong primes is different when used in the context of cryptography.
Task
Find and display (on one line) the first 36 strong primes.
Find and display the count of the strong primes below 1,000,000.
Find and display the count of the strong primes below 10,000,000.
Find and display (on one line) the first 37 weak primes.
Find and display the count of the weak primes below 1,000,000.
Find and display the count of the weak primes below 10,000,000.
(Optional) display the counts and "below numbers" with commas.
Show all output here.
Related Task
Safe primes and unsafe primes.
Also see
The OEIS article A051634: strong primes.
The OEIS article A051635: weak primes.
| #Julia | Julia | using Primes, Formatting
function parseprimelist()
primelist = primes(2, 10000019)
strongs = Vector{Int64}()
weaks = Vector{Int64}()
balanceds = Vector{Int64}()
for (n, p) in enumerate(primelist)
if n == 1 || n == length(primelist)
continue
end
x = (primelist[n - 1] + primelist[n + 1]) / 2
if x > p
push!(weaks, p)
elseif x < p
push!(strongs, p)
else
push!(balanceds, p)
end
end
println("The first 36 strong primes are: ", strongs[1:36])
println("There are ", format(sum(map(x -> x < 1000000, strongs)), commas=true), " stromg primes less than 1 million.")
println("There are ", format(length(strongs), commas=true), " strong primes less than 10 million.")
println("The first 37 weak primes are: ", weaks[1:37])
println("There are ", format(sum(map(x -> x < 1000000, weaks)), commas=true), " weak primes less than 1 million.")
println("There are ", format(length(weaks), commas=true), " weak primes less than 10 million.")
println("The first 28 balanced primes are: ", balanceds[1:28])
println("There are ", format(sum(map(x -> x < 1000000, balanceds)), commas=true), " balanced primes less than 1 million.")
println("There are ", format(length(balanceds), commas=true), " balanced primes less than 10 million.")
end
parseprimelist()
|
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.
| #Kotlin | Kotlin | private const val MAX = 10000000 + 1000
private val primes = BooleanArray(MAX)
fun main() {
sieve()
println("First 36 strong primes:")
displayStrongPrimes(36)
for (n in intArrayOf(1000000, 10000000)) {
System.out.printf("Number of strong primes below %,d = %,d%n", n, strongPrimesBelow(n))
}
println("First 37 weak primes:")
displayWeakPrimes(37)
for (n in intArrayOf(1000000, 10000000)) {
System.out.printf("Number of weak primes below %,d = %,d%n", n, weakPrimesBelow(n))
}
}
private fun weakPrimesBelow(maxPrime: Int): Int {
var priorPrime = 2
var currentPrime = 3
var count = 0
while (currentPrime < maxPrime) {
val nextPrime = getNextPrime(currentPrime)
if (currentPrime * 2 < priorPrime + nextPrime) {
count++
}
priorPrime = currentPrime
currentPrime = nextPrime
}
return count
}
private fun displayWeakPrimes(maxCount: Int) {
var priorPrime = 2
var currentPrime = 3
var count = 0
while (count < maxCount) {
val nextPrime = getNextPrime(currentPrime)
if (currentPrime * 2 < priorPrime + nextPrime) {
count++
print("$currentPrime ")
}
priorPrime = currentPrime
currentPrime = nextPrime
}
println()
}
private fun getNextPrime(currentPrime: Int): Int {
var nextPrime = currentPrime + 2
while (!primes[nextPrime]) {
nextPrime += 2
}
return nextPrime
}
private fun strongPrimesBelow(maxPrime: Int): Int {
var priorPrime = 2
var currentPrime = 3
var count = 0
while (currentPrime < maxPrime) {
val nextPrime = getNextPrime(currentPrime)
if (currentPrime * 2 > priorPrime + nextPrime) {
count++
}
priorPrime = currentPrime
currentPrime = nextPrime
}
return count
}
private fun displayStrongPrimes(maxCount: Int) {
var priorPrime = 2
var currentPrime = 3
var count = 0
while (count < maxCount) {
val nextPrime = getNextPrime(currentPrime)
if (currentPrime * 2 > priorPrime + nextPrime) {
count++
print("$currentPrime ")
}
priorPrime = currentPrime
currentPrime = nextPrime
}
println()
}
private fun sieve() { // primes
for (i in 2 until MAX) {
primes[i] = true
}
for (i in 2 until MAX) {
if (primes[i]) {
var j = 2 * i
while (j < MAX) {
primes[j] = false
j += i
}
}
}
} |
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
| #AWK | AWK | BEGIN {
str = "abcdefghijklmnopqrstuvwxyz"
n = 12
m = 5
print substr(str, n, m)
print substr(str, n)
print substr(str, 1, length(str) - 1)
print substr(str, index(str, "q"), m)
print substr(str, index(str, "pq"), m)
} |
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
| #Axe | Axe | Lbl SUB1
0→{r₁+r₂+r₃}
r₁+r₂
Return
Lbl SUB2
r₁+r₂
Return
Lbl SUB3
0→{r₁+length(r₁)-1}
r₁
Return
Lbl SUB4
inData(r₂,r₁)-1→I
0→{r₁+I+r₃}
r₁+I
Return |
http://rosettacode.org/wiki/Sudoku | Sudoku | Task
Solve a partially filled-in normal 9x9 Sudoku grid and display the result in a human-readable format.
references
Algorithmics of Sudoku may help implement this.
Python Sudoku Solver Computerphile video.
| #Clojure | Clojure | (ns rosettacode.sudoku
(:use [clojure.pprint :only (cl-format)]))
(defn- compatible? [m x y n]
(let [n= #(= n (get-in m [%1 %2]))]
(or (n= y x)
(let [c (count m)]
(and (zero? (get-in m [y x]))
(not-any? #(or (n= y %) (n= % x)) (range c))
(let [zx (* c (quot x c)), zy (* c (quot y c))]
(every? false?
(map n= (range zy (+ zy c)) (range zx (+ zx c))))))))))
(defn solve [m]
(let [c (count m)]
(loop [m m, x 0, y 0]
(if (= y c) m
(let [ng (->> (range 1 c)
(filter #(compatible? m x y %))
first
(assoc-in m [y x]))]
(if (= x (dec c))
(recur ng 0 (inc y))
(recur ng (inc x) y))))))) |
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
| #C.2B.2B | C++ |
#include <fstream>
#include <iostream>
#include <iterator>
#include <vector>
class subleq {
public:
void load_and_run( std::string file ) {
std::ifstream f( file.c_str(), std::ios_base::in );
std::istream_iterator<int> i_v, i_f( f );
std::copy( i_f, i_v, std::back_inserter( memory ) );
f.close();
run();
}
private:
void run() {
int pc = 0, next, a, b, c;
char z;
do {
next = pc + 3;
a = memory[pc]; b = memory[pc + 1]; c = memory[pc + 2];
if( a == -1 ) {
std::cin >> z; memory[b] = static_cast<int>( z );
} else if( b == -1 ) {
std::cout << static_cast<char>( memory[a] );
} else {
memory[b] -= memory[a];
if( memory[b] <= 0 ) next = c;
}
pc = next;
} while( pc >= 0 );
}
std::vector<int> memory;
};
int main( int argc, char* argv[] ) {
subleq s;
if( argc > 1 ) {
s.load_and_run( argv[1] );
} else {
std::cout << "usage: subleq <filename>\n";
}
return 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 | #jq | jq | # Emit a stream of consecutive primes.
# The stream is unbounded if . is null or infinite,
# otherwise it continues up to but excluding `.`.
def primes:
(if . == null then infinite else . end) as $n
| 2, (range(3; $n; 2) | select(is_prime));
# s is a stream
# $deltas is an array
# Output: a stream of arrays, each corresponding to a selection of consecutive
# items from s satisfying the differences requirement.
def filter_differences(s; $deltas):
def diffs_equal: # i.e. equal to $deltas
. as $in
| all( range(1;length);
($in[.] - $in[.-1]) == $deltas[. - 1]);
($deltas|length + 1) as $n
| foreach s as $x ( {};
.emit = null
| .tuple += [$x]
| .tuple |= .[-$n:]
| if (.tuple|length) == $n
then if (.tuple|diffs_equal) then .emit = .tuple
else .
end
else .
end;
select(.emit).emit );
def report_first_last_count(s):
null | {first,last,count}
| reduce s as $x (.;
if .first == null then .first = $x else . end
| .count = .count + 1
| .last = $x ) ;
|
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
| #COBOL | COBOL | identification division.
program-id. toptail.
data division.
working-storage section.
01 data-field.
05 value "[this is a test]".
procedure division.
sample-main.
display data-field
*> Using reference modification, which is (start-position:length)
display data-field(2:)
display data-field(1:length of data-field - 1)
display data-field(2:length of data-field - 2)
goback.
end program toptail. |
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.
| #jq | jq | # If $p is null, then call `subrand`,
# which sets .x as the PRN and which expects the the input to
# be the PRNG state, which is updated.
def subrandSeed($p):
def subrand:
if (.si == .sj) then subrandSeed(0) else . end
| .si |= (if . == 0 then 54 else . - 1 end)
| .sj |= (if . == 0 then 54 else . - 1 end)
| .mod as $mod
| .x = ((.state[.si] - .state[.sj]) | if . < 0 then . + $mod else . end)
| .state[.si] = .x ;
if $p == null then subrand
else
{mod: 1e9, state: [], si: 0, sj: 0, p: $p, p2: 1, j: 21}
| .state[0] = ($p % .mod)
| reduce range(1; 55) as $i (.;
if .j >= 55 then .j += -55 else . end
| .state[.j] = .p2
| .p2 = .p - .p2
| if .p2 < 0 then .p2 = .p2 + .mod else . end
| .p = .state[.j]
| .j += 21)
| .si = 0
| .sj = 24
| reduce range(1; 166) as $i (.; subrand)
end;
def subrand:
subrandSeed(null);
subrandSeed(292929)
| foreach range(0; 10) as $i (.;
subrand;
"r[\($i+220)] = \(.x)") |
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
| #REXX | REXX | /*REXX program implements & demonstrates a substitution cipher for the records in a file*/
parse arg fid.1 fid.2 fid.3 fid.4 . /*obtain optional arguments from the CL*/
if fid.1=='' then fid.1= "CIPHER.IN" /*Not specified? Then use the default.*/
if fid.2=='' then fid.2= "CIPHER.OUT" /* " " " " " " */
if fid.3=='' then fid.3= "CIPHER.KEY" /* " " " " " " */
if fid.4=='' then fid.4= "CIPHER.ORI" /* " " " " " " */
say ' input file: ' fid.1 /*display the fileID used for input. */
say ' output file: ' fid.2 /* " " " " " output. */
say ' cipher file: ' fid.3 /* " " " " " cipher-key*/
say 'decrypted file: ' fid.4 /* " " " " " decrypted*/
call closer /*close all files in case they're open.*/
do c=1 while lines(fid.3)\==0 /*read (hopefully 2 records) from key. */
@.c= space( linein(fid.3), 0) /*assign input record to an @. array.*/
end /*c*/
c= c - 1 /*adjust the number of records (for DO)*/
if c==0 then call ser fid.3, 'not found or is empty.'
if c>2 then call ser fid.3, 'has too many records (>2).'
if c<2 then call ser fid.3, 'has too few records (<2).'
if length(@.1)\==length(@.2) then call ser fid.3, 'has unequal length records.'
call encrypt fid.1, fid.2 /*encrypt the input file ───► output.*/
[email protected]; @[email protected]; @.2=_ /*switch the cipher keys for decryption*/
call encrypt fid.2, fid.4 /*decrypt the output file ───► decrypt.*/
call show 'cipher file ('fid.3")" , fid.3 /*display the cipher─key file. */
call show 'input file ('fid.1")" , fid.1 /* " " input " */
call show 'output file ('fid.2")" , fid.2 /* " " output " */
call show ' decrypted file ('fid.4")" , fid.4 /* " " decrypted " */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
closer: do f=1 for 4; call lineout fid.f; end /*f*/; say; return
ser: say '***error!*** file ' arg(1)" " arg(2); exit
show: say; say center( arg(1), 79, '═'); "TYPE" arg(2); return
/*──────────────────────────────────────────────────────────────────────────────────────*/
encrypt: parse arg @in,@out /* [↓] effectively deletes @out file by*/
call lineout @out,,1 /*setting pointer to rec#1 for the file*/
do j=0 while lines(@in)\==0 /*read the input file*/
call lineout @out, translate( linein(@in), @.2, @.1)
end /*j*/
if j==0 then call ser @in, 'is empty.' /*was the file not found or was empty? */
say @in ' records processed: ' j /*show the number of records processed.*/
call closer /*close all the files to be neat & safe*/
return |
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.
| #FALSE | FALSE | 1 2 3 4 5 {input "array"}
5 {length of input}
0s: {sum}
1p: {product}
[$0=~][1-\$s;+s:p;*p:]#%
"Sum: "s;."
Product: "p;. |
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.
| #Fantom | Fantom |
class Main
{
public static Void main ()
{
Int[] array := (1..20).toList
// you can use a loop
Int sum := 0
array.each |Int n| { sum += n }
echo ("Sum of array is : $sum")
Int product := 1
array.each |Int n| { product *= n }
echo ("Product of array is : $product")
// or use 'reduce'
// 'reduce' takes a function,
// the first argument is the accumulated value
// and the second is the next item in the list
sum = array.reduce(0) |Obj r, Int v -> Obj|
{
return (Int)r + v
}
echo ("Sum of array : $sum")
product = array.reduce(1) |Obj r, Int v -> Obj|
{
return (Int)r * v
}
echo ("Product of array : $product")
}
}
|
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.
| #Elena | Elena | import system'routines;
import extensions;
public program()
{
var sum := new Range(1, 1000).selectBy:(x => 1.0r / (x * x)).summarize(new Real());
console.printLine:sum
} |
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
| #AWK | AWK | #!/usr/local/bin/awk -f
{
sub("[ \t]*[#;].*$","",$0);
print;
} |
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
| #ANSI_BASIC | ANSI BASIC | 100 DECLARE EXTERNAL FUNCTION FNstripcomment$
110 LET marker$="#;"
120 PRINT """";FNstripcomment$("apples, pears # and bananas", marker$);""""
130 PRINT """";FNstripcomment$("apples, pears ; and bananas", marker$);""""
140 PRINT """";FNstripcomment$(" apples, pears ", marker$);""""
150 END
160 !
170 EXTERNAL FUNCTION FNstripcomment$(text$, delim$)
180 FOR I=1 TO LEN(delim$)
190 LET D = POS(text$, delim$(I:I))
200 IF D>0 THEN LET text$ = text$(1:D-1)
210 NEXT I
220 LET FNstripcomment$=RTRIM$(text$)
230 END FUNCTION |
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
| #D | D | import std.algorithm, std.regex;
string[2] separateComments(in string txt,
in string cpat0, in string cpat1) {
int[2] plen; // to handle /*/
int i, j; // cursors
bool inside; // is inside comment?
// pre-compute regex here if desired
//auto r0 = regex(cpat0);
//auto r1 = regex(cpat1);
//enum rct = ctRegex!(r"\n|\r");
bool advCursor() {
auto mo = match(txt[i .. $], inside ? cpat1 : cpat0);
if (mo.empty)
return false;
plen[inside] = max(0, plen[inside], mo.front[0].length);
j = i + mo.pre.length; // got comment head
if (inside)
j += mo.front[0].length; // or comment tail
// special adjust for \n\r
if (!match(mo.front[0], r"\n|\r").empty)
j--;
return true;
}
string[2] result;
while (true) {
if (!advCursor())
break;
result[inside] ~= txt[i .. j]; // save slice of result
// handle /*/ pattern
if (inside && (j - i < plen[0] + plen[1])) {
i = j;
if (!advCursor())
break;
result[inside] ~= txt[i .. j]; // save result again
}
i = j; // advance cursor
inside = !inside; // toggle search type
}
if (inside)
throw new Exception("Mismatched Comment");
result[inside] ~= txt[i .. $]; // save rest(non-comment)
return result;
}
void main() {
import std.stdio;
static void showResults(in string e, in string[2] pair) {
writeln("===Original text:\n", e);
writeln("\n\n===Text without comments:\n", pair[0]);
writeln("\n\n===The stripped comments:\n", pair[1]);
}
// First example ------------------------------
immutable ex1 = ` /**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*/
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
/**
* Another comment.
*/
function something() {
}`;
showResults(ex1, separateComments(ex1, `/\*`, `\*/`));
// Second example ------------------------------
writeln("\n");
immutable ex2 = "apples, pears # and bananas
apples, pears; and bananas "; // test for line comment
showResults(ex2, separateComments(ex2, `#|;`, `[\n\r]|$`));
} |
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).
| #Perl | Perl | #!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };
my $string = '123456789';
my $length = length $string;
my @possible_ops = ("" , '+', '-');
{
my @ops;
sub Next {
return @ops = (0) x ($length) unless @ops;
my $i = 0;
while ($i < $length) {
if ($ops[$i]++ > $#possible_ops - 1) {
$ops[$i++] = 0;
next
}
# + before the first number
next if 0 == $i && '+' eq $possible_ops[ $ops[0] ];
return @ops
}
return
}
}
sub evaluate {
my ($expression) = @_;
my $sum;
$sum += $_ for $expression =~ /([-+]?[0-9]+)/g;
return $sum
}
my %count = ( my $max_count = 0 => 0 );
say 'Show all solutions that sum to 100';
while (my @ops = Next()) {
my $expression = "";
for my $i (0 .. $length - 1) {
$expression .= $possible_ops[ $ops[$i] ];
$expression .= substr $string, $i, 1;
}
my $sum = evaluate($expression);
++$count{$sum};
$max_count = $sum if $count{$sum} > $count{$max_count};
say $expression if 100 == $sum;
}
say 'Show the sum that has the maximum number of solutions';
say "sum: $max_count; solutions: $count{$max_count}";
my $n = 1;
++$n until ! exists $count{$n};
say "Show the lowest positive sum that can't be expressed";
say $n;
say 'Show the ten highest numbers that can be expressed';
say for (sort { $b <=> $a } keys %count)[0 .. 9]; |
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
| #APL | APL | 'She was a soul stripper. She took my heart!' ~ 'aei' |
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
| #AppleScript | AppleScript | stripChar("She was a soul stripper. She took my heart!", "aei")
on stripChar(str, chrs)
tell AppleScript
set oldTIDs to text item delimiters
set text item delimiters to characters of chrs
set TIs to text items of str
set text item delimiters to ""
set str to TIs as string
set text item delimiters to oldTIDs
end tell
return str
end stripChar |
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.
| #Bracmat | Bracmat | World!:?string
& str$("Hello " !string):?string
& out$!string |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.