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/Literals/String | Literals/String | Task
Show literal specification of characters and strings.
If supported, show how the following work:
verbatim strings (quotes where escape sequences are quoted literally)
here-strings
Also, discuss which quotes expand variables.
Related tasks
Special characters
Here document
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Ada | Ada | ch : character := 'a'; |
http://rosettacode.org/wiki/Literals/String | Literals/String | Task
Show literal specification of characters and strings.
If supported, show how the following work:
verbatim strings (quotes where escape sequences are quoted literally)
here-strings
Also, discuss which quotes expand variables.
Related tasks
Special characters
Here document
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Aime | Aime | integer c;
c = 'z'; |
http://rosettacode.org/wiki/Long_literals,_with_continuations | Long literals, with continuations | This task is about writing a computer program that has long literals (character
literals that may require specifying the words/tokens on more than one (source)
line, either with continuations or some other method, such as abutments or
concatenations (or some other mechanisms).
The literal is to be in the form of a "list", a literal that contains many
words (tokens) separated by a blank (space), in this case (so as to have a
common list), the (English) names of the chemical elements of the periodic table.
The list is to be in (ascending) order of the (chemical) element's atomic number:
hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium aluminum silicon ...
... up to the last known (named) chemical element (at this time).
Do not include any of the "unnamed" chemical element names such as:
ununennium unquadnilium triunhexium penthextrium penthexpentium septhexunium octenntrium ennennbium
To make computer programming languages comparable, the statement widths should be
restricted to less than 81 bytes (characters), or less
if a computer programming language has more restrictive limitations or standards.
Also mention what column the programming statements can start in if not
in column one.
The list may have leading/embedded/trailing blanks during the
declaration (the actual program statements), this is allow the list to be
more readable. The "final" list shouldn't have any leading/trailing or superfluous
blanks (when stored in the program's "memory").
This list should be written with the idea in mind that the
program will be updated, most likely someone other than the
original author, as there will be newer (discovered) elements of the periodic
table being added (possibly in the near future). These future updates
should be one of the primary concerns in writing these programs and it should be "easy"
for someone else to add chemical elements to the list (within the computer
program).
Attention should be paid so as to not exceed the clause length of
continued or specified statements, if there is such a restriction. If the
limit is greater than (say) 4,000 bytes or so, it needn't be mentioned here.
Task
Write a computer program (by whatever name) to contain a list of the known elements.
The program should eventually contain a long literal of words (the elements).
The literal should show how one could create a long list of blank-delineated words.
The "final" (stored) list should only have a single blank between elements.
Try to use the most idiomatic approach(es) in creating the final list.
Use continuation if possible, and/or show alternatives (possibly using concatenation).
Use a program comment to explain what the continuation character is if it isn't obvious.
The program should contain a variable that has the date of the last update/revision.
The program, when run, should display with verbiage:
The last update/revision date (and should be unambiguous).
The number of chemical elements in the list.
The name of the highest (last) element name.
Show all output here, on this page.
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
| #BASIC256 | BASIC256 |
ultimaRevision$ = "2021-11-12"
arraybase 1
dim elemento$ = {"hydrogen", "helium", "lithium", "beryllium", "boron", "carbon", "nitrogen", "oxygen", "fluorine", "neon", "sodium", "magnesium", "aluminum", "silicon", "phosphorous", "sulfur", "chlorine", "argon", "potassium", "calcium", "scandium", "titanium", "vanadium", "chromium", "manganese", "iron", "cobalt", "nickel", "copper", "zinc", "gallium", "germanium", "arsenic", "selenium", "bromine", "krypton", "rubidium", "strontium", "yttrium", "zirconium", "niobium", "molybdenum", "technetium", "ruthenium", "rhodium", "palladium", "silver", "cadmium", "indium", "tin", "antimony", "tellurium", "iodine", "xenon", "cesium", "barium", "lanthanum", "cerium", "praseodymium", "neodymium", "promethium", "samarium", "europium", "gadolinium", "terbium", "dysprosium", "holmium", "erbium", "thulium", "ytterbium", "lutetium", "hafnium", "tantalum", "tungsten", "rhenium", "osmium", "iridium", "platinum", "gold", "mercury", "thallium", "lead", "bismuth", "polonium", "astatine", "radon", "francium", "radium", "actinium", "thorium", "protactinium", "uranium", "neptunium", "plutonium", "americium", "curium", "berkelium", "californium", "einsteinium", "fermium", "mendelevium", "nobelium", "lawrencium", "rutherfordium", "dubnium", "seaborgium", "bohrium", "hassium", "meitnerium", "darmstadtium", "roentgenium", "copernicium", "nihonium", "flerovium", "moscovium", "livermorium", "tennessine", "oganesson"}
print "Last updated : "; ultimaRevision$
print "Number of elements : "; elemento$[?]
print "Last element : "; elemento$[elemento$[?]]
end
|
http://rosettacode.org/wiki/Long_literals,_with_continuations | Long literals, with continuations | This task is about writing a computer program that has long literals (character
literals that may require specifying the words/tokens on more than one (source)
line, either with continuations or some other method, such as abutments or
concatenations (or some other mechanisms).
The literal is to be in the form of a "list", a literal that contains many
words (tokens) separated by a blank (space), in this case (so as to have a
common list), the (English) names of the chemical elements of the periodic table.
The list is to be in (ascending) order of the (chemical) element's atomic number:
hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium aluminum silicon ...
... up to the last known (named) chemical element (at this time).
Do not include any of the "unnamed" chemical element names such as:
ununennium unquadnilium triunhexium penthextrium penthexpentium septhexunium octenntrium ennennbium
To make computer programming languages comparable, the statement widths should be
restricted to less than 81 bytes (characters), or less
if a computer programming language has more restrictive limitations or standards.
Also mention what column the programming statements can start in if not
in column one.
The list may have leading/embedded/trailing blanks during the
declaration (the actual program statements), this is allow the list to be
more readable. The "final" list shouldn't have any leading/trailing or superfluous
blanks (when stored in the program's "memory").
This list should be written with the idea in mind that the
program will be updated, most likely someone other than the
original author, as there will be newer (discovered) elements of the periodic
table being added (possibly in the near future). These future updates
should be one of the primary concerns in writing these programs and it should be "easy"
for someone else to add chemical elements to the list (within the computer
program).
Attention should be paid so as to not exceed the clause length of
continued or specified statements, if there is such a restriction. If the
limit is greater than (say) 4,000 bytes or so, it needn't be mentioned here.
Task
Write a computer program (by whatever name) to contain a list of the known elements.
The program should eventually contain a long literal of words (the elements).
The literal should show how one could create a long list of blank-delineated words.
The "final" (stored) list should only have a single blank between elements.
Try to use the most idiomatic approach(es) in creating the final list.
Use continuation if possible, and/or show alternatives (possibly using concatenation).
Use a program comment to explain what the continuation character is if it isn't obvious.
The program should contain a variable that has the date of the last update/revision.
The program, when run, should display with verbiage:
The last update/revision date (and should be unambiguous).
The number of chemical elements in the list.
The name of the highest (last) element name.
Show all output here, on this page.
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
| #Crystal | Crystal | require "time"
last_revision = Time.utc year: 2021, month: 2, day: 25
# the `%w()` literal creates an array from a whitespace-delimited string literal
# it's equivalent to %(string literal).split
# https://crystal-lang.org/reference/syntax_and_semantics/literals/string.html
element_list : Array(String) = %w(
hydrogen helium lithium beryllium
boron carbon nitrogen oxygen
fluorine neon sodium magnesium
aluminum silicon phosphorous sulfur
chlorine argon potassium calcium
scandium titanium vanadium chromium
manganese iron cobalt nickel
copper zinc gallium germanium
arsenic selenium bromine krypton
rubidium strontium yttrium zirconium
niobium molybdenum technetium ruthenium
rhodium palladium silver cadmium
indium tin antimony tellurium
iodine xenon cesium barium
lanthanum cerium praseodymium neodymium
promethium samarium europium gadolinium
terbium dysprosium holmium erbium
thulium ytterbium lutetium hafnium
tantalum tungsten rhenium osmium
iridium platinum gold mercury
thallium lead bismuth polonium
astatine radon francium radium
actinium thorium protactinium uranium
neptunium plutonium americium curium
berkelium californium einsteinium fermium
mendelevium nobelium lawrencium rutherfordium
dubnium seaborgium bohrium hassium
meitnerium darmstadtium roentgenium copernicium
nihonium flerovium moscovium livermorium
tennessine oganesson)
puts last_revision.to_s "last revised %B %e, %Y"
puts "number of elements: #{element_list.size}"
puts "highest element: #{element_list.last}" |
http://rosettacode.org/wiki/Long_literals,_with_continuations | Long literals, with continuations | This task is about writing a computer program that has long literals (character
literals that may require specifying the words/tokens on more than one (source)
line, either with continuations or some other method, such as abutments or
concatenations (or some other mechanisms).
The literal is to be in the form of a "list", a literal that contains many
words (tokens) separated by a blank (space), in this case (so as to have a
common list), the (English) names of the chemical elements of the periodic table.
The list is to be in (ascending) order of the (chemical) element's atomic number:
hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium aluminum silicon ...
... up to the last known (named) chemical element (at this time).
Do not include any of the "unnamed" chemical element names such as:
ununennium unquadnilium triunhexium penthextrium penthexpentium septhexunium octenntrium ennennbium
To make computer programming languages comparable, the statement widths should be
restricted to less than 81 bytes (characters), or less
if a computer programming language has more restrictive limitations or standards.
Also mention what column the programming statements can start in if not
in column one.
The list may have leading/embedded/trailing blanks during the
declaration (the actual program statements), this is allow the list to be
more readable. The "final" list shouldn't have any leading/trailing or superfluous
blanks (when stored in the program's "memory").
This list should be written with the idea in mind that the
program will be updated, most likely someone other than the
original author, as there will be newer (discovered) elements of the periodic
table being added (possibly in the near future). These future updates
should be one of the primary concerns in writing these programs and it should be "easy"
for someone else to add chemical elements to the list (within the computer
program).
Attention should be paid so as to not exceed the clause length of
continued or specified statements, if there is such a restriction. If the
limit is greater than (say) 4,000 bytes or so, it needn't be mentioned here.
Task
Write a computer program (by whatever name) to contain a list of the known elements.
The program should eventually contain a long literal of words (the elements).
The literal should show how one could create a long list of blank-delineated words.
The "final" (stored) list should only have a single blank between elements.
Try to use the most idiomatic approach(es) in creating the final list.
Use continuation if possible, and/or show alternatives (possibly using concatenation).
Use a program comment to explain what the continuation character is if it isn't obvious.
The program should contain a variable that has the date of the last update/revision.
The program, when run, should display with verbiage:
The last update/revision date (and should be unambiguous).
The number of chemical elements in the list.
The name of the highest (last) element name.
Show all output here, on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Delphi | Delphi |
program Long_literals_with_continuations;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.StrUtils;
// Copy and past of Free_Pascal version
const
StdWordDelims: array[0..16] of char = (#0, ' ', ',', '.', ';', '/', '\', ':',
'''', '"', '`', '(', ')', '[', ']', '{', '}');
revisionNotice = 'Last update: %0:s';
elementString = 'hydrogen helium lithium beryllium boron carbon nitrogen oxy'
+ 'gen fluorine neon sodium magnesium aluminum silicon phosphorous sulfur chl'
+ 'orine argon potassium calcium scandium titanium vanadium chromium manganes'
+ 'e iron cobalt nickel copper zinc gallium germanium arsenic selenium bromin'
+ 'e krypton rubidium strontium yttrium zirconium niobium molybdenum techneti'
+ 'um ruthenium rhodium palladium silver cadmium indium tin antimony telluriu'
+ 'm iodine xenon cesium barium lanthanum cerium praseodymium neodymium prome'
+ 'thium samarium europium gadolinium terbium dysprosium holmium erbium thuli'
+ 'um ytterbium lutetium hafnium tantalum tungsten rhenium osmium iridium pla'
+ 'tinum gold mercury thallium lead bismuth polonium astatine radon francium '
+ 'radium actinium thorium protactinium uranium neptunium plutonium americium'
+ ' curium berkelium californium einsteinium fermium mendelevium nobelium law'
+ 'rencium rutherfordium dubnium seaborgium bohrium hassium meitnerium darmst'
+ 'adtium roentgenium copernicium nihonium flerovium moscovium livermorium te'
+ 'nnessine oganesson';
elementRevision = '2020-11-11';
begin
var words := elementString.Split(StdWordDelims);
writeLn(format(revisionNotice, [elementRevision]));
writeln(length(words));
writeln(words[high(words)]);
readln;
end. |
http://rosettacode.org/wiki/List_rooted_trees | List rooted trees | You came back from grocery shopping. After putting away all the goods, you are left with a pile of plastic bags, which you want to save for later use, so you take one bag and stuff all the others into it, and throw it under the sink. In doing so, you realize that there are various ways of nesting the bags, with all bags viewed as identical.
If we use a matching pair of parentheses to represent a bag, the ways are:
For 1 bag, there's one way:
() <- a bag
for 2 bags, there's one way:
(()) <- one bag in another
for 3 bags, there are two:
((())) <- 3 bags nested Russian doll style
(()()) <- 2 bags side by side, inside the third
for 4 bags, four:
(()()())
((())())
((()()))
(((())))
Note that because all bags are identical, the two 4-bag strings ((())()) and (()(())) represent the same configuration.
It's easy to see that each configuration for n bags represents a n-node rooted tree, where a bag is a tree node, and a bag with its content forms a subtree. The outermost bag is the tree root. Number of configurations for given n is given by OEIS A81.
Task
Write a program that, when given n, enumerates all ways of nesting n bags. You can use the parentheses notation above, or any tree representation that's unambiguous and preferably intuitive.
This task asks for enumeration of trees only; for counting solutions without enumeration, that OEIS page lists various formulas, but that's not encouraged by this task, especially if implementing it would significantly increase code size.
As an example output, run 5 bags. There should be 9 ways.
| #C.2B.2B | C++ | #include <iostream>
#include <vector>
std::vector<long> TREE_LIST;
std::vector<int> OFFSET;
void init() {
for (size_t i = 0; i < 32; i++) {
if (i == 1) {
OFFSET.push_back(1);
} else {
OFFSET.push_back(0);
}
}
}
void append(long t) {
TREE_LIST.push_back(1 | (t << 1));
}
void show(long t, int l) {
while (l-- > 0) {
if (t % 2 == 1) {
std::cout << '(';
} else {
std::cout << ')';
}
t = t >> 1;
}
}
void listTrees(int n) {
for (int i = OFFSET[n]; i < OFFSET[n + 1]; i++) {
show(TREE_LIST[i], 2 * n);
std::cout << '\n';
}
}
void assemble(int n, long t, int sl, int pos, int rem) {
if (rem == 0) {
append(t);
return;
}
auto pp = pos;
auto ss = sl;
if (sl > rem) {
ss = rem;
pp = OFFSET[ss];
} else if (pp >= OFFSET[ss + 1]) {
ss--;
if (ss == 0) {
return;
}
pp = OFFSET[ss];
}
assemble(n, t << (2 * ss) | TREE_LIST[pp], ss, pp, rem - ss);
assemble(n, t, ss, pp + 1, rem);
}
void makeTrees(int n) {
if (OFFSET[n + 1] != 0) {
return;
}
if (n > 0) {
makeTrees(n - 1);
}
assemble(n, 0, n - 1, OFFSET[n - 1], n - 1);
OFFSET[n + 1] = TREE_LIST.size();
}
void test(int n) {
if (n < 1 || n > 12) {
throw std::runtime_error("Argument must be between 1 and 12");
}
append(0);
makeTrees(n);
std::cout << "Number of " << n << "-trees: " << OFFSET[n + 1] - OFFSET[n] << '\n';
listTrees(n);
}
int main() {
init();
test(5);
return 0;
} |
http://rosettacode.org/wiki/Literals/Integer | Literals/Integer | Some programming languages have ways of expressing integer literals in bases other than the normal base ten.
Task
Show how integer literals can be expressed in as many bases as your language allows.
Note: this should not involve the calling of any functions/methods, but should be interpreted by the compiler or interpreter as an integer written to a given base.
Also show any other ways of expressing literals, e.g. for different types of integers.
Related task
Literals/Floating point
| #ALGOL_68 | ALGOL 68 | main:(
SHORT SHORT INT ssdec = SHORT SHORT 727,
sshex = ABS SHORT SHORT 16r2d7,
ssoct = ABS SHORT SHORT 8r1327,
ssbin = ABS SHORT SHORT 2r1011010111;
SHORT INT sdec = SHORT 727,
shex = ABS SHORT 16r2d7,
soct = ABS SHORT 8r1327,
sbin = ABS SHORT 2r1011010111;
INT dec = 727,
hex = ABS 16r2d7,
oct = ABS 8r1327,
bin = ABS 2r1011010111;
LONG INT ldec = LONG 727,
lhex = ABS LONG 16r2d7,
loct = ABS LONG 8r1327,
lbin = ABS LONG 2r1011010111;
CO
LONG LONG INT lldec = LONG LONG 727,
llhex = ABS LONG LONG 16r2d7,
lloct = ABS LONG LONG 8r1327,
llbin = ABS LONG LONG 2r1011010111
# etc ... #
END CO
print(("SHORT SHORT INT:", ssdec, sshex, ssoct, ssbin, new line));
print((" SHORT INT:", sdec, shex, soct, sbin, new line));
print((" INT:", dec, hex, oct, bin, new line));
print((" LONG INT:", ldec, lhex, loct, lbin, new line))
CO LONG LONG INT not supported by ELLA ALGOL 68RS
print(("LONG LONG INT:", new line, lldec, new line, llhex, new line, lloct, new line, llbin, new line))
# etc ... #
END CO
) |
http://rosettacode.org/wiki/Logical_operations | Logical operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a function that takes two logical (boolean) values, and outputs the result of "and" and "or" on both arguments as well as "not" on the first arguments.
If the programming language doesn't provide a separate type for logical values, use the type most commonly used for that purpose.
If the language supports additional logical operations on booleans such as XOR, list them as well.
| #360_Assembly | 360 Assembly | Op-codes
Or And Xor
--- --- ---
Memory to memory OC NC XC
Memory to register O N X
Immediate OI NI XI
|
http://rosettacode.org/wiki/Logical_operations | Logical operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a function that takes two logical (boolean) values, and outputs the result of "and" and "or" on both arguments as well as "not" on the first arguments.
If the programming language doesn't provide a separate type for logical values, use the type most commonly used for that purpose.
If the language supports additional logical operations on booleans such as XOR, list them as well.
| #6502_Assembly | 6502 Assembly | LDA myBoolean
BNE isTrue
;code that would execute if myBoolean is false, goes here.
RTS
isTrue:
;code that would execute if myBoolean is true, goes here.
RTS |
http://rosettacode.org/wiki/Loops/N_plus_one_half | Loops/N plus one half | Quite often one needs loops which, in the last iteration, execute only part of the loop body.
Goal
Demonstrate the best way to do this.
Task
Write a loop which writes the comma-separated list
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
using separate output statements for the number
and the comma from within the body of the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Stata | Stata | forv i=1/10 {
di `i' _continue
if `i'<10 {
di ", " _continue
}
else {
di
}
} |
http://rosettacode.org/wiki/Loops/N_plus_one_half | Loops/N plus one half | Quite often one needs loops which, in the last iteration, execute only part of the loop body.
Goal
Demonstrate the best way to do this.
Task
Write a loop which writes the comma-separated list
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
using separate output statements for the number
and the comma from within the body of the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Swift | Swift | for var i = 1; ; i++ {
print(i)
if i == 10 {
println()
break
}
print(", ")
} |
http://rosettacode.org/wiki/Literals/Floating_point | Literals/Floating point | Programming languages have different ways of expressing floating-point literals.
Task
Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features.
You may want to include a regular expression or BNF/ABNF/EBNF defining allowable formats for your language.
Related tasks
Literals/Integer
Extreme floating point values
| #bc | bc | 12.34 .34 99. ABC.DEF |
http://rosettacode.org/wiki/Literals/Floating_point | Literals/Floating point | Programming languages have different ways of expressing floating-point literals.
Task
Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features.
You may want to include a regular expression or BNF/ABNF/EBNF defining allowable formats for your language.
Related tasks
Literals/Integer
Extreme floating point values
| #C | C | ((\d*\.\d+|\d+\.)([eE][+-]?[0-9]+)?[flFL]?)|([0-9]+[eE][+-]?[0-9]+[flFL]?) |
http://rosettacode.org/wiki/Literals/Floating_point | Literals/Floating point | Programming languages have different ways of expressing floating-point literals.
Task
Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features.
You may want to include a regular expression or BNF/ABNF/EBNF defining allowable formats for your language.
Related tasks
Literals/Integer
Extreme floating point values
| #C.23 | C# | double d = 1;
d = 1d;
d = 1D;
d = 1.2; //double is the default if there's no suffix
d = 1.2d; //The suffix is redundant here
d = .2;
d = 12e-12;
d = 12E-12;
d = 1_234e-1_2; //digit separators are allowed since C# 7
float f = 1;
f = 1f;
f = 1F;
f = 1.2f;
f = .2f;
f = 12e-12f;
f = 12E-12f;
f = 1_234e-1_2f;
decimal m = 1;
m = 1m;
m = 1m;
m = 1.2m;
m = .2m;
m = 12e-12m;
m = 12E-12m;
m = 1_234e-1_2m; |
http://rosettacode.org/wiki/Long_year | Long year | Most years have 52 weeks, some have 53, according to ISO8601.
Task
Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
| #CLU | CLU | % We can't hide one procedure inside another, but
% we can hide the helper `p' in a cluster
longyear = cluster is test
rep = null
p = proc (n: int) returns (int)
return ((n + n/4 - n/100 + n/400) // 7)
end p
test = proc (y: int) returns (bool)
return (p(y)=4 | p(y-1)=3)
end test
end longyear
start_up = proc ()
po: stream := stream$primary_output()
for i: int in int$from_to(2000, 2100) do
if longyear$test(i) then
stream$putl(po, int$unparse(i))
end
end
end start_up |
http://rosettacode.org/wiki/Long_year | Long year | Most years have 52 weeks, some have 53, according to ISO8601.
Task
Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
| #Common_Lisp | Common Lisp | (defun december-31-weekday (year)
(mod (+ year (floor year 4) (- (floor year 100)) (floor year 400)) 7))
(defun iso-long-year-p (year)
(or (= 4 (december-31-weekday year)) (= 3 (december-31-weekday (1- year)))))
(format t "Long years between 1800 and 2100:~&~a~%"
(loop for y from 1800 to 2100 if (iso-long-year-p y) collect y)) |
http://rosettacode.org/wiki/Long_primes | Long primes |
A long prime (as defined here) is a prime number whose reciprocal (in decimal) has
a period length of one less than the prime number.
Long primes are also known as:
base ten cyclic numbers
full reptend primes
golden primes
long period primes
maximal period primes
proper primes
Another definition: primes p such that the decimal expansion of 1/p has period p-1, which is the greatest period possible for any integer.
Example
7 is the first long prime, the reciprocal of seven
is 1/7, which
is equal to the repeating decimal fraction 0.142857142857···
The length of the repeating part of the decimal fraction
is six, (the underlined part) which is one less
than the (decimal) prime number 7.
Thus 7 is a long prime.
There are other (more) general definitions of a long prime which
include wording/verbiage for bases other than ten.
Task
Show all long primes up to 500 (preferably on one line).
Show the number of long primes up to 500
Show the number of long primes up to 1,000
Show the number of long primes up to 2,000
Show the number of long primes up to 4,000
Show the number of long primes up to 8,000
Show the number of long primes up to 16,000
Show the number of long primes up to 32,000
Show the number of long primes up to 64,000 (optional)
Show all output here.
Also see
Wikipedia: full reptend prime
MathWorld: full reptend prime
OEIS: A001913
| #Delphi | Delphi |
// Return true if prime n is a long prime. Nigel Galloway: September 25th., 2018
let fN n g = let rec fN i g e l = match e with | 0UL -> i
| _ when e%2UL = 1UL -> fN ((i*g)%l) ((g*g)%l) (e/2UL) l
| _ -> fN i ((g*g)%l) (e/2UL) l
fN 1UL 10UL (uint64 g) (uint64 n)
let isLongPrime n=Seq.length (factors (n-1) |> Seq.filter(fun g->(fN n g)=1UL))=1
|
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously | Loop over multiple arrays simultaneously | Task
Loop over multiple arrays (or lists or tuples or whatever they're called in
your language) and display the i th element of each.
Use your language's "for each" loop if it has one, otherwise iterate
through the collection in order with some other loop.
For this example, loop over the arrays:
(a,b,c)
(A,B,C)
(1,2,3)
to produce the output:
aA1
bB2
cC3
If possible, also describe what happens when the arrays are of different lengths.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Axe | Axe | 'a'→{L₁}
'b'→{L₁+1}
'c'→{L₁+2}
'A'→{L₂}
'B'→{L₂+1}
'C'→{L₂+2}
1→{L₃}
2→{L₃+1}
3→{L₃+2}
For(I,0,2)
Disp {L₁+I}►Char,{L₂+I}►Char,{L₃+I}►Dec,i
End |
http://rosettacode.org/wiki/Loops/Break | Loops/Break | Task
Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive).
If a number is 10, stop the loop after printing it, and do not generate any further numbers.
Otherwise, generate and print a second random number before restarting the loop.
If the number 10 is never generated as the first number in a loop, loop forever.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
| #C | C |
int main(){
time_t t;
int a, b;
srand((unsigned)time(&t));
for(;;){
a = rand() % 20;
printf("%d\n", a);
if(a == 10)
break;
b = rand() % 20;
printf("%d\n", b);
}
return 0;
} |
http://rosettacode.org/wiki/Longest_common_subsequence | Longest common subsequence | Introduction
Define a subsequence to be any output string obtained by deleting zero or more symbols from an input string.
The Longest Common Subsequence (LCS) is a subsequence of maximum length common to two or more strings.
Let A ≡ A[0]… A[m - 1] and B ≡ B[0]… B[n - 1], m < n be strings drawn from an alphabet Σ of size s, containing every distinct symbol in A + B.
An ordered pair (i, j) will be referred to as a match if A[i] = B[j], where 0 < i ≤ m and 0 < j ≤ n.
Define a non-strict product-order (≤) over ordered pairs, such that (i1, j1) ≤ (i2, j2) ⇔ i1 ≤ i2 and j1 ≤ j2. We define (≥) similarly.
We say m1, m2 are comparable if either m1 ≤ m2 or m1 ≥ m2 holds. If i1 < i2 and j2 < j1 (or i2 < i1 and j1 < j2) then neither m1 ≤ m2 nor m1 ≥ m2 are possible; and we say m1, m2 are incomparable.
We also define the strict product-order (<) over ordered pairs, such that (i1, j1) < (i2, j2) ⇔ i1 < i2 and j1 < j2. We define (>) similarly.
Given a set of matches M, a chain C is a subset of M consisting of at least one element m; and where either m1 < m2 or m1 > m2 for every pair of distinct elements m1 and m2. An antichain D is any subset of M in which every pair of distinct elements m1 and m2 are incomparable.
The set M represents a relation over match pairs: M[i, j] ⇔ (i, j) ∈ M. A chain C can be visualized as a curve which strictly increases as it passes through each match pair in the m*n coordinate space.
Finding an LCS can be restated as the problem of finding a chain of maximum cardinality p over the set of matches M.
According to [Dilworth 1950], this cardinality p equals the minimum number of disjoint antichains into which M can be decomposed. Note that such a decomposition into the minimal number p of disjoint antichains may not be unique.
Contours
Forward Contours FC[k] of class k are defined inductively, as follows:
FC[0] consists of those elements m1 for which there exists no element m2 such that m2 < m1.
FC[k] consists of those elements m1 for which there exists no element m2 such that m2 < m1; and where neither m1 nor m2 are contained in FC[l] for any class l < k.
Reverse Contours RC[k] of class k are defined similarly.
Members of the Meet (∧), or Infimum of a Forward Contour are referred to as its Dominant Matches: those m1 for which there exists no m2 such that m2 < m1.
Members of the Join (∨), or Supremum of a Reverse Contour are referred to as its Dominant Matches: those m1 for which there exists no m2 such that m2 > m1.
Where multiple Dominant Matches exist within a Meet (or within a Join, respectively) the Dominant Matches will be incomparable to each other.
Background
Where the number of symbols appearing in matches is small relative to the length of the input strings, reuse of the symbols increases; and the number of matches will tend towards quadratic, O(m*n) growth. This occurs, for example, in the Bioinformatics application of nucleotide and protein sequencing.
The divide-and-conquer approach of [Hirschberg 1975] limits the space required to O(n). However, this approach requires O(m*n) time even in the best case.
This quadratic time dependency may become prohibitive, given very long input strings. Thus, heuristics are often favored over optimal Dynamic Programming solutions.
In the application of comparing file revisions, records from the input files form a large symbol space; and the number of symbols approaches the length of the LCS. In this case the number of matches reduces to linear, O(n) growth.
A binary search optimization due to [Hunt and Szymanski 1977] can be applied to the basic Dynamic Programming approach, resulting in an expected performance of O(n log m). Performance can degrade to O(m*n log m) time in the worst case, as the number of matches grows to O(m*n).
Note
[Rick 2000] describes a linear-space algorithm with a time bound of O(n*s + p*min(m, n - p)).
Legend
A, B are input strings of lengths m, n respectively
p is the length of the LCS
M is the set of match pairs (i, j) such that A[i] = B[j]
r is the magnitude of M
s is the magnitude of the alphabet Σ of distinct symbols in A + B
References
[Dilworth 1950] "A decomposition theorem for partially ordered sets"
by Robert P. Dilworth, published January 1950,
Annals of Mathematics [Volume 51, Number 1, pp. 161-166]
[Goeman and Clausen 2002] "A New Practical Linear Space Algorithm for the Longest Common
Subsequence Problem" by Heiko Goeman and Michael Clausen,
published 2002, Kybernetika [Volume 38, Issue 1, pp. 45-66]
[Hirschberg 1975] "A linear space algorithm for computing maximal common subsequences"
by Daniel S. Hirschberg, published June 1975
Communications of the ACM [Volume 18, Number 6, pp. 341-343]
[Hunt and McIlroy 1976] "An Algorithm for Differential File Comparison"
by James W. Hunt and M. Douglas McIlroy, June 1976
Computing Science Technical Report, Bell Laboratories 41
[Hunt and Szymanski 1977] "A Fast Algorithm for Computing Longest Common Subsequences"
by James W. Hunt and Thomas G. Szymanski, published May 1977
Communications of the ACM [Volume 20, Number 5, pp. 350-353]
[Rick 2000] "Simple and fast linear space computation of longest common subsequences"
by Claus Rick, received 17 March 2000, Information Processing Letters,
Elsevier Science [Volume 75, pp. 275–281]
Examples
The sequences "1234" and "1224533324" have an LCS of "1234":
1234
1224533324
For a string example, consider the sequences "thisisatest" and "testing123testing". An LCS would be "tsitest":
thisisatest
testing123testing
In this puzzle, your code only needs to deal with strings. Write a function which returns an LCS of two strings (case-sensitive). You don't need to show multiple LCS's.
For more information on this problem please see Wikipedia.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #C.2B.2B | C++ | #include <stdint.h>
#include <string>
#include <memory> // for shared_ptr<>
#include <iostream>
#include <deque>
#include <unordered_map>
#include <algorithm> // for lower_bound()
#include <iterator> // for next() and prev()
using namespace std;
class LCS {
protected:
// This linked list class is used to trace the LCS candidates
class Pair {
public:
uint32_t index1;
uint32_t index2;
shared_ptr<Pair> next;
Pair(uint32_t index1, uint32_t index2, shared_ptr<Pair> next = nullptr)
: index1(index1), index2(index2), next(next) {
}
static shared_ptr<Pair> Reverse(const shared_ptr<Pair> pairs) {
shared_ptr<Pair> head = nullptr;
for (auto next = pairs; next != nullptr; next = next->next)
head = make_shared<Pair>(next->index1, next->index2, head);
return head;
}
};
typedef deque<shared_ptr<Pair>> PAIRS;
typedef deque<uint32_t> THRESHOLD;
typedef deque<uint32_t> INDEXES;
typedef unordered_map<char, INDEXES> CHAR_TO_INDEXES_MAP;
typedef deque<INDEXES*> MATCHES;
uint32_t FindLCS(MATCHES& indexesOf2MatchedByIndex1, shared_ptr<Pair>* pairs) {
auto traceLCS = pairs != nullptr;
PAIRS chains;
THRESHOLD threshold;
//
//[Assert]After each index1 iteration threshold[index3] is the least index2
// such that the LCS of s1[0:index1] and s2[0:index2] has length index3 + 1
//
uint32_t index1 = 0;
for (const auto& it1 : indexesOf2MatchedByIndex1) {
if (!it1->empty()) {
auto dq2 = *it1;
auto limit = threshold.end();
for (auto it2 = dq2.rbegin(); it2 != dq2.rend(); it2++) {
// Each of the index1, index2 pairs considered here correspond to a match
auto index2 = *it2;
//
// Note: The reverse iterator it2 visits index2 values in descending order,
// allowing thresholds to be updated in-place. std::lower_bound() is used
// to perform a binary search.
//
limit = lower_bound(threshold.begin(), limit, index2);
auto index3 = distance(threshold.begin(), limit);
//
// Look ahead to the next index2 value to optimize space used in the Hunt
// and Szymanski algorithm. If the next index2 is also an improvement on
// the value currently held in threshold[index3], a new Pair will only be
// superseded on the next index2 iteration.
//
// Depending on match redundancy, the number of Pair constructions may be
// divided by factors ranging from 2 up to 10 or more.
//
auto skipIndex2 = next(it2) != dq2.rend() &&
(limit == threshold.begin() || *prev(limit) < *next(it2));
if (skipIndex2) continue;
if (limit == threshold.end()) {
// Insert Case
threshold.push_back(index2);
// Refresh limit iterator:
limit = prev(threshold.end());
if (traceLCS) {
auto prefix = index3 > 0 ? chains[index3 - 1] : nullptr;
auto last = make_shared<Pair>(index1, index2, prefix);
chains.push_back(last);
}
}
else if (index2 < *limit) {
// Update Case
// Update limit value:
*limit = index2;
if (traceLCS) {
auto prefix = index3 > 0 ? chains[index3 - 1] : nullptr;
auto last = make_shared<Pair>(index1, index2, prefix);
chains[index3] = last;
}
}
} // next index2
}
index1++;
} // next index1
if (traceLCS) {
// Return the LCS as a linked list of matched index pairs:
auto last = chains.size() > 0 ? chains.back() : nullptr;
// Reverse longest chain
*pairs = Pair::Reverse(last);
}
auto length = threshold.size();
return length;
}
//
// Match() avoids m*n comparisons by using CHAR_TO_INDEXES_MAP to
// achieve O(m+n) performance, where m and n are the input lengths.
//
// The lookup time can be assumed constant in the case of characters.
// The symbol space is larger in the case of records; but the lookup
// time will be O(log(m+n)), at most.
//
void Match(CHAR_TO_INDEXES_MAP& indexesOf2MatchedByChar, MATCHES& indexesOf2MatchedByIndex1,
const string& s1, const string& s2) {
uint32_t index = 0;
for (const auto& it : s2)
indexesOf2MatchedByChar[it].push_back(index++);
for (const auto& it : s1) {
auto& dq2 = indexesOf2MatchedByChar[it];
indexesOf2MatchedByIndex1.push_back(&dq2);
}
}
string Select(shared_ptr<Pair> pairs, uint32_t length,
bool right, const string& s1, const string& s2) {
string buffer;
buffer.reserve(length);
for (auto next = pairs; next != nullptr; next = next->next) {
auto c = right ? s2[next->index2] : s1[next->index1];
buffer.push_back(c);
}
return buffer;
}
public:
string Correspondence(const string& s1, const string& s2) {
CHAR_TO_INDEXES_MAP indexesOf2MatchedByChar;
MATCHES indexesOf2MatchedByIndex1; // holds references into indexesOf2MatchedByChar
Match(indexesOf2MatchedByChar, indexesOf2MatchedByIndex1, s1, s2);
shared_ptr<Pair> pairs; // obtain the LCS as index pairs
auto length = FindLCS(indexesOf2MatchedByIndex1, &pairs);
return Select(pairs, length, false, s1, s2);
}
}; |
http://rosettacode.org/wiki/Look-and-say_sequence | Look-and-say sequence | The Look and say sequence is a recursively defined sequence of numbers studied most notably by John Conway.
The look-and-say sequence is also known as the Morris Number Sequence, after cryptographer Robert Morris, and the puzzle What is the next number in the sequence 1, 11, 21, 1211, 111221? is sometimes referred to as the Cuckoo's Egg, from a description of Morris in Clifford Stoll's book The Cuckoo's Egg.
Sequence Definition
Take a decimal number
Look at the number, visually grouping consecutive runs of the same digit.
Say the number, from left to right, group by group; as how many of that digit there are - followed by the digit grouped.
This becomes the next number of the sequence.
An example:
Starting with the number 1, you have one 1 which produces 11
Starting with 11, you have two 1's. I.E.: 21
Starting with 21, you have one 2, then one 1. I.E.: (12)(11) which becomes 1211
Starting with 1211, you have one 1, one 2, then two 1's. I.E.: (11)(12)(21) which becomes 111221
Task
Write a program to generate successive members of the look-and-say sequence.
Related tasks
Fours is the number of letters in the ...
Number names
Self-describing numbers
Self-referential sequence
Spelling of ordinal numbers
See also
Look-and-Say Numbers (feat John Conway), A Numberphile Video.
This task is related to, and an application of, the Run-length encoding task.
Sequence A005150 on The On-Line Encyclopedia of Integer Sequences.
| #BASIC256 | BASIC256 |
# look and say
dim a$(2)
i = 0 # input string index
a$[i] = "1"
print a$[i]
for n=1 to 10
j = 1 - i # output string index
a$[j] = ""
k = 1
while (k <= length(a$[i]))
k0 = k + 1
while ((k0 <= length(a$[i])) and (mid(a$[i], k, 1) = mid(a$[i], k0, 1)))
k0 = k0 + 1
end while
a$[j] += string(k0 - k) + mid(a$[i], k, 1)
k = k0
end while
i = j
print a$[j]
next n
|
http://rosettacode.org/wiki/Longest_string_challenge | Longest string challenge | Background
This "longest string challenge" is inspired by a problem that used to be given to students learning Icon. Students were expected to try to solve the problem in Icon and another language with which the student was already familiar. The basic problem is quite simple; the challenge and fun part came through the introduction of restrictions. Experience has shown that the original restrictions required some adjustment to bring out the intent of the challenge and make it suitable for Rosetta Code.
Basic problem statement
Write a program that reads lines from standard input and, upon end of file, writes the longest line to standard output.
If there are ties for the longest line, the program writes out all the lines that tie.
If there is no input, the program should produce no output.
Task
Implement a solution to the basic problem that adheres to the spirit of the restrictions (see below).
Describe how you circumvented or got around these 'restrictions' and met the 'spirit' of the challenge. Your supporting description may need to describe any challenges to interpreting the restrictions and how you made this interpretation. You should state any assumptions, warnings, or other relevant points. The central idea here is to make the task a bit more interesting by thinking outside of the box and perhaps by showing off the capabilities of your language in a creative way. Because there is potential for considerable variation between solutions, the description is key to helping others see what you've done.
This task is likely to encourage a variety of different types of solutions. They should be substantially different approaches.
Given the input:
a
bb
ccc
ddd
ee
f
ggg
the output should be (possibly rearranged):
ccc
ddd
ggg
Original list of restrictions
No comparison operators may be used.
No arithmetic operations, such as addition and subtraction, may be used.
The only datatypes you may use are integer and string. In particular, you may not use lists.
Do not re-read the input file. Avoid using files as a replacement for lists (this restriction became apparent in the discussion).
Intent of restrictions
Because of the variety of languages on Rosetta Code and the wide variety of concepts used in them, there needs to be a bit of clarification and guidance here to get to the spirit of the challenge and the intent of the restrictions.
The basic problem can be solved very conventionally, but that's boring and pedestrian. The original intent here wasn't to unduly frustrate people with interpreting the restrictions, it was to get people to think outside of their particular box and have a bit of fun doing it.
The guiding principle here should be to be creative in demonstrating some of the capabilities of the programming language being used. If you need to bend the restrictions a bit, explain why and try to follow the intent. If you think you've implemented a 'cheat', call out the fragment yourself and ask readers if they can spot why. If you absolutely can't get around one of the restrictions, explain why in your description.
Now having said that, the restrictions require some elaboration.
In general, the restrictions are meant to avoid the explicit use of these features.
"No comparison operators may be used" - At some level there must be some test that allows the solution to get at the length and determine if one string is longer. Comparison operators, in particular any less/greater comparison should be avoided. Representing the length of any string as a number should also be avoided. Various approaches allow for detecting the end of a string. Some of these involve implicitly using equal/not-equal; however, explicitly using equal/not-equal should be acceptable.
"No arithmetic operations" - Again, at some level something may have to advance through the string. Often there are ways a language can do this implicitly advance a cursor or pointer without explicitly using a +, - , ++, --, add, subtract, etc.
The datatype restrictions are amongst the most difficult to reinterpret. In the language of the original challenge strings are atomic datatypes and structured datatypes like lists are quite distinct and have many different operations that apply to them. This becomes a bit fuzzier with languages with a different programming paradigm. The intent would be to avoid using an easy structure to accumulate the longest strings and spit them out. There will be some natural reinterpretation here.
To make this a bit more concrete, here are a couple of specific examples:
In C, a string is an array of chars, so using a couple of arrays as strings is in the spirit while using a second array in a non-string like fashion would violate the intent.
In APL or J, arrays are the core of the language so ruling them out is unfair. Meeting the spirit will come down to how they are used.
Please keep in mind these are just examples and you may hit new territory finding a solution. There will be other cases like these. Explain your reasoning. You may want to open a discussion on the talk page as well.
The added "No rereading" restriction is for practical reasons, re-reading stdin should be broken. I haven't outright banned the use of other files but I've discouraged them as it is basically another form of a list. Somewhere there may be a language that just sings when doing file manipulation and where that makes sense; however, for most there should be a way to accomplish without resorting to an externality.
At the end of the day for the implementer this should be a bit of fun. As an implementer you represent the expertise in your language, the reader may have no knowledge of your language. For the reader it should give them insight into how people think outside the box in other languages. Comments, especially for non-obvious (to the reader) bits will be extremely helpful. While the implementations may be a bit artificial in the context of this task, the general techniques may be useful elsewhere.
| #Nanoquery | Nanoquery | import Nanoquery.IO
def longer(a, b)
try
b[len(a)-1]
return false
catch
return true
end
end
print "enter filename: "
$f = new(File, input())
longest = ""
lines = ""
for x in $f.read()
if longer(x, longest)
lines = x
longest = x
else if !longer(longest, x)
lines += "\n" + x
end
end
println lines |
http://rosettacode.org/wiki/Longest_string_challenge | Longest string challenge | Background
This "longest string challenge" is inspired by a problem that used to be given to students learning Icon. Students were expected to try to solve the problem in Icon and another language with which the student was already familiar. The basic problem is quite simple; the challenge and fun part came through the introduction of restrictions. Experience has shown that the original restrictions required some adjustment to bring out the intent of the challenge and make it suitable for Rosetta Code.
Basic problem statement
Write a program that reads lines from standard input and, upon end of file, writes the longest line to standard output.
If there are ties for the longest line, the program writes out all the lines that tie.
If there is no input, the program should produce no output.
Task
Implement a solution to the basic problem that adheres to the spirit of the restrictions (see below).
Describe how you circumvented or got around these 'restrictions' and met the 'spirit' of the challenge. Your supporting description may need to describe any challenges to interpreting the restrictions and how you made this interpretation. You should state any assumptions, warnings, or other relevant points. The central idea here is to make the task a bit more interesting by thinking outside of the box and perhaps by showing off the capabilities of your language in a creative way. Because there is potential for considerable variation between solutions, the description is key to helping others see what you've done.
This task is likely to encourage a variety of different types of solutions. They should be substantially different approaches.
Given the input:
a
bb
ccc
ddd
ee
f
ggg
the output should be (possibly rearranged):
ccc
ddd
ggg
Original list of restrictions
No comparison operators may be used.
No arithmetic operations, such as addition and subtraction, may be used.
The only datatypes you may use are integer and string. In particular, you may not use lists.
Do not re-read the input file. Avoid using files as a replacement for lists (this restriction became apparent in the discussion).
Intent of restrictions
Because of the variety of languages on Rosetta Code and the wide variety of concepts used in them, there needs to be a bit of clarification and guidance here to get to the spirit of the challenge and the intent of the restrictions.
The basic problem can be solved very conventionally, but that's boring and pedestrian. The original intent here wasn't to unduly frustrate people with interpreting the restrictions, it was to get people to think outside of their particular box and have a bit of fun doing it.
The guiding principle here should be to be creative in demonstrating some of the capabilities of the programming language being used. If you need to bend the restrictions a bit, explain why and try to follow the intent. If you think you've implemented a 'cheat', call out the fragment yourself and ask readers if they can spot why. If you absolutely can't get around one of the restrictions, explain why in your description.
Now having said that, the restrictions require some elaboration.
In general, the restrictions are meant to avoid the explicit use of these features.
"No comparison operators may be used" - At some level there must be some test that allows the solution to get at the length and determine if one string is longer. Comparison operators, in particular any less/greater comparison should be avoided. Representing the length of any string as a number should also be avoided. Various approaches allow for detecting the end of a string. Some of these involve implicitly using equal/not-equal; however, explicitly using equal/not-equal should be acceptable.
"No arithmetic operations" - Again, at some level something may have to advance through the string. Often there are ways a language can do this implicitly advance a cursor or pointer without explicitly using a +, - , ++, --, add, subtract, etc.
The datatype restrictions are amongst the most difficult to reinterpret. In the language of the original challenge strings are atomic datatypes and structured datatypes like lists are quite distinct and have many different operations that apply to them. This becomes a bit fuzzier with languages with a different programming paradigm. The intent would be to avoid using an easy structure to accumulate the longest strings and spit them out. There will be some natural reinterpretation here.
To make this a bit more concrete, here are a couple of specific examples:
In C, a string is an array of chars, so using a couple of arrays as strings is in the spirit while using a second array in a non-string like fashion would violate the intent.
In APL or J, arrays are the core of the language so ruling them out is unfair. Meeting the spirit will come down to how they are used.
Please keep in mind these are just examples and you may hit new territory finding a solution. There will be other cases like these. Explain your reasoning. You may want to open a discussion on the talk page as well.
The added "No rereading" restriction is for practical reasons, re-reading stdin should be broken. I haven't outright banned the use of other files but I've discouraged them as it is basically another form of a list. Somewhere there may be a language that just sings when doing file manipulation and where that makes sense; however, for most there should be a way to accomplish without resorting to an externality.
At the end of the day for the implementer this should be a bit of fun. As an implementer you represent the expertise in your language, the reader may have no knowledge of your language. For the reader it should give them insight into how people think outside the box in other languages. Comments, especially for non-obvious (to the reader) bits will be extremely helpful. While the implementations may be a bit artificial in the context of this task, the general techniques may be useful elsewhere.
| #Nim | Nim | import strutils
const
# Define int constants instead of an enum to use only ints and strings.
Shorter = -1
SameLength = 0
Longer = 1
type LengthComparison = range[Shorter..Longer]
func cmpLength(a, b: string): LengthComparison =
let a = repeat(' ', a.len)
let b = repeat(' ', b.len)
result = if a in b: (if b in a: SameLength else: Shorter) else: Longer
var longest = ""
var result = ""
for line in "longest_string_challenge.txt".lines:
case cmpLength(line, longest)
of Shorter:
discard
of SameLength:
result.add '\n' & line
of Longer:
longest = line
result = line
echo result |
http://rosettacode.org/wiki/Longest_increasing_subsequence | Longest increasing subsequence | Calculate and show here a longest increasing subsequence of the list:
{
3
,
2
,
6
,
4
,
5
,
1
}
{\displaystyle \{3,2,6,4,5,1\}}
And of the list:
{
0
,
8
,
4
,
12
,
2
,
10
,
6
,
14
,
1
,
9
,
5
,
13
,
3
,
11
,
7
,
15
}
{\displaystyle \{0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15\}}
Note that a list may have more than one subsequence that is of the maximum length.
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
Ref
Dynamic Programming #1: Longest Increasing Subsequence on YouTube
An efficient solution can be based on Patience sorting.
| #jq | jq | def until(cond; update):
def _until:
if cond then . else (update | _until) end;
try _until catch if .== "break" then empty else . end;
# binary search for insertion point
def bsearch(target):
. as $in
| [0, length-1] # [low, high]
| until(.[0] > .[1];
.[0] as $low | .[1] as $high
| ($low + ($high - $low) / 2 | floor) as $mid
| if $in[$mid] >= target
then .[1] = $mid - 1
else .[0] = $mid + 1
end )
| .[0]; |
http://rosettacode.org/wiki/Loops/Continue | Loops/Continue | Task
Show the following output using one loop.
1, 2, 3, 4, 5
6, 7, 8, 9, 10
Try to achieve the result by forcing the next iteration within the loop
upon a specific condition, if your language allows it.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #D | D | import std.stdio;
void main() {
foreach (i; 1 .. 11) {
write(i);
if (i % 5 == 0) {
writeln();
continue;
}
write(", ");
}
} |
http://rosettacode.org/wiki/Loops/Continue | Loops/Continue | Task
Show the following output using one loop.
1, 2, 3, 4, 5
6, 7, 8, 9, 10
Try to achieve the result by forcing the next iteration within the loop
upon a specific condition, if your language allows it.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #dc | dc | 1 si # i = 1
[2Q]sA # A = code to break loop
[[, ]P 1J]sB # B = code to print comma, continue loop
[
li n # print i
li 5 % 0 !=B # call B if i % 5
[
]P # print newline
M # mark from calling B
li 1 + si # i += 1
li 10!<C # continue loop if 10 >= i
]sC li 10!<C # enter loop if 10 >= i |
http://rosettacode.org/wiki/Longest_common_substring | Longest common substring | Task
Write a function that returns the longest common substring of two strings.
Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing".
Note that substrings are consecutive characters within a string. This distinguishes them from subsequences, which is any sequence of characters within a string, even if there are extraneous characters in between them.
Hence, the longest common subsequence between "thisisatest" and "testing123testing" is "tsitest", whereas the longest common substring is just "test".
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
References
Generalize Suffix Tree
Ukkonen’s Suffix Tree Construction
| #Go | Go | package main
import "fmt"
func lcs(a, b string) (output string) {
lengths := make([]int, len(a)*len(b))
greatestLength := 0
for i, x := range a {
for j, y := range b {
if x == y {
if i == 0 || j == 0 {
lengths[i*len(b)+j] = 1
} else {
lengths[i*len(b)+j] = lengths[(i-1)*len(b)+j-1] + 1
}
if lengths[i*len(b)+j] > greatestLength {
greatestLength = lengths[i*len(b)+j]
output = a[i-greatestLength+1 : i+1]
}
}
}
}
return
}
func main() {
fmt.Println(lcs("thisisatest", "testing123testing"))
} |
http://rosettacode.org/wiki/Loops/Nested | Loops/Nested | Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over
[
1
,
…
,
20
]
{\displaystyle [1,\ldots ,20]}
.
The loops iterate rows and columns of the array printing the elements until the value
20
{\displaystyle 20}
is met.
Specifically, this task also shows how to break out of nested loops.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Scheme | Scheme | (call-with-current-continuation
(lambda (return)
(for-each (lambda (a)
(for-each (lambda (b)
(cond ((= 20 b)
(newline)
(return))
(else
(display " ")(display b))))
a)
(newline))
array))) |
http://rosettacode.org/wiki/Loops/Nested | Loops/Nested | Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over
[
1
,
…
,
20
]
{\displaystyle [1,\ldots ,20]}
.
The loops iterate rows and columns of the array printing the elements until the value
20
{\displaystyle 20}
is met.
Specifically, this task also shows how to break out of nested loops.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Scilab | Scilab | ni=3;nj=4
t=int(rand(ni,nj)*20)+1
for i=1:ni
for j=1:nj
printf("%2d ",t(i,j))
if t(i,j)==11 then break; end
end
printf("\n")
if t(i,j)==11 then break; end
end |
http://rosettacode.org/wiki/Loops/Foreach | Loops/Foreach | Loop through and print each element in a collection in order.
Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Vim_Script | Vim Script | for i in ["alpha", "beta", 42, 5.54]
echo i
endfor |
http://rosettacode.org/wiki/Loops/Foreach | Loops/Foreach | Loop through and print each element in a collection in order.
Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Vlang | Vlang | fn print_all(values []int) {
for i, x in values {
println("Item $i = $x")
}
} |
http://rosettacode.org/wiki/Loops/Foreach | Loops/Foreach | Loop through and print each element in a collection in order.
Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Wart | Wart | each x '(1 2 3)
prn x |
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers | Luhn test of credit card numbers | The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits.
Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test:
Reverse the order of the digits in the number.
Take the first, third, ... and every other odd digit in the reversed digits and sum them to form the partial sum s1
Taking the second, fourth ... and every other even digit in the reversed digits:
Multiply each digit by two and sum the digits if the answer is greater than nine to form partial sums for the even digits
Sum the partial sums of the even digits to form s2
If s1 + s2 ends in zero then the original number is in the form of a valid credit card number as verified by the Luhn test.
For example, if the trial number is 49927398716:
Reverse the digits:
61789372994
Sum the odd digits:
6 + 7 + 9 + 7 + 9 + 4 = 42 = s1
The even digits:
1, 8, 3, 2, 9
Two times each even digit:
2, 16, 6, 4, 18
Sum the digits of each multiplication:
2, 7, 6, 4, 9
Sum the last:
2 + 7 + 6 + 4 + 9 = 28 = s2
s1 + s2 = 70 which ends in zero which means that 49927398716 passes the Luhn test
Task
Write a function/method/procedure/subroutine that will validate a number with the Luhn test, and
use it to validate the following numbers:
49927398716
49927398717
1234567812345678
1234567812345670
Related tasks
SEDOL
ISIN
| #Oz | Oz | declare
fun {Luhn N}
{Sum {List.mapInd {Reverse {Digits N}}
fun {$ Idx Dig}
if {IsEven Idx} then {Sum {Digits 2*Dig}}
else Dig
end
end}}
mod 10 == 0
end
fun {Digits N}
{Map {Int.toString N} fun {$ D} D - &0 end}
end
fun {Sum Xs}
{FoldL Xs Number.'+' 0}
end
in
{Show
{Map
[49927398716 49927398717 1234567812345678 1234567812345670]
Luhn}} |
http://rosettacode.org/wiki/Loops/Infinite | Loops/Infinite | Task
Print out SPAM followed by a newline in an infinite loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #PostScript | PostScript | {}loop |
http://rosettacode.org/wiki/Loops/Infinite | Loops/Infinite | Task
Print out SPAM followed by a newline in an infinite loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #PowerShell | PowerShell | for () {
"SPAM"
} |
http://rosettacode.org/wiki/Loops/While | Loops/While | Task
Start an integer value at 1024.
Loop while it is greater than zero.
Print the value (with a newline) and divide it by two each time through the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreachbas
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #PARI.2FGP | PARI/GP | n=1024;
while(n,
print(n);
n/=2
); |
http://rosettacode.org/wiki/Loops/While | Loops/While | Task
Start an integer value at 1024.
Loop while it is greater than zero.
Print the value (with a newline) and divide it by two each time through the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreachbas
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Pascal | Pascal | program divby2(output);
var
i: integer;
begin
i := 1024;
while i > 0 do
begin
writeln(i);
i := i div 2
end
end. |
http://rosettacode.org/wiki/Loops/Downward_for | Loops/Downward for | Task
Write a for loop which writes a countdown from 10 to 0.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #PowerShell | PowerShell | for ($i = 10; $i -ge 0; $i--) {
$i
} |
http://rosettacode.org/wiki/Loops/Downward_for | Loops/Downward for | Task
Write a for loop which writes a countdown from 10 to 0.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Prolog | Prolog | rfor(Hi,Lo,Hi) :- Hi >= Lo.
rfor(Hi,Lo,Val) :- Hi > Lo, H is Hi - 1, !, rfor(H,Lo,Val).
reverse_iter :-
rfor(10,0,Val), write(Val), nl, fail.
reverse_iter. |
http://rosettacode.org/wiki/Loops/Do-while | Loops/Do-while | Start with a value at 0. Loop while value mod 6 is not equal to 0.
Each time through the loop, add 1 to the value then print it.
The loop must execute at least once.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
Reference
Do while loop Wikipedia.
| #Metafont | Metafont | a := 0;
forever: show a; a := a + 1; exitif a mod 6 = 0; endfor
end |
http://rosettacode.org/wiki/Loops/Do-while | Loops/Do-while | Start with a value at 0. Loop while value mod 6 is not equal to 0.
Each time through the loop, add 1 to the value then print it.
The loop must execute at least once.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
Reference
Do while loop Wikipedia.
| #Microsoft_Small_Basic | Microsoft Small Basic |
i = 0
' first iteration - before the While
i = i + 1
TextWindow.WriteLine(i)
While Math.Remainder(i, 6) <> 0
i = i + 1
TextWindow.WriteLine(i)
EndWhile
|
http://rosettacode.org/wiki/Loops/For | Loops/For | “For” loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code.
Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers.
Task
Show how two loops may be nested within each other, with the number of iterations performed by the inner for loop being controlled by the outer for loop.
Specifically print out the following pattern by using one for loop nested in another:
*
**
***
****
*****
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
Reference
For loop Wikipedia.
| #FOCAL | FOCAL | 01.10 FOR I=1,4; DO 2.0
02.10 FOR J=1,I; TYPE "*"
02.20 TYPE ! |
http://rosettacode.org/wiki/Loops/For_with_a_specified_step | Loops/For with a specified step |
Task
Demonstrate a for-loop where the step-value is greater than one.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Lingo | Lingo | step = 3
repeat with i = 0 to 10
put i
i = i + (step-1)
end repeat |
http://rosettacode.org/wiki/Loops/For_with_a_specified_step | Loops/For with a specified step |
Task
Demonstrate a for-loop where the step-value is greater than one.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Lisaac | Lisaac | 1.to 9 by 2 do { i : INTEGER;
i.print;
'\n'.print;
}; |
http://rosettacode.org/wiki/Long_multiplication | Long multiplication | Task
Explicitly implement long multiplication.
This is one possible approach to arbitrary-precision integer algebra.
For output, display the result of 264 * 264.
Optionally, verify your result against builtin arbitrary precision support.
The decimal representation of 264 is:
18,446,744,073,709,551,616
The output of 264 * 264 is 2128, and is:
340,282,366,920,938,463,463,374,607,431,768,211,456
| #Aime | Aime | data b, c, v;
integer d, e, i, j, s;
b = 1.argv;
b.dump(',');
v = 2.argv;
v.dump(',');
c.run(~b + ~v + 1, 0);
for (i, d in b) {
b[i] = d - '0';
}
for (j, d of v) {
d = v[j] - '0';
s = 0;
for (i, e of b) {
s += e * d + c[i + j];
c[i + j] = s % 10;
s /= 10;
}
while (s) {
s += c[i + j];
c[i + j] = s % 10;
s /= 10;
i -= 1;
}
}
c.delete(-1);
c.bf_drop0("");
for (i, d in c) {
c[i] = d + '0';
}
o_form("~\n", c); |
http://rosettacode.org/wiki/Literals/String | Literals/String | Task
Show literal specification of characters and strings.
If supported, show how the following work:
verbatim strings (quotes where escape sequences are quoted literally)
here-strings
Also, discuss which quotes expand variables.
Related tasks
Special characters
Here document
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #ALGOL_68 | ALGOL 68 | CHAR charx = "z"; |
http://rosettacode.org/wiki/Literals/String | Literals/String | Task
Show literal specification of characters and strings.
If supported, show how the following work:
verbatim strings (quotes where escape sequences are quoted literally)
here-strings
Also, discuss which quotes expand variables.
Related tasks
Special characters
Here document
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #ALGOL_W | ALGOL W | begin
% String literals are enclosed in double-quotes in Algol W. %
% There isn't a separate character type but strings of lenghth one can %
% be used instead. %
% There are no escaping conventions used in string literals, except that %
% in order to have a double-quote character in a string, two double %
% quotes must be used. %
% Examples: %
% write a single character %
write( "a" );
% write a double-quote character %
write( """" );
% write a multi-character string - note the "\" is not an escape %
% and a\nb will appear on the output, not a and b on separate lines %
write( "a\nb" );
end. |
http://rosettacode.org/wiki/Long_literals,_with_continuations | Long literals, with continuations | This task is about writing a computer program that has long literals (character
literals that may require specifying the words/tokens on more than one (source)
line, either with continuations or some other method, such as abutments or
concatenations (or some other mechanisms).
The literal is to be in the form of a "list", a literal that contains many
words (tokens) separated by a blank (space), in this case (so as to have a
common list), the (English) names of the chemical elements of the periodic table.
The list is to be in (ascending) order of the (chemical) element's atomic number:
hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium aluminum silicon ...
... up to the last known (named) chemical element (at this time).
Do not include any of the "unnamed" chemical element names such as:
ununennium unquadnilium triunhexium penthextrium penthexpentium septhexunium octenntrium ennennbium
To make computer programming languages comparable, the statement widths should be
restricted to less than 81 bytes (characters), or less
if a computer programming language has more restrictive limitations or standards.
Also mention what column the programming statements can start in if not
in column one.
The list may have leading/embedded/trailing blanks during the
declaration (the actual program statements), this is allow the list to be
more readable. The "final" list shouldn't have any leading/trailing or superfluous
blanks (when stored in the program's "memory").
This list should be written with the idea in mind that the
program will be updated, most likely someone other than the
original author, as there will be newer (discovered) elements of the periodic
table being added (possibly in the near future). These future updates
should be one of the primary concerns in writing these programs and it should be "easy"
for someone else to add chemical elements to the list (within the computer
program).
Attention should be paid so as to not exceed the clause length of
continued or specified statements, if there is such a restriction. If the
limit is greater than (say) 4,000 bytes or so, it needn't be mentioned here.
Task
Write a computer program (by whatever name) to contain a list of the known elements.
The program should eventually contain a long literal of words (the elements).
The literal should show how one could create a long list of blank-delineated words.
The "final" (stored) list should only have a single blank between elements.
Try to use the most idiomatic approach(es) in creating the final list.
Use continuation if possible, and/or show alternatives (possibly using concatenation).
Use a program comment to explain what the continuation character is if it isn't obvious.
The program should contain a variable that has the date of the last update/revision.
The program, when run, should display with verbiage:
The last update/revision date (and should be unambiguous).
The number of chemical elements in the list.
The name of the highest (last) element name.
Show all output here, on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Factor | Factor | qw{ a bc d } |
http://rosettacode.org/wiki/Long_literals,_with_continuations | Long literals, with continuations | This task is about writing a computer program that has long literals (character
literals that may require specifying the words/tokens on more than one (source)
line, either with continuations or some other method, such as abutments or
concatenations (or some other mechanisms).
The literal is to be in the form of a "list", a literal that contains many
words (tokens) separated by a blank (space), in this case (so as to have a
common list), the (English) names of the chemical elements of the periodic table.
The list is to be in (ascending) order of the (chemical) element's atomic number:
hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium aluminum silicon ...
... up to the last known (named) chemical element (at this time).
Do not include any of the "unnamed" chemical element names such as:
ununennium unquadnilium triunhexium penthextrium penthexpentium septhexunium octenntrium ennennbium
To make computer programming languages comparable, the statement widths should be
restricted to less than 81 bytes (characters), or less
if a computer programming language has more restrictive limitations or standards.
Also mention what column the programming statements can start in if not
in column one.
The list may have leading/embedded/trailing blanks during the
declaration (the actual program statements), this is allow the list to be
more readable. The "final" list shouldn't have any leading/trailing or superfluous
blanks (when stored in the program's "memory").
This list should be written with the idea in mind that the
program will be updated, most likely someone other than the
original author, as there will be newer (discovered) elements of the periodic
table being added (possibly in the near future). These future updates
should be one of the primary concerns in writing these programs and it should be "easy"
for someone else to add chemical elements to the list (within the computer
program).
Attention should be paid so as to not exceed the clause length of
continued or specified statements, if there is such a restriction. If the
limit is greater than (say) 4,000 bytes or so, it needn't be mentioned here.
Task
Write a computer program (by whatever name) to contain a list of the known elements.
The program should eventually contain a long literal of words (the elements).
The literal should show how one could create a long list of blank-delineated words.
The "final" (stored) list should only have a single blank between elements.
Try to use the most idiomatic approach(es) in creating the final list.
Use continuation if possible, and/or show alternatives (possibly using concatenation).
Use a program comment to explain what the continuation character is if it isn't obvious.
The program should contain a variable that has the date of the last update/revision.
The program, when run, should display with verbiage:
The last update/revision date (and should be unambiguous).
The number of chemical elements in the list.
The name of the highest (last) element name.
Show all output here, on this page.
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
| #Free_Pascal | Free Pascal |
program longStringLiteralDemo(output);
{$mode objFPC}
{$longStrings on}
uses
// for `format`
sysUtils,
// for `wordCount` and `extractWord`
strUtils;
const
elementString = 'hydrogen helium lithium beryllium boron carbon nitrogen oxy' +
'gen fluorine neon sodium magnesium aluminum silicon phosphorous sulfur chl' +
'orine argon potassium calcium scandium titanium vanadium chromium manganes' +
'e iron cobalt nickel copper zinc gallium germanium arsenic selenium bromin' +
'e krypton rubidium strontium yttrium zirconium niobium molybdenum techneti' +
'um ruthenium rhodium palladium silver cadmium indium tin antimony telluriu' +
'm iodine xenon cesium barium lanthanum cerium praseodymium neodymium prome' +
'thium samarium europium gadolinium terbium dysprosium holmium erbium thuli' +
'um ytterbium lutetium hafnium tantalum tungsten rhenium osmium iridium pla' +
'tinum gold mercury thallium lead bismuth polonium astatine radon francium ' +
'radium actinium thorium protactinium uranium neptunium plutonium americium' +
' curium berkelium californium einsteinium fermium mendelevium nobelium law' +
'rencium rutherfordium dubnium seaborgium bohrium hassium meitnerium darmst' +
'adtium roentgenium copernicium nihonium flerovium moscovium livermorium te' +
'nnessine oganesson';
elementRevision = '2020‑11‑11';
resourcestring
revisionNotice = 'Last update: %0:s';
begin
writeLn(format(revisionNotice, [elementRevision]));
writeLn(wordCount(elementString, stdWordDelims));
writeLn(extractWord(wordCount(elementString, stdWordDelims),
elementString, stdWordDelims));
end.
|
http://rosettacode.org/wiki/Long_literals,_with_continuations | Long literals, with continuations | This task is about writing a computer program that has long literals (character
literals that may require specifying the words/tokens on more than one (source)
line, either with continuations or some other method, such as abutments or
concatenations (or some other mechanisms).
The literal is to be in the form of a "list", a literal that contains many
words (tokens) separated by a blank (space), in this case (so as to have a
common list), the (English) names of the chemical elements of the periodic table.
The list is to be in (ascending) order of the (chemical) element's atomic number:
hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium aluminum silicon ...
... up to the last known (named) chemical element (at this time).
Do not include any of the "unnamed" chemical element names such as:
ununennium unquadnilium triunhexium penthextrium penthexpentium septhexunium octenntrium ennennbium
To make computer programming languages comparable, the statement widths should be
restricted to less than 81 bytes (characters), or less
if a computer programming language has more restrictive limitations or standards.
Also mention what column the programming statements can start in if not
in column one.
The list may have leading/embedded/trailing blanks during the
declaration (the actual program statements), this is allow the list to be
more readable. The "final" list shouldn't have any leading/trailing or superfluous
blanks (when stored in the program's "memory").
This list should be written with the idea in mind that the
program will be updated, most likely someone other than the
original author, as there will be newer (discovered) elements of the periodic
table being added (possibly in the near future). These future updates
should be one of the primary concerns in writing these programs and it should be "easy"
for someone else to add chemical elements to the list (within the computer
program).
Attention should be paid so as to not exceed the clause length of
continued or specified statements, if there is such a restriction. If the
limit is greater than (say) 4,000 bytes or so, it needn't be mentioned here.
Task
Write a computer program (by whatever name) to contain a list of the known elements.
The program should eventually contain a long literal of words (the elements).
The literal should show how one could create a long list of blank-delineated words.
The "final" (stored) list should only have a single blank between elements.
Try to use the most idiomatic approach(es) in creating the final list.
Use continuation if possible, and/or show alternatives (possibly using concatenation).
Use a program comment to explain what the continuation character is if it isn't obvious.
The program should contain a variable that has the date of the last update/revision.
The program, when run, should display with verbiage:
The last update/revision date (and should be unambiguous).
The number of chemical elements in the list.
The name of the highest (last) element name.
Show all output here, on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #FreeBASIC | FreeBASIC |
Dim As String ultimaRevision = "2021-11-12"
Dim As String elemento(0 to ...) => { _
"hydrogen", "helium", "lithium", "beryllium", "boron", "carbon", "nitrogen", _
"oxygen", "fluorine", "neon", "sodium", "magnesium", "aluminum", "silicon", _
"phosphorous", "sulfur", "chlorine", "argon", "potassium", "calcium", _
"scandium", "titanium", "vanadium", "chromium", "manganese", "iron", "cobalt", _
"nickel", "copper", "zinc", "gallium", "germanium", "arsenic", "selenium", _
"bromine", "krypton", "rubidium", "strontium", "yttrium", "zirconium", _
"niobium", "molybdenum", "technetium", "ruthenium", "rhodium", "palladium", _
"silver", "cadmium", "indium", "tin", "antimony", "tellurium", "iodine", _
"xenon", "cesium", "barium", "lanthanum", "cerium", "praseodymium", _
"neodymium", "promethium", "samarium", "europium", "gadolinium", "terbium", _
"dysprosium", "holmium", "erbium", "thulium", "ytterbium", "lutetium", _
"hafnium", "tantalum", "tungsten", "rhenium", "osmium", "iridium", "platinum", _
"gold", "mercury", "thallium", "lead", "bismuth", "polonium", "astatine", _
"radon", "francium", "radium", "actinium", "thorium", "protactinium", _
"uranium", "neptunium", "plutonium", "americium", "curium", "berkelium", _
"californium", "einsteinium", "fermium", "mendelevium", "nobelium", _
"lawrencium", "rutherfordium", "dubnium", "seaborgium", "bohrium", "hassium", _
"meitnerium", "darmstadtium", "roentgenium", "copernicium", "nihonium", _
"flerovium", "moscovium", "livermorium", "tennessine", "oganesson"}
Print "Last updated : "; ultimaRevision
Print "Number of elements : "; Ubound(elemento) - Lbound(elemento) + 1
Print "Last element : "; elemento(Ubound(elemento))
Sleep
|
http://rosettacode.org/wiki/List_rooted_trees | List rooted trees | You came back from grocery shopping. After putting away all the goods, you are left with a pile of plastic bags, which you want to save for later use, so you take one bag and stuff all the others into it, and throw it under the sink. In doing so, you realize that there are various ways of nesting the bags, with all bags viewed as identical.
If we use a matching pair of parentheses to represent a bag, the ways are:
For 1 bag, there's one way:
() <- a bag
for 2 bags, there's one way:
(()) <- one bag in another
for 3 bags, there are two:
((())) <- 3 bags nested Russian doll style
(()()) <- 2 bags side by side, inside the third
for 4 bags, four:
(()()())
((())())
((()()))
(((())))
Note that because all bags are identical, the two 4-bag strings ((())()) and (()(())) represent the same configuration.
It's easy to see that each configuration for n bags represents a n-node rooted tree, where a bag is a tree node, and a bag with its content forms a subtree. The outermost bag is the tree root. Number of configurations for given n is given by OEIS A81.
Task
Write a program that, when given n, enumerates all ways of nesting n bags. You can use the parentheses notation above, or any tree representation that's unambiguous and preferably intuitive.
This task asks for enumeration of trees only; for counting solutions without enumeration, that OEIS page lists various formulas, but that's not encouraged by this task, especially if implementing it would significantly increase code size.
As an example output, run 5 bags. There should be 9 ways.
| #D | D | import std.stdio, std.conv;
alias Tree = ulong,
TreeList = Tree[],
Offset = uint[32];
void listTees(in uint n, in ref Offset offset, in TreeList list) nothrow @nogc @safe {
static void show(in Tree t, in uint len) nothrow @nogc @safe {
foreach (immutable i; 0 .. len)
putchar(t & (2 ^^ i) ? '(' : ')');
}
foreach (immutable i; offset[n] .. offset[n + 1]) {
show(list[i], n * 2);
putchar('\n');
}
}
void append(in Tree t, ref TreeList list, ref uint len) pure nothrow @safe {
if (len == list.length)
list.length = list.length ? list.length * 2 : 2;
list[len] = 1 | (t << 1);
len++;
}
/**
Assemble tree from subtrees.
Params:
n = length of tree we want to make.
t = assembled parts so far.
sl = length of subtree we are looking at.
pos = offset of subtree we are looking at.
rem = remaining length to be put together.
*/
void assemble(in uint n, in Tree t, uint sl, uint pos, in uint rem, in ref Offset offset,
ref TreeList list, ref uint len) pure nothrow @safe {
if (!rem) {
append(t, list, len);
return;
}
if (sl > rem) { // Need smaller subtrees.
sl = rem;
pos = offset[sl];
} else if (pos >= offset[sl + 1]) {
// Used up sl-trees, try smaller ones.
sl--;
if (!sl)
return;
pos = offset[sl];
}
assemble(n, t << (2 * sl) | list[pos], sl, pos, rem - sl, offset, list, len);
assemble(n, t, sl, pos + 1, rem, offset, list, len);
}
void makeTrees(in uint n, ref Offset offset,
ref TreeList list, ref uint len) pure nothrow @safe {
if (offset[n + 1])
return;
if (n)
makeTrees(n - 1, offset, list, len);
assemble(n, 0, n - 1, offset[n - 1], n - 1, offset, list, len);
offset[n + 1] = len;
}
void main(in string[] args) {
immutable uint n = (args.length == 2) ? args[1].to!uint : 5;
if (n >= 25)
return;
Offset offset;
offset[1] = 1;
Tree[] list;
uint len = 0;
// Init 1-tree.
append(0, list, len);
makeTrees(n, offset, list, len);
stderr.writefln("Number of %d-trees: %u", n, offset[n + 1] - offset[n]);
listTees(n, offset, list);
} |
http://rosettacode.org/wiki/Literals/Integer | Literals/Integer | Some programming languages have ways of expressing integer literals in bases other than the normal base ten.
Task
Show how integer literals can be expressed in as many bases as your language allows.
Note: this should not involve the calling of any functions/methods, but should be interpreted by the compiler or interpreter as an integer written to a given base.
Also show any other ways of expressing literals, e.g. for different types of integers.
Related task
Literals/Floating point
| #ALGOL_W | ALGOL W | begin
write( 16, number( #10 ) )
end. |
http://rosettacode.org/wiki/Literals/Integer | Literals/Integer | Some programming languages have ways of expressing integer literals in bases other than the normal base ten.
Task
Show how integer literals can be expressed in as many bases as your language allows.
Note: this should not involve the calling of any functions/methods, but should be interpreted by the compiler or interpreter as an integer written to a given base.
Also show any other ways of expressing literals, e.g. for different types of integers.
Related task
Literals/Floating point
| #AmigaE | AmigaE | PROC main()
IF ($2d7 = 727) AND (%001011010111 = 727) THEN WriteF('true\n')
ENDPROC |
http://rosettacode.org/wiki/Logical_operations | Logical operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a function that takes two logical (boolean) values, and outputs the result of "and" and "or" on both arguments as well as "not" on the first arguments.
If the programming language doesn't provide a separate type for logical values, use the type most commonly used for that purpose.
If the language supports additional logical operations on booleans such as XOR, list them as well.
| #ACL2 | ACL2 | (defun logical-ops (a b)
(progn$ (cw "(and a b) = ~x0~%" (and a b))
(cw "(or a b) = ~x0~%" (or a b))
(cw "(not a) = ~x0~%" (not a)))) |
http://rosettacode.org/wiki/Logical_operations | Logical operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a function that takes two logical (boolean) values, and outputs the result of "and" and "or" on both arguments as well as "not" on the first arguments.
If the programming language doesn't provide a separate type for logical values, use the type most commonly used for that purpose.
If the language supports additional logical operations on booleans such as XOR, list them as well.
| #Action.21 | Action! | BYTE FUNC Not(BYTE a)
IF a=0 THEN
RETURN (1)
FI
RETURN (0)
PROC Main()
BYTE a,b,res
FOR a=0 TO 1
DO
FOR b=0 TO 1
DO
res=a AND b
PrintF("%B AND %B=%B",a,b,res)
res=a OR b
PrintF("|%B OR %B=%B",a,b,res)
res=a ! b
PrintF("|%B XOR %B=%B",a,b,res)
res=Not(a)
PrintF("|NOT %B=%B%E",a,res)
OD
OD
RETURN |
http://rosettacode.org/wiki/Loops/N_plus_one_half | Loops/N plus one half | Quite often one needs loops which, in the last iteration, execute only part of the loop body.
Goal
Demonstrate the best way to do this.
Task
Write a loop which writes the comma-separated list
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
using separate output statements for the number
and the comma from within the body of the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Tcl | Tcl | for {set i 1; set end 10} true {incr i} {
puts -nonewline $i
if {$i >= $end} break
puts -nonewline ", "
}
puts "" |
http://rosettacode.org/wiki/Loops/N_plus_one_half | Loops/N plus one half | Quite often one needs loops which, in the last iteration, execute only part of the loop body.
Goal
Demonstrate the best way to do this.
Task
Write a loop which writes the comma-separated list
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
using separate output statements for the number
and the comma from within the body of the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #TI-89_BASIC | TI-89 BASIC | Local str
"" → str
For i,1,10
str & string(i) → str
If i < 10 Then
str & "," → str
EndIf
EndFor
Disp str |
http://rosettacode.org/wiki/Literals/Floating_point | Literals/Floating point | Programming languages have different ways of expressing floating-point literals.
Task
Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features.
You may want to include a regular expression or BNF/ABNF/EBNF defining allowable formats for your language.
Related tasks
Literals/Integer
Extreme floating point values
| #C.2B.2B | C++ | #include <iostream>
int main()
{
// a numeric literal with decimal point is a double
auto double1 = 2.5;
// an 'f' of 'F' suffix means the literal is a flaot
auto float1 = 2.5f;
// an 'l' or 'L' suffix means a long double
auto longdouble1 = 2.5l;
// a number after an 'e' or 'E' is the base 10 exponent
auto double2 = 2.5e-3;
auto float2 = 2.5e3f;
// a '0x' prefix means the literal is hexadecimal. the 'p' is base 2 the exponent
auto double3 = 0x1p4;
auto float3 = 0xbeefp-8f;
std::cout << "\ndouble1: " << double1;
std::cout << "\nfloat1: " << float1;
std::cout << "\nlongdouble1: " << longdouble1;
std::cout << "\ndouble2: " << double2;
std::cout << "\nfloat2: " << float2;
std::cout << "\ndouble3: " << double3;
std::cout << "\nfloat3: " << float3;
std::cout << "\n";
} |
http://rosettacode.org/wiki/Literals/Floating_point | Literals/Floating point | Programming languages have different ways of expressing floating-point literals.
Task
Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features.
You may want to include a regular expression or BNF/ABNF/EBNF defining allowable formats for your language.
Related tasks
Literals/Integer
Extreme floating point values
| #Clojure | Clojure | user=> 1.
1.0
user=> 1.0
1.0
user=> 3.1415
3.1415
user=> 1.234E-10
1.234E-10
user=> 1e100
1.0E100
user=> (Float/valueOf "1.0f")
1.0 |
http://rosettacode.org/wiki/Long_year | Long year | Most years have 52 weeks, some have 53, according to ISO8601.
Task
Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
| #Dc | Dc | [0q]s0
[1q]s1
[1r- r 1r- * 1r-]sO # O = logical OR
##.............................................................................
# C: for( initcode ; condcode ; incrcode ) {body}
# .[q] [1] [2] [3] [4]
# # [initcode] [condcode] [incrcode] [body] (for)
[ [q]S. 4:.3:.2:.x [2;.x 0=. 4;.x 3;.x 0;.x]d0:.x
Os.L.o
]sF # F = for
##.............................................................................
# [1] [0]
# (.) [cond_code] [then_code] [else_code] (if_CTE)
[ []S. 0:. 1:. x [0=0 1]x ;. s.L. x]sI # I = if
##-----------------------------------------------------------------------------
[S. l. l.4/+ l.100/- l.400/+ 7% s.L.]sp # p
##.............................................................................
[S. [l. lpx 4=1 0]x
[l. 1- lpx 3=1 0]x lOx
s.L.
]si # i = is_long_year
##.............................................................................
[
# f = from
# t = to
# y = year
# c = count
st sf # fetch args from stack
[lfsy 0sc]
[ly lt <0 1] # cond
[ly 1+ sy] # incr y
[
[ly lix] # is_long_year(y)
[
[lc 0 <1 0] # 0<c
[
[ lc 10% 0=1 0] # (c % 10) == 0
[ AP ]
[ [ ]P ]
lIx # if
]
[]
lIx # if
ly n
lc 1+ sc
]
[]
lIx # if
] lFx # for
]sD # D = doit = print_long_years
##.............................................................................
[Long years between 1800 and 2100:]P AP
1800 2100 lDx
AP |
http://rosettacode.org/wiki/Long_year | Long year | Most years have 52 weeks, some have 53, according to ISO8601.
Task
Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
| #Delphi | Delphi |
program Long_year;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils;
function p(const Year: Integer): Integer;
begin
Result := (Year + (Year div 4) - (Year div 100) + (Year div 400)) mod 7;
end;
function IsLongYear(const Year: Integer): Boolean;
begin
Result := (p(Year) = 4) or (p(Year - 1) = 3);
end;
procedure PrintLongYears(const StartYear: Integer; const EndYear: Integer);
var
Year, Count: Integer;
begin
Count := 0;
for Year := 1800 to 2100 do
if IsLongYear(Year) then
begin
if Count mod 10 = 0 then
Writeln;
Write(Year, ' ');
inc(Count);
end;
end;
var
Year: Integer;
begin
Writeln('Long years between 1800 and 2100:');
PrintLongYears(1800, 2100);
Readln;
end.
|
http://rosettacode.org/wiki/Long_primes | Long primes |
A long prime (as defined here) is a prime number whose reciprocal (in decimal) has
a period length of one less than the prime number.
Long primes are also known as:
base ten cyclic numbers
full reptend primes
golden primes
long period primes
maximal period primes
proper primes
Another definition: primes p such that the decimal expansion of 1/p has period p-1, which is the greatest period possible for any integer.
Example
7 is the first long prime, the reciprocal of seven
is 1/7, which
is equal to the repeating decimal fraction 0.142857142857···
The length of the repeating part of the decimal fraction
is six, (the underlined part) which is one less
than the (decimal) prime number 7.
Thus 7 is a long prime.
There are other (more) general definitions of a long prime which
include wording/verbiage for bases other than ten.
Task
Show all long primes up to 500 (preferably on one line).
Show the number of long primes up to 500
Show the number of long primes up to 1,000
Show the number of long primes up to 2,000
Show the number of long primes up to 4,000
Show the number of long primes up to 8,000
Show the number of long primes up to 16,000
Show the number of long primes up to 32,000
Show the number of long primes up to 64,000 (optional)
Show all output here.
Also see
Wikipedia: full reptend prime
MathWorld: full reptend prime
OEIS: A001913
| #F.23 | F# |
// Return true if prime n is a long prime. Nigel Galloway: September 25th., 2018
let fN n g = let rec fN i g e l = match e with | 0UL -> i
| _ when e%2UL = 1UL -> fN ((i*g)%l) ((g*g)%l) (e/2UL) l
| _ -> fN i ((g*g)%l) (e/2UL) l
fN 1UL 10UL (uint64 g) (uint64 n)
let isLongPrime n=Seq.length (factors (n-1) |> Seq.filter(fun g->(fN n g)=1UL))=1
|
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously | Loop over multiple arrays simultaneously | Task
Loop over multiple arrays (or lists or tuples or whatever they're called in
your language) and display the i th element of each.
Use your language's "for each" loop if it has one, otherwise iterate
through the collection in order with some other loop.
For this example, loop over the arrays:
(a,b,c)
(A,B,C)
(1,2,3)
to produce the output:
aA1
bB2
cC3
If possible, also describe what happens when the arrays are of different lengths.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Babel | Babel | main: { (('a' 'b' 'c')('A' 'B' 'C')('1' '2' '3'))
simul_array }
simul_array!:
{ trans
{ { << } each "\n" << } each } |
http://rosettacode.org/wiki/Loops/Break | Loops/Break | Task
Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive).
If a number is 10, stop the loop after printing it, and do not generate any further numbers.
Otherwise, generate and print a second random number before restarting the loop.
If the number 10 is never generated as the first number in a loop, loop forever.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
| #C.23 | C# | class Program
{
static void Main(string[] args)
{
Random random = new Random();
while (true)
{
int a = random.Next(20);
Console.WriteLine(a);
if (a == 10)
break;
int b = random.Next(20)
Console.WriteLine(b);
}
Console.ReadLine();
}
} |
http://rosettacode.org/wiki/Longest_common_subsequence | Longest common subsequence | Introduction
Define a subsequence to be any output string obtained by deleting zero or more symbols from an input string.
The Longest Common Subsequence (LCS) is a subsequence of maximum length common to two or more strings.
Let A ≡ A[0]… A[m - 1] and B ≡ B[0]… B[n - 1], m < n be strings drawn from an alphabet Σ of size s, containing every distinct symbol in A + B.
An ordered pair (i, j) will be referred to as a match if A[i] = B[j], where 0 < i ≤ m and 0 < j ≤ n.
Define a non-strict product-order (≤) over ordered pairs, such that (i1, j1) ≤ (i2, j2) ⇔ i1 ≤ i2 and j1 ≤ j2. We define (≥) similarly.
We say m1, m2 are comparable if either m1 ≤ m2 or m1 ≥ m2 holds. If i1 < i2 and j2 < j1 (or i2 < i1 and j1 < j2) then neither m1 ≤ m2 nor m1 ≥ m2 are possible; and we say m1, m2 are incomparable.
We also define the strict product-order (<) over ordered pairs, such that (i1, j1) < (i2, j2) ⇔ i1 < i2 and j1 < j2. We define (>) similarly.
Given a set of matches M, a chain C is a subset of M consisting of at least one element m; and where either m1 < m2 or m1 > m2 for every pair of distinct elements m1 and m2. An antichain D is any subset of M in which every pair of distinct elements m1 and m2 are incomparable.
The set M represents a relation over match pairs: M[i, j] ⇔ (i, j) ∈ M. A chain C can be visualized as a curve which strictly increases as it passes through each match pair in the m*n coordinate space.
Finding an LCS can be restated as the problem of finding a chain of maximum cardinality p over the set of matches M.
According to [Dilworth 1950], this cardinality p equals the minimum number of disjoint antichains into which M can be decomposed. Note that such a decomposition into the minimal number p of disjoint antichains may not be unique.
Contours
Forward Contours FC[k] of class k are defined inductively, as follows:
FC[0] consists of those elements m1 for which there exists no element m2 such that m2 < m1.
FC[k] consists of those elements m1 for which there exists no element m2 such that m2 < m1; and where neither m1 nor m2 are contained in FC[l] for any class l < k.
Reverse Contours RC[k] of class k are defined similarly.
Members of the Meet (∧), or Infimum of a Forward Contour are referred to as its Dominant Matches: those m1 for which there exists no m2 such that m2 < m1.
Members of the Join (∨), or Supremum of a Reverse Contour are referred to as its Dominant Matches: those m1 for which there exists no m2 such that m2 > m1.
Where multiple Dominant Matches exist within a Meet (or within a Join, respectively) the Dominant Matches will be incomparable to each other.
Background
Where the number of symbols appearing in matches is small relative to the length of the input strings, reuse of the symbols increases; and the number of matches will tend towards quadratic, O(m*n) growth. This occurs, for example, in the Bioinformatics application of nucleotide and protein sequencing.
The divide-and-conquer approach of [Hirschberg 1975] limits the space required to O(n). However, this approach requires O(m*n) time even in the best case.
This quadratic time dependency may become prohibitive, given very long input strings. Thus, heuristics are often favored over optimal Dynamic Programming solutions.
In the application of comparing file revisions, records from the input files form a large symbol space; and the number of symbols approaches the length of the LCS. In this case the number of matches reduces to linear, O(n) growth.
A binary search optimization due to [Hunt and Szymanski 1977] can be applied to the basic Dynamic Programming approach, resulting in an expected performance of O(n log m). Performance can degrade to O(m*n log m) time in the worst case, as the number of matches grows to O(m*n).
Note
[Rick 2000] describes a linear-space algorithm with a time bound of O(n*s + p*min(m, n - p)).
Legend
A, B are input strings of lengths m, n respectively
p is the length of the LCS
M is the set of match pairs (i, j) such that A[i] = B[j]
r is the magnitude of M
s is the magnitude of the alphabet Σ of distinct symbols in A + B
References
[Dilworth 1950] "A decomposition theorem for partially ordered sets"
by Robert P. Dilworth, published January 1950,
Annals of Mathematics [Volume 51, Number 1, pp. 161-166]
[Goeman and Clausen 2002] "A New Practical Linear Space Algorithm for the Longest Common
Subsequence Problem" by Heiko Goeman and Michael Clausen,
published 2002, Kybernetika [Volume 38, Issue 1, pp. 45-66]
[Hirschberg 1975] "A linear space algorithm for computing maximal common subsequences"
by Daniel S. Hirschberg, published June 1975
Communications of the ACM [Volume 18, Number 6, pp. 341-343]
[Hunt and McIlroy 1976] "An Algorithm for Differential File Comparison"
by James W. Hunt and M. Douglas McIlroy, June 1976
Computing Science Technical Report, Bell Laboratories 41
[Hunt and Szymanski 1977] "A Fast Algorithm for Computing Longest Common Subsequences"
by James W. Hunt and Thomas G. Szymanski, published May 1977
Communications of the ACM [Volume 20, Number 5, pp. 350-353]
[Rick 2000] "Simple and fast linear space computation of longest common subsequences"
by Claus Rick, received 17 March 2000, Information Processing Letters,
Elsevier Science [Volume 75, pp. 275–281]
Examples
The sequences "1234" and "1224533324" have an LCS of "1234":
1234
1224533324
For a string example, consider the sequences "thisisatest" and "testing123testing". An LCS would be "tsitest":
thisisatest
testing123testing
In this puzzle, your code only needs to deal with strings. Write a function which returns an LCS of two strings (case-sensitive). You don't need to show multiple LCS's.
For more information on this problem please see Wikipedia.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Clojure | Clojure | (defn longest [xs ys] (if (> (count xs) (count ys)) xs ys))
(def lcs
(memoize
(fn [[x & xs] [y & ys]]
(cond
(or (= x nil) (= y nil)) nil
(= x y) (cons x (lcs xs ys))
:else (longest (lcs (cons x xs) ys)
(lcs xs (cons y ys))))))) |
http://rosettacode.org/wiki/Look-and-say_sequence | Look-and-say sequence | The Look and say sequence is a recursively defined sequence of numbers studied most notably by John Conway.
The look-and-say sequence is also known as the Morris Number Sequence, after cryptographer Robert Morris, and the puzzle What is the next number in the sequence 1, 11, 21, 1211, 111221? is sometimes referred to as the Cuckoo's Egg, from a description of Morris in Clifford Stoll's book The Cuckoo's Egg.
Sequence Definition
Take a decimal number
Look at the number, visually grouping consecutive runs of the same digit.
Say the number, from left to right, group by group; as how many of that digit there are - followed by the digit grouped.
This becomes the next number of the sequence.
An example:
Starting with the number 1, you have one 1 which produces 11
Starting with 11, you have two 1's. I.E.: 21
Starting with 21, you have one 2, then one 1. I.E.: (12)(11) which becomes 1211
Starting with 1211, you have one 1, one 2, then two 1's. I.E.: (11)(12)(21) which becomes 111221
Task
Write a program to generate successive members of the look-and-say sequence.
Related tasks
Fours is the number of letters in the ...
Number names
Self-describing numbers
Self-referential sequence
Spelling of ordinal numbers
See also
Look-and-Say Numbers (feat John Conway), A Numberphile Video.
This task is related to, and an application of, the Run-length encoding task.
Sequence A005150 on The On-Line Encyclopedia of Integer Sequences.
| #BBC_BASIC | BBC BASIC | number$ = "1"
FOR i% = 1 TO 10
number$ = FNlooksay(number$)
PRINT number$
NEXT
END
DEF FNlooksay(n$)
LOCAL i%, j%, c$, o$
i% = 1
REPEAT
c$ = MID$(n$,i%,1)
j% = i% + 1
WHILE MID$(n$,j%,1) = c$
j% += 1
ENDWHILE
o$ += STR$(j%-i%) + c$
i% = j%
UNTIL i% > LEN(n$)
= o$ |
http://rosettacode.org/wiki/Longest_string_challenge | Longest string challenge | Background
This "longest string challenge" is inspired by a problem that used to be given to students learning Icon. Students were expected to try to solve the problem in Icon and another language with which the student was already familiar. The basic problem is quite simple; the challenge and fun part came through the introduction of restrictions. Experience has shown that the original restrictions required some adjustment to bring out the intent of the challenge and make it suitable for Rosetta Code.
Basic problem statement
Write a program that reads lines from standard input and, upon end of file, writes the longest line to standard output.
If there are ties for the longest line, the program writes out all the lines that tie.
If there is no input, the program should produce no output.
Task
Implement a solution to the basic problem that adheres to the spirit of the restrictions (see below).
Describe how you circumvented or got around these 'restrictions' and met the 'spirit' of the challenge. Your supporting description may need to describe any challenges to interpreting the restrictions and how you made this interpretation. You should state any assumptions, warnings, or other relevant points. The central idea here is to make the task a bit more interesting by thinking outside of the box and perhaps by showing off the capabilities of your language in a creative way. Because there is potential for considerable variation between solutions, the description is key to helping others see what you've done.
This task is likely to encourage a variety of different types of solutions. They should be substantially different approaches.
Given the input:
a
bb
ccc
ddd
ee
f
ggg
the output should be (possibly rearranged):
ccc
ddd
ggg
Original list of restrictions
No comparison operators may be used.
No arithmetic operations, such as addition and subtraction, may be used.
The only datatypes you may use are integer and string. In particular, you may not use lists.
Do not re-read the input file. Avoid using files as a replacement for lists (this restriction became apparent in the discussion).
Intent of restrictions
Because of the variety of languages on Rosetta Code and the wide variety of concepts used in them, there needs to be a bit of clarification and guidance here to get to the spirit of the challenge and the intent of the restrictions.
The basic problem can be solved very conventionally, but that's boring and pedestrian. The original intent here wasn't to unduly frustrate people with interpreting the restrictions, it was to get people to think outside of their particular box and have a bit of fun doing it.
The guiding principle here should be to be creative in demonstrating some of the capabilities of the programming language being used. If you need to bend the restrictions a bit, explain why and try to follow the intent. If you think you've implemented a 'cheat', call out the fragment yourself and ask readers if they can spot why. If you absolutely can't get around one of the restrictions, explain why in your description.
Now having said that, the restrictions require some elaboration.
In general, the restrictions are meant to avoid the explicit use of these features.
"No comparison operators may be used" - At some level there must be some test that allows the solution to get at the length and determine if one string is longer. Comparison operators, in particular any less/greater comparison should be avoided. Representing the length of any string as a number should also be avoided. Various approaches allow for detecting the end of a string. Some of these involve implicitly using equal/not-equal; however, explicitly using equal/not-equal should be acceptable.
"No arithmetic operations" - Again, at some level something may have to advance through the string. Often there are ways a language can do this implicitly advance a cursor or pointer without explicitly using a +, - , ++, --, add, subtract, etc.
The datatype restrictions are amongst the most difficult to reinterpret. In the language of the original challenge strings are atomic datatypes and structured datatypes like lists are quite distinct and have many different operations that apply to them. This becomes a bit fuzzier with languages with a different programming paradigm. The intent would be to avoid using an easy structure to accumulate the longest strings and spit them out. There will be some natural reinterpretation here.
To make this a bit more concrete, here are a couple of specific examples:
In C, a string is an array of chars, so using a couple of arrays as strings is in the spirit while using a second array in a non-string like fashion would violate the intent.
In APL or J, arrays are the core of the language so ruling them out is unfair. Meeting the spirit will come down to how they are used.
Please keep in mind these are just examples and you may hit new territory finding a solution. There will be other cases like these. Explain your reasoning. You may want to open a discussion on the talk page as well.
The added "No rereading" restriction is for practical reasons, re-reading stdin should be broken. I haven't outright banned the use of other files but I've discouraged them as it is basically another form of a list. Somewhere there may be a language that just sings when doing file manipulation and where that makes sense; however, for most there should be a way to accomplish without resorting to an externality.
At the end of the day for the implementer this should be a bit of fun. As an implementer you represent the expertise in your language, the reader may have no knowledge of your language. For the reader it should give them insight into how people think outside the box in other languages. Comments, especially for non-obvious (to the reader) bits will be extremely helpful. While the implementations may be a bit artificial in the context of this task, the general techniques may be useful elsewhere.
| #OCaml | OCaml | let input_line_opt ic =
try Some (input_line ic)
with End_of_file -> None
let cmp s1 s2 =
try ignore(s1.[String.length s2]); 1 (* s1 is longer *)
with _ ->
try ignore(s2.[String.length s1]); -1 (* s2 is longer *)
with _ -> 0 (* both same length *)
let () =
let ic = open_in Sys.argv.(1) in
let rec loop longest acc =
match input_line_opt ic with
| Some line ->
( match cmp line longest with
| 1 -> loop line (line ^ "\n")
| 0 -> loop line (acc ^ line ^ "\n")
| _ -> loop longest acc )
| None ->
close_in ic;
print_string acc
in
loop "" "" |
http://rosettacode.org/wiki/Longest_increasing_subsequence | Longest increasing subsequence | Calculate and show here a longest increasing subsequence of the list:
{
3
,
2
,
6
,
4
,
5
,
1
}
{\displaystyle \{3,2,6,4,5,1\}}
And of the list:
{
0
,
8
,
4
,
12
,
2
,
10
,
6
,
14
,
1
,
9
,
5
,
13
,
3
,
11
,
7
,
15
}
{\displaystyle \{0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15\}}
Note that a list may have more than one subsequence that is of the maximum length.
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
Ref
Dynamic Programming #1: Longest Increasing Subsequence on YouTube
An efficient solution can be based on Patience sorting.
| #Julia | Julia |
function lis(arr::Vector)
if length(arr) == 0 return copy(arr) end
L = Vector{typeof(arr)}(length(arr))
L[1] = [arr[1]]
for i in 2:length(arr)
nextL = []
for j in 1:i
if arr[j] < arr[i] && length(L[j]) ≥ length(nextL)
nextL = L[j]
end
end
L[i] = vcat(nextL, arr[i])
end
return L[indmax(length.(L))]
end
@show lis([3, 2, 6, 4, 5, 1])
@show lis([0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]) |
http://rosettacode.org/wiki/Loops/Continue | Loops/Continue | Task
Show the following output using one loop.
1, 2, 3, 4, 5
6, 7, 8, 9, 10
Try to achieve the result by forcing the next iteration within the loop
upon a specific condition, if your language allows it.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Delphi | Delphi | program DoLoop(output);
var
i: integer;
begin
for i := 1 to 10 do
begin
write(i);
if i mod 5 = 0 then
begin
writeln;
continue;
end;
write(', ');
end;
end. |
http://rosettacode.org/wiki/Loops/Continue | Loops/Continue | Task
Show the following output using one loop.
1, 2, 3, 4, 5
6, 7, 8, 9, 10
Try to achieve the result by forcing the next iteration within the loop
upon a specific condition, if your language allows it.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #DWScript | DWScript | var i : Integer;
for i := 1 to 10 do begin
Print(i);
if i mod 5 = 0 then begin
PrintLn('');
continue;
end;
Print(', ');
end; |
http://rosettacode.org/wiki/Longest_common_substring | Longest common substring | Task
Write a function that returns the longest common substring of two strings.
Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing".
Note that substrings are consecutive characters within a string. This distinguishes them from subsequences, which is any sequence of characters within a string, even if there are extraneous characters in between them.
Hence, the longest common subsequence between "thisisatest" and "testing123testing" is "tsitest", whereas the longest common substring is just "test".
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
References
Generalize Suffix Tree
Ukkonen’s Suffix Tree Construction
| #Haskell | Haskell | import Data.Ord (comparing)
import Data.List (maximumBy, intersect)
subStrings :: [a] -> [[a]]
subStrings s =
let intChars = length s
in [ take n $ drop i s
| i <- [0 .. intChars - 1]
, n <- [1 .. intChars - i] ]
longestCommon :: Eq a => [a] -> [a] -> [a]
longestCommon a b =
maximumBy (comparing length) (subStrings a `intersect` subStrings b)
main :: IO ()
main = putStrLn $ longestCommon "testing123testing" "thisisatest" |
http://rosettacode.org/wiki/Loops/Nested | Loops/Nested | Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over
[
1
,
…
,
20
]
{\displaystyle [1,\ldots ,20]}
.
The loops iterate rows and columns of the array printing the elements until the value
20
{\displaystyle 20}
is met.
Specifically, this task also shows how to break out of nested loops.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: main is func
local
var integer: i is 0;
var integer: j is 0;
var array array integer: a is 10 times 10 times 0;
const EXCEPTION: FOUND20 is enumlit;
begin
for i range 1 to 10 do
for j range 1 to 10 do
a[i][j] := rand(1, 20);
end for;
end for;
block
for i range 1 to 10 do
for j range 1 to 10 do
write(a[i][j] lpad 2 <& ", ");
if a[i][j] = 20 then
raise FOUND20;
end if;
end for;
writeln;
end for;
exception
catch FOUND20: writeln;
end block;
end func; |
http://rosettacode.org/wiki/Loops/Nested | Loops/Nested | Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over
[
1
,
…
,
20
]
{\displaystyle [1,\ldots ,20]}
.
The loops iterate rows and columns of the array printing the elements until the value
20
{\displaystyle 20}
is met.
Specifically, this task also shows how to break out of nested loops.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Sidef | Sidef | var arr = 10.of{ 10.of{ 20.irand + 1 } }
for row in arr {
for num in row {
"%3d".printf(num);
num == 20 && goto :OUT
}
print "\n"
} @:OUT
print "\n" |
http://rosettacode.org/wiki/Loops/Foreach | Loops/Foreach | Loop through and print each element in a collection in order.
Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #WDTE | WDTE | let a => import 'arrays';
let s => import 'stream';
a.stream [5; 7; 3]
-> s.map (io.writeln io.stdout)
-> s.drain
; |
http://rosettacode.org/wiki/Loops/Foreach | Loops/Foreach | Loop through and print each element in a collection in order.
Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Wren | Wren | for (f in ["apples", "oranges", "pears"]) System.print(f) |
http://rosettacode.org/wiki/Loops/Foreach | Loops/Foreach | Loop through and print each element in a collection in order.
Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #XLISP | XLISP | (FOR-EACH PRINT '(CYRUS CAMBYSES DARIUS XERXES ARTAXERXES)) |
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers | Luhn test of credit card numbers | The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits.
Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test:
Reverse the order of the digits in the number.
Take the first, third, ... and every other odd digit in the reversed digits and sum them to form the partial sum s1
Taking the second, fourth ... and every other even digit in the reversed digits:
Multiply each digit by two and sum the digits if the answer is greater than nine to form partial sums for the even digits
Sum the partial sums of the even digits to form s2
If s1 + s2 ends in zero then the original number is in the form of a valid credit card number as verified by the Luhn test.
For example, if the trial number is 49927398716:
Reverse the digits:
61789372994
Sum the odd digits:
6 + 7 + 9 + 7 + 9 + 4 = 42 = s1
The even digits:
1, 8, 3, 2, 9
Two times each even digit:
2, 16, 6, 4, 18
Sum the digits of each multiplication:
2, 7, 6, 4, 9
Sum the last:
2 + 7 + 6 + 4 + 9 = 28 = s2
s1 + s2 = 70 which ends in zero which means that 49927398716 passes the Luhn test
Task
Write a function/method/procedure/subroutine that will validate a number with the Luhn test, and
use it to validate the following numbers:
49927398716
49927398717
1234567812345678
1234567812345670
Related tasks
SEDOL
ISIN
| #Pascal | Pascal | program luhnTestOfCreditCardNumbers(input, output);
type
{
`string(…)` is an Extended Pascal, ISO 10206, extension.
`string(64)` discriminates the “schema” data type `string`
to contain at most 64 `char` values.
}
creditCardNumber = string(64);
{
\brief determines whether a string contains digits only
\param sample the string to inspect
\return `false` iff `sample` contains non-digit characters
}
{ Extended Pascal: `protected` means the function cannot modify `sample` }
function containsDigitsOnly(protected sample: creditCardNumber): Boolean;
var
{ EP: the `… value []` initializes this variable as an empty set }
characters: set of char value [];
{ `sample.capacity` refers to `64` in this code. }
i: 1..sample.capacity;
begin
for i := 1 to length(sample) do
begin
{ Union of sets indicated by `+`. }
characters := characters + [sample[i]]
end;
{
In a Pascal `function` definition,
there must be one assignment to the (implicit) variable
bearing the same name as of the function.
This will be the return value.
}
{ NB: This will return `true` even if `length(sample)` is zero. }
containsDigitsOnly := card(characters - ['0'..'9']) = 0
{ `card` is an Extended Pascal extension. }
end;
{
\brief determines whether a string complies with ISO/IEC 7812-1 Luhn test
\param sample the potentially correct credit card number
\return `true` if verification succeeds
}
function luhnCheck(protected sample: creditCardNumber): Boolean;
{
This _nested_ function is only accessible _within_ `luhnCheck`.
Outsourcing this code allows us to write a neat expression below.
}
function check: Boolean;
var
{ Using `integer` sub-ranges ensures only these values are assigned. }
sum: 0..maxInt value 0;
i: 0..sample.capacity-1;
begin
for i := 0 to length(sample) - 1 do
begin
{ `1 + ord(odd(i))` produces an alternating scale factor `* 1`/`* 2`. }
sum := sum + (1 + ord(odd(i))) *
{ Obtain digit value for `integer` calculation. }
(ord(sample[length(sample) - i]) - ord('0')) -
{ Reverse operation if digit sum > 9, i.e. we added “too much”. }
ord(odd(i) and (sample[length(sample) - i] >= '5')) * 9
end;
check := sum mod 10 = 0
end;
begin
{
The Extended Pascal Boolean operator `and_then` (and `or_else`)
allows for “short-circuit evaluation”.
Otherwise, in Pascal `and` and `or` mandate complete evaluation.
}
luhnCheck := (length(sample) > 0) and_then containsDigitsOnly(sample)
and_then check
end;
{ === MAIN ============================================================= }
var
s: creditCardNumber;
begin
{ `EOF` is short for `EOF(input)`. }
while not EOF do
begin
readLn(s); { equivalent to `readLn(input, s)` }
writeLn(luhnCheck(s)) { = `writeLn(output, …)` }
end
end. |
http://rosettacode.org/wiki/Loops/Infinite | Loops/Infinite | Task
Print out SPAM followed by a newline in an infinite loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Prolog | Prolog | repeat, write('SPAM'), nl, fail. |
http://rosettacode.org/wiki/Loops/Infinite | Loops/Infinite | Task
Print out SPAM followed by a newline in an infinite loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Pure_Data | Pure Data | #N canvas 426 88 450 300 10;
#X obj 17 75 print;
#X msg 17 55 SPAM;
#X obj 17 35 metro 1;
#X msg 17 15 1;
#X connect 1 0 0 0;
#X connect 2 0 1 0;
#X connect 3 0 2 0; |
http://rosettacode.org/wiki/Loops/While | Loops/While | Task
Start an integer value at 1024.
Loop while it is greater than zero.
Print the value (with a newline) and divide it by two each time through the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreachbas
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #PeopleCode | PeopleCode |
Local string &CRLF;
Local number &LoopNumber;
&LoopNumber = 1024;
&CRLF = Char(10) | Char(13);
While &LoopNumber > 0;
WinMessage(&LoopNumber | &CRLF);
&LoopNumber = &LoopNumber / 2;
End-While;
|
http://rosettacode.org/wiki/Loops/While | Loops/While | Task
Start an integer value at 1024.
Loop while it is greater than zero.
Print the value (with a newline) and divide it by two each time through the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreachbas
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Perl | Perl | my $n = 1024;
while($n){
print "$n\n";
$n = int $n / 2;
} |
http://rosettacode.org/wiki/Loops/Downward_for | Loops/Downward for | Task
Write a for loop which writes a countdown from 10 to 0.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Python | Python | for i in xrange(10, -1, -1):
print i |
http://rosettacode.org/wiki/Loops/Downward_for | Loops/Downward for | Task
Write a for loop which writes a countdown from 10 to 0.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Quackery | Quackery | 11 times [ i echo sp ] |
http://rosettacode.org/wiki/Loops/Do-while | Loops/Do-while | Start with a value at 0. Loop while value mod 6 is not equal to 0.
Each time through the loop, add 1 to the value then print it.
The loop must execute at least once.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
Reference
Do while loop Wikipedia.
| #min | min | 0 (dup 6 mod 0 == over 0 != and) 'pop (puts succ) () linrec |
http://rosettacode.org/wiki/Loops/For | Loops/For | “For” loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code.
Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers.
Task
Show how two loops may be nested within each other, with the number of iterations performed by the inner for loop being controlled by the outer for loop.
Specifically print out the following pattern by using one for loop nested in another:
*
**
***
****
*****
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
Reference
For loop Wikipedia.
| #Forth | Forth | : triangle ( n -- )
1+ 1 do
cr i 0 do [char] * emit loop
loop ;
5 triangle |
http://rosettacode.org/wiki/Loops/For_with_a_specified_step | Loops/For with a specified step |
Task
Demonstrate a for-loop where the step-value is greater than one.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #LiveCode | LiveCode | repeat with n = 0 to 10 step 2
put n after loopn
if n is not 10 then put comma after loopn
end repeat
put loopn |
http://rosettacode.org/wiki/Long_multiplication | Long multiplication | Task
Explicitly implement long multiplication.
This is one possible approach to arbitrary-precision integer algebra.
For output, display the result of 264 * 264.
Optionally, verify your result against builtin arbitrary precision support.
The decimal representation of 264 is:
18,446,744,073,709,551,616
The output of 264 * 264 is 2128, and is:
340,282,366,920,938,463,463,374,607,431,768,211,456
| #ALGOL_68 | ALGOL 68 | PRAGMAT precision=200 PRAGMAT
MODE INTEGER = LONG LONG INT;
LONG INT default integer width := 69;
INT width = 69+2;
INT fix w = 1, fix h = 1; # round up #
LONG LONG INT golden ratio w := ENTIER ((long long sqrt(5)-1) / 2 * LENG LENG 10 ** default integer width + fix w),
golden ratio h := ENTIER ((long long sqrt(5)+1) / 2 * LENG LENG 10 ** default integer width + fix h);
test: (
print((
"The approximate golden ratios, width: ", whole(golden ratio w,width), new line,
" length: ", whole(golden ratio h,width), new line,
" product is exactly: ", whole(golden ratio w*golden ratio h,width*2), new line));
INTEGER two to the power of 64 = LONG 2 ** 64;
INTEGER neg two to the power of 64 = -(LONG 2 ** 64);
print(("2 ** 64 * -(2 ** 64) = ", whole(two to the power of 64*neg two to the power of 64,width), new line))
) |
http://rosettacode.org/wiki/Literals/String | Literals/String | Task
Show literal specification of characters and strings.
If supported, show how the following work:
verbatim strings (quotes where escape sequences are quoted literally)
here-strings
Also, discuss which quotes expand variables.
Related tasks
Special characters
Here document
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program stringsEx.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/* Initialized data */
.data
szMessString: .asciz "String with final zero \n"
szMessString1: .string "Other string with final zero \n"
sString: .ascii "String without final zero"
.byte 0 @ add final zero for display
sLineSpaces: .byte '>'
.fill 10,1,' ' @ 10 spaces
.asciz "<\n" @ add <, CR and final zero for display
sSpaces1: .space 10,' ' @ other 10 spaces
.byte 0 @ add final zero for display
sCharA: .space 10,'A' @ curious !! 10 A with space instruction
.asciz "\n" @ add CR and final zero for display
cChar1: .byte 'A' @ character A
cChar2: .byte 0x41 @ character A
szCarriageReturn: .asciz "\n"
/* UnInitialized data */
.bss
/* code section */
.text
.global main
main:
ldr r0,iAdrszMessString
bl affichageMess @ display message
ldr r0,iAdrszMessString1
bl affichageMess
ldr r0,iAdrsString
bl affichageMess
ldr r0,iAdrszCarriageReturn
bl affichageMess
ldr r0,iAdrsLineSpaces
bl affichageMess
ldr r0,iAdrsCharA
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
iAdrszMessString1: .int szMessString1
iAdrsString: .int sString
iAdrsLineSpaces: .int sLineSpaces
iAdrszCarriageReturn: .int szCarriageReturn
iAdrsCharA: .int sCharA
/******************************************************************/
/* 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/Long_literals,_with_continuations | Long literals, with continuations | This task is about writing a computer program that has long literals (character
literals that may require specifying the words/tokens on more than one (source)
line, either with continuations or some other method, such as abutments or
concatenations (or some other mechanisms).
The literal is to be in the form of a "list", a literal that contains many
words (tokens) separated by a blank (space), in this case (so as to have a
common list), the (English) names of the chemical elements of the periodic table.
The list is to be in (ascending) order of the (chemical) element's atomic number:
hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium aluminum silicon ...
... up to the last known (named) chemical element (at this time).
Do not include any of the "unnamed" chemical element names such as:
ununennium unquadnilium triunhexium penthextrium penthexpentium septhexunium octenntrium ennennbium
To make computer programming languages comparable, the statement widths should be
restricted to less than 81 bytes (characters), or less
if a computer programming language has more restrictive limitations or standards.
Also mention what column the programming statements can start in if not
in column one.
The list may have leading/embedded/trailing blanks during the
declaration (the actual program statements), this is allow the list to be
more readable. The "final" list shouldn't have any leading/trailing or superfluous
blanks (when stored in the program's "memory").
This list should be written with the idea in mind that the
program will be updated, most likely someone other than the
original author, as there will be newer (discovered) elements of the periodic
table being added (possibly in the near future). These future updates
should be one of the primary concerns in writing these programs and it should be "easy"
for someone else to add chemical elements to the list (within the computer
program).
Attention should be paid so as to not exceed the clause length of
continued or specified statements, if there is such a restriction. If the
limit is greater than (say) 4,000 bytes or so, it needn't be mentioned here.
Task
Write a computer program (by whatever name) to contain a list of the known elements.
The program should eventually contain a long literal of words (the elements).
The literal should show how one could create a long list of blank-delineated words.
The "final" (stored) list should only have a single blank between elements.
Try to use the most idiomatic approach(es) in creating the final list.
Use continuation if possible, and/or show alternatives (possibly using concatenation).
Use a program comment to explain what the continuation character is if it isn't obvious.
The program should contain a variable that has the date of the last update/revision.
The program, when run, should display with verbiage:
The last update/revision date (and should be unambiguous).
The number of chemical elements in the list.
The name of the highest (last) element name.
Show all output here, on this page.
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
| #Go | Go | package main
import (
"fmt"
"regexp"
"strings"
)
// Uses a 'raw string literal' which is a character sequence enclosed in back quotes.
// Within the quotes any character (including new line) may appear except
// back quotes themselves.
var elements = `
hydrogen helium lithium beryllium
boron carbon nitrogen oxygen
fluorine neon sodium magnesium
aluminum silicon phosphorous sulfur
chlorine argon potassium calcium
scandium titanium vanadium chromium
manganese iron cobalt nickel
copper zinc gallium germanium
arsenic selenium bromine krypton
rubidium strontium yttrium zirconium
niobium molybdenum technetium ruthenium
rhodium palladium silver cadmium
indium tin antimony tellurium
iodine xenon cesium barium
lanthanum cerium praseodymium neodymium
promethium samarium europium gadolinium
terbium dysprosium holmium erbium
thulium ytterbium lutetium hafnium
tantalum tungsten rhenium osmium
iridium platinum gold mercury
thallium lead bismuth polonium
astatine radon francium radium
actinium thorium protactinium uranium
neptunium plutonium americium curium
berkelium californium einsteinium fermium
mendelevium nobelium lawrencium rutherfordium
dubnium seaborgium bohrium hassium
meitnerium darmstadtium roentgenium copernicium
nihonium flerovium moscovium livermorium
tennessine oganesson
`
func main() {
lastRevDate := "March 24th, 2020"
re := regexp.MustCompile(`\s+`) // split on one or more whitespace characters
els := re.Split(strings.TrimSpace(elements), -1)
numEls := len(els)
// Recombine as a single string with elements separated by a single space.
elements2 := strings.Join(els, " ")
// Required output.
fmt.Println("Last revision Date: ", lastRevDate)
fmt.Println("Number of elements: ", numEls)
// The compiler complains that 'elements2' is unused if we don't use
// something like this to get the last element rather than just els[numEls-1].
lix := strings.LastIndex(elements2, " ") // get index of last space
fmt.Println("Last element : ", elements2[lix+1:])
} |
http://rosettacode.org/wiki/Long_literals,_with_continuations | Long literals, with continuations | This task is about writing a computer program that has long literals (character
literals that may require specifying the words/tokens on more than one (source)
line, either with continuations or some other method, such as abutments or
concatenations (or some other mechanisms).
The literal is to be in the form of a "list", a literal that contains many
words (tokens) separated by a blank (space), in this case (so as to have a
common list), the (English) names of the chemical elements of the periodic table.
The list is to be in (ascending) order of the (chemical) element's atomic number:
hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium aluminum silicon ...
... up to the last known (named) chemical element (at this time).
Do not include any of the "unnamed" chemical element names such as:
ununennium unquadnilium triunhexium penthextrium penthexpentium septhexunium octenntrium ennennbium
To make computer programming languages comparable, the statement widths should be
restricted to less than 81 bytes (characters), or less
if a computer programming language has more restrictive limitations or standards.
Also mention what column the programming statements can start in if not
in column one.
The list may have leading/embedded/trailing blanks during the
declaration (the actual program statements), this is allow the list to be
more readable. The "final" list shouldn't have any leading/trailing or superfluous
blanks (when stored in the program's "memory").
This list should be written with the idea in mind that the
program will be updated, most likely someone other than the
original author, as there will be newer (discovered) elements of the periodic
table being added (possibly in the near future). These future updates
should be one of the primary concerns in writing these programs and it should be "easy"
for someone else to add chemical elements to the list (within the computer
program).
Attention should be paid so as to not exceed the clause length of
continued or specified statements, if there is such a restriction. If the
limit is greater than (say) 4,000 bytes or so, it needn't be mentioned here.
Task
Write a computer program (by whatever name) to contain a list of the known elements.
The program should eventually contain a long literal of words (the elements).
The literal should show how one could create a long list of blank-delineated words.
The "final" (stored) list should only have a single blank between elements.
Try to use the most idiomatic approach(es) in creating the final list.
Use continuation if possible, and/or show alternatives (possibly using concatenation).
Use a program comment to explain what the continuation character is if it isn't obvious.
The program should contain a variable that has the date of the last update/revision.
The program, when run, should display with verbiage:
The last update/revision date (and should be unambiguous).
The number of chemical elements in the list.
The name of the highest (last) element name.
Show all output here, on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Haskell | Haskell | elements = words "hydrogen \
\ fluorine neon sodium magnesium \
\ aluminum silicon phosphorous sulfur \
\ chlorine argon potassium calcium \
\ scandium titanium vanadium chromium \
\ manganese iron cobalt nickel \
\ copper zinc gallium germanium \
\ arsenic selenium bromine krypton \
\ rubidium strontium yttrium zirconium \
\ niobium molybdenum technetium ruthenium \
\ rhodium palladium silver cadmium \
\ indium tin antimony tellurium \
\ iodine xenon cesium barium \
\ lanthanum cerium praseodymium neodymium \
\ promethium samarium europium gadolinium \
\ terbium dysprosium holmium erbium \
\ thulium ytterbium lutetium hafnium \
\ tantalum tungsten rhenium osmium \
\ iridium platinum gold mercury \
\ thallium lead bismuth polonium \
\ astatine radon francium radium \
\ actinium thorium protactinium uranium \
\ neptunium plutonium americium curium \
\ berkelium californium einsteinium fermium \
\ mendelevium nobelium lawrencium rutherfordium \
\ dubnium seaborgium bohrium hassium \
\ meitnerium darmstadtium roentgenium copernicium \
\ nihonium flerovium moscovium livermorium \
\ tennessine oganesson" |
http://rosettacode.org/wiki/List_rooted_trees | List rooted trees | You came back from grocery shopping. After putting away all the goods, you are left with a pile of plastic bags, which you want to save for later use, so you take one bag and stuff all the others into it, and throw it under the sink. In doing so, you realize that there are various ways of nesting the bags, with all bags viewed as identical.
If we use a matching pair of parentheses to represent a bag, the ways are:
For 1 bag, there's one way:
() <- a bag
for 2 bags, there's one way:
(()) <- one bag in another
for 3 bags, there are two:
((())) <- 3 bags nested Russian doll style
(()()) <- 2 bags side by side, inside the third
for 4 bags, four:
(()()())
((())())
((()()))
(((())))
Note that because all bags are identical, the two 4-bag strings ((())()) and (()(())) represent the same configuration.
It's easy to see that each configuration for n bags represents a n-node rooted tree, where a bag is a tree node, and a bag with its content forms a subtree. The outermost bag is the tree root. Number of configurations for given n is given by OEIS A81.
Task
Write a program that, when given n, enumerates all ways of nesting n bags. You can use the parentheses notation above, or any tree representation that's unambiguous and preferably intuitive.
This task asks for enumeration of trees only; for counting solutions without enumeration, that OEIS page lists various formulas, but that's not encouraged by this task, especially if implementing it would significantly increase code size.
As an example output, run 5 bags. There should be 9 ways.
| #Go | Go | package main
import (
"fmt"
"log"
"os"
"strconv"
)
type tree uint64
var (
list []tree
offset = [32]uint{1: 1}
)
func add(t tree) {
list = append(list, 1|t<<1)
}
func show(t tree, l uint) {
for ; l > 0; t >>= 1 {
l--
var paren byte
if (t & 1) != 0 {
paren = '('
} else {
paren = ')'
}
fmt.Printf("%c", paren)
}
}
func listTrees(n uint) {
for i := offset[n]; i < offset[n+1]; i++ {
show(list[i], n*2)
fmt.Println()
}
}
/* assemble tree from subtrees
n: length of tree we want to make
t: assembled parts so far
sl: length of subtree we are looking at
pos: offset of subtree we are looking at
rem: remaining length to be put together
*/
func assemble(n uint, t tree, sl, pos, rem uint) {
if rem == 0 {
add(t)
return
}
if sl > rem { // need smaller sub-trees
sl = rem
pos = offset[sl]
} else if pos >= offset[sl+1] {
// used up sl-trees, try smaller ones
sl--
if sl == 0 {
return
}
pos = offset[sl]
}
assemble(n, t<<(2*sl)|list[pos], sl, pos, rem-sl)
assemble(n, t, sl, pos+1, rem)
}
func mktrees(n uint) {
if offset[n+1] > 0 {
return
}
if n > 0 {
mktrees(n - 1)
}
assemble(n, 0, n-1, offset[n-1], n-1)
offset[n+1] = uint(len(list))
}
func main() {
if len(os.Args) != 2 {
log.Fatal("There must be exactly 1 command line argument")
}
n, err := strconv.Atoi(os.Args[1])
if err != nil {
log.Fatal("Argument is not a valid number")
}
if n <= 0 || n > 19 { // stack overflow for n == 20
n = 5
}
// init 1-tree
add(0)
mktrees(uint(n))
fmt.Fprintf(os.Stderr, "Number of %d-trees: %d\n", n, offset[n+1]-offset[n])
listTrees(uint(n))
} |
http://rosettacode.org/wiki/Literals/Integer | Literals/Integer | Some programming languages have ways of expressing integer literals in bases other than the normal base ten.
Task
Show how integer literals can be expressed in as many bases as your language allows.
Note: this should not involve the calling of any functions/methods, but should be interpreted by the compiler or interpreter as an integer written to a given base.
Also show any other ways of expressing literals, e.g. for different types of integers.
Related task
Literals/Floating point
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program integer.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/*********************************/
/* Initialized data */
/*********************************/
.data
iNumberBinaire: .int 0b1100100
iNumberOctal: .int 0144
iNumberDecimal: .int 100
iNumberHexa: .int 0x64
szMessResult: .ascii "Resultat = " @ message result
sMessValeur: .fill 12, 1, ' '
.asciz "\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
push {fp,lr} @ saves 2 registers
ldr r0,iAdriNumberBinaire @ number address
ldr r0,[r0] @ load number
ldr r1,iAdrsMessValeur
bl conversion10 @ call function with 2 parameter (r0,r1)
ldr r0,iAdrszMessResult
bl affichageMess @ display message
ldr r0,iAdriNumberOctal
ldr r0,[r0]
ldr r1,iAdrsMessValeur
bl conversion10 @ call function with 2 parameter (r0,r1)
ldr r0,iAdrszMessResult
bl affichageMess @ display message
ldr r0,iAdriNumberDecimal
ldr r0,[r0]
ldr r1,iAdrsMessValeur
bl conversion10 @ call function with 2 parameter (r0,r1)
ldr r0,iAdrszMessResult
bl affichageMess @ display message
ldr r0,iAdriNumberHexa
ldr r0,[r0]
ldr r1,iAdrsMessValeur
bl conversion10 @ call function with 2 parameter (r0,r1)
ldr r0,iAdrszMessResult
bl affichageMess @ display message
100: @ standard end of the program
mov r0, #0 @ return code
pop {fp,lr} @restaur 2 registers
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdriNumberBinaire: .int iNumberBinaire
iAdriNumberOctal: .int iNumberOctal
iAdriNumberDecimal: .int iNumberDecimal
iAdriNumberHexa: .int iNumberHexa
iAdrsMessValeur: .int sMessValeur
iAdrszMessResult: .int szMessResult
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} /* save registres */
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 systeme */
pop {r0,r1,r2,r7,lr} /* restaur des 2 registres */
bx lr /* return */
/******************************************************************/
/* Converting a register to a decimal */
/******************************************************************/
/* r0 contains value and r1 address area */
conversion10:
push {r1-r4,lr} /* save registers */
mov r3,r1
mov r2,#10
1: @ start loop
bl divisionpar10 @ r0 <- dividende. quotient ->r0 reste -> r1
add r1,#48 @ digit
strb r1,[r3,r2] @ store digit on area
sub r2,#1 @ previous position
cmp r0,#0 @ stop if quotient = 0 */
bne 1b @ else loop
@ and move spaves in first on area
mov r1,#' ' @ space
2:
strb r1,[r3,r2] @ store space in area
subs r2,#1 @ @ previous position
bge 2b @ loop if r2 >= zéro
100:
pop {r1-r4,lr} @ restaur registres
bx lr @return
/***************************************************/
/* division par 10 signé */
/* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/*
/* and http://www.hackersdelight.org/ */
/***************************************************/
/* r0 dividende */
/* r0 quotient */
/* r1 remainder */
divisionpar10:
/* r0 contains the argument to be divided by 10 */
push {r2-r4} /* save registers */
mov r4,r0
ldr r3, .Ls_magic_number_10 /* r1 <- magic_number */
smull r1, r2, r3, r0 /* r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) */
mov r2, r2, ASR #2 /* r2 <- r2 >> 2 */
mov r1, r0, LSR #31 /* r1 <- r0 >> 31 */
add r0, r2, r1 /* r0 <- r2 + r1 */
add r2,r0,r0, lsl #2 /* r2 <- r0 * 5 */
sub r1,r4,r2, lsl #1 /* r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) */
pop {r2-r4}
bx lr /* leave function */
.align 4
.Ls_magic_number_10: .word 0x66666667
|
http://rosettacode.org/wiki/Logical_operations | Logical operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a function that takes two logical (boolean) values, and outputs the result of "and" and "or" on both arguments as well as "not" on the first arguments.
If the programming language doesn't provide a separate type for logical values, use the type most commonly used for that purpose.
If the language supports additional logical operations on booleans such as XOR, list them as well.
| #Ada | Ada | procedure Print_Logic(A : Boolean; B : Boolean) is
begin
Put_Line("A and B is " & Boolean'Image(A and B));
Put_Line("A or B is " & Boolean'Image(A or B));
Put_Line("A xor B is " & Boolean'Image(A xor B));
Put_Line("not A is " & Boolean'Image(not A));
end Print_Logic; |
http://rosettacode.org/wiki/Logical_operations | Logical operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a function that takes two logical (boolean) values, and outputs the result of "and" and "or" on both arguments as well as "not" on the first arguments.
If the programming language doesn't provide a separate type for logical values, use the type most commonly used for that purpose.
If the language supports additional logical operations on booleans such as XOR, list them as well.
| #Agda | Agda | module AndOrNot where
open import Data.Bool
open import Data.Product
test : Bool → Bool → Bool × Bool × Bool
test x y = x ∧ y , x ∨ y , not x |
http://rosettacode.org/wiki/Loops/N_plus_one_half | Loops/N plus one half | Quite often one needs loops which, in the last iteration, execute only part of the loop body.
Goal
Demonstrate the best way to do this.
Task
Write a loop which writes the comma-separated list
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
using separate output statements for the number
and the comma from within the body of the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Tiny_BASIC | Tiny BASIC | LET I = 1
10 IF I = 10 THEN PRINT I
IF I < 10 THEN PRINT I,", "
IF I = 10 THEN END
LET I = I + 1
GOTO 10 |
http://rosettacode.org/wiki/Loops/N_plus_one_half | Loops/N plus one half | Quite often one needs loops which, in the last iteration, execute only part of the loop body.
Goal
Demonstrate the best way to do this.
Task
Write a loop which writes the comma-separated list
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
using separate output statements for the number
and the comma from within the body of the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT
line=""
LOOP n=1,10
line=CONCAT (line,n)
IF (n!=10) line=CONCAT (line,", ")
ENDLOOP
PRINT line
|
http://rosettacode.org/wiki/Literals/Floating_point | Literals/Floating point | Programming languages have different ways of expressing floating-point literals.
Task
Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features.
You may want to include a regular expression or BNF/ABNF/EBNF defining allowable formats for your language.
Related tasks
Literals/Integer
Extreme floating point values
| #Common_Lisp | Common Lisp | float = [ sign ], { decimal-digit }, decimal-point, decimal-digit, { decimal-digit }, [exponent]
| [ sign ], decimal-digit, { decimal-digit }, [ decimal-point, { decimal-digit } ], exponent ;
exponent = exponent-marker, [ sign ], decimal-digit, { decimal-digit } ;
sign = "+" | "-" ;
decimal-point = "." ;
decimal-digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" ;
exponent-marker = "e" | "E" | "s" | "S" | "d" | "D" | "f" | "F" | "l" | "L" ; |
http://rosettacode.org/wiki/Literals/Floating_point | Literals/Floating point | Programming languages have different ways of expressing floating-point literals.
Task
Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features.
You may want to include a regular expression or BNF/ABNF/EBNF defining allowable formats for your language.
Related tasks
Literals/Integer
Extreme floating point values
| #D | D | var x = 42.02
var y = 0.174e-17 |
http://rosettacode.org/wiki/Literals/Floating_point | Literals/Floating point | Programming languages have different ways of expressing floating-point literals.
Task
Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features.
You may want to include a regular expression or BNF/ABNF/EBNF defining allowable formats for your language.
Related tasks
Literals/Integer
Extreme floating point values
| #Dyalect | Dyalect | var x = 42.02
var y = 0.174e-17 |
http://rosettacode.org/wiki/Long_year | Long year | Most years have 52 weeks, some have 53, according to ISO8601.
Task
Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
| #Elixir | Elixir | defmodule ISO do
def long_year?(y) do
{:ok, jan1} = Date.new(y,1,1)
{:ok, dec31} = Date.new(y,12,31)
Date.day_of_week(jan1) == 4 or Date.day_of_week(dec31) == 4
end
end
IO.inspect(Enum.filter(1990..2050, &ISO.long_year?/1)) |
Subsets and Splits
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.