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/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
| #Ring | Ring |
size = 5
array = newlist(size,size)
for row = 1 to size
for col = 1 to size
array[row][col] = random(19) + 1
next
next
for row = 1 to size
for col = 1 to size
see "row " + row + " col " + col + "value : " + array[row][col] + nl
if array[row][col] = 20 exit for row ok
next
next
func newlist x, y
if isstring(x) x=0+x ok
if isstring(y) y=0+y ok
aList = list(x)
for t in aList
t = list(y)
next
return aList
|
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
| #Ruby | Ruby | ary = (1..20).to_a.shuffle.each_slice(4).to_a
p ary
catch :found_it do
for row in ary
for element in row
print "%2d " % element
throw :found_it if element == 20
end
puts ","
end
end
puts "done" |
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
| #Tailspin | Tailspin |
['a', 'b', 'c'] ... -> !OUT::write
|
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
| #Tcl | Tcl | foreach i {foo bar baz} {
puts "$i"
} |
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
| #Oforth | Oforth | : luhnTest(n)
| s i |
n asString reverse ->s
0 s size loop: i [
i s at asDigit
i isEven ifTrue: [ 2 * dup 10 >= ifTrue: [ 9 - ] ] +
]
10 mod ==0 ; |
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
| #PicoLisp | PicoLisp | (loop (prinl "SPAM")) |
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
| #Pike | Pike |
while(1)
write("SPAM\n");
|
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
| #Octave | Octave | i = 1024;
while (i > 0)
disp(i)
i = floor(i/2);
endwhile |
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
| #Oforth | Oforth | 1024 while ( dup ) [ dup println 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
| #PHP | PHP | for ($i = 10; $i >= 0; $i--)
echo "$i\n"; |
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
| #PicoLisp | PicoLisp | (for (I 10 (ge0 I) (dec I))
(println I) ) |
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | value = 0;
While[
value++;
Print[value];
Mod[value,6]!=0
] |
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.
| #Fantom | Fantom |
class ForLoops
{
public static Void main ()
{
for (Int i := 1; i <= 5; ++i)
{
for (Int j := 1; j <= i; ++j)
{
Env.cur.out.print ("*")
}
Env.cur.out.printLine ("")
}
}
}
|
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
| #langur | langur | for .i = 1; .i < 10; .i += 2 {
writeln .i
} |
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
| #11l | 11l | F add_with_carry(&result, =addend, =addendpos)
L
L result.len < addendpos + 1
result.append(‘0’)
V addend_result = String(Int(addend) + Int(result[addendpos]))
V addend_digits = Array(addend_result)
result[addendpos] = addend_digits.pop()
I addend_digits.empty
L.break
addend = addend_digits.pop()
addendpos++
F longhand_multiplication(multiplicand, multiplier)
[Char] result
L(multiplicand_digit) reversed(multiplicand)
V multiplicand_offset = L.index
L(multiplier_digit) reversed(multiplier)
V multiplier_offset = L.index + multiplicand_offset
V multiplication_result = String(Int(multiplicand_digit) * Int(multiplier_digit))
L(result_digit_addend) reversed(multiplication_result)
V addend_offset = L.index + multiplier_offset
add_with_carry(&result, result_digit_addend, addend_offset)
result.reverse()
R result.join(‘’)
V sixtyfour = ‘18446744073709551616’
print(longhand_multiplication(sixtyfour, sixtyfour)) |
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
| #11l | 11l | V c = Char(‘a’) |
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
| #11l | 11l | V revdate = ‘2021-11-14’
V 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’
V items = elements.split(‘ ’)
print(‘Last revision date: ’revdate)
print(‘Number of elements: ’items.len)
print(‘Last element : ’items.last) |
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.
| #11l | 11l | F bagchain(x, n, bb, start = 0)
I n == 0
R [x]
[(Int, String)] out
L(i) start .< bb.len
V (c, s) = bb[i]
I c <= n
out.extend(bagchain((x[0] + c, x[1]‘’s), n - c, bb, i))
R out
F bags(n)
I n == 0
R [(0, ‘’)]
[(Int, String)] upto
L(x) (n - 1 .< 0).step(-1)
upto.extend(bags(x))
R bagchain((0, ‘’), n - 1, upto).map((c, s) -> (c + 1, ‘(’s‘)’))
F replace_brackets(s)
V depth = 0
[String] out
L(c) s
I c == ‘(’
out.append(‘([{’[depth % 3])
depth++
E
depth--
out.append(‘)]}’[depth % 3])
R out.join(‘’)
L(x) bags(5)
print(replace_brackets(x[1])) |
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
| #8086_Assembly | 8086 Assembly | MOV AX,4C00h
MOV BX,%1111000011110000
MOV CX,0xBEEF
MOV DL,35 |
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
| #AArch64_Assembly | AArch64 Assembly | .equ STDOUT, 1
.equ SVC_WRITE, 64
.equ SVC_EXIT, 93
.text
.global _start
_start:
stp x29, x30, [sp, -16]!
mov x29, sp
mov x0, #123 // decimal
bl print_uint64
mov x0, #0b01111011 // binary
bl print_uint64
mov x0, #0173 // octal
bl print_uint64
mov x0, #0x7b // hexadecimal
bl print_uint64
mov x0, #'{ // ascii value
bl print_uint64
mov x0, #'\{ // ascii value in another way
bl print_uint64
ldp x29, x30, [sp], 16
mov x0, #0
b _exit // exit(0);
// void print_uint64(uint64_t x) - print an unsigned integer in base 10.
print_uint64:
// x0 = remaining number to convert
// x1 = pointer to most significant digit
// x2 = 10
// x3 = x0 / 10
// x4 = x0 % 10
// compute x0 divmod 10, store a digit, repeat if x0 > 0
ldr x1, =strbuf_end
mov x2, #10
1: udiv x3, x0, x2
msub x4, x3, x2, x0
add x4, x4, #48
mov x0, x3
strb w4, [x1, #-1]!
cbnz x0, 1b
// compute the number of digits to print, then call write()
ldr x3, =strbuf_end_newline
sub x2, x3, x1
mov x0, #STDOUT
b _write
.data
strbuf:
.space 31
strbuf_end:
.ascii "\n"
strbuf_end_newline:
.align 4
.text
//////////////// system call wrappers
// ssize_t _write(int fd, void *buf, size_t count)
_write:
stp x29, x30, [sp, -16]!
mov x8, #SVC_WRITE
mov x29, sp
svc #0
ldp x29, x30, [sp], 16
ret
// void _exit(int retval)
_exit:
mov x8, #SVC_EXIT
svc #0 |
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
| #Smalltalk | Smalltalk | 1 to: 10 do: [:n |
Transcript show: n asString.
n < 10 ifTrue: [ Transcript show: ', ' ]
] |
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
| #SNOBOL4 | SNOBOL4 | loop str = str lt(i,10) (i = i + 1) :f(out)
str = str ne(i,10) ',' :s(loop)
out output = str
end |
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
| #ALGOL_W | ALGOL W | begin
real r; long real lr;
% floating point literals have the following forms: %
% 1 - a digit sequence followed by "." followed by a digit sequence %
% 2 - a digit sequence followed by "." %
% 3 - "." followed by a digit sequence %
% 4 - one of the above, followed by "'" followed by an optional sign %
% folloed by a digit sequence %
% the literal can be followed by "L", indicating it is long real %
% the literal can be followed by "I", indicating it is imaginary %
% the literal can be followed by "LI" or "IL" indicating it is a long %
% imaginary number %
% an integer literal ( digit sequence ) can also be used where a %
% floating point literal is required %
% non-imaginary examples: %
r := 1.23;
r := 1.;
r := .9;
r := 1.23'5;
r := 1.'+4;
r := .9'-12;
r := 7;
lr := 5.4321L;
end. |
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
| #Applesoft_BASIC | Applesoft BASIC | 0
19
-3
29.59
-239.4
1E10
1.9E+09
-6.66E-32
|
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
| #Arturo | Arturo | pi: 3.14
print [pi "->" type pi] |
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.
| #C.23 | C# | using static System.Console;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
public static class Program
{
public static void Main()
{
WriteLine("Long years in the 21st century:");
WriteLine(string.Join(" ", 2000.To(2100).Where(y => ISOWeek.GetWeeksInYear(y) == 53)));
}
public static IEnumerable<int> To(this int start, int end) {
for (int i = start; i < end; i++) yield return i;
}
} |
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.
| #C | C | #include <stdio.h>
#include <math.h>
// https://webspace.science.uu.nl/~gent0113/calendar/isocalendar.htm
int p(int year) {
return (int)((double)year + floor(year/4) - floor(year/100) + floor(year/400)) % 7;
}
int is_long_year(int year) {
return p(year) == 4 || p(year - 1) == 3;
}
void print_long_years(int from, int to) {
for (int year = from; year <= to; ++year) {
if (is_long_year(year)) {
printf("%d ", year);
}
}
}
int main() {
printf("Long (53 week) years between 1800 and 2100\n\n");
print_long_years(1800, 2100);
printf("\n");
return 0;
} |
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
| #Common_Lisp | Common Lisp | ; Primality test using the Sieve of Eratosthenes with a couple minor optimizations
(defun primep (n)
(cond ((and (<= n 3) (> n 1)) t)
((some #'zerop (mapcar (lambda (d) (mod n d)) '(2 3))) nil)
(t (loop for i = 5 then (+ i 6)
while (<= (* i i) n)
when (some #'zerop (mapcar (lambda (d) (mod n (+ i d))) '(0 2))) return nil
finally (return t)))))
; Translation of the long-prime algorithm from the Raku solution
(defun long-prime-p (n)
(cond
((< n 3) nil)
((not (primep n)) nil)
(t (let* ((rr (loop repeat (1+ n)
for r = 1 then (mod (* 10 r) n)
finally (return r)))
(period (loop for p = 0 then (1+ p)
for r = (mod (* 10 rr) n) then (mod (* 10 r) n)
while (and (< p n) (/= r rr))
finally (return (1+ p)))))
(= period (1- n))))))
(format t "~{~a~^, ~}" (loop for n from 1 to 500 if (long-prime-p n) collect n))
|
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
| #AutoHotkey | AutoHotkey | List1 = a,b,c
List2 = A,B,C
List3 = 1,2,3
MsgBox, % LoopMultiArrays()
List1 = a,b,c,d,e
List2 = A,B,C,D
List3 = 1,2,3
MsgBox, % LoopMultiArrays()
;---------------------------------------------------------------------------
LoopMultiArrays()
{ ; print the ith element of each
;---------------------------------------------------------------------------
local Result
StringSplit, List1_, List1, `,
StringSplit, List2_, List2, `,
StringSplit, List3_, List3, `,
Loop, % List1_0
Result .= List1_%A_Index% List2_%A_Index% List3_%A_Index% "`n"
Return, Result
} |
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
| #Batch_File | Batch File | @echo off
:loop
set /a N=%RANDOM% %% 20
echo %N%
if %N%==10 exit /b
set /a N=%RANDOM% %% 20
echo %N%
goto loop |
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
| #BBC_BASIC | BBC BASIC | REPEAT
num% = RND(20)-1
PRINT num%
IF num%=10 THEN EXIT REPEAT
PRINT RND(20)-1
UNTIL FALSE |
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 | C | #include <stdio.h>
#include <stdlib.h>
#define MAX(a, b) (a > b ? a : b)
int lcs (char *a, int n, char *b, int m, char **s) {
int i, j, k, t;
int *z = calloc((n + 1) * (m + 1), sizeof (int));
int **c = calloc((n + 1), sizeof (int *));
for (i = 0; i <= n; i++) {
c[i] = &z[i * (m + 1)];
}
for (i = 1; i <= n; i++) {
for (j = 1; j <= m; j++) {
if (a[i - 1] == b[j - 1]) {
c[i][j] = c[i - 1][j - 1] + 1;
}
else {
c[i][j] = MAX(c[i - 1][j], c[i][j - 1]);
}
}
}
t = c[n][m];
*s = malloc(t);
for (i = n, j = m, k = t - 1; k >= 0;) {
if (a[i - 1] == b[j - 1])
(*s)[k] = a[i - 1], i--, j--, k--;
else if (c[i][j - 1] > c[i - 1][j])
j--;
else
i--;
}
free(c);
free(z);
return t;
}
|
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.
| #AWK | AWK | function lookandsay(a)
{
s = ""
c = 1
p = substr(a, 1, 1)
for(i=2; i <= length(a); i++) {
if ( p == substr(a, i, 1) ) {
c++
} else {
s = s sprintf("%d%s", c, p)
p = substr(a, i, 1)
c = 1
}
}
s = s sprintf("%d%s", c, p)
return s
}
BEGIN {
b = "1"
print b
for(k=1; k <= 10; k++) {
b = lookandsay(b)
print b
}
} |
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.
| #Lua | Lua | function longer(s1, s2)
while true do
s1 = s1:sub(1, -2)
s2 = s2:sub(1, -2)
if s1:find('^$') and not s2:find('^$') then
return false
elseif s2:find('^$') then
return true
end
end
end
local output = ''
local longest = ''
for line in io.lines() do
local islonger = longer(line, longest)
if islonger and longer(longest, line) then
output = output .. line .. '\n'
elseif islonger then
longest = line
output = line .. '\n'
end
end
print(output) |
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.
| #Java | Java | import java.util.*;
public class LIS {
public static <E extends Comparable<? super E>> List<E> lis(List<E> n) {
List<Node<E>> pileTops = new ArrayList<Node<E>>();
// sort into piles
for (E x : n) {
Node<E> node = new Node<E>();
node.value = x;
int i = Collections.binarySearch(pileTops, node);
if (i < 0) i = ~i;
if (i != 0)
node.pointer = pileTops.get(i-1);
if (i != pileTops.size())
pileTops.set(i, node);
else
pileTops.add(node);
}
// extract LIS from nodes
List<E> result = new ArrayList<E>();
for (Node<E> node = pileTops.size() == 0 ? null : pileTops.get(pileTops.size()-1);
node != null; node = node.pointer)
result.add(node.value);
Collections.reverse(result);
return result;
}
private static class Node<E extends Comparable<? super E>> implements Comparable<Node<E>> {
public E value;
public Node<E> pointer;
public int compareTo(Node<E> y) { return value.compareTo(y.value); }
}
public static void main(String[] args) {
List<Integer> d = Arrays.asList(3,2,6,4,5,1);
System.out.printf("an L.I.S. of %s is %s\n", d, lis(d));
d = Arrays.asList(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15);
System.out.printf("an L.I.S. of %s is %s\n", d, lis(d));
}
} |
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
| #ColdFusion | ColdFusion | <cfscript>
for( i = 1; i <= 10; i++ )
{
writeOutput( i );
if( 0 == i % 5 )
{
writeOutput( "< br />" );
continue;
}
writeOutput( "," );
}
</cfscript> |
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
| #Factor | Factor | USING: io sequences.extras ;
"thisisatest" "testing123testing" longest-subseq print |
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
| #Fortran | Fortran |
program main
implicit none
call compare('testing123testingthing', 'thisis', 'thi')
call compare('testing', 'sting', 'sting')
call compare('thisisatest_stinger', 'testing123testingthing', 'sting')
call compare('thisisatest_stinger', 'thisis', 'thisis')
call compare('thisisatest', 'testing123testing', 'test')
call compare('thisisatest', 'thisisatest', 'thisisatest')
contains
subroutine compare(a,b,answer)
character(len=*),intent(in) :: a, b, answer
character(len=:),allocatable :: a2, match
character(len=*),parameter :: g='(*(g0))'
integer :: i
a2=a ! should really make a2 the shortest and b the longest
match=''
do i=1,len(a2)-1
call compare_sub(a2,b,match)
if(len(a2).lt.len(match))exit
a2=a2(:len(a2)-1)
enddo
write(*,g) merge('(PASSED)','(FAILED)',answer.eq.match), &
& ' longest match found: "',match,'"; expected "',answer,'"', &
& ' comparing "',a,'" and "',b,'"'
end subroutine
subroutine compare_sub(a,b,match)
character(len=*),intent(in) :: a, b
character(len=:),allocatable :: match
integer :: left, foundat, len_a
len_a=len(a)
do left=1,len_a
foundat=index(b,a(left:))
if(foundat.ne.0.and.len(match).lt.len_a-left+1)then
if(len(a(left:)).gt.len(match))then
match=a(left:)
exit
endif
endif
enddo
end subroutine compare_sub
end program main
|
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
| #Run_BASIC | Run BASIC | dim a(10,10)
cls
for row = 1 TO 10
for col = 1 TO 10
a(row,col) = INT(20 * RND(1) + 1)
next col
next row
for row = 1 to 10
for col = 1 to 10
print a(row, col)
if a(row, col) = 20 then goto [end]
next col
next row
[end]
print "At row:";row;" col:";col |
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
| #Rust | Rust | use rand::Rng;
extern crate rand;
fn main() {
let mut matrix = [[0u8; 10]; 10];
let mut rng = rand::thread_rng();
for row in matrix.iter_mut() {
for item in row.iter_mut() {
*item = rng.gen_range(0, 21);
}
}
'outer: for row in matrix.iter() {
for &item in row.iter() {
print!("{:2} ", item);
if item == 20 { break 'outer }
}
println!();
}
} |
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
| #Trith | Trith | [1 2 3 4 5] [print] each |
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
| #TUSCRIPT | TUSCRIPT | $$ MODE TUSCRIPT
week="Monday'Tuesday'Wednesday'Thursday'Friday'Saterday'Sunday"
LOOP day=week
PRINT day
ENDLOOP |
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
| #UNIX_Shell | UNIX Shell | for file in *.sh; do
echo "filename is $file"
done |
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
| #OpenEdge.2FProgress | OpenEdge/Progress | FUNCTION fnLuhnAlgorithm RETURNS LOGICAL
(INPUT pcNumber AS CHARACTER):
/*------------------------------------------------------------------------------
Purpose: Applies Luhn Algorithm to check a Number
Notes: Returns True/False Validation based on check digit
------------------------------------------------------------------------------*/
DEFINE VARIABLE cNum AS CHARACTER NO-UNDO.
DEFINE VARIABLE iCheck AS INTEGER NO-UNDO.
DEFINE VARIABLE iLength AS INTEGER NO-UNDO.
DEFINE VARIABLE iLoopCnt AS INTEGER NO-UNDO.
DEFINE VARIABLE iNum AS INTEGER NO-UNDO.
DEFINE VARIABLE iNum1 AS INTEGER NO-UNDO.
DEFINE VARIABLE iNum2 AS INTEGER NO-UNDO.
DEFINE VARIABLE iTestLength AS INTEGER NO-UNDO.
ASSIGN
iLength = LENGTH(pcNumber)
iTestLength = iLength - 1
iCheck = 1. /* 1 for the check digit we skip */
DO iLoopCnt = iTestLength TO 1 BY -1:
ASSIGN
iNum = INTEGER(SUBSTR(pcNumber,iLoopCnt,1))
iCheck = iCheck + 1.
IF iCheck MODULO 2 = 1 THEN
ASSIGN iNum1 = iNum1 + iNum.
ELSE
DO:
ASSIGN iNum2 = iNum * 2.
IF iNum2 < 10 THEN
ASSIGN iNum1 = iNum1 + iNum2.
ELSE
ASSIGN
cNum = STRING(iNum2)
iNum1 = iNum1 + INTEGER(SUBSTR(cNum,1,1)) + INTEGER(SUBSTR(cNum,2,1)).
END.
END.
ASSIGN
iNum2 = iNum1 * 9
iNum = iNum2 MODULO 10.
IF iNum = INTEGER(SUBSTR(pcNumber,iLength,1)) THEN
RETURN TRUE.
ELSE
RETURN FALSE.
END FUNCTION. /* fnLuhnAlgorithm */ |
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
| #PILOT | PILOT | *TypeSpam
type:SPAM
jump:*TypeSpam |
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
| #Pixilang | Pixilang | start:
fputs("SPAM\n")
go start |
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
| #PL.2FI | PL/I |
do forever;
put list ('SPAM'); put skip;
end; |
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
| #OOC | OOC |
main: func {
value := 1024
while (value > 0) {
value toString() println()
value /= 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
| #Oz | Oz | for I in 1024; I>0; I div 2 do
{Show I}
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
| #Pike | Pike | int main(){
for(int i = 10; i >= 0; i--){
write(i + "\n");
}
} |
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
| #PL.2FI | PL/I |
do i = 10 to 0 by -1;
put skip list (i);
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.
| #MATLAB_.2F_Octave | MATLAB / Octave | a=0;
while (1)
a = a+1;
disp(a);
if (~mod(a,6)) break; end;
end; |
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.
| #Fennel | Fennel | (for [i 1 4]
(for [j 1 i]
(io.write "*"))
(print))
|
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
| #Lasso | Lasso | loop(-to=100, -from=1, -by=2) => {^
loop_count
'\r' // for formatting
^} |
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
| #360_Assembly | 360 Assembly | LONGINT CSECT
USING LONGINT,R13
SAVEAREA B PROLOG-SAVEAREA(R15)
DC 17F'0'
DC CL8'LONGINT'
PROLOG STM R14,R12,12(R13)
ST R13,4(R15)
ST R15,8(R13)
LR R13,R15
MVC XX(1),=C'1'
MVC LENXX,=H'1' xx=1
LA R2,64
LOOPII ST R2,RLOOPII do for 64
MVC X-2(LL+2),XX-2 x=xx
MVC Y(1),=C'2'
MVC LENY,=H'1' y=2
BAL R14,LONGMULT
MVC XX-2(LL+2),Z-2 xx=longmult(xx,2) xx=xx*2
L R2,RLOOPII
ELOOPII BCT R2,LOOPII loop
MVC X-2(LL+2),XX-2
MVC Y-2(LL+2),XX-2
BAL R14,LONGMULT
MVC YY-2(LL+2),Z-2 yy=longmult(xx,xx) yy=xx*xx
XPRNT XX,LL output xx
XPRNT YY,LL output yy
RETURN L R13,4(0,R13) epilog
LM R14,R12,12(R13)
XR R15,R15 set return code
BR R14 return to caller
RLOOPII DS F
*
LONGMULT EQU * function longmult z=(x,y)
MVC LENSHIFT,=H'0' shift=''
MVC LENZ,=H'0' z=''
LH R6,LENX
LA R6,1(R6) from lenx
XR R8,R8
BCTR R8,0 by -1
LA R9,0 to 1
LOOPI BXLE R6,R8,ELOOPI do i=lenx to 1 by -1
LA R2,X
AR R2,R6 +i
BCTR R2,0
MVC CI,0(R2) ci=substr(x,i,1)
IC R0,CI ni=integer(ci)
N R0,=X'0000000F'
STH R0,NI
MVC LENT,=H'0' t=''
SR R0,R0
STH R0,CARRY carry=0
LH R7,LENY
LA R7,1(R7) from lenx
XR R10,R10
BCTR R10,0 by -1
LA R11,0 to 1
LOOPJ1 BXLE R7,R10,ELOOPJ1 do j=leny to 1 by -1
LA R2,Y
AR R2,R7 +j
BCTR R2,0
MVC CJ,0(R2) cj=substr(y,j,1)
IC R0,CJ
N R0,=X'0000000F'
STH R0,NJ nj=integer(cj)
LH R2,NI
MH R2,NJ
AH R2,CARRY
STH R2,NKR nkr=ni*nj+carry
LH R2,NKR
LA R1,10
SRDA R2,32
DR R2,R1
STH R2,NK nk=nkr//10
STH R3,CARRY carry=nkr/10
LH R2,NK
O R2,=X'000000F0'
STC R2,CK ck=string(nk)
MVC TEMP,T
MVC T(1),CK
MVC T+1(LL-1),TEMP
LH R2,LENT
LA R2,1(R2)
STH R2,LENT t=ck!!t
B LOOPJ1 next j
ELOOPJ1 EQU *
LH R2,CARRY
O R2,=X'000000F0'
STC R2,CK ck=string(carry)
MVC TEMP,T
MVC T(1),CK
MVC T+1(LL-1),TEMP
LH R2,LENT
LA R2,1(R2)
STH R2,LENT t=ck!!t
LA R2,T
AH R2,LENT
LH R3,LENSHIFT
LA R4,SHIFT
LH R5,LENSHIFT
MVCL R2,R4
LH R2,LENT
AH R2,LENSHIFT
STH R2,LENT t=t!!shift
IF1 LH R4,LENZ
CH R4,LENT if lenz>lent
BNH ELSE1
LH R2,LENZ then
LA R2,1(R2)
STH R2,L l=lenz+1
B EIF1
ELSE1 LH R2,LENT else
LA R2,1(R2)
STH R2,L l=lent+1
EIF1 EQU *
MVI TEMP,C'0' to
MVC TEMP+1(LL-1),TEMP
LA R2,TEMP
AH R2,L
SH R2,LENZ
LH R3,LENZ
LA R4,Z
LH R5,LENZ
MVCL R2,R4
MVC LENZ,L
MVC Z,TEMP z=right(z,l,'0')
MVI TEMP,C'0' to
MVC TEMP+1(LL-1),TEMP
LA R2,TEMP
AH R2,L
SH R2,LENT
LH R3,LENT
LA R4,T
LH R5,LENT
MVCL R2,R4
MVC LENT,L
MVC T,TEMP t=right(t,l,'0')
MVC LENW,=H'0' w=''
SR R0,R0
STH R0,CARRY carry=0
LH R7,L
LA R7,1(R7) from l
XR R10,R10
BCTR R10,0 by -1
LA R11,0 to 1
LOOPJ2 BXLE R7,R10,ELOOPJ2 do j=l to 1 by -1
LA R2,Z
AR R2,R7 +j
BCTR R2,0
MVC CZ,0(R2) cz=substr(z,j,1)
IC R0,CZ
N R0,=X'0000000F'
STH R0,NZ nz=integer(cz)
LA R2,T
AR R2,R7 -j
BCTR R2,0
MVC CT,0(R2) ct=substr(t,j,1)
IC R0,CT
N R0,=X'0000000F'
STH R0,NT nt=integer(ct)
LH R2,NZ
AH R2,NT
AH R2,CARRY
STH R2,NKR nkr=nz+nt+carry
LH R2,NKR
LA R1,10
SRDA R2,32
DR R2,R1
STH R2,NK
STH R3,CARRY nk=nkr//10; carry=nkr/10
LH R2,NK
O R2,=X'000000F0'
STC R2,CK ck=string(nk)
MVC TEMP,W
MVC W(1),CK
MVC W+1(LL-1),TEMP
LH R2,LENW
LA R2,1(R2)
STH R2,LENW w=ck!!w
B LOOPJ2 next j
ELOOPJ2 EQU *
LH R2,CARRY
O R2,=X'000000F0'
STC R2,CK ck=string(carry)
MVC Z(1),CK
MVC Z+1(LL-1),W
LH R2,LENW
LA R2,1(R2)
STH R2,LENZ z=ck!!w
LA R7,0 from 1
LA R10,1 by 1
LH R11,LENZ to lenz
LOOPJ3 BXH R7,R10,ELOOPJ3 do j=1 to lenz
LA R2,Z
AR R2,R7 j
BCTR R2,0
MVC ZJ(1),0(R2) zj=substr(z,j,1)
CLI ZJ,C'0' if zj^='0'
BNE ELOOPJ3 then leave j
B LOOPJ3 next j
ELOOPJ3 EQU *
IF2 CH R7,LENZ if j>lenz
BNH EIF2
LH R7,LENZ then j=lenz
EIF2 EQU *
LA R2,TEMP to
LH R3,LENZ
SR R3,R7 -j
LA R3,1(R3)
STH R3,LENTEMP
LA R4,Z from
AR R4,R7 +j
BCTR R4,0
LR R5,R3
MVCL R2,R4
MVC Z-2(LL+2),TEMP-2 z=substr(z,j)
LA R2,SHIFT
AH R2,LENSHIFT
MVI 0(R2),C'0'
LH R3,LENSHIFT
LA R3,1(R3)
STH R3,LENSHIFT shift=shift!!'0'
MVC TEMP,Z
LA R2,TEMP
AH R2,LENZ
MVC 0(2,R2),=C' '
B LOOPI next i
ELOOPI EQU *
MVI TEMP,C' '
LA R2,Z
AH R2,LENZ
LH R3,=AL2(LL)
SH R3,LENZ
LA R4,TEMP
LH R5,=H'1'
ICM R5,8,=C' '
MVCL R2,R4 z=clean(z)
BR R14 end function longmult
*
L DS H
NI DS H
NJ DS H
NK DS H
NZ DS H
NT DS H
CARRY DS H
NKR DS H
CI DS CL1
CJ DS CL1
CZ DS CL1
CT DS CL1
CK DS CL1
ZJ DS CL1
LENXX DS H
XX DS CL94
LENYY DS H
YY DS CL94
LENX DS H
X DS CL94
LENY DS H
Y DS CL94
LENZ DS H
Z DS CL94
LENT DS H
T DS CL94
LENW DS H
W DS CL94
LENSHIFT DS H
SHIFT DS CL94
LENTEMP DS H
TEMP DS CL94
LL EQU 94
YREGS
END LONGINT |
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
| #6502_Assembly | 6502 Assembly | db "Hello World" |
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
| #68000_Assembly | 68000 Assembly | DC.B "Hello World",0
EVEN |
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
| #6502_Assembly | 6502 Assembly | HelloString:
db "Hello World" ;no null terminator
GoodbyeString:
db "Goodbye World!",0
PrintString HelloString ;unimplemented macro. |
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
| #68000_Assembly | 68000 Assembly | HelloString:
DC.B "Hello World" ;no null terminator
GoodbyeString:
DC.B "Goodbye World!",0
EVEN
PrintString HelloString ;unimplemented macro. |
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
| #Arturo | Arturo | revDate: "2021-02-05"
elementString:
"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"
elements: split.words elementString
print ["Last revision date:" revDate]
print ["Number of elements:" size elements]
print ["Last element in list:" last elements] |
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
| #AWK | AWK |
# syntax: GAWK -f LONG_LITERALS_WITH_CONTINUATIONS.AWK
BEGIN {
ll_using_concatenation() ; ll_info()
ll_using_continuation() ; ll_info()
exit(0)
}
function ll_info( arr,n,x) {
n = split(str,arr," ")
printf("version: %s\n",revised)
printf("number of elements: %d\n",n)
printf("last element: %s\n",arr[n])
x = 30
printf("first & last %d characters: %s & %s\n\n",x,substr(str,1,x),substr(str,length(str)-x))
}
function ll_remove_multiple_spaces(s) {
# all element names were wrapped in one or more spaces for readability and ease of future editing
# they are removed here
gsub(/\n/," ",s) # AWK95 needs, GAWK & TAWK don't
while (s ~ / /) {
gsub(/ +/," ",s)
}
sub(/^ /,"",s)
sub(/ $/,"",s)
return(s)
}
function ll_using_concatenation( s) {
s=s" hydrogen helium lithium beryllium "
s=s" boron carbon nitrogen oxygen "
s=s" fluorine neon sodium magnesium "
s=s" aluminum silicon phosphorous sulfur "
s=s" chlorine argon potassium calcium "
s=s" scandium titanium vanadium chromium "
s=s" manganese iron cobalt nickel "
s=s" copper zinc gallium germanium "
s=s" arsenic selenium bromine krypton "
s=s" rubidium strontium yttrium zirconium "
s=s" niobium molybdenum technetium ruthenium "
s=s" rhodium palladium silver cadmium "
s=s" indium tin antimony tellurium "
s=s" iodine xenon cesium barium "
s=s" lanthanum cerium praseodymium neodymium "
s=s" promethium samarium europium gadolinium "
s=s" terbium dysprosium holmium erbium "
s=s" thulium ytterbium lutetium hafnium "
s=s" tantalum tungsten rhenium osmium "
s=s" iridium platinum gold mercury "
s=s" thallium lead bismuth polonium "
s=s" astatine radon francium radium "
s=s" actinium thorium protactinium uranium "
s=s" neptunium plutonium americium curium "
s=s" berkelium californium einsteinium fermium "
s=s" mendelevium nobelium lawrencium rutherfordium "
s=s" dubnium seaborgium bohrium hassium "
s=s" meitnerium darmstadtium roentgenium copernicium "
s=s" nihonium flerovium moscovium livermorium "
s=s" tennessine oganesson "
str = ll_remove_multiple_spaces(s)
revised = "2020-06-30"
}
function ll_using_continuation( s) {
# works with: AWK95, GAWK 3.1.4, GAWK 5, TAWK
s="\
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 \
"
str = ll_remove_multiple_spaces(s)
revised = "30JUN2020"
}
|
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 | C | #include <stdio.h>
#include <stdlib.h>
typedef unsigned int uint;
typedef unsigned long long tree;
#define B(x) (1ULL<<(x))
tree *list = 0;
uint cap = 0, len = 0;
uint offset[32] = {0, 1, 0};
void append(tree t)
{
if (len == cap) {
cap = cap ? cap*2 : 2;
list = realloc(list, cap*sizeof(tree));
}
list[len++] = 1 | t<<1;
}
void show(tree t, uint len)
{
for (; len--; t >>= 1)
putchar(t&1 ? '(' : ')');
}
void listtrees(uint n)
{
uint i;
for (i = offset[n]; i < offset[n+1]; i++) {
show(list[i], n*2);
putchar('\n');
}
}
/* 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
*/
void assemble(uint n, tree t, uint sl, uint pos, uint rem)
{
if (!rem) {
append(t);
return;
}
if (sl > rem) // need smaller subtrees
pos = offset[sl = rem];
else if (pos >= offset[sl + 1]) {
// used up sl-trees, try smaller ones
if (!--sl) return;
pos = offset[sl];
}
assemble(n, t<<(2*sl) | list[pos], sl, pos, rem - sl);
assemble(n, t, sl, pos + 1, rem);
}
void mktrees(uint n)
{
if (offset[n + 1]) return;
if (n) mktrees(n - 1);
assemble(n, 0, n-1, offset[n-1], n-1);
offset[n+1] = len;
}
int main(int c, char**v)
{
int n;
if (c < 2 || (n = atoi(v[1])) <= 0 || n > 25) n = 5;
// init 1-tree
append(0);
mktrees((uint)n);
fprintf(stderr, "Number of %d-trees: %u\n", n, offset[n+1] - offset[n]);
listtrees((uint)n);
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
| #Ada | Ada | with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
procedure Test_Literals is
begin
Put (16#2D7#);
Put (10#727#);
Put (8#1_327#);
Put (2#10_1101_0111#);
end Test_Literals; |
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
| #Aime | Aime | if ((727 == 0x2d7) && (727 == 01327)) {
o_text("true\n");
} else {
o_text("false\n");
} |
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.
| #11l | 11l | F logic(a, b)
print(‘a and b: ’(a & b))
print(‘a or b: ’(a | b))
print(‘not a: ’(!a)) |
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
| #SNUSP | SNUSP | @\>@\>@\>+++++++++<!/+. >-?\# digit and loop test
| | \@@@+@+++++# \>>.<.<</ comma and space
| \@@+@@+++++#
\@@@@=++++# |
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
| #Spin | Spin | con
_clkmode = xtal1 + pll16x
_clkfreq = 80_000_000
obj
ser : "FullDuplexSerial.spin"
pub main | n
ser.start(31, 30, 0, 115200)
repeat n from 1 to 10
ser.dec(n)
if n<10
ser.str(string(", "))
ser.str(string(13, 10))
waitcnt(_clkfreq + cnt)
ser.stop
cogstop(0) |
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
| #AWK | AWK | 2
2.
.3
45e6
45e+6
78e-9
1.2E34 |
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
| #Axe | Axe | 123→float{L₁}
float{L₁}→I |
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
| #BBC_BASIC | BBC BASIC | REM Floating-point literal syntax:
REM [-]{digit}[.]{digit}[E[-]{digit}]
REM Examples:
PRINT -123.456E-1
PRINT 1000.0
PRINT 1E-5
REM Valid but non-standard examples:
PRINT 67.
PRINT 8.9E
PRINT .33E-
PRINT -. |
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.
| #C.2B.2B | C++ | // Reference:
// https://en.wikipedia.org/wiki/ISO_week_date#Weeks_per_year
#include <iostream>
inline int p(int year) {
return (year + (year/4) - (year/100) + (year/400)) % 7;
}
bool is_long_year(int year) {
return p(year) == 4 || p(year - 1) == 3;
}
void print_long_years(int from, int to) {
for (int year = from, count = 0; year <= to; ++year) {
if (is_long_year(year)) {
if (count > 0)
std::cout << ((count % 10 == 0) ? '\n' : ' ');
std::cout << year;
++count;
}
}
}
int main() {
std::cout << "Long years between 1800 and 2100:\n";
print_long_years(1800, 2100);
std::cout << '\n';
return 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.
| #Clojure | Clojure | (defn long-year? [year]
(-> (java.time.LocalDate/of year 12 28)
(.get (.weekOfYear (java.time.temporal.WeekFields/ISO)))
(= 53)))
(filter long-year? (range 2000 2100)) |
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
| #Crystal | Crystal | require "big"
def prime?(n) # P3 Prime Generator primality test
return n | 1 == 3 if n < 5 # n: 2,3|true; 0,1,4|false
return false if n.gcd(6) != 1 # this filters out 2/3 of all integers
pc = typeof(n).new(5) # first P3 prime candidates sequence value
until pc*pc > n
return false if n % pc == 0 || n % (pc + 2) == 0 # if n is composite
pc += 6 # 1st prime candidate for next residues group
end
true
end
# The smallest divisor d of p-1 such that 10^d = 1 (mod p),
# is the length of the period of the decimal expansion of 1/p.
def long_prime?(p)
return false unless prime? p
(2...p).each do |d|
return d == (p - 1) if (p - 1) % d == 0 && (10.to_big_i ** d) % p == 1
end
false
end
start = Time.monotonic # time of starting
puts "Long primes ≤ 500:"
(2..500).each { |pc| print "#{pc} " if long_prime? pc }
puts
[500, 1000, 2000, 4000, 8000, 16000, 32000, 64000].each do |n|
puts "Number of long primes ≤ #{n}: #{(7..n).count { |pc| long_prime? pc }}"
end
puts "\nTime: #{(Time.monotonic - start).total_seconds} secs" |
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
| #AWK | AWK | BEGIN {
split("a,b,c", a, ",");
split("A,B,C", b, ",");
split("1,2,3", c, ",");
for(i = 1; i <= length(a); i++) {
print a[i] b[i] c[i];
}
} |
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
| #bc | bc | s = 1 /* seed of the random number generator */
scale = 0
/* Random number from 0 to 20. */
define r() {
auto a
while (1) {
/* Formula (from POSIX) for random numbers of low quality. */
s = (s * 1103515245 + 12345) % 4294967296
a = s / 65536 /* a in [0, 65536) */
if (a >= 16) break /* want a >= 65536 % 20 */
}
return (a % 20)
}
while (1) {
n = r()
n /* print 1st number */
if (n == 10) break
r() /* print 2nd number */
}
quit |
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
| #Befunge | Befunge |
>60v *2\<
>?>\1-:|
1+ $
>^ 7
v.:%++67<
>55+-#v_@
>60v *2\<
>?>\1-:|
1+ $
>^ 7
^ .%++67<
|
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.23 | C# | using System;
namespace LCS
{
class Program
{
static void Main(string[] args)
{
string word1 = "thisisatest";
string word2 = "testing123testing";
Console.WriteLine(lcsBack(word1, word2));
Console.ReadKey();
}
public static string lcsBack(string a, string b)
{
string aSub = a.Substring(0, (a.Length - 1 < 0) ? 0 : a.Length - 1);
string bSub = b.Substring(0, (b.Length - 1 < 0) ? 0 : b.Length - 1);
if (a.Length == 0 || b.Length == 0)
return "";
else if (a[a.Length - 1] == b[b.Length - 1])
return lcsBack(aSub, bSub) + a[a.Length - 1];
else
{
string x = lcsBack(a, bSub);
string y = lcsBack(aSub, b);
return (x.Length > y.Length) ? x : y;
}
}
}
} |
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.
| #BASIC | BASIC | 10 DEFINT A-Z: I$="1"
20 FOR Z=1 TO 15
30 PRINT I$
40 O$=""
50 FOR I=1 TO LEN(I$)
60 C=1
70 IF MID$(I$,I,1)=MID$(I$,I+C,1) THEN C=C+1: GOTO 70
80 O$=O$+CHR$(C+48)+MID$(I$,I,1)
90 I=I+C-1
100 NEXT I
110 I$=O$
120 NEXT Z |
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | FixedPoint[
StringReplace[#,
x : "\n" | StartOfString ~~ a : Except["\n"] ... ~~ "\n" ~~
b : Except["\n"] ... ~~ y : "\n" | EndOfString :>
x <> Switch[((#1 + #2) + Abs[#1 - #2])/2 &[StringLength@a,
StringLength@b], Except[StringLength@a], b,
Except[StringLength@b], a, _, a <> "\n" <> b] <> y] &, "a
bb
ccc
ddd
ee
f
ggg"] |
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.
| #MATLAB_.2F_Octave | MATLAB / Octave | function longestString(file);
fid = fopen(file);
maxlen = 0; L = {};
while ~feof(fid)
line = fgetl(fid);
if (length(line)>maxlen)
maxlen = length(line);
L = {line};
elseif (length(line)==maxlen)
L{end+1} = line;
end;
end;
fclose(fid);
disp(L);
end;
|
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.
| #JavaScript | JavaScript | function getLis(input) {
if (input.length === 0) {
return [];
}
var lisLenPerIndex = [];
let max = { index: 0, length: 1 };
for (var i = 0; i < input.length; i++) {
lisLenPerIndex[i] = 1;
for (var j = i - 1; j >= 0; j--) {
if (input[i] > input[j] && lisLenPerIndex[j] >= lisLenPerIndex[i]) {
var length = lisLenPerIndex[i] = lisLenPerIndex[j] + 1;
if (length > max.length) {
max = { index: i, length };
}
}
}
}
var lis = [input[max.index]];
for (var i = max.index; i >= 0 && max.length !== 0; i--) {
if (input[max.index] > input[i] && lisLenPerIndex[i] === max.length - 1) {
lis.unshift(input[i]);
max.length--;
}
}
return lis;
}
console.log(getLongestIncreasingSubsequence([0, 7, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]));
console.log(getLongestIncreasingSubsequence([3, 2, 6, 4, 5, 1]));
|
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
| #Common_Lisp | Common Lisp | (do ((i 1 (1+ i)))
((> i 10))
(format t "~a~:[, ~;~%~]" i (zerop (mod i 5))))
(do ((i 1 (1+ i)))
((> i 10))
(write i)
(when (zerop (mod i 5))
(terpri)
(go end))
(write-string ", ")
end)
(do ((i 1 (1+ i)))
((> i 10))
(write i)
(if (zerop (mod i 5))
(terpri)
(write-string ", "))) |
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
| #FreeBASIC | FreeBASIC | Function LCS(a As String, b As String) As String
If Len(a) = 0 Or Len(b) = 0 Then Return ""
While Len(b)
For j As Integer = Len(b) To 1 Step -1
If Instr(a, Left(b, j)) Then Return Left(b, j)
Next j
b = Mid(b, 2)
Wend
End Function
Print LCS("thisisatest", "testing123testing")
Sleep |
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
| #Sather | Sather | class MAIN is
main is
a:ARRAY2{INT} := #(10,10);
i, j :INT;
RND::seed(1230);
loop i := 0.upto!(9);
loop j := 0.upto!(9);
a[i, j] := RND::int(1, 20);
end;
end;
loopthis ::= true;
loop i := 0.upto!(9); while!( loopthis );
loop j := 0.upto!(9);
#OUT + " " + a[i, j];
if a[i, j] = 20 then
loopthis := false;
break!;
end;
end;
end;
end;
end; |
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
| #Scala | Scala | import scala.util.control.Breaks._
val a=Array.fill(5,4)(scala.util.Random.nextInt(21))
println(a map (_.mkString("[", ", ", "]")) mkString "\n")
breakable {
for(row <- a; x <- row){
println(x)
if (x==20) break
}
} |
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
| #V | V | [1 2 3] [puts] step |
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
| #Vala | Vala | List<string> things = new List<string> ();
things.append("Apple");
things.append("Banana");
things.append("Coconut");
foreach (string thing in things)
{
stdout.printf("%s\n", thing);
} |
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
| #Order | Order | #include <order/interpreter.h>
#define ORDER_PP_DEF_8luhn ORDER_PP_FN( \
8fn(8N, 8if(8is_seq(8N), 8luhn_wk(8num_to_seq(8N)), 8false)) )
#define ORDER_PP_DEF_8num_to_seq ORDER_PP_FN( \
8fn(8N, 8seq_push_back(8seq(8seq_last(8N)), 8seq_pop_back(8N))) )
#define ORDER_PP_DEF_8luhn_wk ORDER_PP_FN( \
8fn(8N, \
8lets((8P, 8unzip(8N, 8nil, 8nil, 8true)) \
(8O, 8seq_fold(8plus, 0, 8tuple_at_0(8P))) \
(8E, 8seq_fold(8plus, 0, \
8seq_map(8dig_map, 8tuple_at_1(8P)))), \
8is_0(8remainder(8plus(8O, 8E), 10)))) )
#define ORDER_PP_DEF_8dig_map ORDER_PP_FN( \
8fn(8X, 8tuple_at(8X, 8tuple(0,2,4,6,8,1,3,5,7,9))) )
#define ORDER_PP_DEF_8unzip ORDER_PP_FN( \
8fn(8S, 8L, 8R, 8O, \
8if(8is_nil(8S), \
8pair(8L, 8R), \
8if(8O, \
8unzip(8seq_tail(8S), 8seq_push_back(8seq_head(8S), 8L), \
8R, 8false), \
8unzip(8seq_tail(8S), 8L, \
8seq_push_back(8seq_head(8S), 8R), 8true)))) )
ORDER_PP(8seq_to_tuple(
8seq_map(8luhn, 8seq(8nat(4,9,9,2,7,3,9,8,7,1,6),
8nat(4,9,9,2,7,3,9,8,7,1,7),
8nat(1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8),
8nat(1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,0)))
)) |
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
| #Plain_English | Plain English | To run:
Start up.
Write SPAM forever.
Shut down.
To write SPAM forever:
Write "SPAM" to the console.
Repeat. |
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
| #Plain_TeX | Plain TeX | \newlinechar`\^^J
\def\spam{\message{SPAM^^J}\spam}%
\spam |
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
| #Pop11 | Pop11 | while true do
printf('SPAM', '%p\n');
endwhile; |
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
| #Panda | Panda | fun half(a) type integer->integer a.divide(2)
1024.trans(func:half).gt(0) nl
|
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
| #Panoramic | Panoramic | dim x%:rem an integer
x%=1024
while x%>0
print x%
x%=x%/2
end_while
rem output starts with 1024 and ends with 1.
terminate |
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
| #Plain_English | Plain English | To run:
Start up.
Put 11 into a counter.
Loop.
If the counter is below 0, break.
Convert the counter to a string.
Write the string on the console.
Repeat.
Wait for the escape key.
Shut down.
To decide if a counter is below a number:
Subtract 1 from the counter.
If the counter is less than the number, say yes.
Say no. |
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
| #Pop11 | Pop11 | lvars i;
for i from 10 by -1 to 0 do
printf(i, '%p\n');
endfor; |
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.
| #Maxima | Maxima | block([n: 0], do (ldisp(n: n + 1), if mod(n, 6) = 0 then return('done)))$ |
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.
| #MAXScript | MAXScript | a = 0
do
(
print a
a += 1
)
while mod a 6 != 0 |
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.
| #Fermat | Fermat |
for i = 1 to 5 do for j = 1 to i do !'*'; od; !; od
|
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
| #LIL | LIL | for {set i 1} {$i < 15} {inc i 3} {print $i} |
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
| #Ada | Ada | package Long_Multiplication is
type Number (<>) is private;
Zero : constant Number;
One : constant Number;
function Value (Item : in String) return Number;
function Image (Item : in Number) return String;
overriding
function "=" (Left, Right : in Number) return Boolean;
function "+" (Left, Right : in Number) return Number;
function "*" (Left, Right : in Number) return Number;
function Trim (Item : in Number) return Number;
private
Bits : constant := 16;
Base : constant := 2 ** Bits;
type Accumulated_Value is range 0 .. (Base - 1) * Base;
subtype Digit is Accumulated_Value range 0 .. Base - 1;
type Number is array (Natural range <>) of Digit;
for Number'Component_Size use Bits; -- or pragma Pack (Number);
Zero : constant Number := (1 .. 0 => 0);
One : constant Number := (0 => 1);
procedure Divide (Dividend : in Number;
Divisor : in Digit;
Result : out Number;
Remainder : out Digit);
end Long_Multiplication; |
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.