task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/String_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
| #VBScript | VBScript | LenB(string|varname) |
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
| #Visual_Basic | Visual Basic | Module ByteLength
Function GetByteLength(s As String, encoding As Text.Encoding) As Integer
Return encoding.GetByteCount(s)
End Function
End Module |
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
| #Visual_Basic_.NET | Visual Basic .NET | Module ByteLength
Function GetByteLength(s As String, encoding As Text.Encoding) As Integer
Return encoding.GetByteCount(s)
End Function
End Module |
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
| #Vlang | Vlang | fn main() {
m := "møøse"
u := "𝔘𝔫𝔦𝔠𝔬𝔡𝔢"
j := "J̲o̲s̲é̲"
println("$m.len $m ${m.bytes()}")
println("$u.len $u ${u.bytes()}")
println("$j.len $j ${j.bytes()}")
} |
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
| #Wren | Wren | System.print("møøse".bytes.count)
System.print("𝔘𝔫𝔦𝔠𝔬𝔡𝔢".bytes.count)
System.print("J̲o̲s̲é̲".bytes.count) |
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
| #x86_Assembly | x86 Assembly |
.data
string: .asciz "Test"
.text
.globl main
main:
pushl %ebp
movl %esp, %ebp
pushl %edi
xorb %al, %al
movl $-1, %ecx
movl $string, %edi
cld
repne scasb
not %ecx
dec %ecx
popl %edi
;; string length is stored in %ecx register
leave
ret
|
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
| #XPL0 | XPL0 | include c:\cxpl\stdlib;
IntOut(0, StrLen("Character length = Byte length = String length = ")) |
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
| #XSLT | XSLT | <?xml version="1.0" encoding="UTF-8"?> |
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
| #xTalk | xTalk | put the length of "Hello World" |
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
| #Yorick | Yorick | strlen("Hello, world!") |
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
| #Z80_Assembly | Z80 Assembly | ; input: HL - pointer to the 0th char of a string.
; outputs length to B. HL will point to the last character in the string just before the terminator.
; length is one-indexed and does not include the terminator. A null string will return 0 in B.
; "Terminator" is a label for a constant that can be configured in the source code. My code uses 0.
; Sample Usage:
; ld hl,MyString
; call GetStringLength
GetStringLength:
ld b,0
loop_getStringLength:
ld a,(hl) ;load the next char
cp Terminator ;is it the terminator?
ret z ;if so, exit.
inc hl ;next char
inc b ;increment the byte count
jr loop_getStringLength |
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
| #zkl | zkl | "abc".len() //-->3
"\ufeff\u00A2 \u20ac".len() //-->9 "BOM¢ €" |
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
| #Zig | Zig | const std = @import("std");
pub fn main() !void {
const string: []const u8 = "Hello, world!";
const cnt_codepts_utf8 = try std.unicode.utf8CountCodepoints(string);
// There is no sane and portable extended ascii, so the best
// we get is counting the bytes and assume regular ascii.
const cnt_bytes_utf8 = string.len;
const stdout_wr = std.io.getStdOut().writer();
try stdout_wr.print("codepoints = {d}, bytes = {d}\n", .{ cnt_codepts_utf8, cnt_bytes_utf8 });
// TODO utf16
} |
http://rosettacode.org/wiki/Stirling_numbers_of_the_second_kind | Stirling numbers of the second kind | Stirling numbers of the second kind, or Stirling partition numbers, are the
number of ways to partition a set of n objects into k non-empty subsets. They are
closely related to Bell numbers, and may be derived from them.
Stirling numbers of the second kind obey the recurrence relation:
S2(n, 0) and S2(0, k) = 0 # for n, k > 0
S2(n, n) = 1
S2(n + 1, k) = k * S2(n, k) + S2(n, k - 1)
Task
Write a routine (function, procedure, whatever) to find Stirling numbers of the second kind. There are several methods to generate Stirling numbers of the second kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.
Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the second kind, S2(n, k), up to S2(12, 12). it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S2(n, k) == 0 (when k > n).
If your language supports large integers, find and show here, on this page, the maximum value of S2(n, k) where n == 100.
See also
Wikipedia - Stirling numbers of the second kind
OEIS:A008277 - Stirling numbers of the second kind
Related Tasks
Stirling numbers of the first kind
Bell numbers
Lah numbers
| #11l | 11l | [(Int, Int) = BigInt] computed
F sterling2(n, k)
V key = (n, k)
I key C :computed
R :computed[key]
I n == k == 0
R BigInt(1)
I (n > 0 & k == 0) | (n == 0 & k > 0)
R BigInt(0)
I n == k
R BigInt(1)
I k > n
R BigInt(0)
V result = k * sterling2(n - 1, k) + sterling2(n - 1, k - 1)
:computed[key] = result
R result
print(‘Stirling numbers of the second kind:’)
V MAX = 12
print(‘n/k’.ljust(10), end' ‘’)
L(n) 0 .. MAX
print(String(n).rjust(10), end' ‘’)
print()
L(n) 0 .. MAX
print(String(n).ljust(10), end' ‘’)
L(k) 0 .. n
print(String(sterling2(n, k)).rjust(10), end' ‘’)
print()
print(‘The maximum value of S2(100, k) = ’)
BigInt previous = 0
L(k) 1 .. 100
V current = sterling2(100, k)
I current > previous
previous = current
E
print("#.\n(#. digits, k = #.)\n".format(previous, String(previous).len, k - 1))
L.break |
http://rosettacode.org/wiki/Stirling_numbers_of_the_second_kind | Stirling numbers of the second kind | Stirling numbers of the second kind, or Stirling partition numbers, are the
number of ways to partition a set of n objects into k non-empty subsets. They are
closely related to Bell numbers, and may be derived from them.
Stirling numbers of the second kind obey the recurrence relation:
S2(n, 0) and S2(0, k) = 0 # for n, k > 0
S2(n, n) = 1
S2(n + 1, k) = k * S2(n, k) + S2(n, k - 1)
Task
Write a routine (function, procedure, whatever) to find Stirling numbers of the second kind. There are several methods to generate Stirling numbers of the second kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.
Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the second kind, S2(n, k), up to S2(12, 12). it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S2(n, k) == 0 (when k > n).
If your language supports large integers, find and show here, on this page, the maximum value of S2(n, k) where n == 100.
See also
Wikipedia - Stirling numbers of the second kind
OEIS:A008277 - Stirling numbers of the second kind
Related Tasks
Stirling numbers of the first kind
Bell numbers
Lah numbers
| #ALGOL_68 | ALGOL 68 | BEGIN
# show some Stirling numbers of the second kind #
# specify the precision of LONG LONG INT, somewhat under 160 digits are #
# needed for Stirling numbers of the second kind with n, k = 100 #
PR precision 160 PR
MODE SINT = LONG LONG INT;
# returns a triangular matrix of Stirling numbers up to max n, max n #
PROC make s2 = ( INT max n )REF[,]SINT:
BEGIN
REF[,]SINT s2 := HEAP[ 0 : max n, 0 : max n ]SINT;
FOR n FROM 0 TO max n DO FOR k FROM 0 TO max n DO s2[ n, k ] := 0 OD OD;
FOR n FROM 0 TO max n DO s2[ n, n ] := 1 OD;
FOR n FROM 0 TO max n - 1 DO
FOR k FROM 1 TO n DO
s2[ n + 1, k ] := k * s2[ n, k ] + s2[ n, k - 1 ]
OD
OD;
s2
END # make s2 # ;
# task requirements: #
# print Stirling numbers up to n, k = 12 #
BEGIN
INT max stirling = 12;
REF[,]SINT s2 = make s2( max stirling );
print( ( "Stirling numbers of the second kind:", newline ) );
print( ( " k" ) );
FOR k FROM 0 TO max stirling DO print( ( whole( k, -10 ) ) ) OD;
print( ( newline, " n", newline ) );
FOR n FROM 0 TO max stirling DO
print( ( whole( n, -2 ) ) );
FOR k FROM 0 TO n DO
print( ( whole( s2[ n, k ], -10 ) ) )
OD;
print( ( newline ) )
OD
END;
# find the maximum Stirling number with n = 100 #
BEGIN
INT max stirling = 100;
REF[,]SINT s2 = make s2( max stirling );
SINT max 100 := 0;
FOR k FROM 0 TO max stirling DO
IF s2[ max stirling, k ] > max 100 THEN max 100 := s2[ max stirling, k ] FI
OD;
print( ( "Maximum Stirling number of the second kind with n = 100:", newline ) );
print( ( whole( max 100, 0 ), newline ) )
END
END |
http://rosettacode.org/wiki/Stirling_numbers_of_the_second_kind | Stirling numbers of the second kind | Stirling numbers of the second kind, or Stirling partition numbers, are the
number of ways to partition a set of n objects into k non-empty subsets. They are
closely related to Bell numbers, and may be derived from them.
Stirling numbers of the second kind obey the recurrence relation:
S2(n, 0) and S2(0, k) = 0 # for n, k > 0
S2(n, n) = 1
S2(n + 1, k) = k * S2(n, k) + S2(n, k - 1)
Task
Write a routine (function, procedure, whatever) to find Stirling numbers of the second kind. There are several methods to generate Stirling numbers of the second kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.
Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the second kind, S2(n, k), up to S2(12, 12). it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S2(n, k) == 0 (when k > n).
If your language supports large integers, find and show here, on this page, the maximum value of S2(n, k) where n == 100.
See also
Wikipedia - Stirling numbers of the second kind
OEIS:A008277 - Stirling numbers of the second kind
Related Tasks
Stirling numbers of the first kind
Bell numbers
Lah numbers
| #ALGOL_W | ALGOL W | begin % show some Stirling numbers of the second kind %
integer MAX_STIRLING;
MAX_STIRLING := 12;
begin
% construct a matrix of Stirling numbers up to max n, max n %
integer array s2 ( 0 :: MAX_STIRLING, 0 :: MAX_STIRLING );
for n := 0 until MAX_STIRLING do begin
for k := 0 until MAX_STIRLING do s2( n, k ) := 0
end for_n ;
for n := 0 until MAX_STIRLING do s2( n, n ) := 1;
for n := 0 until MAX_STIRLING - 1 do begin
for k := 1 until n do begin
s2( n + 1, k ) := k * s2( n, k ) + s2( n, k - 1 );
end for_k
end for_n ;
% print the Stirling numbers %
write( "Stirling numbers of the second kind:" );
write( " k" );
for k := 0 until MAX_STIRLING do writeon( i_w := 10, s_w := 0, k );
write( " n" );
for n := 0 until MAX_STIRLING do begin
write( i_w := 2, s_w := 0, n );
for k := 0 until n do writeon( i_w := 10, s_w := 0, s2( n, k ) );
end for_n
end
end. |
http://rosettacode.org/wiki/Stirling_numbers_of_the_second_kind | Stirling numbers of the second kind | Stirling numbers of the second kind, or Stirling partition numbers, are the
number of ways to partition a set of n objects into k non-empty subsets. They are
closely related to Bell numbers, and may be derived from them.
Stirling numbers of the second kind obey the recurrence relation:
S2(n, 0) and S2(0, k) = 0 # for n, k > 0
S2(n, n) = 1
S2(n + 1, k) = k * S2(n, k) + S2(n, k - 1)
Task
Write a routine (function, procedure, whatever) to find Stirling numbers of the second kind. There are several methods to generate Stirling numbers of the second kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.
Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the second kind, S2(n, k), up to S2(12, 12). it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S2(n, k) == 0 (when k > n).
If your language supports large integers, find and show here, on this page, the maximum value of S2(n, k) where n == 100.
See also
Wikipedia - Stirling numbers of the second kind
OEIS:A008277 - Stirling numbers of the second kind
Related Tasks
Stirling numbers of the first kind
Bell numbers
Lah numbers
| #BASIC | BASIC | 10 DEFINT N,K: DEFDBL S: DEFSTR F
20 DIM S2(12,12),F(12)
30 FOR N=0 TO 12: READ F(N): NEXT N
40 S2(0,0)=1
50 FOR K=1 TO 12
60 FOR N=1 TO 12
70 IF N=K THEN S2(N,K)=1 ELSE S2(N,K)=K*S2(N-1,K)+S2(N-1,K-1)
80 NEXT N,K
90 FOR N=0 TO 12
100 FOR K=0 TO 12
110 IF N>=K THEN PRINT USING F(K);S2(N,K);
120 NEXT K
130 PRINT
140 NEXT N
150 DATA ##,##,#####,######,#######,########
160 DATA ########,#######,#######,######,#####,###,## |
http://rosettacode.org/wiki/Stirling_numbers_of_the_second_kind | Stirling numbers of the second kind | Stirling numbers of the second kind, or Stirling partition numbers, are the
number of ways to partition a set of n objects into k non-empty subsets. They are
closely related to Bell numbers, and may be derived from them.
Stirling numbers of the second kind obey the recurrence relation:
S2(n, 0) and S2(0, k) = 0 # for n, k > 0
S2(n, n) = 1
S2(n + 1, k) = k * S2(n, k) + S2(n, k - 1)
Task
Write a routine (function, procedure, whatever) to find Stirling numbers of the second kind. There are several methods to generate Stirling numbers of the second kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.
Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the second kind, S2(n, k), up to S2(12, 12). it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S2(n, k) == 0 (when k > n).
If your language supports large integers, find and show here, on this page, the maximum value of S2(n, k) where n == 100.
See also
Wikipedia - Stirling numbers of the second kind
OEIS:A008277 - Stirling numbers of the second kind
Related Tasks
Stirling numbers of the first kind
Bell numbers
Lah numbers
| #C | C | #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct stirling_cache_tag {
int max;
int* values;
} stirling_cache;
int stirling_number2(stirling_cache* sc, int n, int k) {
if (k == n)
return 1;
if (k == 0 || k > n || n > sc->max)
return 0;
return sc->values[n*(n-1)/2 + k - 1];
}
bool stirling_cache_create(stirling_cache* sc, int max) {
int* values = calloc(max * (max + 1)/2, sizeof(int));
if (values == NULL)
return false;
sc->max = max;
sc->values = values;
for (int n = 1; n <= max; ++n) {
for (int k = 1; k < n; ++k) {
int s1 = stirling_number2(sc, n - 1, k - 1);
int s2 = stirling_number2(sc, n - 1, k);
values[n*(n-1)/2 + k - 1] = s1 + s2 * k;
}
}
return true;
}
void stirling_cache_destroy(stirling_cache* sc) {
free(sc->values);
sc->values = NULL;
}
void print_stirling_numbers(stirling_cache* sc, int max) {
printf("Stirling numbers of the second kind:\nn/k");
for (int k = 0; k <= max; ++k)
printf(k == 0 ? "%2d" : "%8d", k);
printf("\n");
for (int n = 0; n <= max; ++n) {
printf("%2d ", n);
for (int k = 0; k <= n; ++k)
printf(k == 0 ? "%2d" : "%8d", stirling_number2(sc, n, k));
printf("\n");
}
}
int main() {
stirling_cache sc = { 0 };
const int max = 12;
if (!stirling_cache_create(&sc, max)) {
fprintf(stderr, "Out of memory\n");
return 1;
}
print_stirling_numbers(&sc, max);
stirling_cache_destroy(&sc);
return 0;
} |
http://rosettacode.org/wiki/Stirling_numbers_of_the_second_kind | Stirling numbers of the second kind | Stirling numbers of the second kind, or Stirling partition numbers, are the
number of ways to partition a set of n objects into k non-empty subsets. They are
closely related to Bell numbers, and may be derived from them.
Stirling numbers of the second kind obey the recurrence relation:
S2(n, 0) and S2(0, k) = 0 # for n, k > 0
S2(n, n) = 1
S2(n + 1, k) = k * S2(n, k) + S2(n, k - 1)
Task
Write a routine (function, procedure, whatever) to find Stirling numbers of the second kind. There are several methods to generate Stirling numbers of the second kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.
Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the second kind, S2(n, k), up to S2(12, 12). it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S2(n, k) == 0 (when k > n).
If your language supports large integers, find and show here, on this page, the maximum value of S2(n, k) where n == 100.
See also
Wikipedia - Stirling numbers of the second kind
OEIS:A008277 - Stirling numbers of the second kind
Related Tasks
Stirling numbers of the first kind
Bell numbers
Lah numbers
| #C.2B.2B | C++ | #include <algorithm>
#include <iomanip>
#include <iostream>
#include <map>
#include <gmpxx.h>
using integer = mpz_class;
class stirling2 {
public:
integer get(int n, int k);
private:
std::map<std::pair<int, int>, integer> cache_;
};
integer stirling2::get(int n, int k) {
if (k == n)
return 1;
if (k == 0 || k > n)
return 0;
auto p = std::make_pair(n, k);
auto i = cache_.find(p);
if (i != cache_.end())
return i->second;
integer s = k * get(n - 1, k) + get(n - 1, k - 1);
cache_.emplace(p, s);
return s;
}
void print_stirling_numbers(stirling2& s2, int n) {
std::cout << "Stirling numbers of the second kind:\nn/k";
for (int j = 0; j <= n; ++j) {
std::cout << std::setw(j == 0 ? 2 : 8) << j;
}
std::cout << '\n';
for (int i = 0; i <= n; ++i) {
std::cout << std::setw(2) << i << ' ';
for (int j = 0; j <= i; ++j)
std::cout << std::setw(j == 0 ? 2 : 8) << s2.get(i, j);
std::cout << '\n';
}
}
int main() {
stirling2 s2;
print_stirling_numbers(s2, 12);
std::cout << "Maximum value of S2(n,k) where n == 100:\n";
integer max = 0;
for (int k = 0; k <= 100; ++k)
max = std::max(max, s2.get(100, k));
std::cout << max << '\n';
return 0;
} |
http://rosettacode.org/wiki/Stirling_numbers_of_the_second_kind | Stirling numbers of the second kind | Stirling numbers of the second kind, or Stirling partition numbers, are the
number of ways to partition a set of n objects into k non-empty subsets. They are
closely related to Bell numbers, and may be derived from them.
Stirling numbers of the second kind obey the recurrence relation:
S2(n, 0) and S2(0, k) = 0 # for n, k > 0
S2(n, n) = 1
S2(n + 1, k) = k * S2(n, k) + S2(n, k - 1)
Task
Write a routine (function, procedure, whatever) to find Stirling numbers of the second kind. There are several methods to generate Stirling numbers of the second kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.
Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the second kind, S2(n, k), up to S2(12, 12). it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S2(n, k) == 0 (when k > n).
If your language supports large integers, find and show here, on this page, the maximum value of S2(n, k) where n == 100.
See also
Wikipedia - Stirling numbers of the second kind
OEIS:A008277 - Stirling numbers of the second kind
Related Tasks
Stirling numbers of the first kind
Bell numbers
Lah numbers
| #D | D | import std.bigint;
import std.conv;
import std.functional;
import std.stdio;
alias sterling2 = memoize!sterling2Impl;
BigInt sterling2Impl(int n, int k) {
if (n == 0 && k == 0) {
return BigInt(1);
}
if ((n > 0 && k == 0) || (n == 0 && k > 0)) {
return BigInt(0);
}
if (n == k) {
return BigInt(1);
}
if (k > n) {
return BigInt(0);
}
return BigInt(k) * sterling2(n - 1, k) + sterling2(n - 1, k - 1);
}
void main() {
writeln("Stirling numbers of the second kind:");
int max = 12;
write("n/k");
for (int n = 0; n <= max; n++) {
writef("%10d", n);
}
writeln;
for (int n = 0; n <= max; n++) {
writef("%-3d", n);
for (int k = 0; k <= n; k++) {
writef("%10s", sterling2(n, k));
}
writeln;
}
writeln("The maximum value of S2(100, k) = ");
auto previous = BigInt(0);
for (int k = 1; k <= 100; k++) {
auto current = sterling2(100, k);
if (current > previous) {
previous = current;
} else {
writeln(previous);
auto ps = previous.to!string;
writefln("(%d digits, k = %d)", ps.length, k - 1);
break;
}
}
} |
http://rosettacode.org/wiki/Stirling_numbers_of_the_second_kind | Stirling numbers of the second kind | Stirling numbers of the second kind, or Stirling partition numbers, are the
number of ways to partition a set of n objects into k non-empty subsets. They are
closely related to Bell numbers, and may be derived from them.
Stirling numbers of the second kind obey the recurrence relation:
S2(n, 0) and S2(0, k) = 0 # for n, k > 0
S2(n, n) = 1
S2(n + 1, k) = k * S2(n, k) + S2(n, k - 1)
Task
Write a routine (function, procedure, whatever) to find Stirling numbers of the second kind. There are several methods to generate Stirling numbers of the second kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.
Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the second kind, S2(n, k), up to S2(12, 12). it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S2(n, k) == 0 (when k > n).
If your language supports large integers, find and show here, on this page, the maximum value of S2(n, k) where n == 100.
See also
Wikipedia - Stirling numbers of the second kind
OEIS:A008277 - Stirling numbers of the second kind
Related Tasks
Stirling numbers of the first kind
Bell numbers
Lah numbers
| #Factor | Factor | USING: combinators.short-circuit formatting io kernel math
math.extras prettyprint sequences ;
RENAME: stirling math.extras => (stirling)
IN: rosetta-code.stirling-second
! Tweak Factor's in-built stirling function for k=0
: stirling ( n k -- m )
2dup { [ = not ] [ nip zero? ] } 2&&
[ 2drop 0 ] [ (stirling) ] if ;
"Stirling numbers of the second kind: n k stirling:" print
"n\\k" write 13 dup [ "%8d" printf ] each-integer nl
<iota> [
dup dup "%-2d " printf [0,b] [
stirling "%8d" printf
] with each nl
] each nl
"Maximum value from the 100 _ stirling row:" print
100 <iota> [ 100 swap stirling ] map supremum . |
http://rosettacode.org/wiki/Stirling_numbers_of_the_second_kind | Stirling numbers of the second kind | Stirling numbers of the second kind, or Stirling partition numbers, are the
number of ways to partition a set of n objects into k non-empty subsets. They are
closely related to Bell numbers, and may be derived from them.
Stirling numbers of the second kind obey the recurrence relation:
S2(n, 0) and S2(0, k) = 0 # for n, k > 0
S2(n, n) = 1
S2(n + 1, k) = k * S2(n, k) + S2(n, k - 1)
Task
Write a routine (function, procedure, whatever) to find Stirling numbers of the second kind. There are several methods to generate Stirling numbers of the second kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.
Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the second kind, S2(n, k), up to S2(12, 12). it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S2(n, k) == 0 (when k > n).
If your language supports large integers, find and show here, on this page, the maximum value of S2(n, k) where n == 100.
See also
Wikipedia - Stirling numbers of the second kind
OEIS:A008277 - Stirling numbers of the second kind
Related Tasks
Stirling numbers of the first kind
Bell numbers
Lah numbers
| #FreeBASIC | FreeBASIC | dim as integer S2(0 to 12, 0 to 12) 'initially set with zeroes
dim as ubyte n, k
dim as string outstr
function padto( i as ubyte, j as integer ) as string
return wspace(i-len(str(j)))+str(j)
end function
for k = 0 to 12 'calculate table
S2(k,k)=1
next k
for n = 1 to 11
for k = 1 to 12
S2(n+1,k) = k*S2(n,k) + S2(n,k-1)
next k
next n
print "Stirling numbers of the second kind"
print
outstr = " k"
for k=0 to 12
outstr += padto(12, k)
next k
print outstr
print " n"
for n = 0 to 12
outstr = padto(2, n)+" "
for k = 0 to 12
outstr += padto(12, S2(n, k))
next k
print outstr
next n |
http://rosettacode.org/wiki/Stirling_numbers_of_the_second_kind | Stirling numbers of the second kind | Stirling numbers of the second kind, or Stirling partition numbers, are the
number of ways to partition a set of n objects into k non-empty subsets. They are
closely related to Bell numbers, and may be derived from them.
Stirling numbers of the second kind obey the recurrence relation:
S2(n, 0) and S2(0, k) = 0 # for n, k > 0
S2(n, n) = 1
S2(n + 1, k) = k * S2(n, k) + S2(n, k - 1)
Task
Write a routine (function, procedure, whatever) to find Stirling numbers of the second kind. There are several methods to generate Stirling numbers of the second kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.
Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the second kind, S2(n, k), up to S2(12, 12). it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S2(n, k) == 0 (when k > n).
If your language supports large integers, find and show here, on this page, the maximum value of S2(n, k) where n == 100.
See also
Wikipedia - Stirling numbers of the second kind
OEIS:A008277 - Stirling numbers of the second kind
Related Tasks
Stirling numbers of the first kind
Bell numbers
Lah numbers
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import (
"fmt"
"math/big"
)
func main() {
limit := 100
last := 12
s2 := make([][]*big.Int, limit+1)
for n := 0; n <= limit; n++ {
s2[n] = make([]*big.Int, limit+1)
for k := 0; k <= limit; k++ {
s2[n][k] = new(big.Int)
}
s2[n][n].SetInt64(int64(1))
}
var t big.Int
for n := 1; n <= limit; n++ {
for k := 1; k <= n; k++ {
t.SetInt64(int64(k))
t.Mul(&t, s2[n-1][k])
s2[n][k].Add(&t, s2[n-1][k-1])
}
}
fmt.Println("Stirling numbers of the second kind: S2(n, k):")
fmt.Printf("n/k")
for i := 0; i <= last; i++ {
fmt.Printf("%9d ", i)
}
fmt.Printf("\n--")
for i := 0; i <= last; i++ {
fmt.Printf("----------")
}
fmt.Println()
for n := 0; n <= last; n++ {
fmt.Printf("%2d ", n)
for k := 0; k <= n; k++ {
fmt.Printf("%9d ", s2[n][k])
}
fmt.Println()
}
fmt.Println("\nMaximum value from the S2(100, *) row:")
max := new(big.Int).Set(s2[limit][0])
for k := 1; k <= limit; k++ {
if s2[limit][k].Cmp(max) > 0 {
max.Set(s2[limit][k])
}
}
fmt.Println(max)
fmt.Printf("which has %d digits.\n", len(max.String()))
} |
http://rosettacode.org/wiki/Stirling_numbers_of_the_second_kind | Stirling numbers of the second kind | Stirling numbers of the second kind, or Stirling partition numbers, are the
number of ways to partition a set of n objects into k non-empty subsets. They are
closely related to Bell numbers, and may be derived from them.
Stirling numbers of the second kind obey the recurrence relation:
S2(n, 0) and S2(0, k) = 0 # for n, k > 0
S2(n, n) = 1
S2(n + 1, k) = k * S2(n, k) + S2(n, k - 1)
Task
Write a routine (function, procedure, whatever) to find Stirling numbers of the second kind. There are several methods to generate Stirling numbers of the second kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.
Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the second kind, S2(n, k), up to S2(12, 12). it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S2(n, k) == 0 (when k > n).
If your language supports large integers, find and show here, on this page, the maximum value of S2(n, k) where n == 100.
See also
Wikipedia - Stirling numbers of the second kind
OEIS:A008277 - Stirling numbers of the second kind
Related Tasks
Stirling numbers of the first kind
Bell numbers
Lah numbers
| #Go | Go | package main
import (
"fmt"
"math/big"
)
func main() {
limit := 100
last := 12
s2 := make([][]*big.Int, limit+1)
for n := 0; n <= limit; n++ {
s2[n] = make([]*big.Int, limit+1)
for k := 0; k <= limit; k++ {
s2[n][k] = new(big.Int)
}
s2[n][n].SetInt64(int64(1))
}
var t big.Int
for n := 1; n <= limit; n++ {
for k := 1; k <= n; k++ {
t.SetInt64(int64(k))
t.Mul(&t, s2[n-1][k])
s2[n][k].Add(&t, s2[n-1][k-1])
}
}
fmt.Println("Stirling numbers of the second kind: S2(n, k):")
fmt.Printf("n/k")
for i := 0; i <= last; i++ {
fmt.Printf("%9d ", i)
}
fmt.Printf("\n--")
for i := 0; i <= last; i++ {
fmt.Printf("----------")
}
fmt.Println()
for n := 0; n <= last; n++ {
fmt.Printf("%2d ", n)
for k := 0; k <= n; k++ {
fmt.Printf("%9d ", s2[n][k])
}
fmt.Println()
}
fmt.Println("\nMaximum value from the S2(100, *) row:")
max := new(big.Int).Set(s2[limit][0])
for k := 1; k <= limit; k++ {
if s2[limit][k].Cmp(max) > 0 {
max.Set(s2[limit][k])
}
}
fmt.Println(max)
fmt.Printf("which has %d digits.\n", len(max.String()))
} |
http://rosettacode.org/wiki/Stirling_numbers_of_the_second_kind | Stirling numbers of the second kind | Stirling numbers of the second kind, or Stirling partition numbers, are the
number of ways to partition a set of n objects into k non-empty subsets. They are
closely related to Bell numbers, and may be derived from them.
Stirling numbers of the second kind obey the recurrence relation:
S2(n, 0) and S2(0, k) = 0 # for n, k > 0
S2(n, n) = 1
S2(n + 1, k) = k * S2(n, k) + S2(n, k - 1)
Task
Write a routine (function, procedure, whatever) to find Stirling numbers of the second kind. There are several methods to generate Stirling numbers of the second kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.
Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the second kind, S2(n, k), up to S2(12, 12). it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S2(n, k) == 0 (when k > n).
If your language supports large integers, find and show here, on this page, the maximum value of S2(n, k) where n == 100.
See also
Wikipedia - Stirling numbers of the second kind
OEIS:A008277 - Stirling numbers of the second kind
Related Tasks
Stirling numbers of the first kind
Bell numbers
Lah numbers
| #Haskell | Haskell | import Text.Printf (printf)
import Data.List (groupBy)
import qualified Data.MemoCombinators as Memo
stirling2 :: Integral a => (a, a) -> a
stirling2 = Memo.pair Memo.integral Memo.integral f
where
f (n, k)
| n == 0 && k == 0 = 1
| (n > 0 && k == 0) || (n == 0 && k > 0) = 0
| n == k = 1
| k > n = 0
| otherwise = k * stirling2 (pred n, k) + stirling2 (pred n, pred k)
main :: IO ()
main = do
printf "n/k"
mapM_ (printf "%10d") ([0..12] :: [Int]) >> printf "\n"
printf "%s\n" $ replicate (13 * 10 + 3) '-'
mapM_ (\row -> printf "%2d|" (fst $ head row) >>
mapM_ (printf "%10d" . stirling2) row >> printf "\n") table
printf "\nThe maximum value of S2(100, k):\n%d\n" $
maximum ([stirling2 (100, n) | n <- [1..100]] :: [Integer])
where
table :: [[(Int, Int)]]
table = groupBy (\a b -> fst a == fst b) $ (,) <$> [0..12] <*> [0..12] |
http://rosettacode.org/wiki/Stirling_numbers_of_the_second_kind | Stirling numbers of the second kind | Stirling numbers of the second kind, or Stirling partition numbers, are the
number of ways to partition a set of n objects into k non-empty subsets. They are
closely related to Bell numbers, and may be derived from them.
Stirling numbers of the second kind obey the recurrence relation:
S2(n, 0) and S2(0, k) = 0 # for n, k > 0
S2(n, n) = 1
S2(n + 1, k) = k * S2(n, k) + S2(n, k - 1)
Task
Write a routine (function, procedure, whatever) to find Stirling numbers of the second kind. There are several methods to generate Stirling numbers of the second kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.
Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the second kind, S2(n, k), up to S2(12, 12). it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S2(n, k) == 0 (when k > n).
If your language supports large integers, find and show here, on this page, the maximum value of S2(n, k) where n == 100.
See also
Wikipedia - Stirling numbers of the second kind
OEIS:A008277 - Stirling numbers of the second kind
Related Tasks
Stirling numbers of the first kind
Bell numbers
Lah numbers
| #J | J | test=: 1 i.~ (0 = *) , =
s2=: 0:`1:`($:&<: + ] * <:@:[ $: ])@.test M.
s2&>table i. 13
+----+--------------------------------------------------------------------+
|s2&>|0 1 2 3 4 5 6 7 8 9 10 11 12|
+----+--------------------------------------------------------------------+
| 0 |0 0 0 0 0 0 0 0 0 0 0 0 0|
| 1 |0 1 0 0 0 0 0 0 0 0 0 0 0|
| 2 |0 1 1 0 0 0 0 0 0 0 0 0 0|
| 3 |0 1 3 1 0 0 0 0 0 0 0 0 0|
| 4 |0 1 7 6 1 0 0 0 0 0 0 0 0|
| 5 |0 1 15 25 10 1 0 0 0 0 0 0 0|
| 6 |0 1 31 90 65 15 1 0 0 0 0 0 0|
| 7 |0 1 63 301 350 140 21 1 0 0 0 0 0|
| 8 |0 1 127 966 1701 1050 266 28 1 0 0 0 0|
| 9 |0 1 255 3025 7770 6951 2646 462 36 1 0 0 0|
|10 |0 1 511 9330 34105 42525 22827 5880 750 45 1 0 0|
|11 |0 1 1023 28501 145750 246730 179487 63987 11880 1155 55 1 0|
|12 |0 1 2047 86526 611501 1379400 1323652 627396 159027 22275 1705 66 1|
+----+--------------------------------------------------------------------+
>./ 100 s2&x:&> i. 101
7769730053598745155212806612787584787397878128370115840974992570102386086289805848025074822404843545178960761551674
|
http://rosettacode.org/wiki/Stirling_numbers_of_the_second_kind | Stirling numbers of the second kind | Stirling numbers of the second kind, or Stirling partition numbers, are the
number of ways to partition a set of n objects into k non-empty subsets. They are
closely related to Bell numbers, and may be derived from them.
Stirling numbers of the second kind obey the recurrence relation:
S2(n, 0) and S2(0, k) = 0 # for n, k > 0
S2(n, n) = 1
S2(n + 1, k) = k * S2(n, k) + S2(n, k - 1)
Task
Write a routine (function, procedure, whatever) to find Stirling numbers of the second kind. There are several methods to generate Stirling numbers of the second kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.
Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the second kind, S2(n, k), up to S2(12, 12). it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S2(n, k) == 0 (when k > n).
If your language supports large integers, find and show here, on this page, the maximum value of S2(n, k) where n == 100.
See also
Wikipedia - Stirling numbers of the second kind
OEIS:A008277 - Stirling numbers of the second kind
Related Tasks
Stirling numbers of the first kind
Bell numbers
Lah numbers
| #Java | Java |
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
public class SterlingNumbersSecondKind {
public static void main(String[] args) {
System.out.println("Stirling numbers of the second kind:");
int max = 12;
System.out.printf("n/k");
for ( int n = 0 ; n <= max ; n++ ) {
System.out.printf("%10d", n);
}
System.out.printf("%n");
for ( int n = 0 ; n <= max ; n++ ) {
System.out.printf("%-3d", n);
for ( int k = 0 ; k <= n ; k++ ) {
System.out.printf("%10s", sterling2(n, k));
}
System.out.printf("%n");
}
System.out.println("The maximum value of S2(100, k) = ");
BigInteger previous = BigInteger.ZERO;
for ( int k = 1 ; k <= 100 ; k++ ) {
BigInteger current = sterling2(100, k);
if ( current.compareTo(previous) > 0 ) {
previous = current;
}
else {
System.out.printf("%s%n(%d digits, k = %d)%n", previous, previous.toString().length(), k-1);
break;
}
}
}
private static Map<String,BigInteger> COMPUTED = new HashMap<>();
private static final BigInteger sterling2(int n, int k) {
String key = n + "," + k;
if ( COMPUTED.containsKey(key) ) {
return COMPUTED.get(key);
}
if ( n == 0 && k == 0 ) {
return BigInteger.valueOf(1);
}
if ( (n > 0 && k == 0) || (n == 0 && k > 0) ) {
return BigInteger.ZERO;
}
if ( n == k ) {
return BigInteger.valueOf(1);
}
if ( k > n ) {
return BigInteger.ZERO;
}
BigInteger result = BigInteger.valueOf(k).multiply(sterling2(n-1, k)).add(sterling2(n-1, k-1));
COMPUTED.put(key, result);
return result;
}
}
|
http://rosettacode.org/wiki/Stirling_numbers_of_the_second_kind | Stirling numbers of the second kind | Stirling numbers of the second kind, or Stirling partition numbers, are the
number of ways to partition a set of n objects into k non-empty subsets. They are
closely related to Bell numbers, and may be derived from them.
Stirling numbers of the second kind obey the recurrence relation:
S2(n, 0) and S2(0, k) = 0 # for n, k > 0
S2(n, n) = 1
S2(n + 1, k) = k * S2(n, k) + S2(n, k - 1)
Task
Write a routine (function, procedure, whatever) to find Stirling numbers of the second kind. There are several methods to generate Stirling numbers of the second kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.
Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the second kind, S2(n, k), up to S2(12, 12). it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S2(n, k) == 0 (when k > n).
If your language supports large integers, find and show here, on this page, the maximum value of S2(n, k) where n == 100.
See also
Wikipedia - Stirling numbers of the second kind
OEIS:A008277 - Stirling numbers of the second kind
Related Tasks
Stirling numbers of the first kind
Bell numbers
Lah numbers
| #jq | jq | def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
# Input: {computed} (the cache)
# Output: {computed, result}
def stirling2($n; $k):
"\($n),\($k)" as $key
| if .computed[$key] then .result = .computed[$key]
elif ($n == 0 and $k == 0) then .result = 1
elif (($n > 0 and $k == 0) or ($n == 0 and $k > 0)) then .result = 0
elif ($k == $n) then .result = 1
elif ($k > $n) then .result = 0
else stirling2($n-1; $k-1) as $s1
| ($s1 | stirling2($n-1; $k)) as $s2
| ($s1.result + ($k * $s2.result)) as $result
| $s2
| .computed[$key] = $result
| .result = $result
end ;
# Set .emit to a table of values and .computed to a cache of stirling2 values
# Output: {emit, computed}
def part1(max):
{emit: "Unsigned Stirling numbers of the second kind:"}
| .emit += "\n" + "n/k" +
([range(0; max+1) | lpad(10)] | join(""))
| reduce range(0; max+1) as $n ( .computed = {};
.emit += "\n" + ($n | lpad(3))
| reduce range(0; $n+1) as $k (.;
stirling2($n; $k)
| .emit += (.result | lpad(10) ) )) ;
# "The maximum value of S2($m, k) ..."
# Input: {computed}
def part2($m):
"The maximum value of S2(\($m), k) =",
first(
foreach range(1;$m+1) as $k ({computed:{}, previous: 0};
stirling2($m; $k) as $current
| if ($current.result > .previous)
then .previous = $current.result
else
.emit = "\(.previous)\n(\(.previous|tostring|length) digits, k = \($k - 1))"
end;
select(.emit).emit) );
part1(12)
| .emit,
part2(100)
|
http://rosettacode.org/wiki/Stirling_numbers_of_the_second_kind | Stirling numbers of the second kind | Stirling numbers of the second kind, or Stirling partition numbers, are the
number of ways to partition a set of n objects into k non-empty subsets. They are
closely related to Bell numbers, and may be derived from them.
Stirling numbers of the second kind obey the recurrence relation:
S2(n, 0) and S2(0, k) = 0 # for n, k > 0
S2(n, n) = 1
S2(n + 1, k) = k * S2(n, k) + S2(n, k - 1)
Task
Write a routine (function, procedure, whatever) to find Stirling numbers of the second kind. There are several methods to generate Stirling numbers of the second kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.
Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the second kind, S2(n, k), up to S2(12, 12). it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S2(n, k) == 0 (when k > n).
If your language supports large integers, find and show here, on this page, the maximum value of S2(n, k) where n == 100.
See also
Wikipedia - Stirling numbers of the second kind
OEIS:A008277 - Stirling numbers of the second kind
Related Tasks
Stirling numbers of the first kind
Bell numbers
Lah numbers
| #Julia | Julia | using Combinatorics
const s2cache = Dict()
function stirlings2(n, k)
if haskey(s2cache, Pair(n, k))
return s2cache[Pair(n, k)]
elseif n < 0
throw(DomainError(n, "n must be nonnegative"))
elseif n == k == 0
return one(n)
elseif n == 0 || k == 0
return zero(n)
elseif k == n - 1
return binomial(n, 2)
elseif k == 2
return 2^(n-1) - 1
end
ret = k * stirlings2(n - 1, k) + stirlings2(n - 1, k - 1)
s2cache[Pair(n, k)] = ret
return ret
end
function printstirling2table(kmax)
println(" ", mapreduce(i -> lpad(i, 10), *, 0:kmax))
sstring(n, k) = begin i = stirlings2(n, k); lpad(k > n && i == 0 ? "" : i, 10) end
for n in 0:kmax
println(rpad(n, 2) * mapreduce(k -> sstring(n, k), *, 0:kmax))
end
end
printstirling2table(12)
println("\nThe maximum for stirling2(100, _) is: ", maximum(k-> stirlings2(BigInt(100), BigInt(k)), 1:100))
|
http://rosettacode.org/wiki/Strassen%27s_algorithm | Strassen's algorithm | Description
In linear algebra, the Strassen algorithm (named after Volker Strassen), is an algorithm for matrix multiplication.
It is faster than the standard matrix multiplication algorithm and is useful in practice for large matrices, but would be slower than the fastest known algorithms for extremely large matrices.
Task
Write a routine, function, procedure etc. in your language to implement the Strassen algorithm for matrix multiplication.
While practical implementations of Strassen's algorithm usually switch to standard methods of matrix multiplication for small enough sub-matrices (currently anything less than 512×512 according to Wikipedia), for the purposes of this task you should not switch until reaching a size of 1 or 2.
Related task
Matrix multiplication
See also
Wikipedia article
| #Go | Go | package main
import (
"fmt"
"log"
"math"
)
type Matrix [][]float64
func (m Matrix) rows() int { return len(m) }
func (m Matrix) cols() int { return len(m[0]) }
func (m Matrix) add(m2 Matrix) Matrix {
if m.rows() != m2.rows() || m.cols() != m2.cols() {
log.Fatal("Matrices must have the same dimensions.")
}
c := make(Matrix, m.rows())
for i := 0; i < m.rows(); i++ {
c[i] = make([]float64, m.cols())
for j := 0; j < m.cols(); j++ {
c[i][j] = m[i][j] + m2[i][j]
}
}
return c
}
func (m Matrix) sub(m2 Matrix) Matrix {
if m.rows() != m2.rows() || m.cols() != m2.cols() {
log.Fatal("Matrices must have the same dimensions.")
}
c := make(Matrix, m.rows())
for i := 0; i < m.rows(); i++ {
c[i] = make([]float64, m.cols())
for j := 0; j < m.cols(); j++ {
c[i][j] = m[i][j] - m2[i][j]
}
}
return c
}
func (m Matrix) mul(m2 Matrix) Matrix {
if m.cols() != m2.rows() {
log.Fatal("Cannot multiply these matrices.")
}
c := make(Matrix, m.rows())
for i := 0; i < m.rows(); i++ {
c[i] = make([]float64, m2.cols())
for j := 0; j < m2.cols(); j++ {
for k := 0; k < m2.rows(); k++ {
c[i][j] += m[i][k] * m2[k][j]
}
}
}
return c
}
func (m Matrix) toString(p int) string {
s := make([]string, m.rows())
pow := math.Pow(10, float64(p))
for i := 0; i < m.rows(); i++ {
t := make([]string, m.cols())
for j := 0; j < m.cols(); j++ {
r := math.Round(m[i][j]*pow) / pow
t[j] = fmt.Sprintf("%g", r)
if t[j] == "-0" {
t[j] = "0"
}
}
s[i] = fmt.Sprintf("%v", t)
}
return fmt.Sprintf("%v", s)
}
func params(r, c int) [4][6]int {
return [4][6]int{
{0, r, 0, c, 0, 0},
{0, r, c, 2 * c, 0, c},
{r, 2 * r, 0, c, r, 0},
{r, 2 * r, c, 2 * c, r, c},
}
}
func toQuarters(m Matrix) [4]Matrix {
r := m.rows() / 2
c := m.cols() / 2
p := params(r, c)
var quarters [4]Matrix
for k := 0; k < 4; k++ {
q := make(Matrix, r)
for i := p[k][0]; i < p[k][1]; i++ {
q[i-p[k][4]] = make([]float64, c)
for j := p[k][2]; j < p[k][3]; j++ {
q[i-p[k][4]][j-p[k][5]] = m[i][j]
}
}
quarters[k] = q
}
return quarters
}
func fromQuarters(q [4]Matrix) Matrix {
r := q[0].rows()
c := q[0].cols()
p := params(r, c)
r *= 2
c *= 2
m := make(Matrix, r)
for i := 0; i < c; i++ {
m[i] = make([]float64, c)
}
for k := 0; k < 4; k++ {
for i := p[k][0]; i < p[k][1]; i++ {
for j := p[k][2]; j < p[k][3]; j++ {
m[i][j] = q[k][i-p[k][4]][j-p[k][5]]
}
}
}
return m
}
func strassen(a, b Matrix) Matrix {
if a.rows() != a.cols() || b.rows() != b.cols() || a.rows() != b.rows() {
log.Fatal("Matrices must be square and of equal size.")
}
if a.rows() == 0 || (a.rows()&(a.rows()-1)) != 0 {
log.Fatal("Size of matrices must be a power of two.")
}
if a.rows() == 1 {
return a.mul(b)
}
qa := toQuarters(a)
qb := toQuarters(b)
p1 := strassen(qa[1].sub(qa[3]), qb[2].add(qb[3]))
p2 := strassen(qa[0].add(qa[3]), qb[0].add(qb[3]))
p3 := strassen(qa[0].sub(qa[2]), qb[0].add(qb[1]))
p4 := strassen(qa[0].add(qa[1]), qb[3])
p5 := strassen(qa[0], qb[1].sub(qb[3]))
p6 := strassen(qa[3], qb[2].sub(qb[0]))
p7 := strassen(qa[2].add(qa[3]), qb[0])
var q [4]Matrix
q[0] = p1.add(p2).sub(p4).add(p6)
q[1] = p4.add(p5)
q[2] = p6.add(p7)
q[3] = p2.sub(p3).add(p5).sub(p7)
return fromQuarters(q)
}
func main() {
a := Matrix{{1, 2}, {3, 4}}
b := Matrix{{5, 6}, {7, 8}}
c := Matrix{{1, 1, 1, 1}, {2, 4, 8, 16}, {3, 9, 27, 81}, {4, 16, 64, 256}}
d := Matrix{{4, -3, 4.0 / 3, -1.0 / 4}, {-13.0 / 3, 19.0 / 4, -7.0 / 3, 11.0 / 24},
{3.0 / 2, -2, 7.0 / 6, -1.0 / 4}, {-1.0 / 6, 1.0 / 4, -1.0 / 6, 1.0 / 24}}
e := Matrix{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}
f := Matrix{{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}}
fmt.Println("Using 'normal' matrix multiplication:")
fmt.Printf(" a * b = %v\n", a.mul(b))
fmt.Printf(" c * d = %v\n", c.mul(d).toString(6))
fmt.Printf(" e * f = %v\n", e.mul(f))
fmt.Println("\nUsing 'Strassen' matrix multiplication:")
fmt.Printf(" a * b = %v\n", strassen(a, b))
fmt.Printf(" c * d = %v\n", strassen(c, d).toString(6))
fmt.Printf(" e * f = %v\n", strassen(e, f))
} |
http://rosettacode.org/wiki/String_append | String append |
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
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #11l | 11l | V s = ‘12345678’
s ‘’= ‘9!’
print(s) |
http://rosettacode.org/wiki/Stirling_numbers_of_the_second_kind | Stirling numbers of the second kind | Stirling numbers of the second kind, or Stirling partition numbers, are the
number of ways to partition a set of n objects into k non-empty subsets. They are
closely related to Bell numbers, and may be derived from them.
Stirling numbers of the second kind obey the recurrence relation:
S2(n, 0) and S2(0, k) = 0 # for n, k > 0
S2(n, n) = 1
S2(n + 1, k) = k * S2(n, k) + S2(n, k - 1)
Task
Write a routine (function, procedure, whatever) to find Stirling numbers of the second kind. There are several methods to generate Stirling numbers of the second kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.
Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the second kind, S2(n, k), up to S2(12, 12). it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S2(n, k) == 0 (when k > n).
If your language supports large integers, find and show here, on this page, the maximum value of S2(n, k) where n == 100.
See also
Wikipedia - Stirling numbers of the second kind
OEIS:A008277 - Stirling numbers of the second kind
Related Tasks
Stirling numbers of the first kind
Bell numbers
Lah numbers
| #Kotlin | Kotlin | import java.math.BigInteger
fun main() {
println("Stirling numbers of the second kind:")
val max = 12
print("n/k")
for (n in 0..max) {
print("%10d".format(n))
}
println()
for (n in 0..max) {
print("%-3d".format(n))
for (k in 0..n) {
print("%10s".format(sterling2(n, k)))
}
println()
}
println("The maximum value of S2(100, k) = ")
var previous = BigInteger.ZERO
for (k in 1..100) {
val current = sterling2(100, k)
previous = if (current > previous) {
current
} else {
println("%s%n(%d digits, k = %d)".format(previous, previous.toString().length, k - 1))
break
}
}
}
private val COMPUTED: MutableMap<String, BigInteger> = HashMap()
private fun sterling2(n: Int, k: Int): BigInteger {
val key = "$n,$k"
if (COMPUTED.containsKey(key)) {
return COMPUTED[key]!!
}
if (n == 0 && k == 0) {
return BigInteger.valueOf(1)
}
if (n > 0 && k == 0 || n == 0 && k > 0) {
return BigInteger.ZERO
}
if (n == k) {
return BigInteger.valueOf(1)
}
if (k > n) {
return BigInteger.ZERO
}
val result = BigInteger.valueOf(k.toLong()) * sterling2(n - 1, k) + sterling2(n - 1, k - 1)
COMPUTED[key] = result
return result
} |
http://rosettacode.org/wiki/Strassen%27s_algorithm | Strassen's algorithm | Description
In linear algebra, the Strassen algorithm (named after Volker Strassen), is an algorithm for matrix multiplication.
It is faster than the standard matrix multiplication algorithm and is useful in practice for large matrices, but would be slower than the fastest known algorithms for extremely large matrices.
Task
Write a routine, function, procedure etc. in your language to implement the Strassen algorithm for matrix multiplication.
While practical implementations of Strassen's algorithm usually switch to standard methods of matrix multiplication for small enough sub-matrices (currently anything less than 512×512 according to Wikipedia), for the purposes of this task you should not switch until reaching a size of 1 or 2.
Related task
Matrix multiplication
See also
Wikipedia article
| #Julia | Julia | """
Strassen's matrix multiplication algorithm.
Use dynamic padding in order to reduce required auxiliary memory.
"""
function strassen(x::Matrix, y::Matrix)
# Check that the sizes of these matrices match.
(r1, c1) = size(x)
(r2, c2) = size(y)
if c1 != r2
error("Multiplying $r1 x $c1 and $r2 x $c2 matrix: dimensions do not match.")
end
# Put a matrix into the top left of a matrix of zeros.
# `rows` and `cols` are the dimensions of the output matrix.
function embed(mat, rows, cols)
# If the matrix is already of the right dimensions, don't allocate new memory.
(r, c) = size(mat)
if (r, c) == (rows, cols)
return mat
end
# Pad the matrix with zeros to be the right size.
out = zeros(Int, rows, cols)
out[1:r, 1:c] = mat
out
end
# Make sure both matrices are the same size.
# This is exclusively for simplicity:
# this algorithm can be implemented with matrices of different sizes.
r = max(r1, r2); c = max(c1, c2)
x = embed(x, r, c)
y = embed(y, r, c)
# Our recursive multiplication function.
function block_mult(a, b, rows, cols)
# For small matrices, resort to naive multiplication.
# if rows <= 128 || cols <= 128
if rows == 1 && cols == 1
# if rows == 2 && cols == 2
return a * b
end
# Apply dynamic padding.
if rows % 2 == 1 && cols % 2 == 1
a = embed(a, rows + 1, cols + 1)
b = embed(b, rows + 1, cols + 1)
elseif rows % 2 == 1
a = embed(a, rows + 1, cols)
b = embed(b, rows + 1, cols)
elseif cols % 2 == 1
a = embed(a, rows, cols + 1)
b = embed(b, rows, cols + 1)
end
half_rows = Int(size(a, 1) / 2)
half_cols = Int(size(a, 2) / 2)
# Subdivide input matrices.
a11 = a[1:half_rows, 1:half_cols]
b11 = b[1:half_rows, 1:half_cols]
a12 = a[1:half_rows, half_cols+1:size(a, 2)]
b12 = b[1:half_rows, half_cols+1:size(a, 2)]
a21 = a[half_rows+1:size(a, 1), 1:half_cols]
b21 = b[half_rows+1:size(a, 1), 1:half_cols]
a22 = a[half_rows+1:size(a, 1), half_cols+1:size(a, 2)]
b22 = b[half_rows+1:size(a, 1), half_cols+1:size(a, 2)]
# Compute intermediate values.
multip(x, y) = block_mult(x, y, half_rows, half_cols)
m1 = multip(a11 + a22, b11 + b22)
m2 = multip(a21 + a22, b11)
m3 = multip(a11, b12 - b22)
m4 = multip(a22, b21 - b11)
m5 = multip(a11 + a12, b22)
m6 = multip(a21 - a11, b11 + b12)
m7 = multip(a12 - a22, b21 + b22)
# Combine intermediate values into the output.
c11 = m1 + m4 - m5 + m7
c12 = m3 + m5
c21 = m2 + m4
c22 = m1 - m2 + m3 + m6
# Crop output to the desired size (undo dynamic padding).
out = [c11 c12; c21 c22]
out[1:rows, 1:cols]
end
block_mult(x, y, r, c)
end
const A = [[1, 2] [3, 4]]
const B = [[5, 6] [7, 8]]
const C = [[1, 1, 1, 1] [2, 4, 8, 16] [3, 9, 27, 81] [4, 16, 64, 256]]
const D = [[4, -3, 4/3, -1/4] [-13/3, 19/4, -7/3, 11/24] [3/2, -2, 7/6, -1/4] [-1/6, 1/4, -1/6, 1/24]]
const E = [[1, 2, 3, 4] [5, 6, 7, 8] [9, 10, 11, 12] [13, 14, 15, 16]]
const F = [[1, 0, 0, 0] [0, 1, 0, 0] [0, 0, 1, 0] [0, 0, 0, 1]]
""" For pretty printing: change matrix to integer if it is within 0.00000001 of an integer """
intprint(s, mat) = println(s, map(x -> Int(round(x, digits=8)), mat)')
intprint("Regular multiply: ", A' * B')
intprint("Strassen multiply: ", strassen(Matrix(A'), Matrix(B')))
intprint("Regular multiply: ", C * D)
intprint("Strassen multiply: ", strassen(C, D))
intprint("Regular multiply: ", E * F)
intprint("Strassen multiply: ", strassen(E, F))
const r = sqrt(2)/2
const R = [[r, r] [-r, r]]
intprint("Regular multiply: ", R * R)
intprint("Strassen multiply: ", strassen(R,R))
|
http://rosettacode.org/wiki/Strassen%27s_algorithm | Strassen's algorithm | Description
In linear algebra, the Strassen algorithm (named after Volker Strassen), is an algorithm for matrix multiplication.
It is faster than the standard matrix multiplication algorithm and is useful in practice for large matrices, but would be slower than the fastest known algorithms for extremely large matrices.
Task
Write a routine, function, procedure etc. in your language to implement the Strassen algorithm for matrix multiplication.
While practical implementations of Strassen's algorithm usually switch to standard methods of matrix multiplication for small enough sub-matrices (currently anything less than 512×512 according to Wikipedia), for the purposes of this task you should not switch until reaching a size of 1 or 2.
Related task
Matrix multiplication
See also
Wikipedia article
| #Nim | Nim | import math, sequtils, strutils
type Matrix = seq[seq[float]]
template rows(m: Matrix): Positive = m.len
template cols(m: Matrix): Positive = m[0].len
func `+`(m1, m2: Matrix): Matrix =
doAssert m1.rows == m2.rows and m1.cols == m2.cols, "Matrices must have the same dimensions."
result = newSeqWith(m1.rows, newSeq[float](m1.cols))
for i in 0..<m1.rows:
for j in 0..<m1.cols:
result[i][j] = m1[i][j] + m2[i][j]
func `-`(m1, m2: Matrix): Matrix =
doAssert m1.rows == m2.rows and m1.cols == m2.cols, "Matrices must have the same dimensions."
result = newSeqWith(m1.rows, newSeq[float](m1.cols))
for i in 0..<m1.rows:
for j in 0..<m1.cols:
result[i][j] = m1[i][j] - m2[i][j]
func `*`(m1, m2: Matrix): Matrix =
doAssert m1.cols == m2.rows, "Cannot multiply these matrices."
result = newSeqWith(m1.rows, newSeq[float](m2.cols))
for i in 0..<m1.rows:
for j in 0..<m2.cols:
for k in 0..<m2.rows:
result[i][j] += m1[i][k] * m2[k][j]
func toString(m: Matrix; p: Natural): string =
## Round all elements to 'p' places.
var res: seq[string]
let pow = 10.0^p
for row in m:
var line: seq[string]
for val in row:
let r = round(val * pow) / pow
var s = r.formatFloat(precision = -1)
if s == "-0": s = "0"
line.add s
res.add '[' & line.join(" ") & ']'
result = '[' & res.join(" ") & ']'
func params(r, c: int): array[4, array[6, int]] =
[[0, r, 0, c, 0, 0],
[0, r, c, 2 * c, 0, c],
[r, 2 * r, 0, c, r, 0],
[r, 2 * r, c, 2 * c, r, c]]
func toQuarters(m: Matrix): array[4, Matrix] =
let
r = m.rows() div 2
c = m.cols() div 2
p = params(r, c)
for k in 0..3:
var q = newSeqWith(r, newSeq[float](c))
for i in p[k][0]..<p[k][1]:
for j in p[k][2]..<p[k][3]:
q[i-p[k][4]][j-p[k][5]] = m[i][j]
result[k] = move(q)
func fromQuarters(q: array[4, Matrix]): Matrix =
var
r = q[0].rows
c = q[0].cols
let p = params(r, c)
r *= 2
c *= 2
result = newSeqWith(r, newSeq[float](c))
for k in 0..3:
for i in p[k][0]..<p[k][1]:
for j in p[k][2]..<p[k][3]:
result[i][j] = q[k][i-p[k][4]][j-p[k][5]]
func strassen(a, b: Matrix): Matrix =
doAssert a.rows == a.cols() and b.rows == b.cols and a.rows == b.rows,
"Matrices must be square and of equal size."
doAssert a.rows != 0 and (a.rows and (a.rows-1)) == 0,
"Size of matrices must be a power of two."
if a.rows == 1: return a * b
let
qa = a.toQuarters()
qb = b.toQuarters()
p1 = strassen(qa[1] - qa[3], qb[2] + qb[3])
p2 = strassen(qa[0] + qa[3], qb[0] + qb[3])
p3 = strassen(qa[0] - qa[2], qb[0] + qb[1])
p4 = strassen(qa[0] + qa[1], qb[3])
p5 = strassen(qa[0], qb[1] - qb[3])
p6 = strassen(qa[3], qb[2] - qb[0])
p7 = strassen(qa[2] + qa[3], qb[0])
var q: array[4, Matrix]
q[0] = p1 + p2 - p4 + p6
q[1] = p4 + p5
q[2] = p6 + p7
q[3] = p2 - p3 + p5 - p7
result = fromQuarters(q)
when isMainModule:
let
a = @[@[float 1, 2],
@[float 3, 4]]
b = @[@[float 5, 6],
@[float 7, 8]]
c = @[@[float 1, 1, 1, 1],
@[float 2, 4, 8, 16],
@[float 3, 9, 27, 81],
@[float 4, 16, 64, 256]]
d = @[@[4.0, -3, 4/3, -1/4],
@[-13/3, 19/4, -7/3, 11/24],
@[3/2, -2, 7/6, -1/4],
@[-1/6, 1/4, -1/6, 1/24]]
e = @[@[float 1, 2, 3, 4],
@[float 5, 6, 7, 8],
@[float 9, 10, 11, 12],
@[float 13, 14, 15, 16]]
f = @[@[float 1, 0, 0, 0],
@[float 0, 1, 0, 0],
@[float 0, 0, 1, 0],
@[float 0, 0, 0, 1]]
echo "Using 'normal' matrix multiplication:"
echo " a * b = ", (a * b).toString(10)
echo " c * d = ", (c * d).toString(6)
echo " e * f = ", (e * f).toString(10)
echo "\nUsing 'Strassen' matrix multiplication:"
echo " a * b = ", strassen(a, b).toString(10)
echo " c * d = ", strassen(c, d).toString(6)
echo " e * f = ", strassen(e, f).toString(10) |
http://rosettacode.org/wiki/String_append | String append |
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
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program appendstr64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ BUFFERSIZE, 100
/*******************************************/
/* Initialized data */
/*******************************************/
.data
szMessString: .asciz "String :\n"
szString1: .asciz "Alphabet : "
sComplement: .fill BUFFERSIZE,1,0
szString2: .asciz "abcdefghijklmnopqrstuvwxyz"
szCarriageReturn: .asciz "\n"
/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
/*******************************************/
/* code section */
/*******************************************/
.text
.global main
main:
ldr x0,qAdrszMessString // display message
bl affichageMess
ldr x0,qAdrszString1 // display begin string
bl affichageMess
ldr x0,qAdrszCarriageReturn // display return line
bl affichageMess
ldr x0,qAdrszString1
ldr x1,qAdrszString2
bl append // append sting2 to string1
ldr x0,qAdrszMessString
bl affichageMess
ldr x0,qAdrszString1 // display string
bl affichageMess
ldr x0,qAdrszCarriageReturn
bl affichageMess
100: // standard end of the program
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform system call
qAdrszMessString: .quad szMessString
qAdrszString1: .quad szString1
qAdrszString2: .quad szString2
qAdrszCarriageReturn: .quad szCarriageReturn
/**************************************************/
/* append two strings */
/**************************************************/
/* x0 contains the address of the string1 */
/* x1 contains the address of the string2 */
append:
stp x1,lr,[sp,-16]! // save registers
mov x2,#0 // counter byte string 1
1:
ldrb w3,[x0,x2] // load byte string 1
cmp x3,#0 // zero final ?
add x4,x2,1
csel x2,x4,x2,ne // if x3 not equal 0, x2 = X2 +1 else x2
bne 1b // no -> loop
mov x4,#0 // counter byte string 2
2:
ldrb w3,[x1,x4] // load byte string 2
strb w3,[x0,x2] // store byte string 1
cbz x3,100f // zero final ?
add x2,x2,1 // no -> increment counter 1
add x4,x4,1 // no -> increment counter 2
b 2b // no -> loop
100:
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
http://rosettacode.org/wiki/String_append | String append |
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
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #Action.21 | Action! |
CHAR ARRAY S1,S2
Proc Main()
S1="Hello, "
S2="world!";
Sassign(S1,S2,S1(0)+1)
Print(S1)
Return
|
http://rosettacode.org/wiki/Stirling_numbers_of_the_second_kind | Stirling numbers of the second kind | Stirling numbers of the second kind, or Stirling partition numbers, are the
number of ways to partition a set of n objects into k non-empty subsets. They are
closely related to Bell numbers, and may be derived from them.
Stirling numbers of the second kind obey the recurrence relation:
S2(n, 0) and S2(0, k) = 0 # for n, k > 0
S2(n, n) = 1
S2(n + 1, k) = k * S2(n, k) + S2(n, k - 1)
Task
Write a routine (function, procedure, whatever) to find Stirling numbers of the second kind. There are several methods to generate Stirling numbers of the second kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.
Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the second kind, S2(n, k), up to S2(12, 12). it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S2(n, k) == 0 (when k > n).
If your language supports large integers, find and show here, on this page, the maximum value of S2(n, k) where n == 100.
See also
Wikipedia - Stirling numbers of the second kind
OEIS:A008277 - Stirling numbers of the second kind
Related Tasks
Stirling numbers of the first kind
Bell numbers
Lah numbers
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | TableForm[Array[StirlingS2, {n = 12, k = 12} + 1, {0, 0}], TableHeadings -> {"n=" <> ToString[#] & /@ Range[0, n], "k=" <> ToString[#] & /@ Range[0, k]}]
Max[Abs[StirlingS2[100, #]] & /@ Range[0, 100]] |
http://rosettacode.org/wiki/Strassen%27s_algorithm | Strassen's algorithm | Description
In linear algebra, the Strassen algorithm (named after Volker Strassen), is an algorithm for matrix multiplication.
It is faster than the standard matrix multiplication algorithm and is useful in practice for large matrices, but would be slower than the fastest known algorithms for extremely large matrices.
Task
Write a routine, function, procedure etc. in your language to implement the Strassen algorithm for matrix multiplication.
While practical implementations of Strassen's algorithm usually switch to standard methods of matrix multiplication for small enough sub-matrices (currently anything less than 512×512 according to Wikipedia), for the purposes of this task you should not switch until reaching a size of 1 or 2.
Related task
Matrix multiplication
See also
Wikipedia article
| #Phix | Phix | with javascript_semantics
function strassen(sequence a, b)
integer l = length(a)
if length(a[1])!=l
or length(b)!=l
or length(b[1])!=l then
crash("two equal square matrices only")
end if
if l=1 then return sq_mul(a,b) end if
if remainder(l,1) then
crash("2^n matrices only")
end if
integer h = l/2
sequence {a11,a12,a21,a22,b11,b12,b21,b22} = repeat(repeat(repeat(0,h),h),8)
for i=1 to h do
for j=1 to h do
a11[i][j] = a[i][j]
a12[i][j] = a[i][j+h]
a21[i][j] = a[i+h][j]
a22[i][j] = a[i+h][j+h]
b11[i][j] = b[i][j]
b12[i][j] = b[i][j+h]
b21[i][j] = b[i+h][j]
b22[i][j] = b[i+h][j+h]
end for
end for
sequence p1 = strassen(sq_sub(a12,a22), sq_add(b21,b22)),
p2 = strassen(sq_add(a11,a22), sq_add(b11,b22)),
p3 = strassen(sq_sub(a11,a21), sq_add(b11,b12)),
p4 = strassen(sq_add(a11,a12), b22),
p5 = strassen(a11, sq_sub(b12,b22)),
p6 = strassen(a22, sq_sub(b21,b11)),
p7 = strassen(sq_add(a21,a22), b11),
c11 = sq_add(sq_sub(sq_add(p1,p2),p4),p6),
c12 = sq_add(p4,p5),
c21 = sq_add(p6,p7),
c22 = sq_sub(sq_add(sq_sub(p2,p3),p5),p7),
c = repeat(repeat(0,l),l)
for i=1 to h do
for j=1 to h do
c[i][j] = c11[i][j]
c[i][j+h] = c12[i][j]
c[i+h][j] = c21[i][j]
c[i+h][j+h] = c22[i][j]
end for
end for
return c
end function
ppOpt({pp_Nest,1,pp_IntFmt,"%3d",pp_FltFmt,"%3.0f",pp_IntCh,false})
constant A = {{1,2},
{3,4}},
B = {{5,6},
{7,8}}
pp(strassen(A,B))
constant C = { { 1, 1, 1, 1 },
{ 2, 4, 8, 16 },
{ 3, 9, 27, 81 },
{ 4, 16, 64, 256 }},
D = { { 4, -3, 4/3, -1/ 4 },
{-13/3, 19/4, -7/3, 11/24 },
{ 3/2, -2, 7/6, -1/ 4 },
{ -1/6, 1/4, -1/6, 1/24 }}
pp(strassen(C,D))
constant F = {{ 1, 2, 3, 4},
{ 5, 6, 7, 8},
{ 9,10,11,12},
{13,14,15,16}},
G = {{1, 0, 0, 0},
{0, 1, 0, 0},
{0, 0, 1, 0},
{0, 0, 0, 1}}
pp(strassen(F,G))
constant r = sqrt(2)/2,
R = {{ r,r},
{-r,r}}
pp(strassen(R,R))
|
http://rosettacode.org/wiki/String_append | String append |
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
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #Ada | Ada |
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Text_IO.Unbounded_Io; use Ada.Text_IO.Unbounded_IO;
procedure String_Append is
Str : Unbounded_String := To_Unbounded_String("Hello");
begin
Append(Str, ", world!");
Put_Line(Str);
end String_Append;
|
http://rosettacode.org/wiki/String_append | String append |
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
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #ALGOL_68 | ALGOL 68 | #!/usr/bin/a68g --script #
# -*- coding: utf-8 -*- #
STRING str := "12345678";
str +:= "9!";
print(str) |
http://rosettacode.org/wiki/Stirling_numbers_of_the_second_kind | Stirling numbers of the second kind | Stirling numbers of the second kind, or Stirling partition numbers, are the
number of ways to partition a set of n objects into k non-empty subsets. They are
closely related to Bell numbers, and may be derived from them.
Stirling numbers of the second kind obey the recurrence relation:
S2(n, 0) and S2(0, k) = 0 # for n, k > 0
S2(n, n) = 1
S2(n + 1, k) = k * S2(n, k) + S2(n, k - 1)
Task
Write a routine (function, procedure, whatever) to find Stirling numbers of the second kind. There are several methods to generate Stirling numbers of the second kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.
Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the second kind, S2(n, k), up to S2(12, 12). it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S2(n, k) == 0 (when k > n).
If your language supports large integers, find and show here, on this page, the maximum value of S2(n, k) where n == 100.
See also
Wikipedia - Stirling numbers of the second kind
OEIS:A008277 - Stirling numbers of the second kind
Related Tasks
Stirling numbers of the first kind
Bell numbers
Lah numbers
| #Nim | Nim | import sequtils, strutils
proc s2(n, k: Natural): Natural =
if n == k: return 1
if n == 0 or k == 0: return 0
k * s2(n - 1, k) + s2(n - 1, k - 1)
echo " k ", toSeq(0..12).mapIt(($it).align(2)).join(" ")
echo " n"
for n in 0..12:
stdout.write ($n).align(2)
for k in 0..n:
stdout.write ($s2(n, k)).align(8)
stdout.write '\n' |
http://rosettacode.org/wiki/Stirling_numbers_of_the_second_kind | Stirling numbers of the second kind | Stirling numbers of the second kind, or Stirling partition numbers, are the
number of ways to partition a set of n objects into k non-empty subsets. They are
closely related to Bell numbers, and may be derived from them.
Stirling numbers of the second kind obey the recurrence relation:
S2(n, 0) and S2(0, k) = 0 # for n, k > 0
S2(n, n) = 1
S2(n + 1, k) = k * S2(n, k) + S2(n, k - 1)
Task
Write a routine (function, procedure, whatever) to find Stirling numbers of the second kind. There are several methods to generate Stirling numbers of the second kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.
Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the second kind, S2(n, k), up to S2(12, 12). it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S2(n, k) == 0 (when k > n).
If your language supports large integers, find and show here, on this page, the maximum value of S2(n, k) where n == 100.
See also
Wikipedia - Stirling numbers of the second kind
OEIS:A008277 - Stirling numbers of the second kind
Related Tasks
Stirling numbers of the first kind
Bell numbers
Lah numbers
| #Perl | Perl | use strict;
use warnings;
use bigint;
use feature 'say';
use feature 'state';
no warnings 'recursion';
use List::Util qw(max);
sub Stirling2 {
my($n, $k) = @_;
my $n1 = $n - 1;
return 1 if $n1 == $k;
return 0 unless $n1 && $k;
state %seen;
return ($seen{"{$n1}|{$k}" } //= Stirling2($n1,$k ) * $k) +
($seen{"{$n1}|{$k-1}"} //= Stirling2($n1,$k-1))
}
my $upto = 12;
my $width = 1 + length max map { Stirling2($upto+1,$_) } 0..$upto+1;
say 'Unsigned Stirling2 numbers of the second kind: S2(n, k):';
print 'n\k' . sprintf "%${width}s"x(1+$upto)."\n", 0..$upto;
for my $row (1..$upto+1) {
printf '%-3d', $row-1;
printf "%${width}d", Stirling2($row, $_) for 0..$row-1;
print "\n";
}
say "\nMaximum value from the S2(100, *) row:";
say max map { Stirling2(101,$_) } 0..100; |
http://rosettacode.org/wiki/Strassen%27s_algorithm | Strassen's algorithm | Description
In linear algebra, the Strassen algorithm (named after Volker Strassen), is an algorithm for matrix multiplication.
It is faster than the standard matrix multiplication algorithm and is useful in practice for large matrices, but would be slower than the fastest known algorithms for extremely large matrices.
Task
Write a routine, function, procedure etc. in your language to implement the Strassen algorithm for matrix multiplication.
While practical implementations of Strassen's algorithm usually switch to standard methods of matrix multiplication for small enough sub-matrices (currently anything less than 512×512 according to Wikipedia), for the purposes of this task you should not switch until reaching a size of 1 or 2.
Related task
Matrix multiplication
See also
Wikipedia article
| #Python | Python | """Matrix multiplication using Strassen's algorithm. Requires Python >= 3.7."""
from __future__ import annotations
from itertools import chain
from typing import List
from typing import NamedTuple
from typing import Optional
class Shape(NamedTuple):
rows: int
cols: int
class Matrix(List):
"""A matrix implemented as a two-dimensional list."""
@classmethod
def block(cls, blocks) -> Matrix:
"""Return a new Matrix assembled from nested blocks."""
m = Matrix()
for hblock in blocks:
for row in zip(*hblock):
m.append(list(chain.from_iterable(row)))
return m
def dot(self, b: Matrix) -> Matrix:
"""Return a new Matrix that is the product of this matrix and matrix `b`.
Uses 'simple' or 'naive' matrix multiplication."""
assert self.shape.cols == b.shape.rows
m = Matrix()
for row in self:
new_row = []
for c in range(len(b[0])):
col = [b[r][c] for r in range(len(b))]
new_row.append(sum(x * y for x, y in zip(row, col)))
m.append(new_row)
return m
def __matmul__(self, b: Matrix) -> Matrix:
return self.dot(b)
def __add__(self, b: Matrix) -> Matrix:
"""Matrix addition."""
assert self.shape == b.shape
rows, cols = self.shape
return Matrix(
[[self[i][j] + b[i][j] for j in range(cols)] for i in range(rows)]
)
def __sub__(self, b: Matrix) -> Matrix:
"""Matrix subtraction."""
assert self.shape == b.shape
rows, cols = self.shape
return Matrix(
[[self[i][j] - b[i][j] for j in range(cols)] for i in range(rows)]
)
def strassen(self, b: Matrix) -> Matrix:
"""Return a new Matrix that is the product of this matrix and matrix `b`.
Uses strassen algorithm."""
rows, cols = self.shape
assert rows == cols, "matrices must be square"
assert self.shape == b.shape, "matrices must be the same shape"
assert rows and (rows & rows - 1) == 0, "shape must be a power of 2"
if rows == 1:
return self.dot(b)
p = rows // 2 # partition
a11 = Matrix([n[:p] for n in self[:p]])
a12 = Matrix([n[p:] for n in self[:p]])
a21 = Matrix([n[:p] for n in self[p:]])
a22 = Matrix([n[p:] for n in self[p:]])
b11 = Matrix([n[:p] for n in b[:p]])
b12 = Matrix([n[p:] for n in b[:p]])
b21 = Matrix([n[:p] for n in b[p:]])
b22 = Matrix([n[p:] for n in b[p:]])
m1 = (a11 + a22).strassen(b11 + b22)
m2 = (a21 + a22).strassen(b11)
m3 = a11.strassen(b12 - b22)
m4 = a22.strassen(b21 - b11)
m5 = (a11 + a12).strassen(b22)
m6 = (a21 - a11).strassen(b11 + b12)
m7 = (a12 - a22).strassen(b21 + b22)
c11 = m1 + m4 - m5 + m7
c12 = m3 + m5
c21 = m2 + m4
c22 = m1 - m2 + m3 + m6
return Matrix.block([[c11, c12], [c21, c22]])
def round(self, ndigits: Optional[int] = None) -> Matrix:
return Matrix([[round(i, ndigits) for i in row] for row in self])
@property
def shape(self) -> Shape:
cols = len(self[0]) if self else 0
return Shape(len(self), cols)
def examples():
a = Matrix(
[
[1, 2],
[3, 4],
]
)
b = Matrix(
[
[5, 6],
[7, 8],
]
)
c = Matrix(
[
[1, 1, 1, 1],
[2, 4, 8, 16],
[3, 9, 27, 81],
[4, 16, 64, 256],
]
)
d = Matrix(
[
[4, -3, 4 / 3, -1 / 4],
[-13 / 3, 19 / 4, -7 / 3, 11 / 24],
[3 / 2, -2, 7 / 6, -1 / 4],
[-1 / 6, 1 / 4, -1 / 6, 1 / 24],
]
)
e = Matrix(
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16],
]
)
f = Matrix(
[
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1],
]
)
print("Naive matrix multiplication:")
print(f" a * b = {a @ b}")
print(f" c * d = {(c @ d).round()}")
print(f" e * f = {e @ f}")
print("Strassen's matrix multiplication:")
print(f" a * b = {a.strassen(b)}")
print(f" c * d = {c.strassen(d).round()}")
print(f" e * f = {e.strassen(f)}")
if __name__ == "__main__":
examples()
|
http://rosettacode.org/wiki/String_append | String append |
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
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program appendstr.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
.equ BUFFERSIZE, 100
/* Initialized data */
.data
szMessString: .asciz "String :\n"
szString1: .asciz "Alphabet : "
sComplement: .fill BUFFERSIZE,1,0
szString2: .asciz "abcdefghijklmnopqrstuvwxyz"
szCarriageReturn: .asciz "\n"
/* UnInitialized data */
.bss
/* code section */
.text
.global main
main:
ldr r0,iAdrszMessString @ display message
bl affichageMess
ldr r0,iAdrszString1 @ display begin string
bl affichageMess
ldr r0,iAdrszCarriageReturn @ display line return
bl affichageMess
ldr r0,iAdrszString1
ldr r1,iAdrszString2
bl append @ append sting2 to string1
ldr r0,iAdrszMessString
bl affichageMess
ldr r0,iAdrszString1 @ display string
bl affichageMess
ldr r0,iAdrszCarriageReturn
bl affichageMess
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc 0 @ perform system call
iAdrszMessString: .int szMessString
iAdrszString1: .int szString1
iAdrszString2: .int szString2
iAdrszCarriageReturn: .int szCarriageReturn
/******************************************************************/
/* append two strings */
/******************************************************************/
/* r0 contains the address of the string1 */
/* r1 contains the address of the string2 */
append:
push {r0,r1,r2,r7,lr} @ save registers
mov r2,#0 @ counter byte string 1
1:
ldrb r3,[r0,r2] @ load byte string 1
cmp r3,#0 @ zero final ?
addne r2,#1
bne 1b @ no -> loop
mov r4,#0 @ counter byte string 2
2:
ldrb r3,[r1,r4] @ load byte string 2
strb r3,[r0,r2] @ store byte string 1
cmp r3,#0 @ zero final ?
addne r2,#1 @ no -> increment counter 1
addne r4,#1 @ no -> increment counter 2
bne 2b @ no -> loop
100:
pop {r0,r1,r2,r7,lr} @ restaur registers
bx lr @ return
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registers
mov r2,#0 @ counter length */
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call system
pop {r0,r1,r2,r7,lr} @ restaur registers
bx lr @ return
|
http://rosettacode.org/wiki/Stirling_numbers_of_the_second_kind | Stirling numbers of the second kind | Stirling numbers of the second kind, or Stirling partition numbers, are the
number of ways to partition a set of n objects into k non-empty subsets. They are
closely related to Bell numbers, and may be derived from them.
Stirling numbers of the second kind obey the recurrence relation:
S2(n, 0) and S2(0, k) = 0 # for n, k > 0
S2(n, n) = 1
S2(n + 1, k) = k * S2(n, k) + S2(n, k - 1)
Task
Write a routine (function, procedure, whatever) to find Stirling numbers of the second kind. There are several methods to generate Stirling numbers of the second kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.
Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the second kind, S2(n, k), up to S2(12, 12). it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S2(n, k) == 0 (when k > n).
If your language supports large integers, find and show here, on this page, the maximum value of S2(n, k) where n == 100.
See also
Wikipedia - Stirling numbers of the second kind
OEIS:A008277 - Stirling numbers of the second kind
Related Tasks
Stirling numbers of the first kind
Bell numbers
Lah numbers
| #Phix | Phix | with javascript_semantics
include mpfr.e
constant lim = 100,
lim1 = lim+1,
last = 12
sequence s2 = repeat(0,lim1)
for n=1 to lim1 do
s2[n] = mpz_inits(lim1)
mpz_set_si(s2[n][n],1)
end for
mpz {t, m100} = mpz_inits(2)
for n=1 to lim do
for k=1 to n do
mpz_set_si(t,k)
mpz_mul(t,t,s2[n][k+1])
mpz_add(s2[n+1][k+1],t,s2[n][k])
end for
end for
printf(1,"Stirling numbers of the second kind: S2(n, k):\n n k:")
for i=0 to last do
printf(1,"%5d ", i)
end for
printf(1,"\n--- %s\n",repeat('-',last*10+5))
for n=0 to last do
printf(1,"%2d ", n)
for k=1 to n+1 do
printf(1,"%9s ",{mpz_get_str(s2[n+1][k])})
end for
printf(1,"\n")
end for
for k=1 to lim1 do
mpz s100k = s2[lim1][k]
if mpz_cmp(s100k,m100) > 0 then
mpz_set(m100,s100k)
end if
end for
printf(1,"\nThe maximum S2(100,k): %s\n",shorten(mpz_get_str(m100)))
|
http://rosettacode.org/wiki/Strassen%27s_algorithm | Strassen's algorithm | Description
In linear algebra, the Strassen algorithm (named after Volker Strassen), is an algorithm for matrix multiplication.
It is faster than the standard matrix multiplication algorithm and is useful in practice for large matrices, but would be slower than the fastest known algorithms for extremely large matrices.
Task
Write a routine, function, procedure etc. in your language to implement the Strassen algorithm for matrix multiplication.
While practical implementations of Strassen's algorithm usually switch to standard methods of matrix multiplication for small enough sub-matrices (currently anything less than 512×512 according to Wikipedia), for the purposes of this task you should not switch until reaching a size of 1 or 2.
Related task
Matrix multiplication
See also
Wikipedia article
| #Raku | Raku | # 20210126 Raku programming solution
use Math::Libgsl::Constants;
use Math::Libgsl::Matrix;
use Math::Libgsl::BLAS;
my @M;
sub SQM (\in) { # create custom sq matrix from CSV
die "Not a ■" if (my \L = in.split(/\,/)).sqrt != (my \size = L.sqrt.Int);
my Math::Libgsl::Matrix \M .= new: size, size;
for ^size Z L.rotor(size) -> ($i, @row) { M.set-row: $i, @row }
M
}
sub infix:<⊗>(\x,\y) { # custom multiplication
my Math::Libgsl::Matrix \z .= new: x.size1, x.size2;
dgemm(CblasNoTrans, CblasNoTrans, 1, x, y, 1, z);
z
}
sub infix:<⊕>(\x,\y) { # custom addition
my Math::Libgsl::Matrix \z .= new: x.size1, x.size2;
z.copy(x).add(y)
}
sub infix:<⊖>(\x,\y) { # custom subtraction
my Math::Libgsl::Matrix \z .= new: x.size1, x.size2;
z.copy(x).sub(y)
}
sub Strassen($A, $B) {
{ return $A ⊗ $B } if (my \n = $A.size1) == 1;
my Math::Libgsl::Matrix ($A11,$A12,$A21,$A22,$B11,$B12,$B21,$B22);
my Math::Libgsl::Matrix ($P1,$P2,$P3,$P4,$P5,$P6,$P7);
my Math::Libgsl::Matrix::View ($mv1,$mv2,$mv3,$mv4,$mv5,$mv6,$mv7,$mv8);
($mv1,$mv2,$mv3,$mv4,$mv5,$mv6,$mv7,$mv8)».=new ;
my \half = n div 2; # dimension of quarter submatrices
$A11 = $mv1.submatrix($A, 0,0, half,half); #
$A12 = $mv2.submatrix($A, 0,half, half,half); # create quarter views
$A21 = $mv3.submatrix($A, half,0, half,half); # of operand matrices
$A22 = $mv4.submatrix($A, half,half, half,half); #
$B11 = $mv5.submatrix($B, 0,0, half,half); # 11 12
$B12 = $mv6.submatrix($B, 0,half, half,half); #
$B21 = $mv7.submatrix($B, half,0, half,half); # 21 22
$B22 = $mv8.submatrix($B, half,half, half,half); #
$P1 = Strassen($A12 ⊖ $A22, $B21 ⊕ $B22);
$P2 = Strassen($A11 ⊕ $A22, $B11 ⊕ $B22);
$P3 = Strassen($A11 ⊖ $A21, $B11 ⊕ $B12);
$P4 = Strassen($A11 ⊕ $A12, $B22 );
$P5 = Strassen($A11, $B12 ⊖ $B22);
$P6 = Strassen($A22, $B21 ⊖ $B11);
$P7 = Strassen($A21 ⊕ $A22, $B11 );
my Math::Libgsl::Matrix $C .= new: n, n; # Build C from
my Math::Libgsl::Matrix::View ($mvC11,$mvC12,$mvC21,$mvC22); # C11 C12
($mvC11,$mvC12,$mvC21,$mvC22)».=new ; # C21 C22
given $mvC11.submatrix($C, 0,0, half,half) { .add: (($P1 ⊕ $P2) ⊖ $P4) ⊕ $P6 };
given $mvC12.submatrix($C, 0,half, half,half) { .add: $P4 ⊕ $P5 };
given $mvC21.submatrix($C, half,0, half,half) { .add: $P6 ⊕ $P7 };
given $mvC22.submatrix($C, half,half, half,half) { .add: (($P2 ⊖ $P3) ⊕ $P5) ⊖ $P7 };
$C
}
for $=pod[0].contents { next if /^\n$/ ; @M.append: SQM $_ }
for @M.rotor(2) {
my $product = @_[0] ⊗ @_[1];
# $product.get-row($_)».round(1).fmt('%2d').put for ^$product.size1;
say "Regular multiply:";
$product.get-row($_)».fmt('%.10g').put for ^$product.size1;
$product = Strassen @_[0], @_[1];
say "Strassen multiply:";
$product.get-row($_)».fmt('%.10g').put for ^$product.size1;
}
=begin code
1,2,3,4
5,6,7,8
1,1,1,1,2,4,8,16,3,9,27,81,4,16,64,256
4,-3,4/3,-1/4,-13/3,19/4,-7/3,11/24,3/2,-2,7/6,-1/4,-1/6,1/4,-1/6,1/24
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16
1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1
=end code |
http://rosettacode.org/wiki/String_append | String append |
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
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #AppleScript | AppleScript |
set {a, b} to {"Apple", "Script"}
set a to a & b
return a as string
|
http://rosettacode.org/wiki/String_append | String append |
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
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #APL | APL | s←'hello'
s,'world'
helloworld |
http://rosettacode.org/wiki/Stirling_numbers_of_the_second_kind | Stirling numbers of the second kind | Stirling numbers of the second kind, or Stirling partition numbers, are the
number of ways to partition a set of n objects into k non-empty subsets. They are
closely related to Bell numbers, and may be derived from them.
Stirling numbers of the second kind obey the recurrence relation:
S2(n, 0) and S2(0, k) = 0 # for n, k > 0
S2(n, n) = 1
S2(n + 1, k) = k * S2(n, k) + S2(n, k - 1)
Task
Write a routine (function, procedure, whatever) to find Stirling numbers of the second kind. There are several methods to generate Stirling numbers of the second kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.
Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the second kind, S2(n, k), up to S2(12, 12). it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S2(n, k) == 0 (when k > n).
If your language supports large integers, find and show here, on this page, the maximum value of S2(n, k) where n == 100.
See also
Wikipedia - Stirling numbers of the second kind
OEIS:A008277 - Stirling numbers of the second kind
Related Tasks
Stirling numbers of the first kind
Bell numbers
Lah numbers
| #Prolog | Prolog | :- dynamic stirling2_cache/3.
stirling2(N, N, 1):-!.
stirling2(_, 0, 0):-!.
stirling2(N, K, 0):-
K > N,
!.
stirling2(N, K, L):-
stirling2_cache(N, K, L),
!.
stirling2(N, K, L):-
N1 is N - 1,
K1 is K - 1,
stirling2(N1, K, L1),
stirling2(N1, K1, L2),
!,
L is K * L1 + L2,
assertz(stirling2_cache(N, K, L)).
print_stirling_numbers(N):-
between(1, N, K),
stirling2(N, K, L),
writef('%8r', [L]),
fail.
print_stirling_numbers(_):-
nl.
print_stirling_numbers_up_to(M):-
between(1, M, N),
print_stirling_numbers(N),
fail.
print_stirling_numbers_up_to(_).
max_stirling2(N, Max):-
aggregate_all(max(L), (between(1, N, K), stirling2(N, K, L)), Max).
main:-
writeln('Stirling numbers of the second kind up to S2(12,12):'),
print_stirling_numbers_up_to(12),
writeln('Maximum value of S2(n,k) where n = 100:'),
max_stirling2(100, M),
writeln(M). |
http://rosettacode.org/wiki/Strassen%27s_algorithm | Strassen's algorithm | Description
In linear algebra, the Strassen algorithm (named after Volker Strassen), is an algorithm for matrix multiplication.
It is faster than the standard matrix multiplication algorithm and is useful in practice for large matrices, but would be slower than the fastest known algorithms for extremely large matrices.
Task
Write a routine, function, procedure etc. in your language to implement the Strassen algorithm for matrix multiplication.
While practical implementations of Strassen's algorithm usually switch to standard methods of matrix multiplication for small enough sub-matrices (currently anything less than 512×512 according to Wikipedia), for the purposes of this task you should not switch until reaching a size of 1 or 2.
Related task
Matrix multiplication
See also
Wikipedia article
| #Swift | Swift |
// Matrix Strassen Multiplication
func strassenMultiply(matrix1: Matrix, matrix2: Matrix) -> Matrix {
precondition(matrix1.columns == matrix2.columns,
"Two matrices can only be matrix multiplied if one has dimensions mxn & the other has dimensions nxp where m, n, p are in R")
// Transform to square matrix
let maxColumns = Swift.max(matrix1.rows, matrix1.columns, matrix2.rows, matrix2.columns)
let pwr2 = nextPowerOfTwo(num: maxColumns)
var sqrMatrix1 = Matrix(rows: pwr2, columns: pwr2)
var sqrMatrix2 = Matrix(rows: pwr2, columns: pwr2)
// fill square matrix 1 with values
for i in 0..<matrix1.rows {
for j in 0..<matrix1.columns{
sqrMatrix1[i, j] = matrix1[i, j]
}
}
// fill square matrix 2 with values
for i in 0..<matrix2.rows {
for j in 0..<matrix2.columns{
sqrMatrix2[i, j] = matrix2[i, j]
}
}
// Get strassen result and transfer to array with proper size
let formulaResult = strassenFormula(matrix1: sqrMatrix1, matrix2: sqrMatrix2)
var finalResult = Matrix(rows: matrix1.rows, columns: matrix2.columns)
for i in 0..<finalResult.rows{
for j in 0..<finalResult.columns {
finalResult[i, j] = formulaResult[i, j]
}
}
return finalResult
}
// Calculate next power of 2
func nextPowerOfTwo(num: Int) -> Int {
// formula for next power of 2
return Int(pow(2,(ceil(log2(Double(num))))))
}
// Multiply Matrices Using Strassen Formula
func strassenFormula(matrix1: Matrix, matrix2: Matrix) -> Matrix {
precondition(matrix1.rows == matrix1.columns && matrix2.rows == matrix2.columns, "Matrices need to be square")
guard matrix1.rows > 1 && matrix2.rows > 1 else { return matrix1 * matrix2 }
let rowHalf = matrix1.rows / 2
// Strassen Formula https://www.geeksforgeeks.org/easy-way-remember-strassens-matrix-equation/
// p1 = a(f-h) p2 = (a+b)h
// p2 = (c+d)e p4 = d(g-e)
// p5 = (a+d)(e+h) p6 = (b-d)(g+h)
// p7 = (a-c)(e+f)
|a b| x |e f| = |(p5+p4-p2+p6) (p1+p2)|
|c d| |g h| |(p3+p4) (p1+p5-p3-p7)|
Matrix 1 Matrix 2 Result
// create empty matrices for a, b, c, d, e, f, g, h
var a = Matrix(rows: rowHalf, columns: rowHalf)
var b = Matrix(rows: rowHalf, columns: rowHalf)
var c = Matrix(rows: rowHalf, columns: rowHalf)
var d = Matrix(rows: rowHalf, columns: rowHalf)
var e = Matrix(rows: rowHalf, columns: rowHalf)
var f = Matrix(rows: rowHalf, columns: rowHalf)
var g = Matrix(rows: rowHalf, columns: rowHalf)
var h = Matrix(rows: rowHalf, columns: rowHalf)
// fill the matrices with values
for i in 0..<rowHalf {
for j in 0..<rowHalf {
a[i, j] = matrix1[i, j]
b[i, j] = matrix1[i, j+rowHalf]
c[i, j] = matrix1[i+rowHalf, j]
d[i, j] = matrix1[i+rowHalf, j+rowHalf]
e[i, j] = matrix2[i, j]
f[i, j] = matrix2[i, j+rowHalf]
g[i, j] = matrix2[i+rowHalf, j]
h[i, j] = matrix2[i+rowHalf, j+rowHalf]
}
}
// a * (f - h)
let p1 = strassenFormula(matrix1: a, matrix2: (f - h))
// (a + b) * h
let p2 = strassenFormula(matrix1: (a + b), matrix2: h)
// (c + d) * e
let p3 = strassenFormula(matrix1: (c + d), matrix2: e)
// d * (g - e)
let p4 = strassenFormula(matrix1: d, matrix2: (g - e))
// (a + d) * (e + h)
let p5 = strassenFormula(matrix1: (a + d), matrix2: (e + h))
// (b - d) * (g + h)
let p6 = strassenFormula(matrix1: (b - d), matrix2: (g + h))
// (a - c) * (e + f)
let p7 = strassenFormula(matrix1: (a - c), matrix2: (e + f))
// p5 + p4 - p2 + p6
let result11 = p5 + p4 - p2 + p6
// p1 + p2
let result12 = p1 + p2
// p3 + p4
let result21 = p3 + p4
// p1 + p5 - p3 - p7
let result22 = p1 + p5 - p3 - p7
// create an empty matrix for result and fill with values
var result = Matrix(rows: matrix1.rows, columns: matrix1.rows)
for i in 0..<rowHalf {
for j in 0..<rowHalf {
result[i, j] = result11[i, j]
result[i, j+rowHalf] = result12[i, j]
result[i+rowHalf, j] = result21[i, j]
result[i+rowHalf, j+rowHalf] = result22[i, j]
}
}
return result
}
func main(){
// Matrix Class https://github.com/hollance/Matrix/blob/master/Matrix.swift
var a = Matrix(rows: 2, columns: 2)
a[row: 0] = [1, 2]
a[row: 1] = [3, 4]
var b = Matrix(rows: 2, columns: 2)
b[row: 0] = [5, 6]
b[row: 1] = [7, 8]
var c = Matrix(rows: 4, columns: 4)
c[row: 0] = [1, 1, 1,1]
c[row: 1] = [2, 4, 8, 16]
c[row: 2] = [3, 9, 27, 81]
c[row: 3] = [4, 16, 64, 256]
var d = Matrix(rows: 4, columns: 4)
d[row: 0] = [4, -3, Double(4/3), Double(-1/4)]
d[row: 1] = [Double(-13/3), Double(19/4), Double(-7/3), Double(11/24)]
d[row: 2] = [Double(3/2), Double(-2), Double(7/6), Double(-1/4)]
d[row: 3] = [Double(-1/6), Double(1/4), Double(-1/6), Double(1/24)]
var e = Matrix(rows: 4, columns: 4)
e[row: 0] = [1, 2, 3, 4]
e[row: 1] = [5, 6, 7, 8]
e[row: 2] = [9, 10, 11, 12]
e[row: 3] = [13, 14, 15, 16]
var f = Matrix(rows: 4, columns: 4)
f[row: 0] = [1, 0, 0, 0]
f[row: 1] = [0, 1, 0 ,0]
f[row: 2] = [0 ,0 ,1, 0]
f[row: 3] = [0, 0 ,0 ,1]
let result1 = strassenMultiply(matrix1: a, matrix2: b)
print("AxB")
print(result1.description)
let result2 = strassenMultiply(matrix1: c, matrix2: d)
print("CxD")
print(result2.description)
let result3 = strassenMultiply(matrix1: e, matrix2: f)
print("ExF")
print(result3.description)
}
main() |
http://rosettacode.org/wiki/Strassen%27s_algorithm | Strassen's algorithm | Description
In linear algebra, the Strassen algorithm (named after Volker Strassen), is an algorithm for matrix multiplication.
It is faster than the standard matrix multiplication algorithm and is useful in practice for large matrices, but would be slower than the fastest known algorithms for extremely large matrices.
Task
Write a routine, function, procedure etc. in your language to implement the Strassen algorithm for matrix multiplication.
While practical implementations of Strassen's algorithm usually switch to standard methods of matrix multiplication for small enough sub-matrices (currently anything less than 512×512 according to Wikipedia), for the purposes of this task you should not switch until reaching a size of 1 or 2.
Related task
Matrix multiplication
See also
Wikipedia article
| #Wren | Wren | class Matrix {
construct new(a) {
if (a.type != List || a.count == 0 || a[0].type != List || a[0].count == 0 || a[0][0].type != Num) {
Fiber.abort("Argument must be a non-empty two dimensional list of numbers.")
}
_a = a
}
rows { _a.count }
cols { _a[0].count }
+(b) {
if (b.type != Matrix) Fiber.abort("Argument must be a matrix.")
if ((this.rows != b.rows) || (this.cols != b.cols)) {
Fiber.abort("Matrices must have the same dimensions.")
}
var c = List.filled(rows, null)
for (i in 0...rows) {
c[i] = List.filled(cols, 0)
for (j in 0...cols) c[i][j] = _a[i][j] + b[i, j]
}
return Matrix.new(c)
}
- { this * -1 }
-(b) { this + (-b) }
*(b) {
var c = List.filled(rows, null)
if (b is Num) {
for (i in 0...rows) {
c[i] = List.filled(cols, 0)
for (j in 0...cols) c[i][j] = _a[i][j] * b
}
} else if (b is Matrix) {
if (this.cols != b.rows) Fiber.abort("Cannot multiply these matrices.")
for (i in 0...rows) {
c[i] = List.filled(b.cols, 0)
for (j in 0...b.cols) {
for (k in 0...b.rows) c[i][j] = c[i][j] + _a[i][k] * b[k, j]
}
}
} else {
Fiber.abort("Argument must be a matrix or a number.")
}
return Matrix.new(c)
}
[i] { _a[i].toList }
[i, j] { _a[i][j] }
toString { _a.toString }
// rounds all elements to 'p' places
toString(p) {
var s = List.filled(rows, "")
var pow = 10.pow(p)
for (i in 0...rows) {
var t = List.filled(cols, "")
for (j in 0...cols) {
var r = (_a[i][j]*pow).round / pow
t[j] = r.toString
if (t[j] == "-0") t[j] = "0"
}
s[i] = t.toString
}
return s
}
}
var params = Fn.new { |r, c|
return [
[0...r, 0...c, 0, 0],
[0...r, c...2*c, 0, c],
[r...2*r, 0...c, r, 0],
[r...2*r, c...2*c, r, c]
]
}
var toQuarters = Fn.new { |m|
var r = (m.rows/2).floor
var c = (m.cols/2).floor
var p = params.call(r, c)
var quarters = []
for (k in 0..3) {
var q = List.filled(r, null)
for (i in p[k][0]) {
q[i - p[k][2]] = List.filled(c, 0)
for (j in p[k][1]) q[i - p[k][2]][j - p[k][3]] = m[i, j]
}
quarters.add(Matrix.new(q))
}
return quarters
}
var fromQuarters = Fn.new { |q|
var r = q[0].rows
var c = q[0].cols
var p = params.call(r, c)
r = r * 2
c = c * 2
var m = List.filled(r, null)
for (i in 0...c) m[i] = List.filled(c, 0)
for (k in 0..3) {
for (i in p[k][0]) {
for (j in p[k][1]) m[i][j] = q[k][i - p[k][2], j - p[k][3]]
}
}
return Matrix.new(m)
}
var strassen // recursive
strassen = Fn.new { |a, b|
if (a.rows != a.cols || b.rows != b.cols || a.rows != b.rows) {
Fiber.abort("Matrices must be square and of equal size.")
}
if (a.rows == 0 || (a.rows & (a.rows - 1)) != 0) {
Fiber.abort("Size of matrices must be a power of two.")
}
if (a.rows == 1) return a * b
var qa = toQuarters.call(a)
var qb = toQuarters.call(b)
var p1 = strassen.call(qa[1] - qa[3], qb[2] + qb[3])
var p2 = strassen.call(qa[0] + qa[3], qb[0] + qb[3])
var p3 = strassen.call(qa[0] - qa[2], qb[0] + qb[1])
var p4 = strassen.call(qa[0] + qa[1], qb[3])
var p5 = strassen.call(qa[0], qb[1] - qb[3])
var p6 = strassen.call(qa[3], qb[2] - qb[0])
var p7 = strassen.call(qa[2] + qa[3], qb[0])
var q = List.filled(4, null)
q[0] = p1 + p2 - p4 + p6
q[1] = p4 + p5
q[2] = p6 + p7
q[3] = p2 - p3 + p5 - p7
return fromQuarters.call(q)
}
var a = Matrix.new([ [1,2], [3, 4] ])
var b = Matrix.new([ [5,6], [7, 8] ])
var c = Matrix.new([ [1, 1, 1, 1], [2, 4, 8, 16], [3, 9, 27, 81], [4, 16, 64, 256] ])
var d = Matrix.new([ [4, -3, 4/3, -1/4], [-13/3, 19/4, -7/3, 11/24],
[3/2, -2, 7/6, -1/4], [-1/6, 1/4, -1/6, 1/24] ])
var e = Matrix.new([ [1, 2, 3, 4], [5, 6, 7, 8], [9,10,11,12], [13,14,15,16] ])
var f = Matrix.new([ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1] ])
System.print("Using 'normal' matrix multiplication:")
System.print(" a * b = %(a * b)")
System.print(" c * d = %((c * d).toString(6))")
System.print(" e * f = %(e * f)")
System.print("\nUsing 'Strassen' matrix multiplication:")
System.print(" a * b = %(strassen.call(a, b))")
System.print(" c * d = %(strassen.call(c, d).toString(6))")
System.print(" e * f = %(strassen.call(e, f))") |
http://rosettacode.org/wiki/String_append | String append |
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
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #Arturo | Arturo | print join ["Hello" "World"]
a: new "Hello"
'a ++ "World"
print a
b: new "Hello"
append 'b "World"
print b
c: "Hello"
print append c "World" |
http://rosettacode.org/wiki/String_append | String append |
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
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #Asymptote | Asymptote | string s = "Hello";
s = s + " Wo";
s += "rld!";
write(s); |
http://rosettacode.org/wiki/Stirling_numbers_of_the_second_kind | Stirling numbers of the second kind | Stirling numbers of the second kind, or Stirling partition numbers, are the
number of ways to partition a set of n objects into k non-empty subsets. They are
closely related to Bell numbers, and may be derived from them.
Stirling numbers of the second kind obey the recurrence relation:
S2(n, 0) and S2(0, k) = 0 # for n, k > 0
S2(n, n) = 1
S2(n + 1, k) = k * S2(n, k) + S2(n, k - 1)
Task
Write a routine (function, procedure, whatever) to find Stirling numbers of the second kind. There are several methods to generate Stirling numbers of the second kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.
Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the second kind, S2(n, k), up to S2(12, 12). it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S2(n, k) == 0 (when k > n).
If your language supports large integers, find and show here, on this page, the maximum value of S2(n, k) where n == 100.
See also
Wikipedia - Stirling numbers of the second kind
OEIS:A008277 - Stirling numbers of the second kind
Related Tasks
Stirling numbers of the first kind
Bell numbers
Lah numbers
| #Python | Python |
computed = {}
def sterling2(n, k):
key = str(n) + "," + str(k)
if key in computed.keys():
return computed[key]
if n == k == 0:
return 1
if (n > 0 and k == 0) or (n == 0 and k > 0):
return 0
if n == k:
return 1
if k > n:
return 0
result = k * sterling2(n - 1, k) + sterling2(n - 1, k - 1)
computed[key] = result
return result
print("Stirling numbers of the second kind:")
MAX = 12
print("n/k".ljust(10), end="")
for n in range(MAX + 1):
print(str(n).rjust(10), end="")
print()
for n in range(MAX + 1):
print(str(n).ljust(10), end="")
for k in range(n + 1):
print(str(sterling2(n, k)).rjust(10), end="")
print()
print("The maximum value of S2(100, k) = ")
previous = 0
for k in range(1, 100 + 1):
current = sterling2(100, k)
if current > previous:
previous = current
else:
print("{0}\n({1} digits, k = {2})\n".format(previous, len(str(previous)), k - 1))
break
|
http://rosettacode.org/wiki/String_append | String append |
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
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #AutoHotkey | AutoHotkey | s := "Hello, "
s .= "world."
MsgBox % s |
http://rosettacode.org/wiki/String_append | String append |
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
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #Avail | Avail | str : string := "99 bottles of ";
str ++= "beer";
Print: str; |
http://rosettacode.org/wiki/Stirling_numbers_of_the_second_kind | Stirling numbers of the second kind | Stirling numbers of the second kind, or Stirling partition numbers, are the
number of ways to partition a set of n objects into k non-empty subsets. They are
closely related to Bell numbers, and may be derived from them.
Stirling numbers of the second kind obey the recurrence relation:
S2(n, 0) and S2(0, k) = 0 # for n, k > 0
S2(n, n) = 1
S2(n + 1, k) = k * S2(n, k) + S2(n, k - 1)
Task
Write a routine (function, procedure, whatever) to find Stirling numbers of the second kind. There are several methods to generate Stirling numbers of the second kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.
Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the second kind, S2(n, k), up to S2(12, 12). it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S2(n, k) == 0 (when k > n).
If your language supports large integers, find and show here, on this page, the maximum value of S2(n, k) where n == 100.
See also
Wikipedia - Stirling numbers of the second kind
OEIS:A008277 - Stirling numbers of the second kind
Related Tasks
Stirling numbers of the first kind
Bell numbers
Lah numbers
| #Quackery | Quackery | [ dip number$
over size -
space swap of
swap join echo$ ] is justify ( n n --> )
[ table ] is s2table ( n --> n )
[ swap 101 * + s2table ] is s2 ( n n --> n )
101 times
[ i^ 101 times
[ dup i^
[ 2dup = iff
[ 2drop 1 ] done
over 0 =
over 0 = or iff
[ 2drop 0 ] done
dip [ 1 - ]
2dup tuck s2 *
unrot 1 - s2 + ]
' s2table put ]
drop ]
cr cr
13 times
[ i^ dup 1+ times
[ dup i^ s2
10 justify ]
drop cr ]
cr
0 100 times
[ 100 i^ 1+ s2 max ]
echo cr |
http://rosettacode.org/wiki/Straddling_checkerboard | Straddling checkerboard | Task
Implement functions to encrypt and decrypt a message using the straddling checkerboard method. The checkerboard should take a 28 character alphabet (A-Z plus a full stop and an escape character) and two different numbers representing the blanks in the first row. The output will be a series of decimal digits.
Numbers should be encrypted by inserting the escape character before each digit, then including the digit unencrypted. This should be reversed for decryption.
| #11l | 11l | V t = [[String(‘79’), ‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’],
[String(‘’), ‘H’, ‘O’, ‘L’, ‘’, ‘M’, ‘E’, ‘S’, ‘’, ‘R’, ‘T’],
[String(‘3’), ‘A’, ‘B’, ‘C’, ‘D’, ‘F’, ‘G’, ‘I’, ‘J’, ‘K’, ‘N’],
[String(‘7’), ‘P’, ‘Q’, ‘U’, ‘V’, ‘W’, ‘X’, ‘Y’, ‘Z’, ‘.’, ‘/’]]
F straddle(s)
R multiloop_filtered(Array(s.uppercase()), :t, (c, l) -> c C l, (c, l) -> l[0]‘’:t[0][l.index(c)]).join(‘’)
F unstraddle(s)
[String] r
V si = 0
F next()
R @s[@si++]
L
I si == s.len
L.break
V c = s[si++]
I c C (:t[2][0], :t[3][0])
V i = [:t[2][0], :t[3][0]].index(c)
V n = :t[2 + i][:t[0].index(next())]
r [+]= I n == ‘/’ {next()} E n
E
r [+]= :t[1][:t[0].index(c)]
R r
V O = ‘One night-it was on the twentieth of March, 1888-I was returning’
print(‘Encoded: ’straddle(O))
print(‘Decoded: ’unstraddle(straddle(O)).join(‘’)) |
http://rosettacode.org/wiki/String_append | String append |
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
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #AWK | AWK |
# syntax: GAWK -f STRING_APPEND.AWK
BEGIN {
s = "foo"
s = s "bar"
print(s)
exit(0)
}
|
http://rosettacode.org/wiki/String_append | String append |
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
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #Axe | Axe | Lbl STRCAT
Copy(r₂,r₁+length(r₁),length(r₂)+1)
r₁
Return |
http://rosettacode.org/wiki/Stirling_numbers_of_the_second_kind | Stirling numbers of the second kind | Stirling numbers of the second kind, or Stirling partition numbers, are the
number of ways to partition a set of n objects into k non-empty subsets. They are
closely related to Bell numbers, and may be derived from them.
Stirling numbers of the second kind obey the recurrence relation:
S2(n, 0) and S2(0, k) = 0 # for n, k > 0
S2(n, n) = 1
S2(n + 1, k) = k * S2(n, k) + S2(n, k - 1)
Task
Write a routine (function, procedure, whatever) to find Stirling numbers of the second kind. There are several methods to generate Stirling numbers of the second kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.
Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the second kind, S2(n, k), up to S2(12, 12). it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S2(n, k) == 0 (when k > n).
If your language supports large integers, find and show here, on this page, the maximum value of S2(n, k) where n == 100.
See also
Wikipedia - Stirling numbers of the second kind
OEIS:A008277 - Stirling numbers of the second kind
Related Tasks
Stirling numbers of the first kind
Bell numbers
Lah numbers
| #Raku | Raku | sub Stirling2 (Int \n, Int \k) {
((1,), { (0, |@^last) »+« (|(@^last »*« @^last.keys), 0) } … *)[n;k]
}
my $upto = 12;
my $mx = (1..^$upto).map( { Stirling2($upto, $_) } ).max.chars;
put 'Stirling numbers of the second kind: S2(n, k):';
put 'n\k', (0..$upto)».fmt: "%{$mx}d";
for 0..$upto -> $row {
$row.fmt('%-3d').print;
put (0..$row).map( { Stirling2($row, $_) } )».fmt: "%{$mx}d";
}
say "\nMaximum value from the S2(100, *) row:";
say (^100).map( { Stirling2 100, $_ } ).max; |
http://rosettacode.org/wiki/Straddling_checkerboard | Straddling checkerboard | Task
Implement functions to encrypt and decrypt a message using the straddling checkerboard method. The checkerboard should take a 28 character alphabet (A-Z plus a full stop and an escape character) and two different numbers representing the blanks in the first row. The output will be a series of decimal digits.
Numbers should be encrypted by inserting the escape character before each digit, then including the digit unencrypted. This should be reversed for decryption.
| #ALGOL_68 | ALGOL 68 | #!/usr/local/bin/a68g --script #
PRIO MIN=5, MAX=5;
OP MIN = (INT a, b)INT: (a<b|a|b),
MAX = (INT a, b)INT: (a>b|a|b);
MODE STRADDLINGCHECKERBOARD=STRUCT(
[0:9]CHAR first, second, third,
[ABS ".": ABS "Z"]STRING table,
INT row u, row v,
CHAR esc, skip
);
STRUCT(
PROC (REF STRADDLINGCHECKERBOARD #self#, STRING #alphabet#, INT #u#, INT #v#)VOID init,
PROC (REF STRADDLINGCHECKERBOARD #self#, STRING #plain#)STRING encode,
PROC (REF STRADDLINGCHECKERBOARD #self#, STRING #plain#)STRING decode
) sc class = (
# PROC init = # (REF STRADDLINGCHECKERBOARD self, STRING in alphabet, INT u, v)VOID:
(
STRING alphabet = in alphabet[@0];
esc OF self := alphabet[UPB alphabet]; # use the last CHAR as the escape #
skip OF self := alphabet[UPB alphabet-1];
row u OF self := u MIN v;
row v OF self := u MAX v;
OP DIGIT = (INT i)CHAR: REPR(ABS "0" + i );
INT j := LWB alphabet;
# (first OF self)[u] := (first OF self)[v] := skip; #
FOR i FROM LWB first OF self TO UPB first OF self DO
IF i NE u AND i NE v THEN
(first OF self)[i] := alphabet[j];
(table OF self)[ABS alphabet[j]] := DIGIT i;
j+:=1
FI;
(second OF self)[i] := alphabet[i+8];
(table OF self)[ABS alphabet[i+8]] := DIGIT (row u OF self) + DIGIT i;
(third OF self)[i] := alphabet[i+18];
(table OF self)[ABS alphabet[i+18]] := DIGIT (row v OF self) + DIGIT i
OD
),
# PROC encode = # (REF STRADDLINGCHECKERBOARD self, STRING plain)STRING:
(
STRING esc = (table OF self)[ABS (esc OF self)];
INT l2u = ABS "A" - ABS "a";
STRING out := "";
FOR i FROM LWB plain TO UPB plain DO
CHAR c := plain[i];
IF "a" <= c AND c <= "z" THEN
c := REPR ( ABS c + l2u) FI;
IF "A" <= c AND c <= "Z" THEN
out +:= (table OF self)[ABS c]
ELIF "0" <= c AND c <= "9" THEN
out +:= esc + c
FI
OD;
out # EXIT #
),
# PROC decode = # (REF STRADDLINGCHECKERBOARD self, STRING cipher)STRING:
(
CHAR null = REPR 0;
STRING out;
INT state := 0;
FOR i FROM LWB cipher TO UPB cipher DO
INT n := ABS cipher[i] - ABS "0";
CHAR next :=
CASE state IN
#1:# (second OF self)[n],
#2:# (third OF self)[n],
#3:# cipher[i]
OUT
IF n = row u OF self THEN
state := 1; null
ELIF n = row v OF self THEN
state := 2; null
ELSE
(first OF self)[n]
FI
ESAC;
IF next = "/" THEN
state := 3
ELIF next NE null THEN
state := 0;
out +:= next
FI
OD;
out # EXIT #
)
);
main:
(
STRADDLINGCHECKERBOARD sc; (init OF sc class)(sc, "HOLMESRTABCDFGIJKNPQUVWXYZ./", 3, 7);
STRING original := "One night-it was on the twentieth of March, 1888-I was returning"[@0];
STRING en := (encode OF sc class)(sc, original);
STRING de := (decode OF sc class)(sc, en);
printf(($ggl$,
"Original: ", original,
"Encoded: ", en,
"Decoded: ", de
))
) |
http://rosettacode.org/wiki/String_append | String append |
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
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #BASIC | BASIC | S$ = "Hello"
S$ = S$ + " World!"
PRINT S$ |
http://rosettacode.org/wiki/String_append | String append |
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
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #Bracmat | Bracmat | str="Hello";
str$(!str " World!"):?str;
out$!str; |
http://rosettacode.org/wiki/Stirling_numbers_of_the_second_kind | Stirling numbers of the second kind | Stirling numbers of the second kind, or Stirling partition numbers, are the
number of ways to partition a set of n objects into k non-empty subsets. They are
closely related to Bell numbers, and may be derived from them.
Stirling numbers of the second kind obey the recurrence relation:
S2(n, 0) and S2(0, k) = 0 # for n, k > 0
S2(n, n) = 1
S2(n + 1, k) = k * S2(n, k) + S2(n, k - 1)
Task
Write a routine (function, procedure, whatever) to find Stirling numbers of the second kind. There are several methods to generate Stirling numbers of the second kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.
Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the second kind, S2(n, k), up to S2(12, 12). it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S2(n, k) == 0 (when k > n).
If your language supports large integers, find and show here, on this page, the maximum value of S2(n, k) where n == 100.
See also
Wikipedia - Stirling numbers of the second kind
OEIS:A008277 - Stirling numbers of the second kind
Related Tasks
Stirling numbers of the first kind
Bell numbers
Lah numbers
| #REXX | REXX | /*REXX program to compute and display Stirling numbers of the second kind. */
parse arg lim . /*obtain optional argument from the CL.*/
if lim=='' | lim=="," then lim= 12 /*Not specified? Then use the default.*/
olim= lim /*save the original value of LIM. */
lim= abs(lim) /*only use the absolute value of LIM. */
numeric digits max(9, 2*lim) /*(over) specify maximum number in grid*/
@.=
do j=0 for lim+1
@.j.j = 1; if j==0 then iterate /*define the right descending diagonal.*/
@.0.j = 0; @.j.0 = 0 /* " " zero values. */
end /*j*/
max#.= 0 /* [↓] calculate values for the grid. */
do n=0 for lim+1; np= n + 1
do k=1 for lim; km= k - 1
@.np.k = k * @.n.k + @.n.km /*calculate a number in the grid. */
max#.k= max(max#.k, @.n.k) /*find the maximum value for a column. */
max#.b= max(max#.b, @.n.k) /*find the maximum value for all rows. */
end /*k*/
end /*n*/
/* [↓] only show the maximum value ? */
do k=0 for lim+1 /*find max column width for each column*/
max#.a= max#.a + length(max#.k)
end /*k*/
w= length(max#.b) /*calculate max width of all numbers. */
if olim<0 then do; say 'The maximum value (which has ' w " decimal digits):"
say max#.b /*display maximum number in the grid. */
exit /*stick a fork in it, we're all done. */
end
wgi= max(5, length(lim+1) ) /*the maximum width of the grid's index*/
say '═row═' center("columns", max(9, max#.a + lim), '═') /*display header of the grid.*/
do r=0 for lim+1; $= /* [↓] display the grid to the term. */
do c=0 for lim+1 until c>=r /*build a row of grid, 1 col at a time.*/
$= $ right(@.r.c, length(max#.c) ) /*append a column to a row of the grid.*/
end /*c*/
say center(r, wgi) strip( substr($,2), 'T') /*display a single row of the grid. */
end /*r*/ /*stick a fork in it, we're all done. */ |
http://rosettacode.org/wiki/Straddling_checkerboard | Straddling checkerboard | Task
Implement functions to encrypt and decrypt a message using the straddling checkerboard method. The checkerboard should take a 28 character alphabet (A-Z plus a full stop and an escape character) and two different numbers representing the blanks in the first row. The output will be a series of decimal digits.
Numbers should be encrypted by inserting the escape character before each digit, then including the digit unencrypted. This should be reversed for decryption.
| #AutoHotkey | AutoHotkey | board := "
(
ET AON RIS
BCDFGHJKLM
PQ/UVWXYZ.
)"
Text = One night-it was on the twentieth of March, 1888-I was returning
StringUpper, Text, Text
Text := RegExReplace(text, "[^A-Z0-9]")
Num2 := InStr(board, A_Space) -1
Num3 := InStr(board, A_Space, true, Num1+1) -1
Loop Parse, Text
{
char := A_LoopField
Loop Parse, board, `n
{
If (Pos := InStr(A_LoopField, char))
out .= Num%A_Index% . Pos-1
else if (Pos := InStr(A_LoopField, "/")) && InStr("0123456789", char)
out .= Num%A_Index% . Pos-1 . char
}
}
MsgBox % out
i := 0
While (LoopField := SubStr(out, ++i, 1)) <> ""
{
If (LoopField = num2) or (LoopField = num3)
col := SubStr(out, ++i, 1)
else col := 0
Loop Parse, board, `n
{
If !col && A_Index = 1
dec .= SubStr(A_LoopField, LoopField+1, 1)
Else If (Num%A_Index% = LoopField) && col
dec .= SubStr(A_LoopField, col+1, 1)
If SubStr(dec, 0) = "/"
dec := SubStr(dec, 1, StrLen(dec)-1) . SubStr(out, ++i, 1)
}
}
MsgBox % dec |
http://rosettacode.org/wiki/Stirling_numbers_of_the_first_kind | Stirling numbers of the first kind | Stirling numbers of the first kind, or Stirling cycle numbers, count permutations according to their number
of cycles (counting fixed points as cycles of length one).
They may be defined directly to be the number of permutations of n
elements with k disjoint cycles.
Stirling numbers of the first kind express coefficients of polynomial expansions of falling or rising factorials.
Depending on the application, Stirling numbers of the first kind may be "signed"
or "unsigned". Signed Stirling numbers of the first kind arise when the
polynomial expansion is expressed in terms of falling factorials; unsigned when
expressed in terms of rising factorials. The only substantial difference is that,
for signed Stirling numbers of the first kind, values of S1(n, k) are negative
when n + k is odd.
Stirling numbers of the first kind follow the simple identities:
S1(0, 0) = 1
S1(n, 0) = 0 if n > 0
S1(n, k) = 0 if k > n
S1(n, k) = S1(n - 1, k - 1) + (n - 1) * S1(n - 1, k) # For unsigned
or
S1(n, k) = S1(n - 1, k - 1) - (n - 1) * S1(n - 1, k) # For signed
Task
Write a routine (function, procedure, whatever) to find Stirling numbers of the first kind. There are several methods to generate Stirling numbers of the first kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.
Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the first kind, S1(n, k), up to S1(12, 12). it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S1(n, k) == 0 (when k > n). You may choose to show signed or unsigned Stirling numbers of the first kind, just make a note of which was chosen.
If your language supports large integers, find and show here, on this page, the maximum value of S1(n, k) where n == 100.
See also
Wikipedia - Stirling numbers of the first kind
OEIS:A008275 - Signed Stirling numbers of the first kind
OEIS:A130534 - Unsigned Stirling numbers of the first kind
Related Tasks
Stirling numbers of the second kind
Lah numbers
| #11l | 11l | [(Int, Int) = BigInt] computed
F sterling1(n, k)
V key = (n, k)
I key C :computed
R :computed[key]
I n == k == 0
R BigInt(1)
I n > 0 & k == 0
R BigInt(0)
I k > n
R BigInt(0)
V result = sterling1(n - 1, k - 1) + (n - 1) * sterling1(n - 1, k)
:computed[key] = result
R result
print(‘Unsigned Stirling numbers of the first kind:’)
V MAX = 12
print(‘n/k’.ljust(10), end' ‘’)
L(n) 0 .. MAX
print(String(n).rjust(10), end' ‘’)
print()
L(n) 0 .. MAX
print(String(n).ljust(10), end' ‘’)
L(k) 0 .. n
print(String(sterling1(n, k)).rjust(10), end' ‘’)
print()
print(‘The maximum value of S1(100, k) = ’)
BigInt previous = 0
L(k) 1 .. 100
V current = sterling1(100, k)
I current > previous
previous = current
E
print("#.\n(#. digits, k = #.)\n".format(previous, String(previous).len, k - 1))
L.break |
http://rosettacode.org/wiki/String_append | String append |
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
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #C | C | #include<stdio.h>
#include<string.h>
int main()
{
char str[24]="Good Morning";
char *cstr=" to all";
char *cstr2=" !!!";
int x=0;
//failure when space allocated to str is insufficient.
if(sizeof(str)>strlen(str)+strlen(cstr)+strlen(cstr2))
{
/* 1st method*/
strcat(str,cstr);
/*2nd method*/
x=strlen(str);
sprintf(&str[x],"%s",cstr2);
printf("%s\n",str);
}
return 0;
} |
http://rosettacode.org/wiki/Stirling_numbers_of_the_second_kind | Stirling numbers of the second kind | Stirling numbers of the second kind, or Stirling partition numbers, are the
number of ways to partition a set of n objects into k non-empty subsets. They are
closely related to Bell numbers, and may be derived from them.
Stirling numbers of the second kind obey the recurrence relation:
S2(n, 0) and S2(0, k) = 0 # for n, k > 0
S2(n, n) = 1
S2(n + 1, k) = k * S2(n, k) + S2(n, k - 1)
Task
Write a routine (function, procedure, whatever) to find Stirling numbers of the second kind. There are several methods to generate Stirling numbers of the second kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.
Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the second kind, S2(n, k), up to S2(12, 12). it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S2(n, k) == 0 (when k > n).
If your language supports large integers, find and show here, on this page, the maximum value of S2(n, k) where n == 100.
See also
Wikipedia - Stirling numbers of the second kind
OEIS:A008277 - Stirling numbers of the second kind
Related Tasks
Stirling numbers of the first kind
Bell numbers
Lah numbers
| #Ruby | Ruby | @memo = {}
def sterling2(n, k)
key = [n,k]
return @memo[key] if @memo.key?(key)
return 1 if n.zero? and k.zero?
return 0 if n.zero? or k.zero?
return 1 if n == k
return 0 if k > n
res = k * sterling2(n-1, k) + sterling2(n - 1, k-1)
@memo[key] = res
end
r = (0..12)
puts "Sterling2 numbers:"
puts "n/k #{r.map{|n| "%11d" % n}.join}"
r.each do |row|
print "%-4s" % row
puts "#{(0..row).map{|col| "%11d" % sterling2(row, col)}.join}"
end
puts "\nMaximum value from the sterling2(100, k)";
puts (1..100).map{|a| sterling2(100,a)}.max
|
http://rosettacode.org/wiki/Straddling_checkerboard | Straddling checkerboard | Task
Implement functions to encrypt and decrypt a message using the straddling checkerboard method. The checkerboard should take a 28 character alphabet (A-Z plus a full stop and an escape character) and two different numbers representing the blanks in the first row. The output will be a series of decimal digits.
Numbers should be encrypted by inserting the escape character before each digit, then including the digit unencrypted. This should be reversed for decryption.
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <ctype.h>
#include <glib.h>
#define ROWS 4
#define COLS 10
#define NPRX "/"
/* wikipedia table
const char *table[ROWS][COLS] =
{
{ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" },
{ "E", "T", NULL, "A", "O", "N", NULL, "R", "I", "S },
{ "B", "C", "D", "F", "G", "H", "J", "K", "L", "M" },
{ "P", "Q", NPRX, "U", "V", "W", "X", "Y", "Z", "." }
};
*/
/* example of extending the table, COLS must be 11
const char *table[ROWS][COLS] =
{
{ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ":" },
{ "H", "O", "L", NULL, "M", "E", "S", NULL, "R", "T", "," },
{ "A", "B", "C", "D", "F", "G", "I", "J", "K", "N", "-" },
{ "P", "Q", "U", "V", "W", "X", "Y", "Z", ".", NPRX, "?" }
};
*/
// task table
const char *table[ROWS][COLS] =
{
{ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" },
{ "H", "O", "L", NULL, "M", "E", "S", NULL, "R", "T" },
{ "A", "B", "C", "D", "F", "G", "I", "J", "K", "N" },
{ "P", "Q", "U", "V", "W", "X", "Y", "Z", ".", NPRX }
};
GHashTable *create_table_from_array(const char *table[ROWS][COLS], bool is_encoding)
{
char buf[16];
GHashTable *r = g_hash_table_new_full(g_str_hash, g_str_equal, free, free);
size_t i, j, k, m;
for(i = 0, m = 0; i < COLS; i++)
{
if (table[1][i] == NULL) m++;
}
const size_t SELNUM = m;
size_t selectors[SELNUM];
size_t numprefix_row, numprefix_col;
bool has_numprefix = false;
// selectors keep the indexes of the symbols to select 2nd and 3rd real row;
// nulls must be placed into the 2nd row of the table
for(i = 0, k = 0; i < COLS && k < SELNUM; i++)
{
if ( table[1][i] == NULL )
{
selectors[k] = i;
k++;
}
}
// numprefix is the prefix to insert symbols from the 1st row of table (numbers)
for(j = 1; j < ROWS; j++)
{
for(i = 0; i < COLS; i++)
{
if (table[j][i] == NULL) continue;
if ( strcmp(table[j][i], NPRX) == 0 )
{
numprefix_col = i;
numprefix_row = j;
has_numprefix = true;
break;
}
}
}
// create the map for each symbol
for(i = has_numprefix ? 0 : 1; i < ROWS; i++)
{
for(j = 0; j < COLS; j++)
{
if (table[i][j] == NULL) continue;
if (strlen(table[i][j]) > 1)
{
fprintf(stderr, "symbols must be 1 byte long\n");
continue; // we continue just ignoring the issue
}
if (has_numprefix && i == (ROWS-1) && j == numprefix_col && i == numprefix_row) continue;
if (has_numprefix && i == 0)
{
snprintf(buf, sizeof(buf), "%s%s%s", table[0][selectors[SELNUM-1]], table[0][numprefix_col], table[0][j]);
}
else if (i == 1)
{
snprintf(buf, sizeof(buf), "%s", table[0][j]);
}
else
{
snprintf(buf, sizeof(buf), "%s%s", table[0][selectors[i-2]], table[0][j]);
}
if (is_encoding) g_hash_table_insert(r, strdup(table[i][j]), strdup(buf));
else g_hash_table_insert(r, strdup(buf), strdup(table[i][j]));
}
}
if (is_encoding) g_hash_table_insert(r, strdup("mode"), strdup("encode"));
else g_hash_table_insert(r, strdup("mode"), strdup("decode"));
return r;
}
char *decode(GHashTable *et, const char *enctext)
{
char *r = NULL;
if (et == NULL || enctext == NULL || strlen(enctext) == 0 ||
g_hash_table_lookup(et, "mode") == NULL ||
strcmp(g_hash_table_lookup(et, "mode"), "decode") != 0) return NULL;
GString *res = g_string_new(NULL);
GString *en = g_string_new(NULL);
for( ; *enctext != '\0'; enctext++ )
{
if (en->len < 3)
{
g_string_append_c(en, *enctext);
r = g_hash_table_lookup(et, en->str);
if (r == NULL) continue;
g_string_append(res, r);
g_string_truncate(en, 0);
}
else
{
fprintf(stderr, "decoding error\n");
break;
}
}
r = res->str;
g_string_free(res, FALSE);
g_string_free(en, TRUE);
return r;
}
char *encode(GHashTable *et, const char *plaintext, int (*trasf)(int), bool compress_spaces)
{
GString *s;
char *r = NULL;
char buf[2] = { 0 };
if (plaintext == NULL ||
et == NULL || g_hash_table_lookup(et, "mode") == NULL ||
strcmp(g_hash_table_lookup(et, "mode"), "encode") != 0) return NULL;
s = g_string_new(NULL);
for(buf[0] = trasf ? trasf(*plaintext) : *plaintext;
buf[0] != '\0';
buf[0] = trasf ? trasf(*++plaintext) : *++plaintext)
{
if ( (r = g_hash_table_lookup(et, buf)) != NULL )
{
g_string_append(s, r);
}
else if (isspace(buf[0]))
{
if (!compress_spaces) g_string_append(s, buf);
}
else
{
fprintf(stderr, "char '%s' is not encodable%s\n",
isprint(buf[0]) ? buf : "?",
!compress_spaces ? ", replacing with a space" : "");
if (!compress_spaces) g_string_append_c(s, ' ');
}
}
r = s->str;
g_string_free(s, FALSE);
return r;
}
int main()
{
GHashTable *enctab = create_table_from_array(table, true); // is encoding? true
GHashTable *dectab = create_table_from_array(table, false); // is encoding? false (decoding)
const char *text = "One night-it was on the twentieth of March, 1888-I was returning";
char *encoded = encode(enctab, text, toupper, true);
printf("%s\n", encoded);
char *decoded = decode(dectab, encoded);
printf("%s\n", decoded);
free(decoded);
free(encoded);
g_hash_table_destroy(enctab);
g_hash_table_destroy(dectab);
return 0;
} |
http://rosettacode.org/wiki/Stirling_numbers_of_the_first_kind | Stirling numbers of the first kind | Stirling numbers of the first kind, or Stirling cycle numbers, count permutations according to their number
of cycles (counting fixed points as cycles of length one).
They may be defined directly to be the number of permutations of n
elements with k disjoint cycles.
Stirling numbers of the first kind express coefficients of polynomial expansions of falling or rising factorials.
Depending on the application, Stirling numbers of the first kind may be "signed"
or "unsigned". Signed Stirling numbers of the first kind arise when the
polynomial expansion is expressed in terms of falling factorials; unsigned when
expressed in terms of rising factorials. The only substantial difference is that,
for signed Stirling numbers of the first kind, values of S1(n, k) are negative
when n + k is odd.
Stirling numbers of the first kind follow the simple identities:
S1(0, 0) = 1
S1(n, 0) = 0 if n > 0
S1(n, k) = 0 if k > n
S1(n, k) = S1(n - 1, k - 1) + (n - 1) * S1(n - 1, k) # For unsigned
or
S1(n, k) = S1(n - 1, k - 1) - (n - 1) * S1(n - 1, k) # For signed
Task
Write a routine (function, procedure, whatever) to find Stirling numbers of the first kind. There are several methods to generate Stirling numbers of the first kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.
Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the first kind, S1(n, k), up to S1(12, 12). it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S1(n, k) == 0 (when k > n). You may choose to show signed or unsigned Stirling numbers of the first kind, just make a note of which was chosen.
If your language supports large integers, find and show here, on this page, the maximum value of S1(n, k) where n == 100.
See also
Wikipedia - Stirling numbers of the first kind
OEIS:A008275 - Signed Stirling numbers of the first kind
OEIS:A130534 - Unsigned Stirling numbers of the first kind
Related Tasks
Stirling numbers of the second kind
Lah numbers
| #ALGOL_68 | ALGOL 68 | BEGIN
# show some (unsigned) Stirling numbers of the first kind #
# specify the precision of LONG LONG INT, we need about 160 digits #
# for Stirling numbers of the first kind with n, k = 100 #
PR precision 160 PR
MODE SINT = LONG LONG INT;
# returns a triangular matrix of Stirling numbers up to max n, max n #
# the numbers are signed if signed is TRUE, unsigned otherwise #
PROC make s1 = ( INT max n, BOOL signed )REF[,]SINT:
BEGIN
REF[,]SINT s1 := HEAP[ 0 : max n, 0 : max n ]SINT;
FOR n FROM 0 TO max n DO FOR k FROM 0 TO max n DO s1[ n, k ] := 0 OD OD;
s1[ 0, 0 ] := 1;
FOR n FROM 1 TO max n DO s1[ n, 0 ] := 0 OD;
FOR n FROM 1 TO max n DO
FOR k FROM 1 TO n DO
SINT s1 term = ( ( n - 1 ) * s1[ n - 1, k ] );
s1[ n, k ] := s1[ n - 1, k - 1 ] + IF signed THEN - s1 term ELSE s1 term FI
OD
OD;
s1
END # make s1 # ;
# task requirements: #
# print Stirling numbers up to n, k = 12 #
BEGIN
INT max stirling = 12;
REF[,]SINT s1 = make s1( max stirling, FALSE );
print( ( "Unsigned Stirling numbers of the first kind:", newline ) );
print( ( " k" ) );
FOR k FROM 0 TO max stirling DO print( ( whole( k, -10 ) ) ) OD;
print( ( newline, " n", newline ) );
FOR n FROM 0 TO max stirling DO
print( ( whole( n, -2 ) ) );
FOR k FROM 0 TO n DO
print( ( whole( s1[ n, k ], -10 ) ) )
OD;
print( ( newline ) )
OD
END;
# find the maximum Stirling number with n = 100 #
BEGIN
INT max stirling = 100;
REF[,]SINT s1 = make s1( max stirling, FALSE );
SINT max 100 := 0;
FOR k FROM 0 TO max stirling DO
IF s1[ max stirling, k ] > max 100 THEN max 100 := s1[ max stirling, k ] FI
OD;
print( ( "Maximum Stirling number of the first kind with n = 100:", newline ) );
print( ( whole( max 100, 0 ), newline ) )
END
END |
http://rosettacode.org/wiki/String_append | String append |
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
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #C.23 | C# | class Program
{
static void Main(string[] args)
{
string x = "foo";
x += "bar";
System.Console.WriteLine(x);
}
} |
http://rosettacode.org/wiki/String_append | String append |
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
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #C.2B.2B | C++ | #include <iostream>
#include <string>
int main( ) {
std::string greeting( "Hello" ) ;
greeting.append( " , world!" ) ;
std::cout << greeting << std::endl ;
return 0 ;
} |
http://rosettacode.org/wiki/Stream_merge | Stream merge | 2-stream merge
Read two sorted streams of items from external source (e.g. disk, or network), and write one stream of sorted items to external sink.
Common algorithm: keep 1 buffered item from each source, select minimal of them, write it, fetch another item from that stream from which the written item was.
N-stream merge
The same as above, but reading from N sources.
Common algorithm: same as above, but keep buffered items and their source descriptors in a heap.
Assume streams are very big. You must not suck them whole in the memory, but read them as streams.
| #360_Assembly | 360 Assembly | * Stream Merge 07/02/2017
STRMERGE CSECT
USING STRMERGE,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) prolog
ST R13,4(R15) " <-
ST R15,8(R13) " ->
LR R13,R15 " addressability
OPEN (OUTDCB,OUTPUT) open the output file
LA R6,1 n=1
LA R9,FILE file(n)
LOOPN C R6,=A(NN) do n=1 to nn
BH ELOOPN
L R2,0(R9) @DCB
OPEN ((R2),INPUT) open input file # n
LR R1,R6 n
BAL R14,READ call read(n)
LA R6,1(R6) n=n+1
LA R9,4(R9) file(n++)
B LOOPN end do n
ELOOPN BCTR R6,0 n=n-1
LOOP SR R8,R8 lowest=0
LA R7,1 k=1
LOOPK CR R7,R6 do k=1 to n
BH ELOOPK
LA R2,RECDEF-1(R7) @recdef(k)
CLI 0(R2),X'00' if not recdef(k)
BNE ERECDEF
LR R1,R7 k
BAL R14,READ call read(k)
ERECDEF LR R1,R7 k
LA R2,EOF-1(R1) @eof(k)
CLI 0(R2),X'00' if not eof(k)
BNE EEOF
LTR R8,R8 if lowest<>0
BZ LOWEST0
LR R1,R7 k
SLA R1,6
LA R2,REC-64(R1) @rec(k)
CLC 0(64,R2),PG if rec(k)<y
BNL RECLTY
B LOWEST0 optimization
RECLTY B EEOF
LOWEST0 LR R1,R7 k
SLA R1,6
LA R2,REC-64(R1) @rec(k)
MVC PG,0(R2) y=rec(k)
LR R8,R7 lowest=k
EEOF LA R7,1(R7) k=k+1
B LOOPK end do k
ELOOPK LTR R8,R8 if lowest=0
BZ EXIT goto exit
BAL R14,WRITE call write
LR R1,R8 lowest
BAL R14,READ call read(lowest)
B LOOP
EXIT LA R7,1 k=1
LA R9,FILE file(n)
LOOPKC CR R7,R6 do k=1 to n
BH ELOOPKC
L R2,0(R9) @DCB
CLOSE ((R2)) close input file # k
LA R7,1(R7) k=k+1
LA R9,4(R9) file(n++)
B LOOPKC end do k
ELOOPKC CLOSE (OUTDCB) close output
L R13,4(0,R13) epilog
LM R14,R12,12(R13) " restore
XR R15,R15 " rc=0
BR R14 exit
*------- ---- ----------------------------------------
READ LR R4,R1 z
LA R2,RECDEF-1(R1) @recdef(z)
MVI 0(R2),X'00' recdef(z)=false
LA R2,EOF-1(R1) @eof(z)
CLI 0(R2),X'00' if not eof(z)
BNE EOFZ
LR R1,R4 z
SLA R1,6
LA R3,REC-64(R1) @rec(z)
LR R5,R4 z
SLA R5,2
LA R9,FILE-4(R5) @file(z)
L R5,0(R9) @DCB
GET (R5),(R3) read record
LA R2,RECDEF-1(R4) @recdef(z)
MVI 0(R2),X'01' recdef(z)=true
EOFZ BR R14 return
INEOF LA R2,EOF-1(R4) @eof(z)
MVI 0(R2),X'01' eof(z)=true
B EOFZ
*------- ---- ----------------------------------------
WRITE LR R1,R8 lowest
SLA R1,6
LA R2,REC-64(R1) @rec(lowest)
PUT OUTDCB,(R2) write record
BR R14 return
* ---- ----------------------------------------
IN1DCB DCB DSORG=PS,MACRF=PM,DDNAME=IN1DD,LRECL=64, *
RECFM=FT,EODAD=INEOF
IN2DCB DCB DSORG=PS,MACRF=PM,DDNAME=IN2DD,LRECL=64, *
RECFM=FT,EODAD=INEOF
IN3DCB DCB DSORG=PS,MACRF=PM,DDNAME=IN3DD,LRECL=64, *
RECFM=FT,EODAD=INEOF
IN4DCB DCB DSORG=PS,MACRF=PM,DDNAME=IN4DD,LRECL=64, *
RECFM=FT,EODAD=INEOF
OUTDCB DCB DSORG=PS,MACRF=PM,DDNAME=OUTDD,LRECL=64, *
RECFM=FT
FILE DC A(IN1DCB,IN2DCB,IN3DCB,IN4DCB)
NN EQU (*-FILE)/4
EOF DC (NN)X'00'
RECDEF DC (NN)X'00'
REC DS (NN)CL64
PG DS CL64
YREGS
END STRMERGE |
http://rosettacode.org/wiki/Stirling_numbers_of_the_second_kind | Stirling numbers of the second kind | Stirling numbers of the second kind, or Stirling partition numbers, are the
number of ways to partition a set of n objects into k non-empty subsets. They are
closely related to Bell numbers, and may be derived from them.
Stirling numbers of the second kind obey the recurrence relation:
S2(n, 0) and S2(0, k) = 0 # for n, k > 0
S2(n, n) = 1
S2(n + 1, k) = k * S2(n, k) + S2(n, k - 1)
Task
Write a routine (function, procedure, whatever) to find Stirling numbers of the second kind. There are several methods to generate Stirling numbers of the second kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.
Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the second kind, S2(n, k), up to S2(12, 12). it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S2(n, k) == 0 (when k > n).
If your language supports large integers, find and show here, on this page, the maximum value of S2(n, k) where n == 100.
See also
Wikipedia - Stirling numbers of the second kind
OEIS:A008277 - Stirling numbers of the second kind
Related Tasks
Stirling numbers of the first kind
Bell numbers
Lah numbers
| #Sidef | Sidef | func S2(n, k) { # Stirling numbers of the second kind
stirling2(n, k)
}
const r = (0..12)
var triangle = r.map {|n| 0..n -> map {|k| S2(n, k) } }
var widths = r.map {|n| r.map {|k| (triangle[k][n] \\ 0).len }.max }
say ('n\k ', r.map {|n| "%*s" % (widths[n], n) }.join(' '))
r.each {|n|
var str = ('%-3s ' % n)
str += triangle[n].map_kv {|k,v| "%*s" % (widths[k], v) }.join(' ')
say str
}
with (100) {|n|
say "\nMaximum value from the S2(#{n}, *) row:"
say { S2(n, _) }.map(^n).max
} |
http://rosettacode.org/wiki/Straddling_checkerboard | Straddling checkerboard | Task
Implement functions to encrypt and decrypt a message using the straddling checkerboard method. The checkerboard should take a 28 character alphabet (A-Z plus a full stop and an escape character) and two different numbers representing the blanks in the first row. The output will be a series of decimal digits.
Numbers should be encrypted by inserting the escape character before each digit, then including the digit unencrypted. This should be reversed for decryption.
| #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace StraddlingCheckerboard
{
class Program
{
public readonly static IReadOnlyDictionary<char, string> val2Key;
public readonly static IReadOnlyDictionary<string, char> key2Val;
static Program()
{
val2Key = new Dictionary<char, string> {
{'A',"30"}, {'B',"31"}, {'C',"32"}, {'D',"33"}, {'E',"5"}, {'F',"34"}, {'G',"35"},
{'H',"0"}, {'I',"36"}, {'J',"37"}, {'K',"38"}, {'L',"2"}, {'M',"4"}, {'.',"78"},
{'N',"39"}, {'/',"79"}, {'O',"1"}, {'0',"790"}, {'P',"70"}, {'1',"791"}, {'Q',"71"},
{'2',"792"}, {'R',"8"}, {'3',"793"}, {'S',"6"}, {'4',"794"}, {'T',"9"}, {'5',"795"},
{'U',"72"}, {'6',"796"},{'V',"73"}, {'7',"797"}, {'W',"74"}, {'8',"798"}, {'X',"75"},
{'9',"799"}, {'Y',"76"}, {'Z',"77"}};
key2Val = val2Key.ToDictionary(kv => kv.Value, kv => kv.Key);
}
public static string Encode(string s)
{
return string.Concat(s.ToUpper().ToCharArray()
.Where(c => val2Key.ContainsKey(c)).Select(c => val2Key[c]));
}
public static string Decode(string s)
{
return string.Concat(Regex.Matches(s, "79.|7.|3.|.").Cast<Match>()
.Where(m => key2Val.ContainsKey(m.Value)).Select(m => key2Val[m.Value]));
}
static void Main(string[] args)
{
var enc = Encode("One night-it was on the twentieth of March, 1888-I was returning");
Console.WriteLine(enc);
Console.WriteLine(Decode(enc));
Console.ReadLine();
}
}
} |
http://rosettacode.org/wiki/Stirling_numbers_of_the_first_kind | Stirling numbers of the first kind | Stirling numbers of the first kind, or Stirling cycle numbers, count permutations according to their number
of cycles (counting fixed points as cycles of length one).
They may be defined directly to be the number of permutations of n
elements with k disjoint cycles.
Stirling numbers of the first kind express coefficients of polynomial expansions of falling or rising factorials.
Depending on the application, Stirling numbers of the first kind may be "signed"
or "unsigned". Signed Stirling numbers of the first kind arise when the
polynomial expansion is expressed in terms of falling factorials; unsigned when
expressed in terms of rising factorials. The only substantial difference is that,
for signed Stirling numbers of the first kind, values of S1(n, k) are negative
when n + k is odd.
Stirling numbers of the first kind follow the simple identities:
S1(0, 0) = 1
S1(n, 0) = 0 if n > 0
S1(n, k) = 0 if k > n
S1(n, k) = S1(n - 1, k - 1) + (n - 1) * S1(n - 1, k) # For unsigned
or
S1(n, k) = S1(n - 1, k - 1) - (n - 1) * S1(n - 1, k) # For signed
Task
Write a routine (function, procedure, whatever) to find Stirling numbers of the first kind. There are several methods to generate Stirling numbers of the first kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.
Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the first kind, S1(n, k), up to S1(12, 12). it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S1(n, k) == 0 (when k > n). You may choose to show signed or unsigned Stirling numbers of the first kind, just make a note of which was chosen.
If your language supports large integers, find and show here, on this page, the maximum value of S1(n, k) where n == 100.
See also
Wikipedia - Stirling numbers of the first kind
OEIS:A008275 - Signed Stirling numbers of the first kind
OEIS:A130534 - Unsigned Stirling numbers of the first kind
Related Tasks
Stirling numbers of the second kind
Lah numbers
| #ALGOL_W | ALGOL W | begin % show some (unsigned) Stirling numbers of the first kind %
integer MAX_STIRLING;
MAX_STIRLING := 12;
begin
% construct a matrix of Stirling numbers up to max n, max n %
integer array s1 ( 0 :: MAX_STIRLING, 0 :: MAX_STIRLING );
for n := 0 until MAX_STIRLING do begin
for k := 0 until MAX_STIRLING do s1( n, k ) := 0
end for_n ;
s1( 0, 0 ) := 1;
for n := 1 until MAX_STIRLING do s1( n, 0 ) := 0;
for n := 1 until MAX_STIRLING do begin
for k := 1 until n do begin
integer s1Term;
s1Term := ( ( n - 1 ) * s1( n - 1, k ) );
s1( n, k ) := s1( n - 1, k - 1 ) + s1Term
end for_k
end for_n ;
% print the Stirling numbers up to n, k = 12 %
write( "Unsigned Stirling numbers of the first kind:" );
write( " k" );
for k := 0 until MAX_STIRLING do writeon( i_w := 10, s_w := 0, k );
write( " n" );
for n := 0 until MAX_STIRLING do begin
write( i_w := 2, s_w := 0, n );
for k := 0 until n do begin
writeon( i_w := 10, s_w := 0, s1( n, k ) )
end for_k
end for_n
end
end. |
http://rosettacode.org/wiki/Stirling_numbers_of_the_first_kind | Stirling numbers of the first kind | Stirling numbers of the first kind, or Stirling cycle numbers, count permutations according to their number
of cycles (counting fixed points as cycles of length one).
They may be defined directly to be the number of permutations of n
elements with k disjoint cycles.
Stirling numbers of the first kind express coefficients of polynomial expansions of falling or rising factorials.
Depending on the application, Stirling numbers of the first kind may be "signed"
or "unsigned". Signed Stirling numbers of the first kind arise when the
polynomial expansion is expressed in terms of falling factorials; unsigned when
expressed in terms of rising factorials. The only substantial difference is that,
for signed Stirling numbers of the first kind, values of S1(n, k) are negative
when n + k is odd.
Stirling numbers of the first kind follow the simple identities:
S1(0, 0) = 1
S1(n, 0) = 0 if n > 0
S1(n, k) = 0 if k > n
S1(n, k) = S1(n - 1, k - 1) + (n - 1) * S1(n - 1, k) # For unsigned
or
S1(n, k) = S1(n - 1, k - 1) - (n - 1) * S1(n - 1, k) # For signed
Task
Write a routine (function, procedure, whatever) to find Stirling numbers of the first kind. There are several methods to generate Stirling numbers of the first kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.
Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the first kind, S1(n, k), up to S1(12, 12). it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S1(n, k) == 0 (when k > n). You may choose to show signed or unsigned Stirling numbers of the first kind, just make a note of which was chosen.
If your language supports large integers, find and show here, on this page, the maximum value of S1(n, k) where n == 100.
See also
Wikipedia - Stirling numbers of the first kind
OEIS:A008275 - Signed Stirling numbers of the first kind
OEIS:A130534 - Unsigned Stirling numbers of the first kind
Related Tasks
Stirling numbers of the second kind
Lah numbers
| #C | C | #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct stirling_cache_tag {
int max;
int* values;
} stirling_cache;
int stirling_number1(stirling_cache* sc, int n, int k) {
if (k == 0)
return n == 0 ? 1 : 0;
if (n > sc->max || k > n)
return 0;
return sc->values[n*(n-1)/2 + k - 1];
}
bool stirling_cache_create(stirling_cache* sc, int max) {
int* values = calloc(max * (max + 1)/2, sizeof(int));
if (values == NULL)
return false;
sc->max = max;
sc->values = values;
for (int n = 1; n <= max; ++n) {
for (int k = 1; k <= n; ++k) {
int s1 = stirling_number1(sc, n - 1, k - 1);
int s2 = stirling_number1(sc, n - 1, k);
values[n*(n-1)/2 + k - 1] = s1 + s2 * (n - 1);
}
}
return true;
}
void stirling_cache_destroy(stirling_cache* sc) {
free(sc->values);
sc->values = NULL;
}
void print_stirling_numbers(stirling_cache* sc, int max) {
printf("Unsigned Stirling numbers of the first kind:\nn/k");
for (int k = 0; k <= max; ++k)
printf(k == 0 ? "%2d" : "%10d", k);
printf("\n");
for (int n = 0; n <= max; ++n) {
printf("%2d ", n);
for (int k = 0; k <= n; ++k)
printf(k == 0 ? "%2d" : "%10d", stirling_number1(sc, n, k));
printf("\n");
}
}
int main() {
stirling_cache sc = { 0 };
const int max = 12;
if (!stirling_cache_create(&sc, max)) {
fprintf(stderr, "Out of memory\n");
return 1;
}
print_stirling_numbers(&sc, max);
stirling_cache_destroy(&sc);
return 0;
} |
http://rosettacode.org/wiki/String_append | String append |
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
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #Clojure | Clojure | user=> (def s "app")
#'user/s
user=> s
"app"
user=> (def s (str s "end"))
#'user/s
user=> s
"append" |
http://rosettacode.org/wiki/String_append | String append |
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
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #COBOL | COBOL | identification division.
program-id. string-append.
data division.
working-storage section.
01 some-string.
05 elements pic x occurs 0 to 80 times depending on limiter.
01 limiter usage index value 7.
01 current usage index.
procedure division.
append-main.
move "Hello, " to some-string
*> extend the limit and move using reference modification
set current to length of some-string
set limiter up by 5
move "world" to some-string(current + 1:)
display some-string
goback.
end program string-append.
|
http://rosettacode.org/wiki/Stream_merge | Stream merge | 2-stream merge
Read two sorted streams of items from external source (e.g. disk, or network), and write one stream of sorted items to external sink.
Common algorithm: keep 1 buffered item from each source, select minimal of them, write it, fetch another item from that stream from which the written item was.
N-stream merge
The same as above, but reading from N sources.
Common algorithm: same as above, but keep buffered items and their source descriptors in a heap.
Assume streams are very big. You must not suck them whole in the memory, but read them as streams.
| #Ada | Ada | with Ada.Text_Io;
with Ada.Command_Line;
with Ada.Containers.Indefinite_Holders;
procedure Stream_Merge is
package String_Holders
is new Ada.Containers.Indefinite_Holders (String);
use Ada.Text_Io, String_Holders;
type Stream_Type is
record
File : File_Type;
Value : Holder;
end record;
subtype Index_Type is Positive range 1 .. Ada.Command_Line.Argument_Count;
Streams : array (Index_Type) of Stream_Type;
procedure Fetch (Stream : in out Stream_Type) is
begin
Stream.Value := (if End_Of_File (Stream.File)
then Empty_Holder
else To_Holder (Get_Line (Stream.File)));
end Fetch;
function Next_Stream return Index_Type is
Index : Index_Type := Index_Type'First;
Value : Holder;
begin
for I in Streams'Range loop
if Value.Is_Empty and not Streams (I).Value.Is_Empty then
Value := Streams (I).Value;
Index := I;
elsif not Streams (I).Value.Is_Empty and then Streams (I).Value.Element < Value.Element then
Value := Streams (I).Value;
Index := I;
end if;
end loop;
if Value.Is_Empty then
raise Program_Error;
end if;
return Index;
end Next_Stream;
function More_Data return Boolean
is (for some Stream of Streams => not Stream.Value.Is_Empty);
begin
if Ada.Command_Line.Argument_Count = 0 then
Put_Line ("Usage: prog <file1> <file2> ...");
Put_Line ("Merge the sorted files file1, file2...");
return;
end if;
for I in Streams'Range loop
Open (Streams (I).File, In_File, Ada.Command_Line.Argument (I));
Fetch (Streams (I));
end loop;
while More_Data loop
declare
Stream : Stream_Type renames Streams (Next_Stream);
begin
Put_Line (Stream.Value.Element);
Fetch (Stream);
end;
end loop;
end Stream_Merge; |
http://rosettacode.org/wiki/Stirling_numbers_of_the_second_kind | Stirling numbers of the second kind | Stirling numbers of the second kind, or Stirling partition numbers, are the
number of ways to partition a set of n objects into k non-empty subsets. They are
closely related to Bell numbers, and may be derived from them.
Stirling numbers of the second kind obey the recurrence relation:
S2(n, 0) and S2(0, k) = 0 # for n, k > 0
S2(n, n) = 1
S2(n + 1, k) = k * S2(n, k) + S2(n, k - 1)
Task
Write a routine (function, procedure, whatever) to find Stirling numbers of the second kind. There are several methods to generate Stirling numbers of the second kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.
Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the second kind, S2(n, k), up to S2(12, 12). it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S2(n, k) == 0 (when k > n).
If your language supports large integers, find and show here, on this page, the maximum value of S2(n, k) where n == 100.
See also
Wikipedia - Stirling numbers of the second kind
OEIS:A008277 - Stirling numbers of the second kind
Related Tasks
Stirling numbers of the first kind
Bell numbers
Lah numbers
| #Tcl | Tcl | proc S2 {n k} {
set nk [list $n $k]
if {[info exists ::S2cache($nk)]} {
return $::S2cache($nk)
}
if {($n > 0 && $k == 0) || ($n == 0 && $k > 0)} {
return 0
}
if {$n == $k} {
return 1
}
if {$n < $k} {
return 0
}
set n1 [expr {$n - 1}]
set k1 [expr {$k - 1}]
set r [expr {($k * [S2 $n1 $k]) + [S2 $n1 $k1]}]
set ::S2cache($nk) $r
}
proc main {} {
puts "Stirling numbers of the second kind:"
set max 12 ;# last table line to print
set L 8 ;# space to use for 1 number
puts -nonewline "n\\k"
for {set n 0} {$n <= $max} {incr n} {
puts -nonewline [format %${L}d $n]
}
puts ""
for {set n 0} {$n <= $max} {incr n} {
puts -nonewline [format %-3d $n]
for {set k 0} {$k <= $n} {incr k} {
puts -nonewline [format %${L}s [S2 $n $k]]
}
puts ""
}
puts "The maximum value of S2(100, k) = "
set previous 0
for {set k 1} {$k <= 100} {incr k} {
set current [S2 100 $k]
if {$current > $previous} {
set previous $current
} else {
puts $previous
puts "([string length $previous] digits, k = [expr {$k-1}])"
break
}
}
}
main |
http://rosettacode.org/wiki/Straddling_checkerboard | Straddling checkerboard | Task
Implement functions to encrypt and decrypt a message using the straddling checkerboard method. The checkerboard should take a 28 character alphabet (A-Z plus a full stop and an escape character) and two different numbers representing the blanks in the first row. The output will be a series of decimal digits.
Numbers should be encrypted by inserting the escape character before each digit, then including the digit unencrypted. This should be reversed for decryption.
| #C.2B.2B | C++ | #include <iostream>
#include <string>
#include <map>
#include <algorithm> // for min, max
using namespace std;
class StraddlingCheckerboard
{
map<char, string> table;
char first[10], second[10], third[10];
int rowU, rowV;
public:
StraddlingCheckerboard(const string &alphabet, int u, int v)
{
rowU = min(u, v);
rowV = max(u, v);
for(int i = 0, j = 0; i < 10; ++i)
{
if(i != u && i != v)
{
first[i] = alphabet[j];
table[alphabet[j]] = '0' + i;
++j;
}
second[i] = alphabet[i+8];
table[alphabet[i+8]] = '0' + rowU;
table[alphabet[i+8]] += '0' + i;
third[i] = alphabet[i+18];
table[alphabet[i+18]] = '0' + rowV;
table[alphabet[i+18]] += '0' + i;
}
}
string encode(const string &plain)
{
string out;
for(int i = 0; i < plain.size(); ++i)
{
char c = plain[i];
if(c >= 'a' && c <= 'z')
c += 'A' - 'a';
if(c >= 'A' && c <= 'Z')
out += table[c];
else if(c >= '0' && c <= '9')
{
out += table['/'];
out += c;
}
}
return out;
}
string decode(const string &cipher)
{
string out;
int state = 0;
for(int i = 0; i < cipher.size(); ++i)
{
int n = cipher[i] - '0';
char next = 0;
if(state == 1)
next = second[n];
else if(state == 2)
next = third[n];
else if(state == 3)
next = cipher[i];
else if(n == rowU)
state = 1;
else if(n == rowV)
state = 2;
else
next = first[n];
if(next == '/')
state = 3;
else if(next != 0)
{
state = 0;
out += next;
}
}
return out;
}
}; |
http://rosettacode.org/wiki/Stirling_numbers_of_the_first_kind | Stirling numbers of the first kind | Stirling numbers of the first kind, or Stirling cycle numbers, count permutations according to their number
of cycles (counting fixed points as cycles of length one).
They may be defined directly to be the number of permutations of n
elements with k disjoint cycles.
Stirling numbers of the first kind express coefficients of polynomial expansions of falling or rising factorials.
Depending on the application, Stirling numbers of the first kind may be "signed"
or "unsigned". Signed Stirling numbers of the first kind arise when the
polynomial expansion is expressed in terms of falling factorials; unsigned when
expressed in terms of rising factorials. The only substantial difference is that,
for signed Stirling numbers of the first kind, values of S1(n, k) are negative
when n + k is odd.
Stirling numbers of the first kind follow the simple identities:
S1(0, 0) = 1
S1(n, 0) = 0 if n > 0
S1(n, k) = 0 if k > n
S1(n, k) = S1(n - 1, k - 1) + (n - 1) * S1(n - 1, k) # For unsigned
or
S1(n, k) = S1(n - 1, k - 1) - (n - 1) * S1(n - 1, k) # For signed
Task
Write a routine (function, procedure, whatever) to find Stirling numbers of the first kind. There are several methods to generate Stirling numbers of the first kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.
Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the first kind, S1(n, k), up to S1(12, 12). it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S1(n, k) == 0 (when k > n). You may choose to show signed or unsigned Stirling numbers of the first kind, just make a note of which was chosen.
If your language supports large integers, find and show here, on this page, the maximum value of S1(n, k) where n == 100.
See also
Wikipedia - Stirling numbers of the first kind
OEIS:A008275 - Signed Stirling numbers of the first kind
OEIS:A130534 - Unsigned Stirling numbers of the first kind
Related Tasks
Stirling numbers of the second kind
Lah numbers
| #C.2B.2B | C++ | #include <algorithm>
#include <iomanip>
#include <iostream>
#include <map>
#include <gmpxx.h>
using integer = mpz_class;
class unsigned_stirling1 {
public:
integer get(int n, int k);
private:
std::map<std::pair<int, int>, integer> cache_;
};
integer unsigned_stirling1::get(int n, int k) {
if (k == 0)
return n == 0 ? 1 : 0;
if (k > n)
return 0;
auto p = std::make_pair(n, k);
auto i = cache_.find(p);
if (i != cache_.end())
return i->second;
integer s = get(n - 1, k - 1) + (n - 1) * get(n - 1, k);
cache_.emplace(p, s);
return s;
}
void print_stirling_numbers(unsigned_stirling1& s1, int n) {
std::cout << "Unsigned Stirling numbers of the first kind:\nn/k";
for (int j = 0; j <= n; ++j) {
std::cout << std::setw(j == 0 ? 2 : 10) << j;
}
std::cout << '\n';
for (int i = 0; i <= n; ++i) {
std::cout << std::setw(2) << i << ' ';
for (int j = 0; j <= i; ++j)
std::cout << std::setw(j == 0 ? 2 : 10) << s1.get(i, j);
std::cout << '\n';
}
}
int main() {
unsigned_stirling1 s1;
print_stirling_numbers(s1, 12);
std::cout << "Maximum value of S1(n,k) where n == 100:\n";
integer max = 0;
for (int k = 0; k <= 100; ++k)
max = std::max(max, s1.get(100, k));
std::cout << max << '\n';
return 0;
} |
http://rosettacode.org/wiki/String_append | String append |
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
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #CoffeeScript | CoffeeScript | a = "Hello, "
b = "World!"
c = a + b
console.log c |
http://rosettacode.org/wiki/String_append | String append |
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
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #Common_Lisp | Common Lisp | (defmacro concatenatef (s &rest strs)
"Append additional strings to the first string in-place."
`(setf ,s (concatenate 'string ,s ,@strs)))
(defvar *str* "foo")
(concatenatef *str* "bar")
(format T "~a~%" *str*)
(concatenatef *str* "baz" "abc" "def")
(format T "~a~%" *str*) |
http://rosettacode.org/wiki/Stream_merge | Stream merge | 2-stream merge
Read two sorted streams of items from external source (e.g. disk, or network), and write one stream of sorted items to external sink.
Common algorithm: keep 1 buffered item from each source, select minimal of them, write it, fetch another item from that stream from which the written item was.
N-stream merge
The same as above, but reading from N sources.
Common algorithm: same as above, but keep buffered items and their source descriptors in a heap.
Assume streams are very big. You must not suck them whole in the memory, but read them as streams.
| #ALGOL_68 | ALGOL 68 | # merge a number of input files to an output file #
PROC mergenf = ( []REF FILE inf, REF FILE out )VOID:
BEGIN
INT eof count := 0;
BOOL at eof := FALSE;
[]REF FILE inputs = inf[ AT 1 ];
INT number of files = UPB inputs;
[ number of files ]BOOL eof;
[ number of files ]STRING line;
FOR f TO number of files DO
eof[ f ] := FALSE;
on logical file end( inf[ f ], ( REF FILE f )BOOL:
BEGIN
# note that we reached EOF on the latest read #
# and return TRUE so processing can continue #
at eof := TRUE
END
)
OD;
# read a line from one of the input files #
PROC read line = ( INT file number )VOID:
BEGIN
at eof := FALSE;
get( inputs[ file number ], ( line[ file number ], newline ) );
eof[ file number ] := at eof;
IF at eof THEN
# reached eof on this file #
eof count +:= 1
FI
END; # read line #
# get the first line from each input file #
FOR f TO number of files DO read line( f ) OD;
# merge the files #
WHILE eof count < number of files DO
# find the lowest line in the current set #
INT low pos := 0;
STRING low line := "";
BOOL first file := TRUE;
FOR file pos TO number of files DO
IF eof[ file pos ] THEN
# file is at eof - ignore it #
SKIP
ELIF first file THEN
# this is the first file not at eof #
low pos := file pos;
low line := line[ file pos ];
first file := FALSE
ELIF line[ file pos ] < low line THEN
# this line is lower than the previous one #
low pos := file pos;
low line := line[ file pos ]
FI
OD;
# write the record from the lowest file and get the next record #
# from it #
put( out, ( line[ low pos ], newline ) );
read line( low pos )
OD
END; # mergenf #
# merges the files named in input list, the results are written to the file #
# named output name #
# the output file must already exist and will be overwritten #
PROC mergen = ( []STRING input list, STRING output name )VOID:
BEGIN
[]STRING inputs = input list[ AT 1 ];
INT number of files = UPB inputs;
[ number of files ]REF FILE inf;
# open the input files #
FOR f TO number of files DO
inf[ f ] := LOC FILE;
IF open( inf[ f ], inputs[ f ], stand in channel ) /= 0
THEN
# failed to open the input file #
print( ( "Unable to open """ + input list[ f ] + """", newline ) );
stop
FI
OD;
# open the output file (which must already exist & will be overwritten) #
IF FILE output file;
open( output file, output name, stand out channel ) /= 0
THEN
# failed to open the output file #
print( ( "Unable to open """ + output name + """", newline ) );
stop
ELSE
# files opened OK, merge them #
mergenf( inf, output file );
# close the files #
close( output file );
FOR f TO number of files DO close( inf[ f ] ) OD
FI
END; # mergen #
# merges the two files in1 and in2 to output file #
PROC merge2f = ( REF FILE in1, REF FILE in2, REF FILE output file )VOID: mergenf( ( in1, in2 ), output file );
# merges the two files named in1 and in2 to the file named output file #
PROC merge2 = ( STRING in1, STRING in2, STRING output file )VOID: mergen( ( in1, in2 ), output file );
# test the file merge #
merge2( "in1.txt", "in2.txt", "out2.txt" );
mergen( ( "in1.txt", "in2.txt", "in3.txt", "in4.txt" ), "outn.txt" ) |
http://rosettacode.org/wiki/Stirling_numbers_of_the_second_kind | Stirling numbers of the second kind | Stirling numbers of the second kind, or Stirling partition numbers, are the
number of ways to partition a set of n objects into k non-empty subsets. They are
closely related to Bell numbers, and may be derived from them.
Stirling numbers of the second kind obey the recurrence relation:
S2(n, 0) and S2(0, k) = 0 # for n, k > 0
S2(n, n) = 1
S2(n + 1, k) = k * S2(n, k) + S2(n, k - 1)
Task
Write a routine (function, procedure, whatever) to find Stirling numbers of the second kind. There are several methods to generate Stirling numbers of the second kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.
Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the second kind, S2(n, k), up to S2(12, 12). it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S2(n, k) == 0 (when k > n).
If your language supports large integers, find and show here, on this page, the maximum value of S2(n, k) where n == 100.
See also
Wikipedia - Stirling numbers of the second kind
OEIS:A008277 - Stirling numbers of the second kind
Related Tasks
Stirling numbers of the first kind
Bell numbers
Lah numbers
| #Visual_Basic_.NET | Visual Basic .NET | Imports System.Numerics
Module Module1
Class Sterling
Private Shared ReadOnly COMPUTED As New Dictionary(Of String, BigInteger)
Private Shared Function CacheKey(n As Integer, k As Integer) As String
Return String.Format("{0}:{1}", n, k)
End Function
Private Shared Function Impl(n As Integer, k As Integer) As BigInteger
If n = 0 AndAlso k = 0 Then
Return 1
End If
If (n > 0 AndAlso k = 0) OrElse (n = 0 AndAlso k > 0) Then
Return 0
End If
If n = k Then
Return 1
End If
If k > n Then
Return 0
End If
Return k * Sterling2(n - 1, k) + Sterling2(n - 1, k - 1)
End Function
Public Shared Function Sterling2(n As Integer, k As Integer) As BigInteger
Dim key = CacheKey(n, k)
If COMPUTED.ContainsKey(key) Then
Return COMPUTED(key)
End If
Dim result = Impl(n, k)
COMPUTED.Add(key, result)
Return result
End Function
End Class
Sub Main()
Console.WriteLine("Stirling numbers of the second kind:")
Dim max = 12
Console.Write("n/k")
For n = 0 To max
Console.Write("{0,10}", n)
Next
Console.WriteLine()
For n = 0 To max
Console.Write("{0,3}", n)
For k = 0 To n
Console.Write("{0,10}", Sterling.Sterling2(n, k))
Next
Console.WriteLine()
Next
Console.WriteLine("The maximum value of S2(100, k) = ")
Dim previous = BigInteger.Zero
For k = 1 To 100
Dim current = Sterling.Sterling2(100, k)
If current > previous Then
previous = current
Else
Console.WriteLine(previous)
Console.WriteLine("({0} digits, k = {1})", previous.ToString().Length, k - 1)
Exit For
End If
Next
End Sub
End Module |
http://rosettacode.org/wiki/Straddling_checkerboard | Straddling checkerboard | Task
Implement functions to encrypt and decrypt a message using the straddling checkerboard method. The checkerboard should take a 28 character alphabet (A-Z plus a full stop and an escape character) and two different numbers representing the blanks in the first row. The output will be a series of decimal digits.
Numbers should be encrypted by inserting the escape character before each digit, then including the digit unencrypted. This should be reversed for decryption.
| #D | D | import std.stdio, std.algorithm, std.string, std.array;
immutable T = ["79|0|1|2|3|4|5|6|7|8|9", "|H|O|L||M|E|S||R|T",
"3|A|B|C|D|F|G|I|J|K|N", "7|P|Q|U|V|W|X|Y|Z|.|/"]
.map!(r => r.split("|")).array;
enum straddle = (in string s) pure /*nothrow @safe*/ =>
toUpper(s)
.split("")
.cartesianProduct(T)
.filter!(cL => cL[1].canFind(cL[0]))
.map!(cL => cL[1][0] ~ T[0][cL[1].countUntil(cL[0])])
.join;
string unStraddle(string s) pure nothrow @safe {
string result;
for (; !s.empty; s.popFront) {
immutable i = [T[2][0], T[3][0]].countUntil([s[0]]);
if (i >= 0) {
s.popFront;
immutable n = T[2 + i][T[0].countUntil([s[0]])];
if (n == "/") {
s.popFront;
result ~= s[0];
} else result ~= n;
} else
result ~= T[1][T[0].countUntil([s[0]])];
}
return result;
}
void main() {
immutable O = "One night-it was on the twentieth of March, 1888-I was returning";
writeln("Encoded: ", O.straddle);
writeln("Decoded: ", O.straddle.unStraddle);
} |
http://rosettacode.org/wiki/Stirling_numbers_of_the_first_kind | Stirling numbers of the first kind | Stirling numbers of the first kind, or Stirling cycle numbers, count permutations according to their number
of cycles (counting fixed points as cycles of length one).
They may be defined directly to be the number of permutations of n
elements with k disjoint cycles.
Stirling numbers of the first kind express coefficients of polynomial expansions of falling or rising factorials.
Depending on the application, Stirling numbers of the first kind may be "signed"
or "unsigned". Signed Stirling numbers of the first kind arise when the
polynomial expansion is expressed in terms of falling factorials; unsigned when
expressed in terms of rising factorials. The only substantial difference is that,
for signed Stirling numbers of the first kind, values of S1(n, k) are negative
when n + k is odd.
Stirling numbers of the first kind follow the simple identities:
S1(0, 0) = 1
S1(n, 0) = 0 if n > 0
S1(n, k) = 0 if k > n
S1(n, k) = S1(n - 1, k - 1) + (n - 1) * S1(n - 1, k) # For unsigned
or
S1(n, k) = S1(n - 1, k - 1) - (n - 1) * S1(n - 1, k) # For signed
Task
Write a routine (function, procedure, whatever) to find Stirling numbers of the first kind. There are several methods to generate Stirling numbers of the first kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.
Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the first kind, S1(n, k), up to S1(12, 12). it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S1(n, k) == 0 (when k > n). You may choose to show signed or unsigned Stirling numbers of the first kind, just make a note of which was chosen.
If your language supports large integers, find and show here, on this page, the maximum value of S1(n, k) where n == 100.
See also
Wikipedia - Stirling numbers of the first kind
OEIS:A008275 - Signed Stirling numbers of the first kind
OEIS:A130534 - Unsigned Stirling numbers of the first kind
Related Tasks
Stirling numbers of the second kind
Lah numbers
| #D | D | import std.bigint;
import std.functional;
import std.stdio;
alias sterling1 = memoize!sterling1Impl;
BigInt sterling1Impl(int n, int k) {
if (n == 0 && k == 0) {
return BigInt(1);
}
if (n > 0 && k == 0) {
return BigInt(0);
}
if (k > n) {
return BigInt(0);
}
return sterling1(n - 1, k - 1) + (n - 1) * sterling1(n - 1, k);
}
void main() {
writeln("Unsigned Stirling numbers of the first kind:");
int max = 12;
write("n/k");
foreach (n; 0 .. max + 1) {
writef("%10d", n);
}
writeln;
foreach (n; 0 .. max + 1) {
writef("%-3d", n);
foreach (k; 0 .. n + 1) {
writef("%10s", sterling1(n, k));
}
writeln;
}
writeln("The maximum value of S1(100, k) = ");
auto previous = BigInt(0);
foreach (k; 1 .. 101) {
auto current = sterling1(100, k);
if (previous < current) {
previous = current;
} else {
import std.conv;
writeln(previous);
writefln("(%d digits, k = %d)", previous.to!string.length, k - 1);
break;
}
}
} |
http://rosettacode.org/wiki/String_append | String append |
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
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #D | D | import std.stdio;
void main() {
string s = "Hello";
s ~= " world!";
writeln(s);
} |
http://rosettacode.org/wiki/String_append | String append |
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
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #DBL | DBL | ;Concatenate "Hello world!"
STR='Hello'
STR(%TRIM(STR)+2:5)='world'
STR(%TRIM(STR)+1:1)='!' |
http://rosettacode.org/wiki/Stream_merge | Stream merge | 2-stream merge
Read two sorted streams of items from external source (e.g. disk, or network), and write one stream of sorted items to external sink.
Common algorithm: keep 1 buffered item from each source, select minimal of them, write it, fetch another item from that stream from which the written item was.
N-stream merge
The same as above, but reading from N sources.
Common algorithm: same as above, but keep buffered items and their source descriptors in a heap.
Assume streams are very big. You must not suck them whole in the memory, but read them as streams.
| #ATS | ATS |
(* ****** ****** *)
//
// This is a memory-clean implementation:
// Every byte of allocated memory is freed
// before the program exits.
//
(* ****** ****** *)
//
#include
"share/atspre_define.hats"
#include
"share/atspre_staload.hats"
//
(*
#include
"share/HATS/atspre_staload_libats_ML.hats"
*)
//
(* ****** ****** *)
staload UN = $UNSAFE
(* ****** ****** *)
fun
streamize_fileptr_line
(inp: FILEref) = let
//
val lines =
streamize_fileref_line(inp)
//
val
closing =
$ldelay
(
(
fileref_close(inp);
stream_vt_nil((*void*))
)
,
fileref_close(inp)
)
//
in
//
stream_vt_append(lines, closing)
//
end // end of [streamize_fileptr_line]
(* ****** ****** *)
//
extern
fun
{a:vt@ype}
stream_merge_2
(
xs: stream_vt(a), ys: stream_vt(a)
) : stream_vt(a) // end-of-function
//
(* ****** ****** *)
implement
{a}(*tmp*)
stream_merge_2
(xs, ys) =
aux0(xs, ys) where
{
//
fun
aux0
(
xs: stream_vt(a)
,
ys: stream_vt(a)
) : stream_vt(a) = $ldelay
(
case+ !xs of
| ~stream_vt_nil() => !ys
| ~stream_vt_cons(x, xs) => !(aux1(x, xs, ys))
,
(~xs; ~ys)
)
//
and
aux1
(
x0: a
,
xs: stream_vt(a)
,
ys: stream_vt(a)
) : stream_vt(a) = $ldelay
(
case+ !ys of
| ~stream_vt_nil() => stream_vt_cons(x0, xs)
| ~stream_vt_cons(y, ys) => !(aux2(x0, xs, y, ys))
,
(gfree_val<a>(x0); ~xs; ~ys)
)
//
and
aux2
(
x0: a
,
xs: stream_vt(a)
,
y0: a
,
ys: stream_vt(a)
) : stream_vt(a) = $ldelay
(
let
//
var x0 = x0
and y0 = y0
//
val sgn = gcompare_ref_ref<a>(x0, y0)
//
in
//
if
(sgn <= 0)
then stream_vt_cons(x0, aux1(y0, ys, xs))
else stream_vt_cons(y0, aux1(x0, xs, ys))
//
end // end of [let]
,
(gfree_val<a>(x0); gfree_val<a>(y0); ~xs; ~ys)
)
//
} (* end of [stream_merge_2] *)
(* ****** ****** *)
implement
main0(argc, argv) =
{
//
val () = assertloc(argc >= 3)
//
val xs =
(
case+
fileref_open_opt
(
argv[1], file_mode_r
) of // case+
| ~None_vt() => stream_vt_make_nil()
| ~Some_vt(inp) => streamize_fileptr_line(inp)
) : stream_vt(Strptr1)
//
val ys =
(
case+
fileref_open_opt
(
argv[2], file_mode_r
) of // case+
| ~None_vt() => stream_vt_make_nil()
| ~Some_vt(inp) => streamize_fileptr_line(inp)
) : stream_vt(Strptr1)
//
local
//
implement
(a:vt@ype)
gfree_val<a>(z) =
strptr_free($UN.castvwtp0{Strptr1}(z))
//
implement
(a:vt@ype)
gcompare_ref_ref<a>
(x, y) =
(
compare($UN.castvwtp1{String}(x), $UN.castvwtp1{String}(y))
) (* end of [gcompare_ref_ref] *)
//
in
//
val zs = stream_merge_2<Strptr1>(xs, ys)
//
end // end of [local]
//
val ((*void*)) =
stream_vt_foreach_cloptr(zs, lam(z) => (println!(z); strptr_free(z)))
//
} (* end of [main0] *)
|
http://rosettacode.org/wiki/Stream_merge | Stream merge | 2-stream merge
Read two sorted streams of items from external source (e.g. disk, or network), and write one stream of sorted items to external sink.
Common algorithm: keep 1 buffered item from each source, select minimal of them, write it, fetch another item from that stream from which the written item was.
N-stream merge
The same as above, but reading from N sources.
Common algorithm: same as above, but keep buffered items and their source descriptors in a heap.
Assume streams are very big. You must not suck them whole in the memory, but read them as streams.
| #AWK | AWK |
# syntax: GAWK -f STREAM_MERGE.AWK filename(s) >output
# handles 1 .. N files
#
# variable purpose
# ---------- -------
# data_arr holds last record read
# fn_arr filenames on command line
# fnr_arr record counts for each file
# status_arr file status: 1=more data, 0=EOF, -1=error
#
BEGIN {
files = ARGC-1
# get filename, file status and first record
for (i=1; i<=files; i++) {
fn_arr[i] = ARGV[i]
status_arr[i] = getline <fn_arr[i]
if (status_arr[i] == 1) {
nr++ # records read
fnr_arr[i]++
data_arr[i] = $0
}
else if (status_arr[i] < 0) {
error(sprintf("FILENAME=%s, status=%d, file not found",fn_arr[i],status_arr[i]))
}
}
while (1) { # until EOF in all files
# get file number of the first file still containing data
fno = 0 # file number
for (i=1; i<=files; i++) {
if (status_arr[i] == 1) {
fno = i
break
}
}
if (fno == 0) { # EOF in all files
break
}
# determine which file has the lowest record in collating sequence
for (i=1; i<=files; i++) {
if (status_arr[i] == 1) {
if (data_arr[i] < data_arr[fno]) {
fno = i
}
}
}
# output record, get next record, if not EOF then check sequence
printf("%s\n",data_arr[fno])
status_arr[fno] = getline <fn_arr[fno] # get next record from this file
if (status_arr[fno] == 1) {
nr++
fnr_arr[fno]++
if (data_arr[fno] > $0) {
error(sprintf("FILENAME=%s, FNR=%d, out of sequence",fn_arr[fno],fnr_arr[fno]))
}
data_arr[fno] = $0
}
}
# EOJ
printf("input: %d files, %d records, %d errors\n",files,nr,errors) >"con"
exit(0)
}
function error(message) {
printf("error: %s\n",message) >"con"
errors++
}
|
http://rosettacode.org/wiki/Stirling_numbers_of_the_second_kind | Stirling numbers of the second kind | Stirling numbers of the second kind, or Stirling partition numbers, are the
number of ways to partition a set of n objects into k non-empty subsets. They are
closely related to Bell numbers, and may be derived from them.
Stirling numbers of the second kind obey the recurrence relation:
S2(n, 0) and S2(0, k) = 0 # for n, k > 0
S2(n, n) = 1
S2(n + 1, k) = k * S2(n, k) + S2(n, k - 1)
Task
Write a routine (function, procedure, whatever) to find Stirling numbers of the second kind. There are several methods to generate Stirling numbers of the second kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.
Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the second kind, S2(n, k), up to S2(12, 12). it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S2(n, k) == 0 (when k > n).
If your language supports large integers, find and show here, on this page, the maximum value of S2(n, k) where n == 100.
See also
Wikipedia - Stirling numbers of the second kind
OEIS:A008277 - Stirling numbers of the second kind
Related Tasks
Stirling numbers of the first kind
Bell numbers
Lah numbers
| #Wren | Wren | import "/big" for BigInt
import "/fmt" for Fmt
var computed = {}
var stirling2 // recursive
stirling2 = Fn.new { |n, k|
var key = "%(n),%(k)"
if (computed.containsKey(key)) return computed[key]
if (n == 0 && k == 0) return BigInt.one
if ((n > 0 && k == 0) || (n == 0 && k > 0)) return BigInt.zero
if (k == n) return BigInt.one
if (k > n) return BigInt.zero
var result = stirling2.call(n-1, k-1) + stirling2.call(n-1, k)*k
computed[key] = result
return result
}
System.print("Unsigned Stirling numbers of the second kind:")
var max = 12
System.write("n/k")
for (n in 0..max) Fmt.write("$10d", n)
System.print()
for (n in 0..max) {
Fmt.write("$-3d", n)
for (k in 0..n) Fmt.write("$10i", stirling2.call(n, k))
System.print()
}
System.print("The maximum value of S2(100, k) =")
var previous = BigInt.zero
for (k in 1..100) {
var current = stirling2.call(100, k)
if (current > previous) {
previous = current
} else {
Fmt.print("$i\n($d digits, k = $d)", previous, previous.toString.count, k - 1)
break
}
} |
http://rosettacode.org/wiki/Straddling_checkerboard | Straddling checkerboard | Task
Implement functions to encrypt and decrypt a message using the straddling checkerboard method. The checkerboard should take a 28 character alphabet (A-Z plus a full stop and an escape character) and two different numbers representing the blanks in the first row. The output will be a series of decimal digits.
Numbers should be encrypted by inserting the escape character before each digit, then including the digit unencrypted. This should be reversed for decryption.
| #F.23 | F# |
(*
Encode and Decode using StraddlingCheckerboard
Nigel Galloway May 15th., 2017
*)
type G={n:char;i:char;g:System.Collections.Generic.Dictionary<(char*char),string>;e:System.Collections.Generic.Dictionary<char,string>}
member G.encode n=n|>Seq.map(fun n->if (n='/') then G.e.['/']+string n else match (G.e.TryGetValue(n)) with |(true,n)->n|(false,_)->G.e.['/']+string n)
member G.decode n =
let rec fn n = seq{ if not (Seq.isEmpty n)
then match (match Seq.head n with |g when g=G.n||g=G.i->(G.g.[(g,(Seq.item 1 n))],(Seq.skip 2 n))|g->(G.g.[('/',g)],(Seq.tail n))) with
|(a,b) when a="/"->yield string (Seq.head b); yield! fn (Seq.tail b)
|(a,b) ->yield a; yield! fn b
}
fn n
let G n i g e l z=
let a = new System.Collections.Generic.Dictionary<(char*char),string>()
let b = new System.Collections.Generic.Dictionary<char,string>()
Seq.iter2 (fun ng gn->a.[('/' ,char ng)]<-string gn;b.[gn]<-ng) (List.except [n;i] z) g
Seq.iter2 (fun ng gn->a.[(char n,char ng)]<-string gn;b.[gn]<-n+ng) z e
Seq.iter2 (fun ng gn->a.[(char i,char ng)]<-string gn;b.[gn]<-i+ng) z l
{n=char n;i=char i;g=a;e=b}
|
http://rosettacode.org/wiki/Stirling_numbers_of_the_first_kind | Stirling numbers of the first kind | Stirling numbers of the first kind, or Stirling cycle numbers, count permutations according to their number
of cycles (counting fixed points as cycles of length one).
They may be defined directly to be the number of permutations of n
elements with k disjoint cycles.
Stirling numbers of the first kind express coefficients of polynomial expansions of falling or rising factorials.
Depending on the application, Stirling numbers of the first kind may be "signed"
or "unsigned". Signed Stirling numbers of the first kind arise when the
polynomial expansion is expressed in terms of falling factorials; unsigned when
expressed in terms of rising factorials. The only substantial difference is that,
for signed Stirling numbers of the first kind, values of S1(n, k) are negative
when n + k is odd.
Stirling numbers of the first kind follow the simple identities:
S1(0, 0) = 1
S1(n, 0) = 0 if n > 0
S1(n, k) = 0 if k > n
S1(n, k) = S1(n - 1, k - 1) + (n - 1) * S1(n - 1, k) # For unsigned
or
S1(n, k) = S1(n - 1, k - 1) - (n - 1) * S1(n - 1, k) # For signed
Task
Write a routine (function, procedure, whatever) to find Stirling numbers of the first kind. There are several methods to generate Stirling numbers of the first kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.
Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the first kind, S1(n, k), up to S1(12, 12). it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S1(n, k) == 0 (when k > n). You may choose to show signed or unsigned Stirling numbers of the first kind, just make a note of which was chosen.
If your language supports large integers, find and show here, on this page, the maximum value of S1(n, k) where n == 100.
See also
Wikipedia - Stirling numbers of the first kind
OEIS:A008275 - Signed Stirling numbers of the first kind
OEIS:A130534 - Unsigned Stirling numbers of the first kind
Related Tasks
Stirling numbers of the second kind
Lah numbers
| #Factor | Factor | USING: arrays assocs formatting io kernel math math.polynomials
math.ranges prettyprint sequences ;
IN: rosetta-code.stirling-first
: stirling-row ( n -- seq )
[ { 1 } ] [
[ -1 ] dip neg [a,b) dup length 1 <array> zip
{ 0 1 } [ p* ] reduce [ abs ] map
] if-zero ;
"Unsigned Stirling numbers of the first kind:" print
"n\\k" write 13 dup [ "%10d" printf ] each-integer nl
[ dup "%-2d " printf stirling-row [ "%10d" printf ] each nl ]
each-integer nl
"Maximum value from 100th stirling row:" print
100 stirling-row supremum . |
http://rosettacode.org/wiki/Stirling_numbers_of_the_first_kind | Stirling numbers of the first kind | Stirling numbers of the first kind, or Stirling cycle numbers, count permutations according to their number
of cycles (counting fixed points as cycles of length one).
They may be defined directly to be the number of permutations of n
elements with k disjoint cycles.
Stirling numbers of the first kind express coefficients of polynomial expansions of falling or rising factorials.
Depending on the application, Stirling numbers of the first kind may be "signed"
or "unsigned". Signed Stirling numbers of the first kind arise when the
polynomial expansion is expressed in terms of falling factorials; unsigned when
expressed in terms of rising factorials. The only substantial difference is that,
for signed Stirling numbers of the first kind, values of S1(n, k) are negative
when n + k is odd.
Stirling numbers of the first kind follow the simple identities:
S1(0, 0) = 1
S1(n, 0) = 0 if n > 0
S1(n, k) = 0 if k > n
S1(n, k) = S1(n - 1, k - 1) + (n - 1) * S1(n - 1, k) # For unsigned
or
S1(n, k) = S1(n - 1, k - 1) - (n - 1) * S1(n - 1, k) # For signed
Task
Write a routine (function, procedure, whatever) to find Stirling numbers of the first kind. There are several methods to generate Stirling numbers of the first kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.
Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the first kind, S1(n, k), up to S1(12, 12). it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S1(n, k) == 0 (when k > n). You may choose to show signed or unsigned Stirling numbers of the first kind, just make a note of which was chosen.
If your language supports large integers, find and show here, on this page, the maximum value of S1(n, k) where n == 100.
See also
Wikipedia - Stirling numbers of the first kind
OEIS:A008275 - Signed Stirling numbers of the first kind
OEIS:A130534 - Unsigned Stirling numbers of the first kind
Related Tasks
Stirling numbers of the second kind
Lah numbers
| #FreeBASIC | FreeBASIC | dim as integer S1(0 to 12, 0 to 12) 'initially set with zeroes
dim as ubyte n, k
dim as string outstr
function padto( i as ubyte, j as integer ) as string
return wspace(i-len(str(j)))+str(j)
end function
S1(0, 0) = 1
for n = 0 to 12 'calculate table
for k = 1 to n
S1(n, k) = S1(n-1, k-1) - (n-1) * S1(n-1, k)
next k
next n
print "Signed Stirling numbers of the first kind"
print
outstr = " k"
for k=0 to 12
outstr += padto(12, k)
next k
print outstr
print " n"
for n = 0 to 12
outstr = padto(2, n)+" "
for k = 0 to 12
outstr += padto(12, S1(n, k))
next k
print outstr
next n |
http://rosettacode.org/wiki/String_append | String append |
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
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #Delphi | Delphi |
program String_append;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
type
TStringHelper = record helper for string
procedure Append(str: string);
end;
{ TStringHelper }
procedure TStringHelper.Append(str: string);
begin
Self := self + str;
end;
begin
var h: string;
// with + operator
h := 'Hello';
h := h + ' World';
writeln(h);
// with a function concat
h := 'Hello';
h := Concat(h, ' World');
writeln(h);
// with helper
h := 'Hello';
h.Append(' World');
writeln(h);
readln;
end. |
http://rosettacode.org/wiki/Stream_merge | Stream merge | 2-stream merge
Read two sorted streams of items from external source (e.g. disk, or network), and write one stream of sorted items to external sink.
Common algorithm: keep 1 buffered item from each source, select minimal of them, write it, fetch another item from that stream from which the written item was.
N-stream merge
The same as above, but reading from N sources.
Common algorithm: same as above, but keep buffered items and their source descriptors in a heap.
Assume streams are very big. You must not suck them whole in the memory, but read them as streams.
| #C | C | /*
* Rosetta Code - stream merge in C.
*
* Two streams (text files) with integer numbers, C89, Visual Studio 2010.
*
*/
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#define GET(N) { if(fscanf(f##N,"%d",&b##N ) != 1) f##N = NULL; }
#define PUT(N) { printf("%d\n", b##N); GET(N) }
void merge(FILE* f1, FILE* f2, FILE* out)
{
int b1;
int b2;
if(f1) GET(1)
if(f2) GET(2)
while ( f1 && f2 )
{
if ( b1 <= b2 ) PUT(1)
else PUT(2)
}
while (f1 ) PUT(1)
while (f2 ) PUT(2)
}
int main(int argc, char* argv[])
{
if ( argc < 3 || argc > 3 )
{
puts("streammerge filename1 filename2");
exit(EXIT_FAILURE);
}
else
merge(fopen(argv[1],"r"),fopen(argv[2],"r"),stdout);
return EXIT_SUCCESS;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.