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/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
| #Icon_and_Unicon | Icon and Unicon | procedure main(a)
write(dsum(a[1]|1234,a[2]|10))
end
procedure dsum(n,b)
n := integer((\b|10)||"r"||n)
sum := 0
while sum +:= (0 < n) % b do n /:= b
return sum
end |
http://rosettacode.org/wiki/Sum_of_squares | Sum of squares | Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| #K | K |
ss: {+/x*x}
ss 1 2 3 4 5
55
ss@!0
0
|
http://rosettacode.org/wiki/Sum_of_squares | Sum of squares | Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| #Kotlin | Kotlin | import kotlin.random.Random
import kotlin.system.measureTimeMillis
import kotlin.time.milliseconds
enum class Summer {
MAPPING {
override fun sum(values: DoubleArray) = values.map {it * it}.sum()
},
SEQUENCING {
override fun sum(values: DoubleArray) = values.asSequence().map {it * it}.sum()
},
FOLDING {
override fun sum(values: DoubleArray) = values.fold(0.0) {acc, it -> acc + it * it}
},
FOR_LOOP {
override fun sum(values: DoubleArray): Double {
var sum = 0.0
values.forEach { sum += it * it }
return sum
}
},
;
abstract fun sum(values: DoubleArray): Double
}
fun main() {
run {
val testArrays = listOf(
doubleArrayOf(),
doubleArrayOf(Random.nextInt(100) / 10.0),
DoubleArray(6) { Random.nextInt(100) / 10.0 },
)
for (impl in Summer.values()) {
println("Test with ${impl.name}:")
for (v in testArrays) println(" ${v.contentToString()} -> ${impl.sum(v)}")
}
}
run {
val elements = 100_000
val longArray = DoubleArray(elements) { Random.nextDouble(10.0) }
for (impl in Summer.values()) {
val time = measureTimeMillis {
impl.sum(longArray)
}.milliseconds
println("Summing $elements with ${impl.name} takes: $time")
}
var acc = 0.0
for (v in longArray) acc += v
}
} |
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
| #DWScript | DWScript | const TEST_STRING = ' String with spaces ';
PrintLn('"' + TEST_STRING + '"');
PrintLn('"' + TrimLeft(TEST_STRING) + '"');
PrintLn('"' + TrimRight(TEST_STRING) + '"');
PrintLn('"' + Trim(TEST_STRING) + '"'); |
http://rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail | Strip whitespace from a string/Top and tail | Task
Demonstrate how to strip leading and trailing whitespace from a string.
The solution should demonstrate how to achieve the following three results:
String with leading whitespace removed
String with trailing whitespace removed
String with both leading and trailing whitespace removed
For the purposes of this task whitespace includes non printable characters such as the space character, the tab character, and other such characters that have no corresponding graphical representation.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #EchoLisp | EchoLisp |
(define witt
" The limits of my world are the limits of my langage. ")
(string->html (string-trim witt))
→ "The limits of my world are the limits of my langage."
(string->html (string-trim-left witt))
→ "The limits of my world are the limits of my langage. "
(string->html (string-trim-right witt))
→ " The limits of my world are the limits of my langage."
|
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.
| #PureBasic | PureBasic | #MAX=10000000+20
Global Dim P.b(#MAX) : FillMemory(@P(),#MAX,1,#PB_Byte)
Global NewList Primes.i()
Global NewList Strong.i()
Global NewList Weak.i()
For n=2 To Sqr(#MAX)+1 : If P(n) : m=n*n : While m<=#MAX : P(m)=0 : m+n : Wend : EndIf : Next
For i=2 To #MAX : If p(i) : AddElement(Primes()) : Primes()=i : EndIf : Next
If FirstElement(Primes())
pp=Primes()
While NextElement(Primes())
ap=Primes()
If NextElement(Primes()) : np=Primes() : Else : Break : EndIf
If ap>(pp+np)/2.0 : AddElement(Strong()) : Strong()=ap : If ap<1000000 : c1+1 : EndIf : EndIf
If ap<(pp+np)/2.0 : AddElement(Weak()) : Weak()=ap : If ap<1000000 : c2+1 : EndIf : EndIf
PreviousElement(Primes()) : pp=Primes()
Wend
EndIf
OpenConsole()
If FirstElement(Strong())
PrintN("First 36 strong primes:")
Print(Str(Strong())+" ")
For i=2 To 36 : If NextElement(Strong()) : Print(Str(Strong())+" ") : Else : Break : EndIf : Next
PrintN("")
EndIf
PrintN("Number of strong primes below 1'000'000 = "+FormatNumber(c1,0,".","'"))
PrintN("Number of strong primes below 10'000'000 = "+FormatNumber(ListSize(Strong()),0,".","'"))
If FirstElement(Weak())
PrintN("First 37 weak primes:")
Print(Str(Weak())+" ")
For i=2 To 37 : If NextElement(Weak()) : Print(Str(Weak())+" ") : Else : Break : EndIf : Next
PrintN("")
EndIf
PrintN("Number of weak primes below 1'000'000 = "+FormatNumber(c2,0,".","'"))
PrintN("Number of weak primes below 10'000'000 = "+FormatNumber(ListSize(Weak()),0,".","'"))
Input() |
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
| #Clojure | Clojure |
(def string "alphabet")
(def n 2)
(def m 4)
(def len (count string))
;starting from n characters in and of m length;
(println
(subs string n (+ n m))) ;phab
;starting from n characters in, up to the end of the string;
(println
(subs string n)) ;phabet
;whole string minus last character;
(println
(subs string 0 (dec len))) ;alphabe
;starting from a known character within the string and of m length;
(let [pos (.indexOf string (int \l))]
(println
(subs string pos (+ pos m)))) ;lpha
;starting from a known substring within the string and of m length.
(let [pos (.indexOf string "ph")]
(println
(subs string pos (+ pos m)))) ;phab
|
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.
| #EasyLang | EasyLang | len row[] 810
len col[] 810
len box[] 810
len grid[] 82
#
func init . .
for pos range 81
if pos mod 9 = 0
s$[] = strsplit input " "
.
dig = number s$[pos mod 9]
grid[pos] = dig
r = pos div 9
c = pos mod 9
b = r div 3 * 3 + c div 3
row[r * 10 + dig] = 1
col[c * 10 + dig] = 1
box[b * 10 + dig] = 1
.
.
call init
#
func display . .
for i range 81
write grid[i] & " "
if i mod 3 = 2
write " "
.
if i mod 9 = 8
print ""
.
if i mod 27 = 26
print ""
.
.
.
#
func solve pos . .
while grid[pos] <> 0
pos += 1
.
if pos = 81
# solved
call display
break 1
.
r = pos div 9
c = pos mod 9
b = r div 3 * 3 + c div 3
r *= 10
c *= 10
b *= 10
for d = 1 to 9
if row[r + d] = 0 and col[c + d] = 0 and box[b + d] = 0
grid[pos] = d
row[r + d] = 1
col[c + d] = 1
box[b + d] = 1
call solve pos + 1
row[r + d] = 0
col[c + d] = 0
box[b + d] = 0
.
.
grid[pos] = 0
.
call solve 0
#
input_data
5 3 0 0 2 4 7 0 0
0 0 2 0 0 0 8 0 0
1 0 0 7 0 3 9 0 2
0 0 8 0 7 2 0 4 9
0 2 0 9 8 0 0 7 0
7 9 0 0 0 0 0 8 0
0 0 0 0 3 0 5 0 6
9 6 0 0 1 0 3 0 0
0 5 0 6 9 0 0 1 0 |
http://rosettacode.org/wiki/Subleq | Subleq | Subleq is an example of a One-Instruction Set Computer (OISC).
It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero.
Task
Your task is to create an interpreter which emulates a SUBLEQ machine.
The machine's memory consists of an array of signed integers. These integers may be interpreted in three ways:
simple numeric values
memory addresses
characters for input or output
Any reasonable word size that accommodates all three of the above uses is fine.
The program should load the initial contents of the emulated machine's memory, set the instruction pointer to the first address (which is defined to be address 0), and begin emulating the machine, which works as follows:
Let A be the value in the memory location identified by the instruction pointer; let B and C be the values stored in the next two consecutive addresses in memory.
Advance the instruction pointer three words, to point at the address after the address containing C.
If A is -1 (negative unity), then a character is read from the machine's input and its numeric value stored in the address given by B. C is unused.
If B is -1 (negative unity), then the number contained in the address given by A is interpreted as a character and written to the machine's output. C is unused.
Otherwise, both A and B are treated as addresses. The number contained in address A is subtracted from the number in address B (and the difference left in address B). If the result is positive, execution continues uninterrupted; if the result is zero or negative, the number in C becomes the new instruction pointer.
If the instruction pointer becomes negative, execution halts.
Your solution may initialize the emulated machine's memory in any convenient manner, but if you accept it as input, it should be a separate input stream from the one fed to the emulated machine once it is running. And if fed as text input, it should be in the form of raw subleq "machine code" - whitespace-separated decimal numbers, with no symbolic names or other assembly-level extensions, to be loaded into memory starting at address 0 (zero).
For purposes of this task, show the output of your solution when fed the below "Hello, world!" program.
As written, this example assumes ASCII or a superset of it, such as any of the Latin-N character sets or Unicode; you may translate the numbers representing characters (starting with 72=ASCII 'H') into another character set if your implementation runs in a non-ASCII-compatible environment. If 0 is not an appropriate terminator in your character set, the program logic will need some adjustment as well.
15 17 -1 17 -1 -1 16 1 -1 16 3 -1 15 15 0 0 -1 72 101 108 108 111 44 32 119 111 114 108 100 33 10 0
The above "machine code" corresponds to something like this in a hypothetical assembler language for a signed 8-bit version of the machine:
start:
0f 11 ff subleq (zero), (message), -1
11 ff ff subleq (message), -1, -1 ; output character at message
10 01 ff subleq (neg1), (start+1), -1
10 03 ff subleq (neg1), (start+3), -1
0f 0f 00 subleq (zero), (zero), start
; useful constants
zero:
00 .data 0
neg1:
ff .data -1
; the message to print
message: .data "Hello, world!\n\0"
48 65 6c 6c 6f 2c 20 77 6f 72 6c 64 21 0a 00
| #Fortran | Fortran |
PROGRAM SUBLEQ0 !Simulates a One-Instruction computer, with Subtract and Branch if <= 0.
INTEGER LOTS,LOAD !Document some bounds.
PARAMETER (LOTS = 36, LOAD = 31) !Sufficient for the example.
INTEGER IAR, MEM(0:LOTS) !The basic storage of a computer. IAR could be in memory too.
INTEGER ABC(3),A,B,C !A hardware register. Could use INTEGER*1 for everything...
EQUIVALENCE (ABC(1),A),(ABC(2),B),(ABC(3),C) !It has components.
INTEGER INITIAL(0:LOAD) !There is no sign of a bootstrap loader sequence!
DATA INITIAL/15,17,-1,17,-1,-1,16,1,-1,16,3,-1,15,15,0,0,-1, !These are operations, it so happens.
1 72,101,108,108,111,44,32,119,111,114,108,100,33,10,0/ !And these happen to be ASCII character code numbers.
Core memory initialisation.
MEM = -66 !Accessing uninitialised memory is improper. This might cause hiccoughs..
MEM(0:LOAD) = INITIAL !No bootstrap!
IAR = 0 !The Instruction Address Register starts at the start.
Commence execution of the current instruction.
100 ABC = MEM(IAR:IAR + 2) !Load the three-word instruction.
IAR = IAR + 3 !Advance IAR accordingly.
IF (A .EQ. -1) THEN !Decode the instruction as per the design.
WRITE (6,102) !Supply a prompt, otherwise, obscurity results.
102 FORMAT (" A number:",$) !But, that will make a mess of the layout.
READ (5,*) MEM(B) !The specified action is to read as a number.
ELSE IF (B .EQ. -1) THEN !This is for output.
WRITE (6,103) CHAR(MEM(A)) !As specified, interpret a number as a character.
103 FORMAT (A1,$) !The $, obviously, states: do not end the line and start the next.
ELSE !And this is a two-part action.
MEM(B) = MEM(B) - MEM(A) !Perform arithmetic.
IF (MEM(B).LE.0) IAR = C !And based on the result, maybe a GO TO.
END IF !So much for decoding.
IF (IAR.GE.0) GO TO 100 !Keep at it.
END !That was simple.
|
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 | #Phix | Phix | with javascript_semantics
constant primes = get_primes_le(1_000_000)
procedure test(sequence differences)
sequence res = {}
integer ld = length(differences)
for i=1 to length(primes)-ld do
integer pi = primes[i]
for j=1 to ld do
pi += differences[j]
if pi!=primes[i+j] then
pi = 0
exit
end if
end for
if pi!=0 then
res = append(res,primes[i..i+ld])
end if
end for
res = {differences,length(res),res[1],res[$]}
printf(1,"%8V : %8d %14V...%V\n",res)
end procedure
printf(1,"Differences Count First Last\n")
papply({{2},{1},{2,2},{2,4},{4,2},{6,4,2}},test)
|
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
| #Euphoria | Euphoria | function strip_first(sequence s)
return s[2..$]
end function
function strip_last(sequence s)
return s[1..$-1]
end function
function strip_both(sequence s)
return s[2..$-1]
end function
puts(1, strip_first("knight")) -- strip first character
puts(1, strip_last("write")) -- strip last character
puts(1, strip_both("brooms")) -- strip both first and last characters |
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.
| #PARI.2FGP | PARI/GP | sgv=vector(55,i,random(10^9));sgi=1;
sg()=sgv[sgi=sgi%55+1]=(sgv[sgi]-sgv[(sgi+30)%55+1])%10^9 |
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.
| #Perl | Perl | use 5.10.0;
use strict;
{ # bracket state data into a lexical scope
my @state;
my $mod = 1_000_000_000;
sub bentley_clever {
my @s = ( shift() % $mod, 1);
push @s, ($s[-2] - $s[-1]) % $mod while @s < 55;
@state = map($s[(34 + 34 * $_) % 55], 0 .. 54);
subrand() for (55 .. 219);
}
sub subrand()
{
bentley_clever(0) unless @state; # just incase
my $x = (shift(@state) - $state[-24]) % $mod;
push @state, $x;
$x;
}
}
bentley_clever(292929);
say subrand() for (1 .. 10); |
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.
| #GAP | GAP | v := [1 .. 8];
Sum(v);
# 36
Product(v);
# 40320
# You can sum or multiply the result of a function
Sum(v, n -> n^2);
# 204
Product(v, n -> 1/n);
# 1/40320 |
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.
| #GFA_Basic | GFA Basic |
DIM a%(10)
' put some values into the array
FOR i%=1 TO 10
a%(i%)=i%
NEXT i%
'
sum%=0
product%=1
FOR i%=1 TO 10
sum%=sum%+a%(i%)
product%=product%*a%(i%)
NEXT i%
'
PRINT "Sum is ";sum%
PRINT "Product is ";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.
| #Ezhil | Ezhil |
## இந்த நிரல் தொடர் கூட்டல் (Sum Of Series) என்ற வகையைச் சேர்ந்தது
## இந்த நிரல் ஒன்று முதல் தரப்பட்ட எண் வரை 1/(எண் * எண்) எனக் கணக்கிட்டுக் கூட்டி விடை தரும்
நிரல்பாகம் தொடர்க்கூட்டல்(எண்1)
எண்2 = 0
@(எண்3 = 1, எண்3 <= எண்1, எண்3 = எண்3 + 1) ஆக
## ஒவ்வோர் எண்ணின் வர்க்கத்தைக் கணக்கிட்டு, ஒன்றை அதனால் வகுத்துக் கூட்டுகிறோம்
எண்2 = எண்2 + (1 / (எண்3 * எண்3))
முடி
பின்கொடு (எண்2)
முடி
அ = int(உள்ளீடு("ஓர் எண்ணைச் சொல்லுங்கள்: "))
பதிப்பி "நீங்கள் தந்த எண் " அ
பதிப்பி "அதன் தொடர்க் கூட்டல் " தொடர்க்கூட்டல்(அ)
|
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
| #Erlang | Erlang |
-module( strip_comments_from_string ).
-export( [task/0] ).
task() ->
io:fwrite( "~s~n", [keep_until_comment("apples, pears and bananas")] ),
io:fwrite( "~s~n", [keep_until_comment("apples, pears # and bananas")] ),
io:fwrite( "~s~n", [keep_until_comment("apples, pears ; and bananas")] ).
keep_until_comment( String ) -> lists:takewhile( fun not_comment/1, String ).
not_comment( $# ) -> false;
not_comment( $; ) -> false;
not_comment( _ ) -> true.
|
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
| #F.23 | F# | let stripComments s =
s
|> Seq.takeWhile (fun c -> c <> '#' && c <> ';')
|> Seq.map System.Char.ToString
|> Seq.fold (+) "" |
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
| #Groovy | Groovy | def code = """
/**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*/
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
/**
* Another comment.
*/
function something() {
}
"""
println ((code =~ "(?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/)|(?://.*)").replaceAll('')) |
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
| #Haskell | Haskell | test = "This {- is not the beginning of a block comment" -- Do your homework properly -} |
http://rosettacode.org/wiki/String_interpolation_(included) | String interpolation (included) |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Given a string and defined variables or values, string interpolation is the replacement of defined character sequences in the string by values or variable values.
For example, given an original string of "Mary had a X lamb.", a value of "big", and if the language replaces X in its interpolation routine, then the result of its interpolation would be the string "Mary had a big lamb".
(Languages usually include an infrequently used character or sequence of characters to indicate what is to be replaced such as "%", or "#" rather than "X").
Task
Use your languages inbuilt string interpolation abilities to interpolate a string missing the text "little" which is held in a variable, to produce the output string "Mary had a little lamb".
If possible, give links to further documentation on your languages string interpolation features.
Note: The task is not to create a string interpolation routine, but to show a language's built-in capability.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #APL | APL |
s ← 'Mary had a ∆ lamb' ⋄ s[s⍳'∆'] ← ⊂'little' ⋄ s ← ∊s
s
Mary had a little lamb
⍝⍝⍝ Or, for a more general version which interpolates multiple positional arguments and can
⍝⍝⍝ handle both string and numeric types...
∇r ← s sInterp sv
⍝⍝ Interpolate items in sv into s (string field substitution)
⍝ s: string - format string, '∆' used for interpolation points
⍝ sv: vector - vector of items to interpolate into s
⍝ r: interpolated string
s[('∆'=s)/⍳⍴s] ← ⊃¨(⍕¨sv)
r ← ∊s
∇
'Mary had a ∆ lamb, its fleece was ∆ as ∆.' sInterp 'little' 'black' 'night'
Mary had a little lamb, its fleece was black as night.
'Mary had a ∆ lamb, its fleece was ∆ as ∆.' sInterp 'little' 'large' 42
Mary had a little lamb, its fleece was large as 42.
|
http://rosettacode.org/wiki/String_interpolation_(included) | String interpolation (included) |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Given a string and defined variables or values, string interpolation is the replacement of defined character sequences in the string by values or variable values.
For example, given an original string of "Mary had a X lamb.", a value of "big", and if the language replaces X in its interpolation routine, then the result of its interpolation would be the string "Mary had a big lamb".
(Languages usually include an infrequently used character or sequence of characters to indicate what is to be replaced such as "%", or "#" rather than "X").
Task
Use your languages inbuilt string interpolation abilities to interpolate a string missing the text "little" which is held in a variable, to produce the output string "Mary had a little lamb".
If possible, give links to further documentation on your languages string interpolation features.
Note: The task is not to create a string interpolation routine, but to show a language's built-in capability.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Arturo | Arturo | sizeOfLamb: "little"
print ~"Mary had a |sizeOfLamb| lamb." |
http://rosettacode.org/wiki/Sum_to_100 | Sum to 100 | Task
Find solutions to the sum to one hundred puzzle.
Add (insert) the mathematical
operators + or - (plus
or minus) before any of the digits in the
decimal numeric string 123456789 such that the
resulting mathematical expression adds up to a
particular sum (in this iconic case, 100).
Example:
123 + 4 - 5 + 67 - 89 = 100
Show all output here.
Show all solutions that sum to 100
Show the sum that has the maximum number of solutions (from zero to infinity‡)
Show the lowest positive sum that can't be expressed (has no solutions), using the rules for this task
Show the ten highest numbers that can be expressed using the rules for this task (extra credit)
‡ (where infinity would be a relatively small 123,456,789)
An example of a sum that can't be expressed (within the rules of this task) is: 5074
(which, of course, isn't the lowest positive sum that can't be expressed).
| #Raku | Raku | my $sum = 100;
my $N = 10;
my @ops = ['-', ''], |( [' + ', ' - ', ''] xx 8 );
my @str = [X~] map { .Slip }, ( @ops Z 1..9 );
my %sol = @str.classify: *.subst( ' - ', ' -', :g )\
.subst( ' + ', ' ', :g ).words.sum;
my %count.push: %sol.map({ .value.elems => .key });
my $max-solutions = %count.max( + *.key );
my $first-unsolvable = first { %sol{$_} :!exists }, 1..*;
sub n-largest-sums (Int $n) { %sol.sort(-*.key)[^$n].fmt: "%8s => %s\n" }
given %sol{$sum}:p {
say "{.value.elems} solutions for sum {.key}:";
say " $_" for .value.list;
}
.say for :$max-solutions, :$first-unsolvable, "$N largest sums:", n-largest-sums($N); |
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
| #BCPL | BCPL | get "libhdr"
let contains(str, chr) = valof
$( for i = 1 to str%0
if str%i = chr resultis true
resultis false
$)
let stripchars(str, chars, buf) = valof
$( buf%0 := 0
for i = 1 to str%0
if ~contains(chars, str%i)
$( buf%0 := buf%0 + 1
buf%(buf%0) := str%i
$)
resultis buf
$)
let start() be
$( let buf = vec 127
writef("%S*N",
stripchars("She was a soul stripper. She took my heart!",
"aei",
buf))
$) |
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
| #BQN | BQN | StripChars ← (¬∘∊/⊣)
¬∘∊/⊣
"She was a soul stripper. She took my heart!" StripChars "aei"
"Sh ws soul strppr. Sh took my hrt!" |
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.
| #Elixir | Elixir |
str1 = "World!"
str = "Hello, " <> str1
|
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.
| #Emacs_Lisp | Emacs Lisp | (defvar str "bar")
(setq str (concat "foo" str))
str ;=> "foobar" |
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.
| #Erlang | Erlang | 1> S = "world".
"world"
2> "Hello " ++ S.
"Hello world"
|
http://rosettacode.org/wiki/String_comparison | String comparison |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Demonstrate how to compare two strings from within the language and how to achieve a lexical comparison.
The task should demonstrate:
Comparing two strings for exact equality
Comparing two strings for inequality (i.e., the inverse of exact equality)
Comparing two strings to see if one is lexically ordered before than the other
Comparing two strings to see if one is lexically ordered after than the other
How to achieve both case sensitive comparisons and case insensitive comparisons within the language
How the language handles comparison of numeric strings if these are not treated lexically
Demonstrate any other kinds of string comparisons that the language provides, particularly as it relates to your type system.
For example, you might demonstrate the difference between generic/polymorphic comparison and coercive/allomorphic comparison if your language supports such a distinction.
Here "generic/polymorphic" comparison means that the function or operator you're using doesn't always do string comparison, but bends the actual semantics of the comparison depending on the types one or both arguments; with such an operator, you achieve string comparison only if the arguments are sufficiently string-like in type or appearance.
In contrast, a "coercive/allomorphic" comparison function or operator has fixed string-comparison semantics regardless of the argument type; instead of the operator bending, it's the arguments that are forced to bend instead and behave like strings if they can, and the operator simply fails if the arguments cannot be viewed somehow as strings. A language may have one or both of these kinds of operators; see the Raku entry for an example of a language with both kinds of operators.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program comparString.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/* Initialized data */
.data
szMessStringEqu: .asciz "The strings are equals.\n"
szMessStringNotEqu: .asciz "The strings are not equals.\n"
szCarriageReturn: .asciz "\n"
szString1: .asciz "ABCDE"
szString2: .asciz "ABCDE"
szString3: .asciz "ABCFG"
szString4: .asciz "ABC"
szString5: .asciz "abcde"
/* UnInitialized data */
.bss
/* code section */
.text
.global main
main: /* entry of program */
push {fp,lr} /* saves 2 registers */
ldr r0,iAdrszString1
ldr r1,iAdrszString2
bl Comparaison
ldr r0,iAdrszString1
ldr r1,iAdrszString3
bl Comparaison
ldr r0,iAdrszString1
ldr r1,iAdrszString4
bl Comparaison
@ case sensitive comparisons ABCDE et abcde
ldr r0,iAdrszString1
ldr r1,iAdrszString5
bl Comparaison
@ case insensitive comparisons ABCDE et abcde
ldr r0,iAdrszString1
ldr r1,iAdrszString5
bl comparStringsInsensitive
cmp r0,#0
bne 1f
ldr r0,iAdrszMessStringEqu
bl affichageMess
b 2f
1:
ldr r0,iAdrszMessStringNotEqu
bl affichageMess
2:
100: /* standard end of the program */
mov r0, #0 @ return code
pop {fp,lr} @restaur 2 registers
mov r7, #EXIT @ request to exit program
swi 0 @ perform the system call
iAdrszString1: .int szString1
iAdrszString2: .int szString2
iAdrszString3: .int szString3
iAdrszString4: .int szString4
iAdrszString5: .int szString5
iAdrszMessStringEqu: .int szMessStringEqu
iAdrszMessStringNotEqu: .int szMessStringNotEqu
iAdrszCarriageReturn: .int szCarriageReturn
/*********************************************/
/* comparaison */
/*********************************************/
/* r0 contains address String 1 */
/* r1 contains address String 2 */
Comparaison:
push {fp,lr} /* save registres */
bl comparStrings
cmp r0,#0
bne 1f
ldr r0,iAdrszMessStringEqu
bl affichageMess
b 2f
1:
ldr r0,iAdrszMessStringNotEqu
bl affichageMess
2:
pop {fp,lr} /* restaur des 2 registres */
bx lr /* return */
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {fp,lr} /* save registres */
push {r0,r1,r2,r7} /* save others registers */
mov r2,#0 /* counter length */
1: /* loop length calculation */
ldrb r1,[r0,r2] /* read octet start position + index */
cmp r1,#0 /* if 0 its over */
addne r2,r2,#1 /* else add 1 in the length */
bne 1b /* and loop */
/* so here r2 contains the length of the message */
mov r1,r0 /* address message in r1 */
mov r0,#STDOUT /* code to write to the standard output Linux */
mov r7, #WRITE /* code call system "write" */
swi #0 /* call systeme */
pop {r0,r1,r2,r7} /* restaur others registers */
pop {fp,lr} /* restaur des 2 registres */
bx lr /* return */
/************************************/
/* Strings case sensitive comparisons */
/************************************/
/* r0 et r1 contains the address of strings */
/* return 0 in r0 if equals */
/* return -1 if string r0 < string r1 */
/* return 1 if string r0 > string r1 */
comparStrings:
push {r1-r4} /* save des registres */
mov r2,#0 /* counter */
1:
ldrb r3,[r0,r2] /* byte string 1 */
ldrb r4,[r1,r2] /* byte string 2 */
cmp r3,r4
movlt r0,#-1 /* small */
movgt r0,#1 /* greather */
bne 100f /* not equals */
cmp r3,#0 /* 0 end string */
moveq r0,#0 /* equals */
beq 100f /* end string */
add r2,r2,#1 /* else add 1 in counter */
b 1b /* and loop */
100:
pop {r1-r4}
bx lr
/************************************/
/* Strings case insensitive comparisons */
/************************************/
/* r0 et r1 contains the address of strings */
/* return 0 in r0 if equals */
/* return -1 if string r0 < string r1 */
/* return 1 if string r0 > string r1 */
comparStringsInsensitive:
push {r1-r4} /* save des registres */
mov r2,#0 /* counter */
1:
ldrb r3,[r0,r2] /* byte string 1 */
ldrb r4,[r1,r2] /* byte string 2 */
@ majuscules --> minuscules byte 1
cmp r3,#65
blt 2f
cmp r3,#90
bgt 2f
add r3,#32
2: @ majuscules --> minuscules byte 2
cmp r4,#65
blt 3f
cmp r4,#90
bgt 3f
add r4,#32
3:
cmp r3,r4
movlt r0,#-1 /* small */
movgt r0,#1 /* greather */
bne 100f /* not equals */
cmp r3,#0 /* 0 end string */
moveq r0,#0 /* equal */
beq 100f /* end strings */
add r2,r2,#1 /* else add 1 in counter */
b 1b /* and loop */
100:
pop {r1-r4}
bx lr /* end procedure */
|
http://rosettacode.org/wiki/String_case | String case | Task
Take the string alphaBETA and demonstrate how to convert it to:
upper-case and
lower-case
Use the default encoding of a string literal or plain ASCII if there is no string literal in your language.
Note: In some languages alphabets toLower and toUpper is not reversable.
Show any additional case conversion functions (e.g. swapping case, capitalizing the first letter, etc.) that may be included in the library of your language.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #ALGOL_68 | ALGOL 68 | #!/usr/local/bin/a68g --script #
# Demonstrate toupper and tolower for standard ALGOL 68
strings. This does not work for multibyte character sets. #
INT l2u = ABS "A" - ABS "a";
PROC to upper = (CHAR c)CHAR:
(ABS "a" > ABS c | c |: ABS c > ABS "z" | c | REPR ( ABS c + l2u ));
PROC to lower = (CHAR c)CHAR:
(ABS "A" > ABS c | c |: ABS c > ABS "Z" | c | REPR ( ABS c - l2u ));
# Operators can be defined in ALGOL 68 #
OP (CHAR)CHAR TOLOWER = to lower, TOUPPER = to upper;
# upper-cases s in place #
PROC string to upper = (REF STRING s)VOID:
FOR i FROM LWB s TO UPB s DO s[i] := to upper(s[i]) OD;
# lower-cases s in place #
PROC string to lower = (REF STRING s)VOID:
FOR i FROM LWB s TO UPB s DO s[i] := to lower(s[i]) OD;
main: (
STRING t := "alphaBETA";
string to upper(t);
printf(($"uppercase: "gl$, t));
string to lower(t);
printf(($"lowercase: "gl$, t))
) |
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
| #AutoHotkey | AutoHotkey |
String1 = abcd
String2 = abab
If (SubStr(String1,1,StrLen(String2)) = String2)
MsgBox, "%String1%" starts with "%String2%".
IfInString, String1, %String2%
{
Position := InStr(String1,String2)
StringReplace, String1, String1, %String2%, %String2%, UseErrorLevel
MsgBox, "%String1%" contains "%String2%" at position %Position%`, and appears %ErrorLevel% times.
}
StringRight, TempVar, String1, StrLen(String2)
If TempVar = %String2%
MsgBox, "%String1%" ends with "%String2%".
|
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
| #ALGOL_68 | ALGOL 68 | BITS bits := bits pack((TRUE, TRUE, FALSE, FALSE)); # packed array of BOOL #
BYTES bytes := bytes pack("Hello, world"); # packed array of CHAR #
print((
"BITS and BYTES are fixed width:", new line,
"bits width:", bits width, ", max bits: ", max bits, ", bits:", bits, new line,
"bytes width: ",bytes width, ", UPB:",UPB STRING(bytes), ", string:", STRING(bytes),"!", new line
)) |
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
| #Forth | Forth | : strip ( buf len -- buf len' ) \ repacks buffer, so len' <= len
over + over swap over ( buf dst limit src )
do
i c@ 32 127 within if
i c@ over c! char+
then
loop
over - ; |
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
| #Fortran | Fortran | module stripcharacters
implicit none
contains
pure logical function not_control(ch)
character, intent(in) :: ch
not_control = iachar(ch) >= 32 .and. iachar(ch) /= 127
end function not_control
pure logical function not_extended(ch)
character, intent(in) :: ch
not_extended = iachar(ch) >= 32 .and. iachar(ch) < 127
end function not_extended
pure function strip(string,accept) result(str)
character(len=*), intent(in) :: string
character(len=len(string)) :: str
interface
pure logical function accept(ch)
character, intent(in) :: ch
end function except
end interface
integer :: i,n
str = repeat(' ',len(string))
n = 0
do i=1,len(string)
if ( accept(string(i:i)) ) then
n = n+1
str(n:n) = string(i:i)
end if
end do
end function strip
end module stripcharacters
program test
use stripcharacters
character(len=256) :: string, str
integer :: ascii(256), i
forall (i=0:255) ascii(i) = i
forall (i=1:len(string)) string(i:i) = achar(ascii(i))
write (*,*) string
write (*,*) 'Control characters deleted:'
str = strip(string,not_control)
write (*,*) str
forall (i=1:len(string)) string(i:i) = achar(ascii(i))
write (*,*) 'Extended characters deleted:'
write (*,*) strip(string,not_extended)
end program test
|
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
| #AutoHotkey | AutoHotkey | s := "hello"
Msgbox, %s%
s1 := s . " literal" ;the . is optional
Msgbox, %s1% |
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
| #AWK | AWK | BEGIN {
s = "hello"
print s " literal"
s1 = s " literal"
print s1
} |
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.
| #J | J |
NB. Naive method
NB. joins two lists of the multiples of 3 and 5, then uses the ~. operator to remove duplicates.
echo 'The sum of the multiples of 3 or 5 < 1000 is ', ": +/ ~. (3*i.334), (5*i.200)
NB. inclusion/exclusion
triangular =: -:@:(*: + 1&*)
sumdiv =: dyad define
(triangular <. x % y) * y
)
echo 'For 10^20 - 1, the sum is ', ": +/ (".(20#'9'),'x') sumdiv 3 5 _15
exit ''
|
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
| #J | J | digsum=: 10&$: : (+/@(#.inv)) |
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
| #Lambdatalk | Lambdatalk |
{def sumsq
{lambda {:s}
{+ {S.map {lambda {:i} {* :i :i}} :s}}}}
-> sumsq
{sumsq 1 2 3 4 5}
-> 55
{sumsq 0}
-> 0
|
http://rosettacode.org/wiki/Sum_of_squares | Sum of squares | Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| #Lang5 | Lang5 | [1 2 3 4 5] 2 ** '+ reduce . |
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
| #Elena | Elena | import extensions;
public program()
{
var toTrim := " Trim me ";
console.printLine("'", toTrim.trimLeft(),"'");
console.printLine("'", toTrim.trimRight(),"'");
console.printLine("'", toTrim.trim(),"'");
} |
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
| #Elixir | Elixir | str = "\n \t foo \n\t bar \t \n"
IO.inspect String.strip(str)
IO.inspect String.rstrip(str)
IO.inspect String.lstrip(str) |
http://rosettacode.org/wiki/Strong_and_weak_primes | Strong and weak primes |
Definitions (as per number theory)
The prime(p) is the pth prime.
prime(1) is 2
prime(4) is 7
A strong prime is when prime(p) is > [prime(p-1) + prime(p+1)] ÷ 2
A weak prime is when prime(p) is < [prime(p-1) + prime(p+1)] ÷ 2
Note that the definition for strong primes is different when used in the context of cryptography.
Task
Find and display (on one line) the first 36 strong primes.
Find and display the count of the strong primes below 1,000,000.
Find and display the count of the strong primes below 10,000,000.
Find and display (on one line) the first 37 weak primes.
Find and display the count of the weak primes below 1,000,000.
Find and display the count of the weak primes below 10,000,000.
(Optional) display the counts and "below numbers" with commas.
Show all output here.
Related Task
Safe primes and unsafe primes.
Also see
The OEIS article A051634: strong primes.
The OEIS article A051635: weak primes.
| #Python | Python | import numpy as np
def primesfrom2to(n):
# https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188
""" Input n>=6, Returns a array of primes, 2 <= p < n """
sieve = np.ones(n//3 + (n%6==2), dtype=np.bool)
sieve[0] = False
for i in range(int(n**0.5)//3+1):
if sieve[i]:
k=3*i+1|1
sieve[ ((k*k)//3) ::2*k] = False
sieve[(k*k+4*k-2*k*(i&1))//3::2*k] = False
return np.r_[2,3,((3*np.nonzero(sieve)[0]+1)|1)]
p = primes10m = primesfrom2to(10_000_000)
s = strong10m = [t for s, t, u in zip(p, p[1:], p[2:])
if t > (s + u) / 2]
w = weak10m = [t for s, t, u in zip(p, p[1:], p[2:])
if t < (s + u) / 2]
b = balanced10m = [t for s, t, u in zip(p, p[1:], p[2:])
if t == (s + u) / 2]
print('The first 36 strong primes:', s[:36])
print('The count of the strong primes below 1,000,000:',
sum(1 for p in s if p < 1_000_000))
print('The count of the strong primes below 10,000,000:', len(s))
print('\nThe first 37 weak primes:', w[:37])
print('The count of the weak primes below 1,000,000:',
sum(1 for p in w if p < 1_000_000))
print('The count of the weak primes below 10,000,000:', len(w))
print('\n\nThe first 10 balanced primes:', b[:10])
print('The count of balanced primes below 1,000,000:',
sum(1 for p in b if p < 1_000_000))
print('The count of balanced primes below 10,000,000:', len(b))
print('\nTOTAL primes below 1,000,000:',
sum(1 for pr in p if pr < 1_000_000))
print('TOTAL primes below 10,000,000:', len(p)) |
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
| #COBOL | COBOL | identification division.
program-id. substring.
environment division.
configuration section.
repository.
function all intrinsic.
data division.
working-storage section.
01 original.
05 value "this is a string".
01 starting pic 99 value 3.
01 width pic 99 value 8.
01 pos pic 99.
01 ender pic 99.
01 looking pic 99.
01 indicator pic x.
88 found value high-value when set to false is low-value.
01 look-for pic x(8).
procedure division.
substring-main.
display "Original |" original "|, n = " starting " m = " width
display original(starting : width)
display original(starting :)
display original(1 : length(original) - 1)
move "a" to look-for
move 1 to looking
perform find-position
if found
display original(pos : width)
end-if
move "is a st" to look-for
move length(trim(look-for)) to looking
perform find-position
if found
display original(pos : width)
end-if
goback.
find-position.
set found to false
compute ender = length(original) - looking
perform varying pos from 1 by 1 until pos > ender
if original(pos : looking) equal look-for then
set found to true
exit perform
end-if
end-perform
.
end program 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.
| #Elixir | Elixir | defmodule Sudoku do
def display( grid ), do: ( for y <- 1..9, do: display_row(y, grid) )
def start( knowns ), do: Enum.into( knowns, Map.new )
def solve( grid ) do
sure = solve_all_sure( grid )
solve_unsure( potentials(sure), sure )
end
def task( knowns ) do
IO.puts "start"
start = start( knowns )
display( start )
IO.puts "solved"
solved = solve( start )
display( solved )
IO.puts ""
end
defp bt( grid ), do: bt_reject( is_not_allowed(grid), grid )
defp bt_accept( true, board ), do: throw( {:ok, board} )
defp bt_accept( false, grid ), do: bt_loop( potentials_one_position(grid), grid )
defp bt_loop( {position, values}, grid ), do: ( for x <- values, do: bt( Map.put(grid, position, x) ) )
defp bt_reject( true, _grid ), do: :backtrack
defp bt_reject( false, grid ), do: bt_accept( is_all_correct(grid), grid )
defp display_row( row, grid ) do
for x <- [1, 4, 7], do: display_row_group( x, row, grid )
display_row_nl( row )
end
defp display_row_group( start, row, grid ) do
Enum.each(start..start+2, &IO.write " #{Map.get( grid, {&1, row}, ".")}")
IO.write " "
end
defp display_row_nl( n ) when n in [3,6,9], do: IO.puts "\n"
defp display_row_nl( _n ), do: IO.puts ""
defp is_all_correct( grid ), do: map_size( grid ) == 81
defp is_not_allowed( grid ) do
is_not_allowed_rows( grid ) or is_not_allowed_columns( grid ) or is_not_allowed_groups( grid )
end
defp is_not_allowed_columns( grid ), do: values_all_columns(grid) |> Enum.any?(&is_not_allowed_values/1)
defp is_not_allowed_groups( grid ), do: values_all_groups(grid) |> Enum.any?(&is_not_allowed_values/1)
defp is_not_allowed_rows( grid ), do: values_all_rows(grid) |> Enum.any?(&is_not_allowed_values/1)
defp is_not_allowed_values( values ), do: length( values ) != length( Enum.uniq(values) )
defp group_positions( {x, y} ) do
for colum <- group_positions_close(x), row <- group_positions_close(y), do: {colum, row}
end
defp group_positions_close( n ) when n < 4, do: [1,2,3]
defp group_positions_close( n ) when n < 7, do: [4,5,6]
defp group_positions_close( _n ) , do: [7,8,9]
defp positions_not_in_grid( grid ) do
keys = Map.keys( grid )
for x <- 1..9, y <- 1..9, not {x, y} in keys, do: {x, y}
end
defp potentials_one_position( grid ) do
Enum.min_by( potentials( grid ), fn {_position, values} -> length(values) end )
end
defp potentials( grid ), do: List.flatten( for x <- positions_not_in_grid(grid), do: potentials(x, grid) )
defp potentials( position, grid ) do
useds = potentials_used_values( position, grid )
{position, Enum.to_list(1..9) -- useds }
end
defp potentials_used_values( {x, y}, grid ) do
row_values = (for row <- 1..9, row != x, do: {row, y}) |> potentials_values( grid )
column_values = (for column <- 1..9, column != y, do: {x, column}) |> potentials_values( grid )
group_values = group_positions({x, y}) -- [ {x, y} ] |> potentials_values( grid )
row_values ++ column_values ++ group_values
end
defp potentials_values( keys, grid ) do
for x <- keys, val = grid[x], do: val
end
defp values_all_columns( grid ) do
for x <- 1..9, do:
( for y <- 1..9, do: {x, y} ) |> potentials_values( grid )
end
defp values_all_groups( grid ) do
[[g1,g2,g3], [g4,g5,g6], [g7,g8,g9]] = for x <- [1,4,7], do: values_all_groups(x, grid)
[g1,g2,g3,g4,g5,g6,g7,g8,g9]
end
defp values_all_groups( x, grid ) do
for x_offset <- x..x+2, do: values_all_groups(x, x_offset, grid)
end
defp values_all_groups( _x, x_offset, grid ) do
( for y_offset <- group_positions_close(x_offset), do: {x_offset, y_offset} )
|> potentials_values( grid )
end
defp values_all_rows( grid ) do
for y <- 1..9, do:
( for x <- 1..9, do: {x, y} ) |> potentials_values( grid )
end
defp solve_all_sure( grid ), do: solve_all_sure( solve_all_sure_values(grid), grid )
defp solve_all_sure( [], grid ), do: grid
defp solve_all_sure( sures, grid ) do
solve_all_sure( Enum.reduce(sures, grid, &solve_all_sure_store/2) )
end
defp solve_all_sure_values( grid ), do: (for{position, [value]} <- potentials(grid), do: {position, value} )
defp solve_all_sure_store( {position, value}, acc ), do: Map.put( acc, position, value )
defp solve_unsure( [], grid ), do: grid
defp solve_unsure( _potentials, grid ) do
try do
bt( grid )
catch
{:ok, board} -> board
end
end
end
simple = [{{1, 1}, 3}, {{2, 1}, 9}, {{3, 1},4}, {{6, 1}, 2}, {{7, 1}, 6}, {{8, 1}, 7},
{{4, 2}, 3}, {{7, 2}, 4},
{{1, 3}, 5}, {{4, 3}, 6}, {{5, 3}, 9}, {{8, 3}, 2},
{{2, 4}, 4}, {{3, 4}, 5}, {{7, 4}, 9},
{{1, 5}, 6}, {{9, 5}, 7},
{{3, 6}, 7}, {{7, 6}, 5}, {{8, 6}, 8},
{{2, 7}, 1}, {{5, 7}, 6}, {{6, 7}, 7}, {{9, 7}, 8},
{{3, 8}, 9}, {{6, 8}, 8},
{{2, 9}, 2}, {{3, 9}, 6}, {{4, 9}, 4}, {{7, 9}, 7}, {{8, 9}, 3}, {{9, 9}, 5}]
Sudoku.task( simple )
difficult = [{{6, 2}, 3}, {{8, 2}, 8}, {{9, 2}, 5},
{{3, 3}, 1}, {{5, 3}, 2},
{{4, 4}, 5}, {{6, 4}, 7},
{{3, 5}, 4}, {{7, 5}, 1},
{{2, 6}, 9},
{{1, 7}, 5}, {{8, 7}, 7}, {{9, 7}, 3},
{{3, 8}, 2}, {{5, 8}, 1},
{{5, 9}, 4}, {{9, 9}, 9}]
Sudoku.task( difficult ) |
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
| #FreeBASIC | FreeBASIC |
Dim As Integer memoria(255), contador = 0
Dim As String codigo, caracter
Input "SUBLEQ> ", codigo
While Instr(codigo, " ")
memoria(contador) = Val(Left(codigo, Instr(codigo, " ") - 1))
codigo = Mid(codigo, Instr(codigo, " ") + 1)
contador += 1
Wend
memoria(contador) = Val(codigo)
contador = 0
Do
Dim As Integer a = memoria(contador)
Dim As Integer b = memoria(contador + 1)
Dim As Integer c = memoria(contador + 2)
contador += 3
If a = -1 Then
Input "SUBLEQ> ", caracter
memoria(b) = Asc(caracter)
Else
If b = -1 Then
Print Chr(memoria(a));
Else
memoria(b) -= memoria(a)
If memoria(b) <= 0 Then contador = c
End If
End If
Loop Until contador < 0
Sleep
|
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 | #Picat | Picat | main =>
Num is 1_000_000,
statistics(runtime,[Start|_]),
PrimeList = primes(Num),
NumPrimes = PrimeList.len,
statistics(runtime,[Stop|_]),
RunTime = Stop - Start,
printf("There are %w primes until %w [time(ms) %w]%n",NumPrimes, Num, RunTime),
DiffList = [[1], [2], [2,2], [2,4], [4,2], [2,4,6],
[2,6,4], [4,2,6], [4,6,2], [6,2,4], [6,4,2],[6,4,2,4]],
run(DiffList, PrimeList).
primesByDiffs([],_,[]).
primesByDiffs([Prime|Primes], Diff, [Slide|Slides]):-
Slide = new_list(Diff.len+1),
append(Slide, _, [Prime|Primes]),
select(Diff, Slide),!,
primesByDiffs(Primes, Diff, Slides).
primesByDiffs([_|Primes], Diff, Slides):-
primesByDiffs(Primes, Diff, Slides).
select([],_).
select([Diff|Diffs],[S1, S2|Stail]):-
S2 = S1 + Diff,
select(Diffs, [S2|Stail]).
run([],_).
run([Diff|Dtail], PrimeList):-
statistics(runtime,[Start|_]),
primesByDiffs(PrimeList, Diff, SlideList),
Num = SlideList.len,
statistics(runtime,[Stop|_]),
Runtime = Stop - Start,
printf("%-10w number: %5w (%2wms) first: %-22w last: %-22w\n", Diff, Num, Runtime, SlideList.first, SlideList.last),
!,
run(Dtail, PrimeList). |
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
| #F.23 | F# | [<EntryPoint>]
let main args =
let s = "一二三四五六七八九十"
printfn "%A" (s.Substring(1))
printfn "%A" (s.Substring(0, s.Length - 1))
printfn "%A" (s.Substring(1, s.Length - 2))
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.
| #Phix | Phix | with javascript_semantics
sequence state = repeat(0,55)
integer pos
constant MAX = 1e9
function cap(integer n)
if n<0 then n += MAX end if
return n
end function
function next()
pos = mod(pos,55)+1
integer temp = cap(state[pos]-state[mod(pos+30,55)+1])
state[pos] = temp
return temp
end function
procedure init(integer seed)
sequence temp = repeat(0,55)
temp[1] = cap(seed)
temp[2] = 1
for i=3 to 55 do
temp[i] = cap(temp[i-2]-temp[i-1])
end for
for i=1 to 55 do
state[i] = temp[mod(34*i,55)+1]
end for
pos = 55
for i=55 to 219 do
{} = next()
end for
end procedure
init(292929)
for i=220 to 222 do
printf(1,"%d: %d\n",{i,next()})
end for
|
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.
| #Go | Go | package main
import "fmt"
func main() {
sum, prod := 0, 1
for _, x := range []int{1,2,5} {
sum += x
prod *= x
}
fmt.Println(sum, prod)
} |
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.
| #Groovy | Groovy | [1,2,3,4,5].sum() |
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.
| #F.23 | F# | let rec f (x : float) =
match x with
| 0. -> x
| x -> (1. / (x * x)) + f (x - 1.) |
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
| #Factor | Factor | USE: sequences.extras
: strip-comments ( str -- str' )
[ "#;" member? not ] take-while "" like ; |
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
| #Fantom | Fantom | class Main
{
static Str removeComment (Str str)
{
regex := Regex <|(;|#)|>
matcher := regex.matcher (str)
if (matcher.find)
return str[0..<matcher.start]
else
return str
}
public static Void main ()
{
echo (removeComment ("String with comment here"))
echo (removeComment ("String with comment # here"))
echo (removeComment ("String with comment ; here"))
}
} |
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
| #Forth | Forth | \ Rosetta Code Strip Comment
: LASTCHAR ( addr len -- addr len c) 2DUP + C@ ;
: COMMENT? ( char -- ? ) S" #;" ROT SCAN NIP ; \ test char for "#;"
: -LEADING ( addr len -- addr' len') BL SKIP ; \ remove leading space characters
: -COMMENT ( addr len -- addr len') \ removes # or ; comments
1-
BEGIN
LASTCHAR COMMENT? 0=
WHILE \ while not a comment char...
1- \ reduce length by 1
REPEAT
1- ; \ remove 1 more (the comment char)
: -TRAILING ( adr len -- addr len') \ remove trailing spaces
1-
BEGIN
LASTCHAR BL =
WHILE \ while lastchar = blank
1- \ reduce length by 1
REPEAT
1+ ;
: COMMENT-STRIP ( addr len -- addr 'len) -LEADING -COMMENT -TRAILING ;
|
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
| #Icon_and_Unicon | Icon and Unicon | procedure main()
every (unstripped := "") ||:= !&input || "\n" # Load file as one string
write(stripBlockComment(unstripped,"/*","*/"))
end
procedure stripBlockComment(s1,s2,s3) #: strip comments between s2-s3 from s1
result := ""
s1 ? {
while result ||:= tab(find(s2)) do {
move(*s2)
tab(find(s3)|0) # or end of string
move(*s3)
}
return result || tab(0)
}
end |
http://rosettacode.org/wiki/Strip_block_comments | Strip block comments | A block comment begins with a beginning delimiter and ends with a ending delimiter, including the delimiters. These delimiters are often multi-character sequences.
Task
Strip block comments from program text (of a programming language much like classic C).
Your demos should at least handle simple, non-nested and multi-line block comment delimiters.
The block comment delimiters are the two-character sequences:
/* (beginning delimiter)
*/ (ending delimiter)
Sample text for stripping:
/**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*/
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
/**
* Another comment.
*/
function something() {
}
Extra credit
Ensure that the stripping code is not hard-coded to the particular delimiters described above, but instead allows the caller to specify them. (If your language supports them, optional parameters may be useful for this.)
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #J | J | strip=:#~1 0 _1*./@:(|."0 1)2>4{"1(5;(0,"0~".;._2]0 :0);'/*'i.a.)&;:
1 0 0
0 2 0
2 3 2
0 2 2
) |
http://rosettacode.org/wiki/String_interpolation_(included) | String interpolation (included) |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Given a string and defined variables or values, string interpolation is the replacement of defined character sequences in the string by values or variable values.
For example, given an original string of "Mary had a X lamb.", a value of "big", and if the language replaces X in its interpolation routine, then the result of its interpolation would be the string "Mary had a big lamb".
(Languages usually include an infrequently used character or sequence of characters to indicate what is to be replaced such as "%", or "#" rather than "X").
Task
Use your languages inbuilt string interpolation abilities to interpolate a string missing the text "little" which is held in a variable, to produce the output string "Mary had a little lamb".
If possible, give links to further documentation on your languages string interpolation features.
Note: The task is not to create a string interpolation routine, but to show a language's built-in capability.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Asymptote | Asymptote | string s1 = "big";
write("Mary had a " + s1 + " lamb");
s1 = "little";
write("Mary also had a ", s1, "lamb"); |
http://rosettacode.org/wiki/String_interpolation_(included) | String interpolation (included) |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Given a string and defined variables or values, string interpolation is the replacement of defined character sequences in the string by values or variable values.
For example, given an original string of "Mary had a X lamb.", a value of "big", and if the language replaces X in its interpolation routine, then the result of its interpolation would be the string "Mary had a big lamb".
(Languages usually include an infrequently used character or sequence of characters to indicate what is to be replaced such as "%", or "#" rather than "X").
Task
Use your languages inbuilt string interpolation abilities to interpolate a string missing the text "little" which is held in a variable, to produce the output string "Mary had a little lamb".
If possible, give links to further documentation on your languages string interpolation features.
Note: The task is not to create a string interpolation routine, but to show a language's built-in capability.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #AutoHotkey | AutoHotkey | ; Using the = operator
LIT = little
string = Mary had a %LIT% lamb.
; Using the := operator
LIT := "little"
string := "Mary had a" LIT " lamb."
MsgBox %string% |
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).
| #REXX | REXX | /*REXX pgm solves a puzzle: using the string 123456789, insert - or + to sum to 100*/
parse arg LO HI . /*obtain optional arguments from the CL*/
if LO=='' | LO=="," then LO= 100 /*Not specified? Then use the default.*/
if HI=='' | HI=="," then HI= LO /* " " " " " " */
if LO==00 then HI= 123456789 /*LOW specified as zero with leading 0.*/
ops= '+-'; L= length(ops) + 1 /*define operators (and their length). */
@.=; do i=1 for L-1; @.i= substr(ops,i,1) /* " some handy-dandy REXX literals*/
end /*i*/ /* " individual operators for speed*/
mx= 0; mn= 999999 /*initialize the minimums and maximums.*/
mxL=; mnL=; do j=LO to HI until LO==00 & mn==0 /*solve with range of sums*/
z= ???(j) /*find # solutions for J. */
if z> mx then mxL= /*is this a new maximum ? */
if z>=mx then do; mxL=mxL j; mx=z; end /*remember this new max. */
if z< mn then mnL= /*is this a new minimum ? */
if z<=mn then do; mnL=mnL j; mn=z; end /*remember this new min. */
end /*j*/
if LO==HI then exit 0 /*don't display max&min ? */
@@= 'number of solutions: '; say
_= words(mxL); say 'sum's(_) "of" mxL ' 's(_,"have",'has') 'the maximum' @@ mx
_= words(mnL); say 'sum's(_) "of" mnL ' 's(_,"have",'has') 'the minimum' @@ mn
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
s: if arg(1)==1 then return arg(3); return word( arg(2) "s",1) /*simple pluralizer*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
???: parse arg answer; #= 0 /*obtain the answer (sum) to the puzzle*/
do a=L-1 for 2; aa= @.a'1' /*choose one of - or nothing. */
do b=1 for L; bb= aa || @.b'2' /* " " " - +, or abutment.*/
do c=1 for L; cc= bb || @.c'3' /* " " " " " " " */
do d=1 for L; dd= cc || @.d'4' /* " " " " " " " */
do e=1 for L; ee= dd || @.e'5' /* " " " " " " " */
do f=1 for L; ff= ee || @.f'6' /* " " " " " " " */
do g=1 for L; gg= ff || @.g'7' /* " " " " " " " */
do h=1 for L; hh= gg || @.h'8' /* " " " " " " " */
do i=1 for L; ii= hh || @.i'9' /* " " " " " " " */
interpret '$=' ii /*calculate the sum of modified string.*/
if $\==answer then iterate /*Is sum not equal to answer? Then skip*/
#= # + 1; if LO==HI then say 'solution: ' $ " ◄───► " ii
end /*i*/ /* */
end /*h*/ /* d */
end /*g*/ /* d */
end /*f*/ /* eeeee n nnnn dddddd sssss */
end /*e*/ /* e e nn n d d s */
end /*d*/ /* eeeeeee n n d d sssss */
end /*c*/ /* e n n d d s */
end /*b*/ /* eeeee n n ddddd sssss */
end /*a*/ /* */
y= # /* [↓] adjust the number of solutions?*/
if y==0 then y= 'no' /* [↓] left justify plural of solution*/
if LO\==00 then say right(y, 9) 'solution's(#, , " ") 'found for' ,
right(j, length(HI) ) left('', #, "─")
return # /*return the number of solutions found.*/ |
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
| #Bracmat | Bracmat | ( ( strip
= string chars s pat
. !arg:(?string.?chars)
& :?s
&
' ( ?
( %
: [%( utf$!sjt
& ( @($chars:? !sjt ?)
| rev$!sjt !s:?s
)
& ~
)
)
?
)
: (=?pat)
& @(!string:!pat)
| rev$(str$!s)
)
& out
$ (strip$("Аппетит приходит во время еды".веп)
); |
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
| #Burlesque | Burlesque |
blsq ) "She was a soul stripper. She took my heart!"{"aei"\/~[n!}f[
"Sh ws soul strppr. Sh took my hrt!"
|
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.
| #ERRE | ERRE |
......
S$=" World!"
S$="Hello"+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.
| #F.23 | F# | let mutable s = "world!"
s <- "Hello, " + s
printfn "%s" 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.
| #Factor | Factor |
"world"
"Hello " prepend
|
http://rosettacode.org/wiki/String_comparison | String comparison |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Demonstrate how to compare two strings from within the language and how to achieve a lexical comparison.
The task should demonstrate:
Comparing two strings for exact equality
Comparing two strings for inequality (i.e., the inverse of exact equality)
Comparing two strings to see if one is lexically ordered before than the other
Comparing two strings to see if one is lexically ordered after than the other
How to achieve both case sensitive comparisons and case insensitive comparisons within the language
How the language handles comparison of numeric strings if these are not treated lexically
Demonstrate any other kinds of string comparisons that the language provides, particularly as it relates to your type system.
For example, you might demonstrate the difference between generic/polymorphic comparison and coercive/allomorphic comparison if your language supports such a distinction.
Here "generic/polymorphic" comparison means that the function or operator you're using doesn't always do string comparison, but bends the actual semantics of the comparison depending on the types one or both arguments; with such an operator, you achieve string comparison only if the arguments are sufficiently string-like in type or appearance.
In contrast, a "coercive/allomorphic" comparison function or operator has fixed string-comparison semantics regardless of the argument type; instead of the operator bending, it's the arguments that are forced to bend instead and behave like strings if they can, and the operator simply fails if the arguments cannot be viewed somehow as strings. A language may have one or both of these kinds of operators; see the Raku entry for an example of a language with both kinds of operators.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Arturo | Arturo | loop [["YUP" "YUP"] ["YUP" "Yup"] ["bot" "bat"] ["aaa" "zz"]] 'x [
print [x\0 "=" x\1 "=>" x\0 = x\1]
print [x\0 "=" x\1 "(case-insensitive) =>" (upper x\0) = upper x\1]
print [x\0 "<>" x\1 "=>" x\0 <> x\1]
print [x\0 ">" x\1 "=>" x\0 > x\1]
print [x\0 ">=" x\1 "=>" x\0 >= x\1]
print [x\0 "<" x\1 "=>" x\0 < x\1]
print [x\0 "=<" x\1 "=>" x\0 =< x\1]
print "----"
] |
http://rosettacode.org/wiki/String_case | String case | Task
Take the string alphaBETA and demonstrate how to convert it to:
upper-case and
lower-case
Use the default encoding of a string literal or plain ASCII if there is no string literal in your language.
Note: In some languages alphabets toLower and toUpper is not reversable.
Show any additional case conversion functions (e.g. swapping case, capitalizing the first letter, etc.) that may be included in the library of your language.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #ALGOL_W | ALGOL W | begin
% algol W doesn't have standard case conversion routines, this is one way %
% such facilities could be provided %
% converts text to upper case %
% assumes the letters are contiguous in the character set (as in ASCII) %
% would not work in EBCDIC (as the original algol W implementations used) %
procedure upCase( string(256) value result text ) ;
for i := 0 until 255 do begin
string(1) c;
c := text( i // 1 );
if c >= "a" and c <= "z"
then begin
text( i // 1 ) := code( decode( "A" )
+ ( decode( c ) - decode( "a" ) )
)
end
end upCase ;
% converts text to lower case %
% assumes the letters are contiguous in the character set (as in ASCII) %
% would not work in EBCDIC (as the original algol W implementations used) %
procedure dnCase( string(256) value result text ) ;
for i := 0 until 255 do begin
string(1) c;
c := text( i // 1 );
if c >= "A" and c <= "Z"
then begin
text( i // 1 ) := code( decode( "a" )
+ ( decode( c ) - decode( "A" ) )
)
end
end dnCase ;
string(256) text;
text := "alphaBETA";
upCase( text );
write( text( 0 // 40 ) );
dnCase( text );
write( text( 0 // 40 ) );
end. |
http://rosettacode.org/wiki/String_case | String case | Task
Take the string alphaBETA and demonstrate how to convert it to:
upper-case and
lower-case
Use the default encoding of a string literal or plain ASCII if there is no string literal in your language.
Note: In some languages alphabets toLower and toUpper is not reversable.
Show any additional case conversion functions (e.g. swapping case, capitalizing the first letter, etc.) that may be included in the library of your language.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Amazing_Hopper | Amazing Hopper |
#include <hopper.h>
#proto swapcase(_X_)
main:
// literal:
String to process = "alphaBETA", {"String to process: ",String to process}println
{"UPPER: ",String to process} upper,println
{"LOWER: ",String to process} lower,println
{"SWAP CASE: "}
s="", let( s := _swap case(String to process)),{s}println
// arrays:
vArray=0, {5,5} new array(vArray), vArray=String to process
{"ARRAY UPPER: \n",vArray} upper,println
{"ARRAY LOWER: \n",vArray} lower,println
[1:2:end,1:2:end]get(vArray),upper, put(vArray)
[2:2:end,2:2:end]get(vArray),lower, put(vArray)
{"INTERVAL ARRAY UPPER/LOWER: \n",vArray},println
exit(0)
.locals
swapcase(_X_)
nLen=0, {_X_}len,mov(nLen)
__SWAPCASE__:
if( [nLen:nLen]get(_X_),{"upper"}!typechar? )
lower
else
upper
end if
put(_X_)
--nLen,{nLen}jnz(__SWAPCASE__)
{_X_} // put processed string into the stack...
back
|
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
| #AutoIt | AutoIt | $string1 = "arduinoardblobard"
$string2 = "ard"
; == Determining if the first string starts with second string
If StringLeft($string1, StringLen($string2)) = $string2 Then
ConsoleWrite("1st string starts with 2nd string." & @CRLF)
Else
ConsoleWrite("1st string does'nt starts with 2nd string." & @CRLF)
EndIf
; == Determining if the first string contains the second string at any location
; == Print the location of the match for part 2
; == Handle multiple occurrences of a string for part 2
$start = 1
$count = 0
$pos = StringInStr($string1, $string2)
While $pos
$count += 1
ConsoleWrite("1st string contains 2nd string at position: " & $pos & @CRLF)
$pos = StringInStr($string1, $string2, 0, 1, $start + $pos + StringLen($string2))
WEnd
If $count = 0 Then ConsoleWrite("1st string does'nt contain 2nd string." & @CRLF)
; == Determining if the first string ends with the second string
If StringRight($string1, StringLen($string2)) = $string2 Then
ConsoleWrite("1st string ends with 2nd string." & @CRLF)
Else
ConsoleWrite("1st string does'nt ends with 2nd string." & @CRLF)
EndIf
|
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
| #Apex | Apex |
String myString = 'abcd';
System.debug('Size of String', myString.length());
|
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
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Function stripControlChars(s As Const String) As String
If s = "" Then Return ""
Dim count As Integer = 0
Dim strip(0 To Len(s) - 1) As Boolean
For i As Integer = 0 To Len(s) - 1
For j As Integer = 0 To 31
If s[i] = j OrElse s[i] = 127 Then
count += 1
strip(i) = True
Exit For
End If
Next j
Next i
Dim buffer As String = Space(Len(s) - count)
count = 0
For i As Integer = 0 To Len(s) - 1
If Not Strip(i) Then
buffer[count] = s[i]
count += 1
End If
Next
Return buffer
End Function
Function stripExtendedChars(s As Const String) As String
If s = "" Then Return ""
Dim count As Integer = 0
Dim strip(0 To Len(s) - 1) As Boolean
For i As Integer = 0 To Len(s) - 1
For j As Integer = 128 To 255
If s[i] = j Then
count += 1
strip(i) = True
Exit For
End If
Next j
Next i
Dim buffer As String = Space(Len(s) - count)
count = 0
For i As Integer = 0 To Len(s) - 1
If Not Strip(i) Then
buffer[count] = s[i]
count += 1
End If
Next
Return buffer
End Function
Dim s As String = !"\v\001The\t quick\255 \vbrown\127\f fox\156"
Dim s1 As String = stripControlChars(s)
Dim s2 As String = stripExtendedChars(s)
Dim s3 As String = stripExtendedChars(s1)
' Under Windows console, code page 850 :
' "vertical tab" displays as ♂
' "form feed" displays as ♀
' Chr(1) displays as ☺
' Chr(127) displays as ⌂
' the other control characters do what it says on the tin
' Chr(156) displays as £
' Chr(255) displays as space
Print "Before stripping :" , s
Print "Ctl chars stripped :" , s1
Print "Ext chars stripped :" , s2
Print "Both sets stripped :" , s3
Print
Print "Before stripping" , "Length => " ; Len(s)
Print "Ctl chars stripped" , "Length => " ; Len(s1)
Print "Ext chars stripped" , "Length => " ; Len(s2)
Print "Both sets stripped" , "Length => " ; Len(s3)
Print
Print "Press any key to quit"
Sleep |
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
| #Axe | Axe | Lbl CONCAT
Copy(r₁,L₁,length(r₁))
Copy(r₂,L₁+length(r₁),length(r₂)+1)
L₁
Return |
http://rosettacode.org/wiki/String_concatenation | String concatenation | String concatenation
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a string variable equal to any text value.
Create another string variable whose value is the original variable concatenated with another string literal.
To illustrate the operation, show the content of the variables.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #BASIC | BASIC | s$ = "hello"
PRINT s$ + " literal"
s2$ = s$ + " literal"
PRINT s$
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.
| #Java | Java | class SumMultiples {
public static long getSum(long n) {
long sum = 0;
for (int i = 3; i < n; i++) {
if (i % 3 == 0 || i % 5 == 0) sum += i;
}
return sum;
}
public static void main(String[] args) {
System.out.println(getSum(1000));
}
} |
http://rosettacode.org/wiki/Sum_digits_of_an_integer | Sum digits of an integer | Task
Take a Natural Number in a given base and return the sum of its digits:
110 sums to 1
123410 sums to 10
fe16 sums to 29
f0e16 sums to 29
| #Java | Java | import java.math.BigInteger;
public class SumDigits {
public static int sumDigits(long num) {
return sumDigits(num, 10);
}
public static int sumDigits(long num, int base) {
String s = Long.toString(num, base);
int result = 0;
for (int i = 0; i < s.length(); i++)
result += Character.digit(s.charAt(i), base);
return result;
}
public static int sumDigits(BigInteger num) {
return sumDigits(num, 10);
}
public static int sumDigits(BigInteger num, int base) {
String s = num.toString(base);
int result = 0;
for (int i = 0; i < s.length(); i++)
result += Character.digit(s.charAt(i), base);
return result;
}
public static void main(String[] args) {
System.out.println(sumDigits(1));
System.out.println(sumDigits(12345));
System.out.println(sumDigits(123045));
System.out.println(sumDigits(0xfe, 16));
System.out.println(sumDigits(0xf0e, 16));
System.out.println(sumDigits(new BigInteger("12345678901234567890")));
}
} |
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
| #Lasso | Lasso | define sumofsquares(values::array) => {
local(sum = 0)
with value in #values do {
#sum += #value * #value
}
return #sum
}
sumofsquares(array(1,2,3,4,5)) |
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
| #LFE | LFE |
(defun sum-sq (nums)
(lists:foldl
(lambda (x acc)
(+ acc (* x x)))
0 nums))
|
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
| #Emacs_Lisp | Emacs Lisp | (string-trim-left " left center right ") ;=> "left center right "
(string-trim-right " left center right ") ;=> " left center right"
(string-trim " left center right ") ;=> "left center right" |
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
| #Erlang | Erlang | % Implemented by Arjun Sunel
1> string:strip(" Hello World! ", left). %remove leading whitespaces
"Hello World! "
2> string:strip(" Hello World! ", right). % remove trailing whitespaces
" Hello World!"
3> string:strip(" Hello World! ", both). % remove both leading and trailing whitespace
"Hello World!"
|
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.
| #Raku | Raku | sub comma { $^i.flip.comb(3).join(',').flip }
use Math::Primesieve;
my $sieve = Math::Primesieve.new;
my @primes = $sieve.primes(10_000_019);
my (@weak, @balanced, @strong);
for 1 ..^ @primes - 1 -> $p {
given (@primes[$p - 1] + @primes[$p + 1]) / 2 {
when * > @primes[$p] { @weak.push: @primes[$p] }
when * < @primes[$p] { @strong.push: @primes[$p] }
default { @balanced.push: @primes[$p] }
}
}
for @strong, 'strong', 36,
@weak, 'weak', 37,
@balanced, 'balanced', 28
-> @pr, $type, $d {
say "\nFirst $d $type primes:\n", @pr[^$d]».,
say "Count of $type primes <= {comma 1e6}: ", comma +@pr[^(@pr.first: * > 1e6,:k)];
say "Count of $type primes <= {comma 1e7}: ", comma +@pr;
} |
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
| #ColdFusion | ColdFusion |
<cfoutput>
<cfset str = "abcdefg">
<cfset n = 2>
<cfset m = 3>
<!--- Note: In CF index starts at 1 rather than 0
starting from n characters in and of m length --->
#mid( str, n, m )#
<!--- starting from n characters in, up to the end of the string --->
<cfset countFromRight = Len( str ) - n + 1>
#right( str, countFromRight )#
<!--- whole string minus last character --->
<cfset allButLast = Len( str ) - 1>
#left( str, allButLast )#
<!--- starting from a known character within the string and of m length --->
<cfset startingIndex = find( "b", str )>
#mid( str, startingIndex, m )#
<!--- starting from a known substring within the string and of m length --->
<cfset startingIndexSubString = find( "bc", str )>
#mid( str, startingIndexSubString, m )#
</cfoutput>
|
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.
| #Erlang | Erlang |
-module( sudoku ).
-export( [display/1, start/1, solve/1, task/0] ).
display( Grid ) -> [display_row(Y, Grid) || Y <- lists:seq(1, 9)].
%% A known value is {{Column, Row}, Value}
%% Top left corner is {1, 1}, Bottom right corner is {9,9}
start( Knowns ) -> dict:from_list( Knowns ).
solve( Grid ) ->
Sure = solve_all_sure( Grid ),
solve_unsure( potentials(Sure), Sure ).
task() ->
Simple = [{{1, 1}, 3}, {{2, 1}, 9}, {{3, 1},4}, {{6, 1}, 2}, {{7, 1}, 6}, {{8, 1}, 7},
{{4, 2}, 3}, {{7, 2}, 4},
{{1, 3}, 5}, {{4, 3}, 6}, {{5, 3}, 9}, {{8, 3}, 2},
{{2, 4}, 4}, {{3, 4}, 5}, {{7, 4}, 9},
{{1, 5}, 6}, {{9, 5}, 7},
{{3, 6}, 7}, {{7, 6}, 5}, {{8, 6}, 8},
{{2, 7}, 1}, {{5, 7}, 6}, {{6, 7}, 7}, {{9, 7}, 8},
{{3, 8}, 9}, {{6, 8}, 8},
{{2, 9}, 2}, {{3, 9}, 6}, {{4, 9}, 4}, {{7, 9}, 7}, {{8, 9}, 3}, {{9, 9}, 5}],
task( Simple ),
Difficult = [{{6, 2}, 3}, {{8, 2}, 8}, {{9, 2}, 5},
{{3, 3}, 1}, {{5, 3}, 2},
{{4, 4}, 5}, {{6, 4}, 7},
{{3, 5}, 4}, {{7, 5}, 1},
{{2, 6}, 9},
{{1, 7}, 5}, {{8, 7}, 7}, {{9, 7}, 3},
{{3, 8}, 2}, {{5, 8}, 1},
{{5, 9}, 4}, {{9, 9}, 9}],
task( Difficult ).
bt( Grid ) -> bt_reject( is_not_allowed(Grid), Grid ).
bt_accept( true, Board ) -> erlang:throw( {ok, Board} );
bt_accept( false, Grid ) -> bt_loop( potentials_one_position(Grid), Grid ).
bt_loop( {Position, Values}, Grid ) -> [bt( dict:store(Position, X, Grid) ) || X <- Values].
bt_reject( true, _Grid ) -> backtrack;
bt_reject( false, Grid ) -> bt_accept( is_all_correct(Grid), Grid ).
display_row( Row, Grid ) ->
[display_row_group( X, Row, Grid ) || X <- [1, 4, 7]],
display_row_nl( Row ).
display_row_group( Start, Row, Grid ) ->
[io:fwrite(" ~c", [display_value(X, Row, Grid)]) || X <- [Start, Start+1, Start+2]],
io:fwrite( " " ).
display_row_nl( N ) when N =:= 3; N =:= 6; N =:= 9 -> io:nl(), io:nl();
display_row_nl( _N ) -> io:nl().
display_value( X, Y, Grid ) -> display_value( dict:find({X, Y}, Grid) ).
display_value( error ) -> $.;
display_value( {ok, Value} ) -> Value + $0.
is_all_correct( Grid ) -> dict:size( Grid ) =:= 81.
is_not_allowed( Grid ) ->
is_not_allowed_rows( Grid )
orelse is_not_allowed_columns( Grid )
orelse is_not_allowed_groups( Grid ).
is_not_allowed_columns( Grid ) -> lists:any( fun is_not_allowed_values/1, values_all_columns(Grid) ).
is_not_allowed_groups( Grid ) -> lists:any( fun is_not_allowed_values/1, values_all_groups(Grid) ).
is_not_allowed_rows( Grid ) -> lists:any( fun is_not_allowed_values/1, values_all_rows(Grid) ).
is_not_allowed_values( Values ) -> erlang:length( Values ) =/= erlang:length( lists:usort(Values) ).
group_positions( {X, Y} ) -> [{Colum, Row} || Colum <- group_positions_close(X), Row <- group_positions_close(Y)].
group_positions_close( N ) when N < 4 -> [1,2,3];
group_positions_close( N ) when N < 7 -> [4,5,6];
group_positions_close( _N ) -> [7,8,9].
positions_not_in_grid( Grid ) ->
Keys = dict:fetch_keys( Grid ),
[{X, Y} || X <- lists:seq(1, 9), Y <- lists:seq(1, 9), not lists:member({X, Y}, Keys)].
potentials_one_position( Grid ) ->
[{_Shortest, Position, Values} | _T] = lists:sort( [{erlang:length(Values), Position, Values} || {Position, Values} <- potentials( Grid )] ),
{Position, Values}.
potentials( Grid ) -> lists:flatten( [potentials(X, Grid) || X <- positions_not_in_grid(Grid)] ).
potentials( Position, Grid ) ->
Useds = potentials_used_values( Position, Grid ),
{Position, [Value || Value <- lists:seq(1, 9) -- Useds]}.
potentials_used_values( {X, Y}, Grid ) ->
Row_positions = [{Row, Y} || Row <- lists:seq(1, 9), Row =/= X],
Row_values = potentials_values( Row_positions, Grid ),
Column_positions = [{X, Column} || Column <- lists:seq(1, 9), Column =/= Y],
Column_values = potentials_values( Column_positions, Grid ),
Group_positions = lists:delete( {X, Y}, group_positions({X, Y}) ),
Group_values = potentials_values( Group_positions, Grid ),
Row_values ++ Column_values ++ Group_values.
potentials_values( Keys, Grid ) ->
Row_values_unfiltered = [dict:find(X, Grid) || X <- Keys],
[Value || {ok, Value} <- Row_values_unfiltered].
values_all_columns( Grid ) -> [values_all_columns(X, Grid) || X <- lists:seq(1, 9)].
values_all_columns( X, Grid ) ->
Positions = [{X, Y} || Y <- lists:seq(1, 9)],
potentials_values( Positions, Grid ).
values_all_groups( Grid ) ->
[G123, G456, G789] = [values_all_groups(X, Grid) || X <- [1, 4, 7]],
[G1,G2,G3] = G123,
[G4,G5,G6] = G456,
[G7,G8,G9] = G789,
[G1,G2,G3,G4,G5,G6,G7,G8,G9].
values_all_groups( X, Grid ) ->[values_all_groups(X, X_offset, Grid) || X_offset <- [X, X+1, X+2]].
values_all_groups( _X, X_offset, Grid ) ->
Positions = [{X_offset, Y_offset} || Y_offset <- group_positions_close(X_offset)],
potentials_values( Positions, Grid ).
values_all_rows( Grid ) ->[values_all_rows(Y, Grid) || Y <- lists:seq(1, 9)].
values_all_rows( Y, Grid ) ->
Positions = [{X, Y} || X <- lists:seq(1, 9)],
potentials_values( Positions, Grid ).
solve_all_sure( Grid ) -> solve_all_sure( solve_all_sure_values(Grid), Grid ).
solve_all_sure( [], Grid ) -> Grid;
solve_all_sure( Sures, Grid ) -> solve_all_sure( lists:foldl(fun solve_all_sure_store/2, Grid, Sures) ).
solve_all_sure_values( Grid ) -> [{Position, Value} || {Position, [Value]} <- potentials(Grid)].
solve_all_sure_store( {Position, Value}, Acc ) -> dict:store( Position, Value, Acc ).
solve_unsure( [], Grid ) -> Grid;
solve_unsure( _Potentials, Grid ) ->
try
bt( Grid )
catch
_:{ok, Board} -> Board
end.
task( Knowns ) ->
io:fwrite( "Start~n" ),
Start = start( Knowns ),
display( Start ),
io:fwrite( "Solved~n" ),
Solved = solve( Start ),
display( Solved ),
io:nl().
|
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
| #Go | Go | package main
import (
"io"
"log"
"os"
)
func main() {
var mem = []int{
15, 17, -1, 17, -1, -1, 16, 1, -1, 16, 3, -1, 15, 15, 0, 0, -1,
//'H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!', '\n',
72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33, 10,
0,
}
for ip := 0; ip >= 0; {
switch {
case mem[ip] == -1:
mem[mem[ip+1]] = readbyte()
case mem[ip+1] == -1:
writebyte(mem[mem[ip]])
default:
b := mem[ip+1]
v := mem[b] - mem[mem[ip]]
mem[b] = v
if v <= 0 {
ip = mem[ip+2]
continue
}
}
ip += 3
}
}
func readbyte() int {
var b [1]byte
if _, err := io.ReadFull(os.Stdin, b[:]); err != nil {
log.Fatalln("read:", err)
}
return int(b[0])
}
func writebyte(b int) {
if _, err := os.Stdout.Write([]byte{byte(b)}); err != nil {
log.Fatalln("write:", err)
}
} |
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 | #Prolog | Prolog | prime(2). % use swi prolog
prime(N):-
N /\ 1 > 0, % odd
M is floor(sqrt(N)) - 1, % reverse 2*I+1
Max is M // 2, % integer division
forall(between(1, Max, I), N mod (2*I+1) > 0).
primesByDiffs([],_,[]).
primesByDiffs([Prime|Primes], Diff, [Slide|Slides]):-
length(Diff, Len0),
Len is Len0 + 1,
length(Slide, Len),
append(Slide, _, [Prime|Primes]),
select(Diff, Slide),!,
primesByDiffs(Primes, Diff, Slides).
primesByDiffs([_|Primes], Diff, Slides):-
primesByDiffs(Primes, Diff, Slides).
select([],_).
select([Diff|Diffs],[S1, S2|Stail]):-
S2 is S1 + Diff,
select(Diffs, [S2|Stail]).
run([],_).
run([Diff|Dtail], PrimeList):-
statistics(runtime,[Start|_]),
primesByDiffs(PrimeList, Diff, SlideList),
length(SlideList, Num),
statistics(runtime,[Stop|_]),
Runtime is Stop - Start,
SlideList = [First|SlideTail],
format('~|~w~t~7+ number: ~|~t~d~4+ [time(ms) ~|~t~d~3+] first: ~|~w~t~22+',[Diff, Num, Runtime, First]),
writeLast(SlideTail),!, nl,
run(Dtail, PrimeList).
writeLast([]).
writeLast(SlideTail):-
last(SlideTail, Last),
format('last: ~w',[Last]).
do:- Num is 1000000,
statistics(runtime,[Start|_]),
numlist(2, Num, List),
include(prime, List, PrimeList),
length(PrimeList, NumPrimes),
statistics(runtime,[Stop|_]),
RunTime is Stop - Start,
format('there are ~w primes until ~w [time(ms) ~w]~n',[NumPrimes, Num, RunTime]),
DiffList = [[1], [2], [2,2], [2,4], [4,2], [2,4,6],
[2,6,4], [4,2,6], [4,6,2], [6,2,4], [6,4,2]],
run(DiffList, PrimeList). |
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
| #Factor | Factor | USING: io kernel sequences ;
"Rosetta code" [ rest ] [ but-last ] [ rest but-last ] tri
[ print ] tri@ |
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.
| #PicoLisp | PicoLisp | (setq
*Bentley (apply circ (need 55))
*Bentley2 (nth *Bentley 32) )
(de subRandSeed (S)
(let (N 1 P (nth *Bentley 55))
(set P S)
(do 54
(set (setq P (nth P 35)) N)
(when (lt0 (setq N (- S N)))
(inc 'N 1000000000) )
(setq S (car P)) ) )
(do 165 (subRand)) )
(de subRand ()
(when (lt0 (dec *Bentley (pop '*Bentley2)))
(inc *Bentley 1000000000) )
(pop '*Bentley) ) |
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.
| #PL.2FI | PL/I |
subtractive_generator: procedure options (main);
declare (r, s) (0:54) fixed binary (31);
declare (i, n, seed) fixed binary (31);
/* Bentley's initialization */
seed = 292929;
s(0) = seed; s(1) = 1;
/* Compute s2,s3,...,s54 using the subtractive formula sn = s(n-2) - s(n-1)(mod 10**9). */
do n = 2 to hbound(s,1);
s(n) = mod ( s(n-2) - s(n-1), 1000000000);
end;
/* Rearrange initial values. */
do n = 0 to hbound(r,1);
r(n) = s( mod(34*(n+1), 55));
end;
do n = 55 to 219;
i = mod (n, 55);
r(i) = mod ( r(mod(n-55, 55)) - r(mod(n-24, 55)), 1000000000);
end;
do n = 220 to 235;
i = mod(n, 55);
r(i) = mod ( r(mod(n-55, 55)) - r(mod(n-24, 55)), 1000000000);
put skip list (r(i));
end;
end subtractive_generator;
|
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.
| #GW-BASIC | GW-BASIC | 10 REM Create an array with some test DATA in it
20 DIM A(5)
30 FOR I = 1 TO 5: READ A(I): NEXT I
40 DATA 1, 2, 3, 4, 5
50 REM Find the sum of elements in the array
60 S = 0
65 P = 1
70 FOR I = 1 TO 5
72 S = SUM + A(I)
75 P = P * A(I)
77 NEXT I
80 PRINT "The sum is "; S;
90 PRINT " and the product is "; P |
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.
| #Factor | Factor | 1000 [1,b] [ >float sq recip ] map-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
| #Fortran | Fortran | !****************************************************
module string_routines
!****************************************************
implicit none
private
public :: strip_comments
contains
!****************************************************
function strip_comments(str,c) result(str2)
implicit none
character(len=*),intent(in) :: str
character(len=1),intent(in) :: c !comment character
character(len=len(str)) :: str2
integer :: i
i = index(str,c)
if (i>0) then
str2 = str(1:i-1)
else
str2 = str
end if
end function strip_comments
!****************************************************
end module string_routines
!****************************************************
!****************************************************
program main
!****************************************************
! Example use of strip_comments function
!****************************************************
use string_routines, only: strip_comments
implicit none
write(*,*) strip_comments('apples, pears # and bananas', '#')
write(*,*) strip_comments('apples, pears ; and bananas', ';')
!****************************************************
end program main
!**************************************************** |
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
| #Java | Java | import java.io.*;
public class StripBlockComments{
public static String readFile(String filename) {
BufferedReader reader = new BufferedReader(new FileReader(filename));
try {
StringBuilder fileContents = new StringBuilder();
char[] buffer = new char[4096];
while (reader.read(buffer, 0, 4096) > 0) {
fileContents.append(buffer);
}
return fileContents.toString();
} finally {
reader.close();
}
}
public static String stripComments(String beginToken, String endToken,
String input) {
StringBuilder output = new StringBuilder();
while (true) {
int begin = input.indexOf(beginToken);
int end = input.indexOf(endToken, begin+beginToken.length());
if (begin == -1 || end == -1) {
output.append(input);
return output.toString();
}
output.append(input.substring(0, begin));
input = input.substring(end + endToken.length());
}
}
public static void main(String[] args) {
if (args.length < 3) {
System.out.println("Usage: BeginToken EndToken FileToProcess");
System.exit(1);
}
String begin = args[0];
String end = args[1];
String input = args[2];
try {
System.out.println(stripComments(begin, end, readFile(input)));
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
} |
http://rosettacode.org/wiki/String_interpolation_(included) | String interpolation (included) |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Given a string and defined variables or values, string interpolation is the replacement of defined character sequences in the string by values or variable values.
For example, given an original string of "Mary had a X lamb.", a value of "big", and if the language replaces X in its interpolation routine, then the result of its interpolation would be the string "Mary had a big lamb".
(Languages usually include an infrequently used character or sequence of characters to indicate what is to be replaced such as "%", or "#" rather than "X").
Task
Use your languages inbuilt string interpolation abilities to interpolate a string missing the text "little" which is held in a variable, to produce the output string "Mary had a little lamb".
If possible, give links to further documentation on your languages string interpolation features.
Note: The task is not to create a string interpolation routine, but to show a language's built-in capability.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #AWK | AWK | #!/usr/bin/awk -f
BEGIN {
str="Mary had a # lamb."
gsub(/#/, "little", str)
print str
} |
http://rosettacode.org/wiki/String_interpolation_(included) | String interpolation (included) |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Given a string and defined variables or values, string interpolation is the replacement of defined character sequences in the string by values or variable values.
For example, given an original string of "Mary had a X lamb.", a value of "big", and if the language replaces X in its interpolation routine, then the result of its interpolation would be the string "Mary had a big lamb".
(Languages usually include an infrequently used character or sequence of characters to indicate what is to be replaced such as "%", or "#" rather than "X").
Task
Use your languages inbuilt string interpolation abilities to interpolate a string missing the text "little" which is held in a variable, to produce the output string "Mary had a little lamb".
If possible, give links to further documentation on your languages string interpolation features.
Note: The task is not to create a string interpolation routine, but to show a language's built-in capability.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #BASIC | BASIC | x$ = "big"
print "Mary had a "; x$; " lamb"
x$ = "little"
print "Mary also had a "; ljust(x$, length(x$)); " lamb" |
http://rosettacode.org/wiki/Sum_to_100 | Sum to 100 | Task
Find solutions to the sum to one hundred puzzle.
Add (insert) the mathematical
operators + or - (plus
or minus) before any of the digits in the
decimal numeric string 123456789 such that the
resulting mathematical expression adds up to a
particular sum (in this iconic case, 100).
Example:
123 + 4 - 5 + 67 - 89 = 100
Show all output here.
Show all solutions that sum to 100
Show the sum that has the maximum number of solutions (from zero to infinity‡)
Show the lowest positive sum that can't be expressed (has no solutions), using the rules for this task
Show the ten highest numbers that can be expressed using the rules for this task (extra credit)
‡ (where infinity would be a relatively small 123,456,789)
An example of a sum that can't be expressed (within the rules of this task) is: 5074
(which, of course, isn't the lowest positive sum that can't be expressed).
| #Ruby | Ruby | digits = ("1".."9").to_a
ar = ["+", "-", ""].repeated_permutation(digits.size).filter_map do |op_perm|
str = op_perm.zip(digits).join
str unless str.start_with?("+")
end
res = ar.group_by{|str| eval(str)}
puts res[100] , ""
sum, solutions = res.max_by{|k,v| v.size}
puts "#{sum} has #{solutions.size} solutions.", ""
no_solution = (1..).find{|n| res[n] == nil}
puts "#{no_solution} is the lowest positive number without a solution.", ""
puts res.max(10).map{|pair| pair.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
| #C | C | #include <string.h>
#include <stdio.h>
#include <stdlib.h>
/* removes all chars from string */
char *strip_chars(const char *string, const char *chars)
{
char * newstr = malloc(strlen(string) + 1);
int counter = 0;
for ( ; *string; string++) {
if (!strchr(chars, *string)) {
newstr[ counter ] = *string;
++ counter;
}
}
newstr[counter] = 0;
return newstr;
}
int main(void)
{
char *new = strip_chars("She was a soul stripper. She took my heart!", "aei");
printf("%s\n", new);
free(new);
return 0;
} |
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
| #C.23 | C# | using System;
public static string RemoveCharactersFromString(string testString, string removeChars)
{
char[] charAry = removeChars.ToCharArray();
string returnString = testString;
foreach (char c in charAry)
{
while (returnString.IndexOf(c) > -1)
{
returnString = returnString.Remove(returnString.IndexOf(c), 1);
}
}
return returnString;
} |
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.
| #Falcon | Falcon |
/* created by Aykayayciti Earl Lamont Montgomery
April 9th, 2018 */
s = "fun "
s = s + "Falcon"
> 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.
| #Forth | Forth | \ the following functions are commonly native to a Forth system. Shown for completeness
: C+! ( n addr -- ) dup c@ rot + swap c! ; \ primitive: increment a byte at addr by n
: +PLACE ( addr1 length addr2 -- ) \ Append addr1 length to addr2
2dup 2>r count + swap move 2r> c+! ;
: PLACE ( addr1 len addr2 -- ) \ addr1 and length, placed at addr2 as counted string
2dup 2>r 1+ swap move 2r> c! ;
\ Example begins here
: PREPEND ( addr len addr2 -- addr2)
>R \ push addr2 to return stack
PAD PLACE \ place the 1st string in PAD
R@ count PAD +PLACE \ append PAD with addr2 string
PAD count R@ PLACE \ move the whole thing back into addr2
R> ; \ leave a copy of addr2 on the data stack
: writeln ( addr -- ) cr count type ; \ syntax sugar for testing |
http://rosettacode.org/wiki/String_comparison | String comparison |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Demonstrate how to compare two strings from within the language and how to achieve a lexical comparison.
The task should demonstrate:
Comparing two strings for exact equality
Comparing two strings for inequality (i.e., the inverse of exact equality)
Comparing two strings to see if one is lexically ordered before than the other
Comparing two strings to see if one is lexically ordered after than the other
How to achieve both case sensitive comparisons and case insensitive comparisons within the language
How the language handles comparison of numeric strings if these are not treated lexically
Demonstrate any other kinds of string comparisons that the language provides, particularly as it relates to your type system.
For example, you might demonstrate the difference between generic/polymorphic comparison and coercive/allomorphic comparison if your language supports such a distinction.
Here "generic/polymorphic" comparison means that the function or operator you're using doesn't always do string comparison, but bends the actual semantics of the comparison depending on the types one or both arguments; with such an operator, you achieve string comparison only if the arguments are sufficiently string-like in type or appearance.
In contrast, a "coercive/allomorphic" comparison function or operator has fixed string-comparison semantics regardless of the argument type; instead of the operator bending, it's the arguments that are forced to bend instead and behave like strings if they can, and the operator simply fails if the arguments cannot be viewed somehow as strings. A language may have one or both of these kinds of operators; see the Raku entry for an example of a language with both kinds of operators.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Astro | Astro | fun compare(a, b):
print("\n$a is of type ${typeof(a)} and $b is of type ${typeof(b)}")
if a < b: print("$a is strictly less than $b")
if a <= b: print("$a is less than or equal to $b")
if a > b: print("$a is strictly greater than $b")
if a >= b: print("$a is greater than or equal to $b")
if a == b: print("$a is equal to $b")
if a != b: print("$a is not equal to $b")
if a is b: print("$a has object identity with $b")
if a is not b: print("$a has negated object identity with $b")
compare("YUP", "YUP")
compare('a', 'z')
compare("24", "123")
compare(24, 123)
compare(5.0, 5)
|
http://rosettacode.org/wiki/String_case | String case | Task
Take the string alphaBETA and demonstrate how to convert it to:
upper-case and
lower-case
Use the default encoding of a string literal or plain ASCII if there is no string literal in your language.
Note: In some languages alphabets toLower and toUpper is not reversable.
Show any additional case conversion functions (e.g. swapping case, capitalizing the first letter, etc.) that may be included in the library of your language.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #APL | APL | a←'abcdefghijklmnopqrstuvwxyz'
A←'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
X←'alphaBETA'
(a,⎕AV)[(A,⎕AV)⍳'alphaBETA']
alphabeta
(A,⎕AV)[(a,⎕AV)⍳'alphaBETA']
ALPHABETA
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.