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/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
| #Scilab | Scilab | for e=["a","b","c"]
printf("%s\n",e)
end |
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
| #Nanoquery | Nanoquery | def reverse_str(string)
to_return = ""
for i in range(len(string) - 1, 0, -1)
to_return += string[i]
end for
return to_return
end reverse_str
def luhnTest(number)
s1 = 0; s2 = 0
reversed = reverse_str(number)
for i in range(0, len(reversed) - 1)
digit = int(reversed[i])
if (i % 2) = 0
s1 += digit
else
s2 += 2 * digit
if digit >= 5
s2 -= 9
end if
end if
end for
return ((s1 + s2) % 10) = 0
end luhnTest
println luhnTest("49927398716")
println luhnTest("49927398717")
println luhnTest("1234567812345678")
println luhnTest("1234567812345670") |
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
| #Oberon-2 | Oberon-2 |
MODULE InfiniteLoop;
IMPORT
Out;
BEGIN
LOOP
Out.String("SPAM");Out.Ln
END
END InfiniteLoop.
|
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
| #Objeck | Objeck |
while(true) {
"SPAM"->PrintLine();
};
|
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
| #Monte | Monte |
var i := 1024
while (i > 0):
traceln(i)
i //= 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
| #MOO | MOO | i = 1024;
while (i > 0)
player:tell(i);
i /= 2;
endwhile |
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
| #NewLISP | NewLISP | (for (i 10 0)
(println i)) |
http://rosettacode.org/wiki/Loops/Downward_for | Loops/Downward for | Task
Write a for loop which writes a countdown from 10 to 0.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Nim | Nim | for x in countdown(10,0): echo(x) |
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.
| #LabVIEW | LabVIEW | local(x = 0)
while(#x % 6 > 0 || #x == 0) => {^
++#x
'\r' // for formatting
^} |
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.
| #Elixir | Elixir | defmodule Loops do
def loops_for(n) do
Enum.each(1..n, fn i ->
Enum.each(1..i, fn _ -> IO.write "*" end)
IO.puts ""
end)
end
end
Loops.loops_for(5) |
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
| #JavaScript | JavaScript | var output = '',
i;
for (i = 2; i <= 8; i += 2) {
output += i + ', ';
}
output += 'who do we appreciate?';
document.write(output); |
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
| #Red | Red | Red[]
repeat i 10 [
prin i
if 10 = i [break]
prin ", "
]
print "" |
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
| #Relation | Relation |
set i = 1
set result = ""
while i <= 10
set result = result . i
if i < 10
set result = result . ", "
end if
set i = i + 1
end while
echo result
|
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.
| #Action.21 | Action! | BYTE FUNC P(CARD y)
RETURN ((y+(y/4)-(y/100)+(y/400)) MOD 7)
BYTE FUNC IsLongYear(CARD y)
IF P(y)=4 OR P(y-1)=3 THEN
RETURN (1)
FI
RETURN (0)
PROC Main()
CARD y
BYTE LMARGIN=$52,oldLMARGIN
oldLMARGIN=LMARGIN
LMARGIN=0 ;remove left margin on the screen
Put(125) PutE() ;clear the screen
FOR y=1900 TO 2400
DO
IF IsLongYear(y) THEN
PrintC(y) Put(32)
FI
OD
LMARGIN=oldLMARGIN ;restore left margin on the screen
RETURN |
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.
| #Ada | Ada | -------------------------------------------------------------
-- Calculate long years
-- Reference: https://en.wikipedia.org/wiki/ISO_week_date#Weeks_per_year
-------------------------------------------------------------
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Calendar; use Ada.Calendar;
with Ada.Calendar.Formatting; use Ada.Calendar.Formatting;
procedure Main is
First_Day : Time;
Last_Day : Time;
package AC renames Ada.Calendar;
type Counter is mod 10;
Count : Counter := 0;
begin
for Yr in Year_Number loop
First_Day := AC.Time_Of (Year => Yr, Month => 1, Day => 1);
Last_Day := AC.Time_Of (Year => Yr, Month => 12, Day => 31);
-- If Jan 1 is Thursday or Dec 31 is Thursday then
-- the year is a long year
if Day_Of_Week (First_Day) = Thursday
or else Day_Of_Week (Last_Day) = Thursday
then
if Count = 0 then
New_Line;
end if;
Put (Yr'Image);
Count := Count + 1;
end if;
end loop;
end Main;
|
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
| #Action.21 | Action! | PROC Main()
CHAR ARRAY a="abc",b="ABC"
BYTE ARRAY c=[1 2 3]
BYTE i
FOR i=0 TO 2
DO
PrintF("%C%C%B%E",a(i+1),b(i+1),c(i))
OD
RETURN |
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
| #ALGOL_68 | ALGOL 68 | main: (
INT a, b;
INT seed := 4; # chosen by a fair dice roll, guaranteed to be random c.f. http://xkcd.com/221/ #
# first random; #
WHILE
a := ENTIER (next random(seed) * 20);
print((a));
# WHILE # NOT (a = 10) DO
b := ENTIER (next random(seed) * 20);
print((b, new line))
OD;
print(new line)
) |
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
| #Arturo | Arturo | lcs: function [a,b][
ls: new array.of: @[inc size a, inc size b] 0
loop.with:'i a 'x [
loop.with:'j b 'y [
ls\[i+1]\[j+1]: (x=y)? -> ls\[i]\[j] + 1
-> max @[ls\[i+1]\[j], ls\[i]\[j+1]]
]
]
[result, x, y]: @[new "", size a, size b]
while [and? [x > 0][y > 0]][
if? ls\[x]\[y] = ls\[x-1]\[y] -> x: x-1
else [
if? ls\[x]\[y] = ls\[x]\[y-1] -> y: y-1
else [
result: a\[x-1] ++ result
x: x-1
y: y-1
]
]
]
return result
]
print lcs "1234" "1224533324"
print lcs "thisisatest" "testing123testing" |
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.
| #Ada | Ada | with Ada.Text_IO, Ada.Strings.Fixed;
use Ada.Text_IO, Ada.Strings, Ada.Strings.Fixed;
function "+" (S : String) return String is
Item : constant Character := S (S'First);
begin
for Index in S'First + 1..S'Last loop
if Item /= S (Index) then
return Trim (Integer'Image (Index - S'First), Both) & Item & (+(S (Index..S'Last)));
end if;
end loop;
return Trim (Integer'Image (S'Length), Both) & Item;
end "+"; |
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.
| #FreeBASIC | FreeBASIC |
Dim As String test, test1, test2
Data "a", "bb", "ccc", "ddd", "ee", "f", "ggg", "~" ' la tilde es solo para mantener el código compacto
Do
Read test
If test = "~" Then Exit Do : End If
If Len(test) > Len(test1) Then
test1 = test
test2 = test1 & Chr(10)
Elseif Len(test) = Len(test1) Then
test2 += test & Chr(10)
End If
Loop
Print(test2)
Sleep
|
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.
| #D.C3.A9j.C3.A0_Vu | Déjà Vu | in-pair:
if = :nil dup:
false drop
else:
@in-pair &> swap &< dup
get-last lst:
get-from lst -- len lst
lis-sub pile i di:
for j range 0 -- len pile:
local :pj get-from pile j
if > &< get-last pj di:
push-to pj & di if j get-last get-from pile -- j :nil
return
push-to pile [ & di get-last get-last pile ]
lis d:
local :pile [ [ & get-from d 0 :nil ] ]
for i range 1 -- len d:
lis-sub pile i get-from d i
[ for in-pair get-last get-last pile ]
!. lis [ 3 2 6 4 5 1 ]
!. lis [ 0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15 ]
|
http://rosettacode.org/wiki/Loops/Continue | Loops/Continue | Task
Show the following output using one loop.
1, 2, 3, 4, 5
6, 7, 8, 9, 10
Try to achieve the result by forcing the next iteration within the loop
upon a specific condition, if your language allows it.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Befunge | Befunge |
1>:56+\`#v_@
+v %5:.:<
1>#v_55+,v
^ <
>" ,",,v
^ <
|
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
| #C | C | #include <stdio.h>
void lcs(const char * const sa, const char * const sb, char ** const beg, char ** const end) {
size_t apos, bpos;
ptrdiff_t len;
*beg = 0;
*end = 0;
len = 0;
for (apos = 0; sa[apos] != 0; ++apos) {
for (bpos = 0; sb[bpos] != 0; ++bpos) {
if (sa[apos] == sb[bpos]) {
len = 1;
while (sa[apos + len] != 0 && sb[bpos + len] != 0 && sa[apos + len] == sb[bpos + len]) {
len++;
}
}
if (len > *end - *beg) {
*beg = sa + apos;
*end = *beg + len;
len = 0;
}
}
}
}
int main() {
char *s1 = "thisisatest";
char *s2 = "testing123testing";
char *beg, *end, *it;
lcs(s1, s2, &beg, &end);
for (it = beg; it != end; it++) {
putchar(*it);
}
printf("\n");
return 0;
} |
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
| #Qi | Qi |
(define random-list
0 -> []
M -> [(1+ (RANDOM 20)) | (random-list (1- M))])
(define random-array
0 _ -> []
N M -> [(random-list M) | (random-array (1- N) M)])
(define array->list
_ [] -> [] \ "end outer loop" \
Stop [[] | Ra] -> (array->list Stop Ra) \ "outer loop" \
Stop [[Stop | _ ] | _ ] -> [] \ "break out from inner loop" \
Stop [[X | Rl] | Ra] -> [X | (array->list Stop [Rl | Ra])]) \ "inner loop" \
(array->list 20 (random-array 10 10))
|
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
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
var array string: things is [] ("Apple", "Banana", "Coconut");
const proc: main is func
local
var string: thing is "";
begin
for thing range things do
writeln(thing);
end for;
end func; |
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
| #Self | Self | aCollection do: [| :element | element printLine ]. |
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
| #NetRexx | NetRexx |
class LuhnTest
method main(args=String[]) static
cc = 0
cc[1] = '49927398716'
cc[2] = '49927398717'
cc[3] = '1234567812345678'
cc[4] = '1234567812345670'
loop k=1 while cc[k] <> 0
r = checksum(cc[k])
if r==0 then say cc[k].right(20) 'passed'
else say cc[k].right(20) 'failed'
end
-- Luhn algorithm checksum for credit card numbers
method checksum(t) static
if t.length()//2 then t = '0't --pad # on left with 0
t = t.reverse()
s = 0
loop j = 1 to t.length()-1 by 2
q = 2*t.substr(j+1,1)
if q>9 then q = q.left(1) + q.right(1)
s= s+t.substr(j,1)+q
end
return s//10\==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
| #OCaml | OCaml | while true do
print_endline "SPAM"
done |
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
| #Occam | Occam | #USE "course.lib"
PROC main (CHAN BYTE screen!)
WHILE TRUE
out.string("SPAM*c*n", 0, screen)
: |
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
| #Morfa | Morfa |
import morfa.io.print;
var i = 1024;
while(i > 0)
{
println(i);
i /= 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
| #Nanoquery | Nanoquery | $n = 1024
while ($n > 0)
println $n
$n = $n/2
end while |
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
| #Oberon-2 | Oberon-2 | FOR i := 10 TO 0 BY -1 DO
Out.Int(i,0);
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
| #Objeck | Objeck |
for(i := 10; i >= 0; i--;) {
i->PrintLine();
};
|
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.
| #Lasso | Lasso | local(x = 0)
while(#x % 6 > 0 || #x == 0) => {^
++#x
'\r' // for formatting
^} |
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.
| #Lambdatalk | Lambdatalk |
{def do_while
{def do_while.r
{lambda {:i}
{if {= {% :i 6} 0}
then :i (end of loop)
else :i {do_while.r {+ :i 1}}}}}
{lambda {:i}
:i {do_while.r {+ :i 1}}}}
-> do_while
{do_while 0}
-> 0 1 2 3 4 5 6 (end of loop)
|
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.
| #Erlang | Erlang | %% Implemented by Arjun Sunel
-module(nested_loops).
-export([main/0, inner_loop/0]).
main() ->
outer_loop(1).
inner_loop()->
inner_loop(1).
inner_loop(N) when N rem 5 =:= 0 ->
io:format("* ");
inner_loop(N) ->
io:fwrite("* "),
inner_loop(N+1).
outer_loop(N) when N rem 5 =:= 0 ->
io:format("*");
outer_loop(N) ->
outer_loop(N+1),
io:format("~n"),
inner_loop(N).
|
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
| #jq | jq | # If your version of jq does not have range/3, use this:
def range(m;n;step): range(0; ((n-m)/step) ) | m + (. * step);
range(2;9;2) |
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
| #REXX | REXX | /*REXX program displays: 1,2,3,4,5,6,7,8,9,10 */
do j=1 to 10
call charout ,j /*write the DO loop index (no LF). */
if j<10 then call charout ,"," /*append a comma for one-digit numbers.*/
end /*j*/
/*stick a fork in it, we're all done. */ |
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
| #Ring | Ring |
for x = 1 to 10 see x if x=10 exit ok see ", " next see nl
|
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.
| #ALGOL_68 | ALGOL 68 | BEGIN # find "long years" - years which have 53 weeks this is equivalent to #
# finding years where 1st Jan or 31st Dec are Thursdays #
# returns the day of the week of the specified date (d/m/y), Sunday = 1 #
PROC day of week = ( INT d, m, y )INT:
BEGIN
INT mm := m;
INT yy := y;
IF mm <= 2 THEN
mm := mm + 12;
yy := yy - 1
FI;
INT j = yy OVER 100;
INT k = yy MOD 100;
(d + ( ( mm + 1 ) * 26 ) OVER 10 + k + k OVER 4 + j OVER 4 + 5 * j ) MOD 7
END # day of week # ;
# returns TRUE if year is a long year, FALSE otherwise #
PROC is long year = ( INT year )BOOL:
day of week( 1, 1, year ) = 5 OR day of week( 31, 12, year ) = 5;
# show long years from 2000-2099 #
print( ( "long years 2000-2099:" ) );
FOR year FROM 2000 TO 2099 DO
IF is long year( year ) THEN print( ( " ", whole( year, 0 ) ) ) FI
OD
END |
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.
| #ALGOL-M | ALGOL-M | BEGIN
COMMENT
FIND ISO CALENDAR YEARS HAVING 53 WEEKS. THE SIMPLEST
TEST IS THAT A GIVEN YEAR WILL BE "LONG" IF EITHER THE
FIRST OR LAST DAY IS A THURSDAY;
% CALCULATE P MOD Q %
INTEGER FUNCTION MOD(P, Q);
INTEGER P, Q;
BEGIN
MOD := P - Q * (P / Q);
END;
COMMENT
RETURN DAY OF WEEK (SUN=0, MON=1, ETC.) FOR A GIVEN
GREGORIAN CALENDAR DATE USING ZELLER'S CONGRUENCE;
INTEGER FUNCTION DAYOFWEEK(MO, DA, YR);
INTEGER MO, DA, YR;
BEGIN
INTEGER Y, C, Z;
IF MO < 3 THEN
BEGIN
MO := MO + 10;
YR := YR - 1;
END
ELSE MO := MO - 2;
Y := MOD(YR, 100);
C := YR / 100;
Z := (26 * MO - 2) / 10;
Z := Z + DA + Y + (Y / 4) + (C /4) - 2 * C + 777;
DAYOFWEEK := MOD(Z, 7);
END;
% RETURN 1 IF YEAR IS LONG, OTHERWISE 0 %
INTEGER FUNCTION ISLONGYEAR(YR);
INTEGER YR;
BEGIN
INTEGER THURSDAY;
THURSDAY := 4;
IF (DAYOFWEEK(1,1,YR) = THURSDAY) OR
(DAYOFWEEK(12,31,YR) = THURSDAY) THEN
ISLONGYEAR := 1
ELSE
ISLONGYEAR := 0;
END;
% MAIN PROGRAM STARTS HERE %
INTEGER YEAR;
WRITE("ISO YEARS THAT WILL BE LONG IN THIS CENTURY:");
WRITE("");
FOR YEAR := 2000 STEP 1 UNTIL 2099 DO
BEGIN
IF ISLONGYEAR(YEAR) = 1 THEN WRITEON(YEAR);
END;
END
|
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
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure Array_Loop_Test is
type Array_Index is range 1..3;
A1 : array (Array_Index) of Character := "abc";
A2 : array (Array_Index) of Character := "ABC";
A3 : array (Array_Index) of Integer := (1, 2, 3);
begin
for Index in Array_Index'Range loop
Put_Line (A1 (Index) & A2 (Index) & Integer'Image (A3
(Index))(2));
end loop;
end Array_Loop_Test; |
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
| #AppleScript | AppleScript | repeat
set a to random number from 0 to 19
if a is 10 then
log a
exit repeat
end if
set b to random number from 0 to 19
log a & b
end repeat |
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
| #Arc | Arc | (point break
(while t
(let x (rand 20)
(prn "a: " x)
(if (is x 10)
(break)))
(prn "b: " (rand 20)))) |
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
| #AutoHotkey | AutoHotkey | lcs(a,b) { ; Longest Common Subsequence of strings, using Dynamic Programming
Loop % StrLen(a)+2 { ; Initialize
i := A_Index-1
Loop % StrLen(b)+2
j := A_Index-1, len%i%_%j% := 0
}
Loop Parse, a ; scan a
{
i := A_Index, i1 := i+1, x := A_LoopField
Loop Parse, b ; scan b
{
j := A_Index, j1 := j+1, y := A_LoopField
len%i1%_%j1% := x=y ? len%i%_%j% + 1
: (u:=len%i1%_%j%) > (v:=len%i%_%j1%) ? u : v
}
}
x := StrLen(a)+1, y := StrLen(b)+1
While x*y { ; construct solution from lengths
x1 := x-1, y1 := y-1
If (len%x%_%y% = len%x1%_%y%)
x := x1
Else If (len%x%_%y% = len%x%_%y1%)
y := y1
Else
x := x1, y := y1, t := SubStr(a,x,1) t
}
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.
| #ALGOL_68 | ALGOL 68 | OP + = (STRING s)STRING:
BEGIN
CHAR item = s[LWB s];
STRING out;
FOR index FROM LWB s + 1 TO UPB s DO
IF item /= s [index] THEN
out := whole(index - LWB s, 0) + item + (+(s [index:UPB s]));
GO TO return out
FI
OD;
out := whole (UPB s, 0) + item;
return out: out
END # + #;
OP + = (CHAR s)STRING:
+ STRING(s);
print ((+"1", new line));
print ((+(+"1"), new line));
print ((+(+(+"1")), new line));
print ((+(+(+(+"1"))), new line));
print ((+(+(+(+(+"1")))), new line));
print ((+(+(+(+(+(+"1"))))), new line));
print ((+(+(+(+(+(+(+"1")))))), new line));
print ((+(+(+(+(+(+(+(+"1"))))))), new line));
print ((+(+(+(+(+(+(+(+(+"1")))))))), new line));
print ((+(+(+(+(+(+(+(+(+(+"1"))))))))), new line)) |
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.
| #Go | Go | package main
import (
"bufio"
"os"
)
func main() {
in := bufio.NewReader(os.Stdin)
var blankLine = "\n"
var printLongest func(string) string
printLongest = func(candidate string) (longest string) {
longest = candidate
s, err := in.ReadString('\n')
defer func() {
recover()
defer func() {
recover()
}()
_ = blankLine[0]
func() {
defer func() {
recover()
}()
_ = s[len(longest)]
longest = s
}()
longest = printLongest(longest)
func() {
defer func() {
recover()
os.Stdout.WriteString(s)
}()
_ = longest[len(s)]
s = ""
}()
}()
_ = err.(error)
os.Stdout.WriteString(blankLine)
blankLine = ""
return
}
printLongest("")
} |
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.
| #Elixir | Elixir | defmodule Longest_increasing_subsequence do
# Naive implementation
def lis(l) do
(for ss <- combos(l), ss == Enum.sort(ss), do: ss)
|> Enum.max_by(fn ss -> length(ss) end)
end
defp combos(l) do
Enum.reduce(1..length(l), [[]], fn k, acc -> acc ++ (combos(k, l)) end)
end
defp combos(1, l), do: (for x <- l, do: [x])
defp combos(k, l) when k == length(l), do: [l]
defp combos(k, [h|t]) do
(for subcombos <- combos(k-1, t), do: [h | subcombos]) ++ combos(k, t)
end
end
IO.inspect Longest_increasing_subsequence.lis([3,2,6,4,5,1])
IO.inspect Longest_increasing_subsequence.lis([0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15]) |
http://rosettacode.org/wiki/Loops/Continue | Loops/Continue | Task
Show the following output using one loop.
1, 2, 3, 4, 5
6, 7, 8, 9, 10
Try to achieve the result by forcing the next iteration within the loop
upon a specific condition, if your language allows it.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Bracmat | Bracmat | ( 0:?i
& whl
' ( 1+!i:~>10:?i
& put
$ ( str
$ ( !i
(mod$(!i.5):0&\n|", ")
)
)
)
); |
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
| #C.23 | C# | using System;
namespace LongestCommonSubstring
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(lcs("thisisatest", "testing123testing"));
Console.ReadKey(true);
}
public static string lcs(string a, string b)
{
var lengths = new int[a.Length, b.Length];
int greatestLength = 0;
string output = "";
for (int i = 0; i < a.Length; i++)
{
for (int j = 0; j < b.Length; j++)
{
if (a[i] == b[j])
{
lengths[i, j] = i == 0 || j == 0 ? 1 : lengths[i - 1, j - 1] + 1;
if (lengths[i, j] > greatestLength)
{
greatestLength = lengths[i, j];
output = a.Substring(i - greatestLength + 1, greatestLength);
}
}
else
{
lengths[i, j] = 0;
}
}
}
return output;
}
}
} |
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
| #Quackery | Quackery | []
5 times
[ []
5 times [ 20 random 1+ join ]
nested join ]
dup say "Array contains:" cr
witheach
[ witheach
[ echo sp ]
cr ]
cr
say "Array up to item = 20:" cr
witheach
[ false swap
witheach
[ dup 20 = iff
[ drop not conclude ]
else
[ echo sp ] ]
iff conclude
else cr ] |
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
| #R | R | m <- 10
n <- 10
mat <- matrix(sample(1:20L, m*n, replace=TRUE), nrow=m); mat
done <- FALSE
for(i in seq_len(m))
{
for(j in seq_len(n))
{
cat(mat[i,j])
if(mat[i,j] == 20)
{
done <- TRUE
break
}
cat(", ")
}
if(done)
{
cat("\n")
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
| #SETL | SETL | S := {1,2,3,5,8,13,21,34,55,89};
for e in S loop
print(e);
end loop; |
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
| #Sidef | Sidef | foreach [1,2,3] { |i|
say 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
| #Nim | Nim | proc luhn(cc: string): bool =
const m = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9]
var sum = 0
var odd = true
for i in countdown(cc.high, 0):
let digit = ord(cc[i]) - ord('0')
sum += (if odd: digit else: m[digit])
odd = not odd
result = sum mod 10 == 0
for cc in ["49927398716", "49927398717", "1234567812345678", "1234567812345670"]:
echo cc, ' ', luhn(cc) |
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
| #Octave | Octave | while(1)
disp("SPAM")
endwhile |
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
| #Oforth | Oforth | begin "SPAM" . again |
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
| #Neko | Neko |
var i = 1024
while(i > 0) {
$print(i + "\n");
i = $idiv(i, 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
| #Nemerle | Nemerle | mutable x = 1024;
while (x > 0)
{
WriteLine($"$x");
x /= 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
| #OCaml | OCaml | for i = 10 downto 0 do
Printf.printf "%d\n" i
done |
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
| #Octave | Octave | for i = 10:-1:0
% ...
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.
| #Liberty_BASIC | Liberty BASIC |
a = 0
do
a =a +1
print a
loop until ( a mod 6) = 0
|
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.
| #Lingo | Lingo | i = 0
repeat while TRUE
i = i+1
put i
if i mod 6 = 0 then exit repeat
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.
| #ERRE | ERRE |
FOR I=1 TO 5 DO
FOR J=1 TO I DO
PRINT("*";)
END FOR
PRINT
END FOR
|
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
| #Julia | Julia | for i in 2:2:8
print(i, ", ")
end
println("whom do we appreciate?") |
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
| #Ruby | Ruby |
(1..10).each do |i|
print i
break if i == 10
print ", "
end
puts |
http://rosettacode.org/wiki/Loops/N_plus_one_half | Loops/N plus one half | Quite often one needs loops which, in the last iteration, execute only part of the loop body.
Goal
Demonstrate the best way to do this.
Task
Write a loop which writes the comma-separated list
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
using separate output statements for the number
and the comma from within the body of the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Run_BASIC | Run BASIC |
FOR i = 1 TO 10
PRINT cma$;i;
cma$ = " , "
NEXT 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.
| #ALGOL_W | ALGOL W | begin % find "long years" - years which have 53 weeks %
% this is equivalent to finding years where %
% 1st Jan or 31st Dec are Thursdays %
% finds the day of the week - Sunday = 1 %
integer procedure Day_of_week ( integer value d, m, y );
begin
integer j, k, mm, yy;
mm := m;
yy := y;
if mm <= 2 then begin
mm := mm + 12;
yy := yy - 1;
end if_m_le_2;
j := yy div 100;
k := yy rem 100;
(d + ( ( mm + 1 ) * 26 ) div 10 + k + k div 4 + j div 4 + 5 * j ) rem 7
end Day_of_week;
% returns true if year is a long year, false otherwise %
logical procedure isLongYear ( integer value year );
Day_of_week( 1, 1, year ) = 5 or Day_of_week( 31, 12, year ) = 5;
% show long years from 2000-2099 %
write( "long years 2000-2099:" );
for year := 2000 until 2099 do begin
if isLongYear( year ) then writeon( I_W := 5, S_W := 0, year )
end for_year
end. |
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.
| #APL | APL | dec31weekday ← {7|(⍵+⌊(⍵÷4)+⌊(⍵÷400)-⌊⍵÷100)}
isolongyear ← {(4 = dec31weekday ⍵) ∨ (3 = dec31weekday (⍵ - 1))} |
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
| #11l | 11l | F sieve(limit)
[Int] primes
V c = [0B] * (limit + 1)
V p = 3
L
V p2 = p * p
I p2 > limit
L.break
L(i) (p2 .< limit).step(2 * p)
c[i] = 1B
L
p += 2
I !c[p]
L.break
L(i) (3 .< limit).step(2)
I !(c[i])
primes.append(i)
R primes
F findPeriod(n)
V r = 1
L(i) 1 .< n
r = (10 * r) % n
V rr = r
V period = 0
L
r = (10 * r) % n
period++
I r == rr
L.break
R period
V primes = sieve(64000)
[Int] longPrimes
L(prime) primes
I findPeriod(prime) == prime - 1
longPrimes.append(prime)
V numbers = [500, 1000, 2000, 4000, 8000, 16000, 32000, 64000]
V count = 0
V index = 0
V totals = [0] * numbers.len
L(longPrime) longPrimes
I longPrime > numbers[index]
totals[index] = count
index++
count++
totals.last = count
print(‘The long primes up to 500 are:’)
print(String(longPrimes[0 .< totals[0]]).replace(‘,’, ‘’))
print("\nThe number of long primes up to:")
L(total) totals
print(‘ #5 is #.’.format(numbers[L.index], total)) |
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
| #ALGOL_68 | ALGOL 68 | []UNION(CHAR,INT) x=("a","b","c"), y=("A","B","C"),
z=(1,2,3);
FOR i TO UPB x DO
printf(($ggd$, x[i], y[i], z[i], $l$))
OD |
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
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program loopbreak.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessEndLoop: .asciz "loop break with value : \n"
szMessResult: .ascii "Resultat = " @ message result
sMessValeur: .fill 12, 1, ' '
.asciz "\n"
.align 4
iGraine: .int 123456
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
push {fp,lr} @ saves 2 registers
1: @ begin loop
mov r4,#20
2:
mov r0,#19
bl genereraleas @ generate number
cmp r0,#10 @ compar value
beq 3f @ break if equal
ldr r1,iAdrsMessValeur @ display value
bl conversion10 @ call function with 2 parameter (r0,r1)
ldr r0,iAdrszMessResult
bl affichageMess @ display message
subs r4,#1 @ decrement counter
bgt 2b @ loop if greather
b 1b @ begin loop one
3:
mov r2,r0 @ save value
ldr r0,iAdrszMessEndLoop
bl affichageMess @ display message
mov r0,r2
ldr r1,iAdrsMessValeur
bl conversion10 @ call function with 2 parameter (r0,r1)
ldr r0,iAdrszMessResult
bl affichageMess @ display message
100: @ standard end of the program
mov r0, #0 @ return code
pop {fp,lr} @restaur 2 registers
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrsMessValeur: .int sMessValeur
iAdrszMessResult: .int szMessResult
iAdrszMessEndLoop: .int szMessEndLoop
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registres
mov r2,#0 @ counter length
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call systeme
pop {r0,r1,r2,r7,lr} @ restaur des 2 registres */
bx lr @ return
/******************************************************************/
/* Converting a register to a decimal */
/******************************************************************/
/* r0 contains value and r1 address area */
conversion10:
push {r1-r4,lr} @ save registers
mov r3,r1
mov r2,#10
1: @ start loop
bl divisionpar10 @ r0 <- dividende. quotient ->r0 reste -> r1
add r1,#48 @ digit
strb r1,[r3,r2] @ store digit on area
sub r2,#1 @ previous position
cmp r0,#0 @ stop if quotient = 0 */
bne 1b @ else loop
@ and move spaces in first on area
mov r1,#' ' @ space
2:
strb r1,[r3,r2] @ store space in area
subs r2,#1 @ @ previous position
bge 2b @ loop if r2 >= zéro
100:
pop {r1-r4,lr} @ restaur registres
bx lr @return
/***************************************************/
/* division par 10 signé */
/* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/*
/* and http://www.hackersdelight.org/ */
/***************************************************/
/* r0 dividende */
/* r0 quotient */
/* r1 remainder */
divisionpar10:
/* r0 contains the argument to be divided by 10 */
push {r2-r4} /* save registers */
mov r4,r0
mov r3,#0x6667 @ r3 <- magic_number lower
movt r3,#0x6666 @ r3 <- magic_number upper
smull r1, r2, r3, r0 @ r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0)
mov r2, r2, ASR #2 /* r2 <- r2 >> 2 */
mov r1, r0, LSR #31 /* r1 <- r0 >> 31 */
add r0, r2, r1 /* r0 <- r2 + r1 */
add r2,r0,r0, lsl #2 /* r2 <- r0 * 5 */
sub r1,r4,r2, lsl #1 /* r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) */
pop {r2-r4}
bx lr /* leave function */
/***************************************************/
/* Generation random number */
/***************************************************/
/* r0 contains limit */
genereraleas:
push {r1-r4,lr} @ save registers
ldr r4,iAdriGraine
ldr r2,[r4]
ldr r3,iNbDep1
mul r2,r3,r2
ldr r3,iNbDep1
add r2,r2,r3
str r2,[r4] @ maj de la graine pour l appel suivant
mov r1,r0 @ divisor
mov r0,r2 @ dividende
bl division
mov r0,r3 @ résult = remainder
100: @ end function
pop {r1-r4,lr} @ restaur registers
bx lr @ return
/********************************************************************/
iAdriGraine: .int iGraine
iNbDep1: .int 0x343FD
iNbDep2: .int 0x269EC3
/***************************************************/
/* integer division unsigned */
/***************************************************/
division:
/* r0 contains dividend */
/* r1 contains divisor */
/* r2 returns quotient */
/* r3 returns remainder */
push {r4, lr}
mov r2, #0 @ init quotient
mov r3, #0 @ init remainder
mov r4, #32 @ init counter bits
b 2f
1: @ loop
movs r0, r0, LSL #1 @ r0 <- r0 << 1 updating cpsr (sets C if 31st bit of r0 was 1)
adc r3, r3, r3 @ r3 <- r3 + r3 + C. This is equivalent to r3 <- (r3 << 1) + C
cmp r3, r1 @ compute r3 - r1 and update cpsr
subhs r3, r3, r1 @ if r3 >= r1 (C=1) then r3 <- r3 - r1
adc r2, r2, r2 @ r2 <- r2 + r2 + C. This is equivalent to r2 <- (r2 << 1) + C
2:
subs r4, r4, #1 @ r4 <- r4 - 1
bpl 1b @ if r4 >= 0 (N=0) then loop
pop {r4, lr}
bx lr
|
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
| #BASIC | BASIC | FUNCTION lcs$ (a$, b$)
IF LEN(a$) = 0 OR LEN(b$) = 0 THEN
lcs$ = ""
ELSEIF RIGHT$(a$, 1) = RIGHT$(b$, 1) THEN
lcs$ = lcs$(LEFT$(a$, LEN(a$) - 1), LEFT$(b$, LEN(b$) - 1)) + RIGHT$(a$, 1)
ELSE
x$ = lcs$(a$, LEFT$(b$, LEN(b$) - 1))
y$ = lcs$(LEFT$(a$, LEN(a$) - 1), b$)
IF LEN(x$) > LEN(y$) THEN
lcs$ = x$
ELSE
lcs$ = y$
END IF
END IF
END FUNCTION |
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.
| #ALGOL-M | ALGOL-M | begin
string(1) function digit(n);
integer n;
case n of begin
digit := "0"; digit := "1"; digit := "2";
digit := "3"; digit := "4"; digit := "5";
digit := "6"; digit := "7"; digit := "8";
digit := "9";
end;
string(1) array cur[1:128];
string(1) array next[1:128];
integer curlen, i, cnt, j, n;
cur[1] := "1";
curlen := 1;
for n := 1 step 1 until 15 do begin
write("");
for i := 1 step 1 until curlen do
writeon(cur[i]);
i := j := 1;
while i <= curlen do begin
cnt := 1;
while cur[i + cnt] = cur[i] do
cnt := cnt + 1;
next[j] := digit(cnt);
next[j + 1] := cur[i];
j := j + 2;
i := i + cnt;
end;
for i := 1 step 1 until j-1 do
cur[i] := next[i];
curlen := j - 1;
end;
end |
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.
| #Groovy | Groovy | def longer = { a, b ->
def aa = a, bb = b
while (bb && aa) {
bb = bb.substring(1)
aa = aa.substring(1)
}
aa ? a : b
}
def longestStrings
longestStrings = { BufferedReader source, String longest = '' ->
String current = source.readLine()
def finalLongest = current == null \
? longest \
: longestStrings(source,longer(current,longest))
if (longer(finalLongest, current) == current) {
println current
}
return finalLongest
} |
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.
| #Erlang | Erlang |
-module(longest_increasing_subsequence).
-export([test_naive/0, test_memo/0, test_patience/0, test_patience2/0, test_compare/1]).
% **************************************************
% Interface to test the implementation
% **************************************************
test_compare(N) when N =< 20 ->
Funs = [
{"Naive", fun lis/1},
{"Memo", fun memo/1},
{"Patience", fun patience_lis/1},
{"Patience2", fun patience2/1}
],
do_compare(Funs, N);
test_compare(N) when N =< 500 ->
Funs = [
{"Memo", fun memo/1},
{"Patience", fun patience_lis/1},
{"Patience2", fun patience2/1}
],
do_compare(Funs, N);
test_compare(N) ->
Funs = [
{"Patience", fun patience_lis/1},
{"Patience2", fun patience2/1}
],
do_compare(Funs, N).
do_compare(Funs, N) ->
List = [rand:uniform(1000) || _ <- lists:seq(1,N)],
Results = [{Name, timer:tc(fun() -> F(List) end)} || {Name,F} <- Funs],
Times = [{Name, Time} || {Name, {Time, _Result}} <- Results],
io:format("Result Times: ~p~n", [Times]).
test_naive() ->
test_gen(fun lis/1).
test_memo() ->
test_gen(fun memo/1).
test_patience() ->
test_gen(fun patience_lis/1).
test_patience2() ->
test_gen(fun patience2/1).
test_gen(F) ->
show_result(F([3,2,6,4,5,1])),
show_result(F([0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15])).
show_result(Res) ->
io:format("~w\n", [Res]).
% **************************************************
% **************************************************
% Naive implementation
% **************************************************
lis(L) ->
maxBy(
fun(SS) -> length(SS) end,
[ lists:usort(SS)
|| SS <- combos(L),
SS == lists:sort(SS)]
).
% **************************************************
% Copied from http://stackoverflow.com/a/4762387/4162959
% **************************************************
maxBy(F, L) ->
element(
2,
lists:max([ {F(X), X} || X <- L])
).
% **************************************************
% Copied from https://panduwana.wordpress.com/2010/04/21/combination-in-erlang/
% **************************************************
combos(L) ->
lists:foldl(
fun(K, Acc) -> Acc++(combos(K, L)) end,
[[]],
lists:seq(1, length(L))
).
combos(1, L) ->
[[X] || X <- L];
combos(K, L) when K == length(L) ->
[L];
combos(K, [H|T]) ->
[[H | Subcombos]
|| Subcombos <- combos(K-1, T)]
++ (combos(K, T)).
% **************************************************
% **************************************************
% Memoization implementation, Roman Rabinovich
% **************************************************
memo(S) ->
put(test, #{}),
memo(S, -1).
memo([], _) -> [];
memo([H | Tail] = S, Min) when H > Min ->
case maps:get({S,Min}, get(test), undefined) of
undefined ->
L1 = [H | memo(Tail, H)],
L2 = memo(Tail, Min),
case length(L1) >= length(L2) of
true ->
Map = get(test),
put(test, Map#{{S, Min} => L1}),
L1;
_ ->
Map = get(test),
put(test, Map#{{S, Min} => L2}),
L2
end;
X -> X
end;
memo([_|Tail], Min) ->
memo(Tail, Min).
% **************************************************
% **************************************************
% Patience sort implementation
% **************************************************
patience_lis(L) ->
patience_lis(L, []).
patience_lis([H | T], Stacks) ->
NStacks =
case Stacks of
[] ->
[[{H,[]}]];
_ ->
place_in_stack(H, Stacks, [])
end,
patience_lis(T, NStacks);
patience_lis([], Stacks) ->
case Stacks of
[] ->
[];
[_|_] ->
lists:reverse( recover_lis( get_previous(Stacks) ) )
end.
place_in_stack(E, [Stack = [{H,_} | _] | TStacks], PrevStacks) when H > E ->
PrevStacks ++ [[{E, get_previous(PrevStacks)} | Stack] | TStacks];
place_in_stack(E, [Stack = [{H,_} | _] | TStacks], PrevStacks) when H =< E ->
place_in_stack(E, TStacks, PrevStacks ++ [Stack]);
place_in_stack(E, [], PrevStacks)->
PrevStacks ++ [[{E, get_previous(PrevStacks)}]].
get_previous(Stack = [_|_]) ->
hd(lists:last(Stack));
get_previous([]) ->
[].
recover_lis({E,Prev}) ->
[E|recover_lis(Prev)];
recover_lis([]) ->
[].
% **************************************************
% **************************************************
% Patience2 by Roman Rabinovich, improved performance over above
% **************************************************
patience2([]) -> [];
patience2([H|L]) ->
Piles = [[{H, undefined}]],
patience2(L, Piles, []).
patience2([], Piles, _) ->
get_seq(lists:reverse(Piles));
patience2([H|T], [[{PE,_}|_Rest] = Pile| Piles], PrevPiles) when H =< PE ->
case PrevPiles of
[] -> patience2(T, [[{H, undefined}|Pile]|Piles], []);
[[{K,_}|_]|_] -> patience2(T, lists:reverse(PrevPiles) ++ [[{H, K}|Pile]|Piles], [])
end;
patience2([H|_T] = L, [[{PE,_}|_Rest] = Pile| Piles], PrevPiles) when H > PE ->
patience2(L, Piles, [Pile|PrevPiles]);
patience2([H|T], [], [[{K,_}|_]|_]=PrevPiles) ->
patience2(T, lists:reverse([[{H,K}]|PrevPiles]), []).
get_seq([]) -> [];
get_seq([[{K,P}|_]|Rest]) ->
get_seq(P, Rest, [K]).
get_seq(undefined, [], Seq) -> Seq;
get_seq(K, [Pile|Rest], Seq) ->
case lists:keyfind(K, 1, Pile) of
undefined -> get_seq(K, Rest, Seq);
{K, P} -> get_seq(P, Rest, [K|Seq])
end.
% **************************************************
|
http://rosettacode.org/wiki/Loops/Continue | Loops/Continue | Task
Show the following output using one loop.
1, 2, 3, 4, 5
6, 7, 8, 9, 10
Try to achieve the result by forcing the next iteration within the loop
upon a specific condition, if your language allows it.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #C | C | for(int i = 1;i <= 10; i++){
printf("%d", i);
if(i % 5 == 0){
printf("\n");
continue;
}
printf(", ");
} |
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
| #C.23 | C# | using System;
class Program {
static void Main(string[] args) {
for (int i = 1; i <= 10; i++) {
Console.Write(i);
if (i % 5 == 0) {
Console.WriteLine();
continue;
}
Console.Write(", ");
}
}
} |
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
| #C.2B.2B | C++ | #include <string>
#include <algorithm>
#include <iostream>
#include <set>
#include <vector>
auto collectSubStrings( const std::string& s, int maxSubLength )
{
int l = s.length();
auto res = std::set<std::string>();
for ( int start = 0; start < l; start++ )
{
int m = std::min( maxSubLength, l - start + 1 );
for ( int length = 1; length < m; length++ )
{
res.insert( s.substr( start, length ) );
}
}
return res;
}
std::string lcs( const std::string& s0, const std::string& s1 )
{
// collect substring set
auto maxSubLength = std::min( s0.length(), s1.length() );
auto set0 = collectSubStrings( s0, maxSubLength );
auto set1 = collectSubStrings( s1, maxSubLength );
// get commons into a vector
auto common = std::vector<std::string>();
std::set_intersection( set0.begin(), set0.end(), set1.begin(), set1.end(),
std::back_inserter( common ) );
// get the longest one
std::nth_element( common.begin(), common.begin(), common.end(),
[]( const std::string& s1, const std::string& s2 ) {
return s1.length() > s2.length();
} );
return *common.begin();
}
int main( int argc, char* argv[] )
{
auto s1 = std::string( "thisisatest" );
auto s2 = std::string( "testing123testing" );
std::cout << "The longest common substring of " << s1 << " and " << s2
<< " is:\n";
std::cout << "\"" << lcs( s1, s2 ) << "\" !\n";
return 0;
} |
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
| #Racket | Racket |
#lang racket
(define (scan xss)
(for* ([xs xss]
[x xs]
#:final (= x 20))
(displayln x)))
(define matrix
(for/list ([x 10])
(for/list ([y 10])
(+ (random 20) 1))))
(scan matrix) |
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
| #Raku | Raku | my @a = [ (1..20).roll(10) ] xx *;
LINE: for @a -> @line {
for @line -> $elem {
print " $elem";
last LINE if $elem == 20;
}
print "\n";
}
print "\n"; |
http://rosettacode.org/wiki/Loops/Foreach | Loops/Foreach | Loop through and print each element in a collection in order.
Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Slate | Slate | c do: [| :obj | print: obj]. |
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
| #Smalltalk | Smalltalk | aCollection do: [ :element | element displayNl ]. |
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
| #Objeck | Objeck | bundle Default {
class Luhn {
function : IsValid(cc : String) ~ Bool {
isOdd := true;
oddSum := 0;
evenSum := 0;
for(i := cc->Size() - 1; i >= 0; i -= 1;) {
digit : Int := cc->Get(i) - '0';
if(isOdd) {
oddSum += digit;
}
else {
evenSum += digit / 5 + (2 * digit) % 10;
};
isOdd := isOdd <> true;
};
return (oddSum + evenSum) % 10 = 0;
}
function : Main(args : String[]) ~ Nil {
IsValid("49927398716")->PrintLine();
IsValid("49927398717")->PrintLine();
IsValid("1234567812345678")->PrintLine();
IsValid("1234567812345670")->PrintLine();
}
}
} |
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
| #Ol | Ol |
(let loop ()
(display "SPAM")
(loop))
|
http://rosettacode.org/wiki/Loops/Infinite | Loops/Infinite | Task
Print out SPAM followed by a newline in an infinite loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #OPL | OPL | PROC main:
LOCAL loop%
loop%=1
while loop%=1
PRINT "SPAM"
ENDWH
ENDP |
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
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref savelog symbols nobinary
say
say 'Loops/While'
x_ = 1024
loop while x_ > 0
say x_.right(6)
x_ = x_ % 2 -- integer division
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
| #NewLISP | NewLISP | (let (i 1024)
(while (> i 0)
(println i)
(setq i (/ i 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
| #Oforth | Oforth | 10 0 -1 step: i [ i println ] |
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
| #Oz | Oz | for I in 10..0;~1 do
{Show 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.
| #Lisaac | Lisaac | + val : INTEGER;
{
val := val + 1;
val.print;
'\n'.print;
val % 6 != 0
}.while_do { }; |
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.
| #Euphoria | Euphoria |
for i = 1 to 5 do
for j = 1 to i do
puts(1, "*") -- Same as "puts(1, {'*'})"
end for
puts(1, "\n") -- Same as "puts(1, {'\n'})"
end for
|
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
| #Kotlin | Kotlin | // version 1.0.6
fun main(args: Array<String>) {
for (i in 1 .. 21 step 2) print("$i ")
} |
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
| #Rust | Rust | fn main() {
for i in 1..=10 {
print!("{}{}", i, if i < 10 { ", " } else { "\n" });
}
} |
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
| #S-lang | S-lang | variable more = 0, i;
foreach i ([1:10]) {
if (more) () = printf(", ");
printf("%d", i);
more = 1;
} |
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.
| #AppleScript | AppleScript | on isLongYear(y)
-- ISO8601 weeks begin on Mondays and belong to the year in which they have the most days.
-- A year which begins on a Thursday, or which begins on a Wednesday and is a leap year,
-- has majority stakes in the weeks it overlaps at *both* ends and so has 53 weeks instead of 52.
-- Leap years divisible by 400 begin on Saturdays and so don't so need to be considered in the leap year check.
tell (current date) to set {Jan1, its day, its month, its year} to {it, 1, January, y}
set startWeekday to Jan1's weekday
return ((startWeekday is Thursday) or ((startWeekday is Wednesday) and (y mod 4 is 0) and (y mod 100 > 0)))
end isLongYear
set longYears to {}
repeat with y from 2001 to 2100
if (isLongYear(y)) then set end of longYears to y
end repeat
return longYears |
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
| #AppleScript | AppleScript | on sieveOfEratosthenes(limit)
script o
property numberList : {missing value}
end script
repeat with n from 2 to limit
set end of o's numberList to n
end repeat
repeat with n from 2 to (limit ^ 0.5 div 1)
if (item n of o's numberList is n) then
repeat with multiple from (n * n) to limit by n
set item multiple of o's numberList to missing value
end repeat
end if
end repeat
return o's numberList's numbers
end sieveOfEratosthenes
on factors(n)
set output to {}
if (n < 0) then set n to -n
set sqrt to n ^ 0.5
set limit to sqrt div 1
if (limit = sqrt) then
set end of output to limit
set limit to limit - 1
end if
repeat with i from limit to 1 by -1
if (n mod i is 0) then
set beginning of output to i
set end of output to n div i
end if
end repeat
return output
end factors
on isLongPrime(n)
if (n < 3) then return false
script o
property f : factors(n - 1)
end script
set counter to 0
repeat with fi in o's f
set fi to fi's contents
set e to 1
set base to 10
repeat until (fi = 0)
if (fi mod 2 = 1) then set e to e * base mod n
set base to base * base mod n
set fi to fi div 2
end repeat
if (e = 1) then
set counter to counter + 1
if (counter > 1) then exit repeat
end if
end repeat
return (counter = 1)
end isLongPrime
-- Task code:
on longPrimesTask()
script o
-- The isLongPrime() handler above returns the correct result for any number
-- passed to it, but feeeding it only primes in the first place speeds things up.
property primes : sieveOfEratosthenes(64000)
property longs : {}
end script
set output to {}
set counter to 0
set mileposts to {500, 1000, 2000, 4000, 8000, 16000, 32000, 64000}
set m to 1
set nextMilepost to beginning of mileposts
set astid to AppleScript's text item delimiters
repeat with p in o's primes
set p to p's contents
if (isLongPrime(p)) then
-- p being odd, it's never exactly one of the even mileposts.
if (p < 500) then
set end of o's longs to p
else if (p > nextMilepost) then
if (nextMilepost = 500) then
set AppleScript's text item delimiters to space
set end of output to "Long primes up to 500:"
set end of output to o's longs as text
end if
set end of output to "Number of long primes up to " & nextMilepost & ": " & counter
set m to m + 1
set nextMilepost to item m of mileposts
end if
set counter to counter + 1
end if
end repeat
set end of output to "Number of long primes up to " & nextMilepost & ": " & counter
set AppleScript's text item delimiters to linefeed
set output to output as text
set AppleScript's text item delimiters to astid
return output
end longPrimesTask
longPrimesTask() |
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
| #ALGOL_W | ALGOL W | begin
% declare the three arrays %
string(1) array a, b ( 1 :: 3 );
integer array c ( 1 :: 3 );
% initialise the arrays - have to do this element by element in Algol W %
a(1) := "a"; a(2) := "b"; a(3) := "c";
b(1) := "A"; b(2) := "B"; b(3) := "C";
c(1) := 1; c(2) := 2; c(3) := 3;
% loop over the arrays %
for i := 1 until 3 do write( i_w := 1, s_w := 0, a(i), b(i), c(i) );
end. |
http://rosettacode.org/wiki/Loops/Break | Loops/Break | Task
Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive).
If a number is 10, stop the loop after printing it, and do not generate any further numbers.
Otherwise, generate and print a second random number before restarting the loop.
If the number 10 is never generated as the first number in a loop, loop forever.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
| #Arturo | Arturo | while ø [
a: random 0 19
prints [a ""]
if a=10 -> break
b: random 0 19
print b
]
print "" |
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
| #BASIC256 | BASIC256 | function LCS(a, b)
if length(a) = 0 or length(b) = 0 then return ""
if right(a, 1) = right(b, 1) then
LCS = LCS(left(a, length(a) - 1), left(b, length(b) - 1)) + right(a, 1)
else
x = LCS(a, left(b, length(b) - 1))
y = LCS(left(a, length(a) - 1), b)
if length(x) > length(y) then return x else return y
end if
end function
print LCS("1234", "1224533324")
print LCS("thisisatest", "testing123testing")
end |
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.