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/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
#Perl
Perl
for my $i(1..10) { print $i; last if $i == 10; print ', '; } print "\n";
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.
#AppleScript
AppleScript
on longestIncreasingSubsequences(aList) script o property inputList : aList property m : {} -- End indices of identified subsequences. property p : {} -- 'Predecessor' indices for each point in each subsequence. property subsequence : {} -- Reconstructed longest sequence. end script -- Set m and p to lists of the same length as the input. Their initial contents don't matter! copy aList to o's m copy aList to o's p   set bestLength to 0 repeat with i from 1 to (count o's inputList) -- Comments adapted from those in the Wikipedia article — as far as they can be understood! -- Binary search for the largest possible 'lo' ≤ bestLength such that inputList[m[lo]] ≤ inputList[i]. set lo to 1 set hi to bestLength repeat until (lo > hi) set mid to (lo + hi + 1) div 2 if (item (item mid of o's m) of o's inputList < item i of o's inputList) then set lo to mid + 1 else set hi to mid - 1 end if end repeat -- After searching, lo is 1 greater than the length of the longest prefix of inputList[i]. -- The predecessor of inputList[i] is the last index of the subsequence of length lo - 1. if (lo > 1) then set item i of o's p to item (lo - 1) of o's m set item lo of o's m to i -- If we found a subsequence longer than or the same length as any we've found yet, -- update bestLength and store the end index associated with it. if (lo > bestLength) then set bestLength to lo set bestEndIndices to {item bestLength of o's m} else if (lo = bestLength) then set end of bestEndIndices to item bestLength of o's m end if end repeat -- Reconstruct the longest increasing subsequence(s). set output to {} if (bestLength > 0) then repeat with k in bestEndIndices set o's subsequence to {} repeat bestLength times set beginning of o's subsequence to item k of o's inputList set k to item k of o's p end repeat set end of output to o's subsequence end repeat end if   return output end longestIncreasingSubsequences   -- Task code and other tests: local tests, output, input set tests to {{3, 2, 6, 4, 5, 1}, {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}, ¬ {9, 10, 11, 3, 8, 9, 6, 7, 4, 5}, {4, 5, 5, 6}, {5, 5}} set output to {} repeat with input in tests set end of output to {finds:longestIncreasingSubsequences(input's contents)} end repeat return output
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
#360_Assembly
360 Assembly
* Loops/Continue 12/08/2015 LOOPCONT CSECT USING LOOPCONT,R12 LR R12,R15 BEGIN LA R8,0 SR R5,R5 LA R6,1 LA R7,10 LOOPI BXH R5,R6,ELOOPI for i=1 to 10 LA R3,MVC(R8) XDECO R5,XDEC MVC 0(4,R3),XDEC+8 LA R8,4(R8) LR R10,R5 LA R1,5 SRDA R10,32 DR R10,R1 LTR R10,R10 BNZ COMMA XPRNT MVC,80 LA R8,0 B NEXTI COMMA LA R3,MVC(R8) MVC 0(2,R3),=C', ' LA R8,2(R8) NEXTI B LOOPI next i ELOOPI XR R15,R15 BR R14 MVC DC CL80' ' XDEC DS CL16 YREGS END LOOPCONT
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
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO;   procedure Loop_Continue is begin for I in 1..10 loop Put (Integer'Image(I)); if I = 5 or I = 10 then New_Line; goto Continue; end if; Put (","); <<Continue>> --Ada 2012 no longer requires a statement after the label end loop; end Loop_Continue;
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
#Action.21
Action!
BYTE Func Equals(CHAR ARRAY a,b) BYTE i   IF a(0)#b(0) THEN RETURN (0) FI   FOR i=1 TO a(0) DO IF a(i)#b(i) THEN RETURN (0) FI OD RETURN (1)   PROC Lcs(CHAR ARRAY a,b,res) CHAR ARRAY t(100) BYTE i,j,len   IF a(0)<b(0) THEN len=a(0) ELSE len=b(0) FI   WHILE len>0 DO FOR i=1 to a(0)-len+1 DO SCopyS(res,a,i,i+len-1) FOR j=1 to b(0)-len+1 DO SCopyS(t,b,j,j+len-1) IF Equals(res,t) THEN RETURN FI OD OD len==-1 OD res(0)=0 RETURN   PROC Test(CHAR ARRAY a,b) CHAR ARRAY res(100)   Lcs(a,b,res) PrintF("lcs(""%S"",""%S"")=""%S""%E",a,b,res) RETURN   PROC Main() Test("thisisatest","testing123testing") RETURN
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
#PARI.2FGP
PARI/GP
M=matrix(10,10,i,j,random(20)+1); for(i=1,10,for(j=1,10,if(M[i,j]==20,break(2))))
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
#Python
Python
for i in collection: print i
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
#Quackery
Quackery
$ "Sweet Boom Pungent Prickle Orange" nest$ witheach [ i times sp echo$ cr ]
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
#R
R
a <- list("First", "Second", "Third", 5, 6) for(i in a) print(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
#Logo
Logo
to small? :list output or [empty? :list] [empty? bf :list] end to every.other :list if small? :list [output :list] output fput first :list every.other bf bf :list end to wordtolist :word output map.se [?] :word end   to double.digit :digit output item :digit {0 2 4 6 8 1 3 5 7 9}@0  ; output ifelse :digit < 5 [2*:digit] [1 + modulo 2*:digit 10] end   to luhn :credit localmake "digits reverse filter [number? ?] wordtolist :credit localmake "s1 apply "sum every.other :digits localmake "s2 apply "sum map "double.digit every.other bf :digits output equal? 0 last sum :s1 :s2 end   show luhn "49927398716  ; true show luhn "49927398717  ; false show luhn "1234-5678-1234-5678  ; false show luhn "1234-5678-1234-5670  ; true
http://rosettacode.org/wiki/Lucas-Lehmer_test
Lucas-Lehmer test
Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2 − 2 {\displaystyle S(n+1)=(S(n))^{2}-2} , and S ( 1 ) = 4 {\displaystyle S(1)=4} . Task Calculate all Mersenne primes up to the implementation's maximum precision, or the 47th Mersenne prime   (whichever comes first).
#Visual_Basic_.NET
Visual Basic .NET
Public Class LucasLehmer Private Sub btnGo_Click(sender As Object, e As EventArgs) Handles btnGo.Click Const iexpmax = 31 Dim s, n As Long Dim i, iexp As Integer n = 1 txtOut.Text = "" For iexp = 2 To iexpmax If iexp = 2 Then s = 0 Else s = 4 End If n = (n + 1) * 2 - 1 For i = 1 To iexp - 2 s = (s * s - 2) Mod n Next i If s = 0 Then txtOut.Text = txtOut.Text & "M" & iexp & " " End If Next iexp End Sub End Class
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
#MAXScript
MAXScript
while true do print "SPAM\n"
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
#MelonBasic
MelonBasic
Say:"SPAM" Goto:1
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
#Metafont
Metafont
forever: message "SPAM"; endfor 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
#Make
Make
NEXT=`expr $* / 2` MAX=10   all: $(MAX)-n;   0-n:;   %-n: %-echo @-make -f while.mk $(NEXT)-n MAX=$(MAX)   %-echo: @echo $*
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
#Maple
Maple
> n := 1024: while n > 0 do print(n); n := iquo(n,2) end: 1024 512 256 128 64 32 16 8 4 2 1
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
#Maple
Maple
for i from 10 to 0 by -1 do print(i) end:
http://rosettacode.org/wiki/Loops/Downward_for
Loops/Downward for
Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
For[i = 10, i >= 0, i--, Print[i]]
http://rosettacode.org/wiki/Loops/Do-while
Loops/Do-while
Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges Reference Do while loop Wikipedia.
#GW-BASIC
GW-BASIC
  10 LET I% = 0 20 ' first iteration - before the WHILE 30 LET I% = I% + 1 40 PRINT I% 50 WHILE I% MOD 6 <> 0 60 LET I% = I% + 1 70 PRINT I% 80 WEND  
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.
#DWScript
DWScript
var i, j : Integer;   for i := 1 to 5 do begin for j := 1 to i do Print('*'); PrintLn(''); end;
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
#Haxe
Haxe
class Step { var end:Int; var step:Int; var index:Int;   public inline function new(start:Int, end:Int, step:Int) { this.index = start; this.end = end; this.step = step; }   public inline function hasNext() return step > 0 ? end >= index : index >= end; public inline function next() return (index += step) - step; }   class Main { static function main() { for (i in new Step(2, 8, 2)) { Sys.print('$i '); } Sys.println('WHOM do we appreciate? GRAMMAR! GRAMMAR! GRAMMAR!'); } }
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
#Phix
Phix
for i=1 to 10 do printf(1,"%d",i) if i=10 then exit end if printf(1,", ") end for
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
#PHP
PHP
for ($i = 1; $i <= 11; $i++) { echo $i; if ($i == 10) break; echo ', '; } echo "\n";
http://rosettacode.org/wiki/Longest_string_challenge
Longest string challenge
Background This "longest string challenge" is inspired by a problem that used to be given to students learning Icon. Students were expected to try to solve the problem in Icon and another language with which the student was already familiar. The basic problem is quite simple; the challenge and fun part came through the introduction of restrictions. Experience has shown that the original restrictions required some adjustment to bring out the intent of the challenge and make it suitable for Rosetta Code. Basic problem statement Write a program that reads lines from standard input and, upon end of file, writes the longest line to standard output. If there are ties for the longest line, the program writes out all the lines that tie. If there is no input, the program should produce no output. Task Implement a solution to the basic problem that adheres to the spirit of the restrictions (see below). Describe how you circumvented or got around these 'restrictions' and met the 'spirit' of the challenge. Your supporting description may need to describe any challenges to interpreting the restrictions and how you made this interpretation. You should state any assumptions, warnings, or other relevant points. The central idea here is to make the task a bit more interesting by thinking outside of the box and perhaps by showing off the capabilities of your language in a creative way. Because there is potential for considerable variation between solutions, the description is key to helping others see what you've done. This task is likely to encourage a variety of different types of solutions. They should be substantially different approaches. Given the input: a bb ccc ddd ee f ggg the output should be (possibly rearranged): ccc ddd ggg Original list of restrictions No comparison operators may be used. No arithmetic operations, such as addition and subtraction, may be used. The only datatypes you may use are integer and string. In particular, you may not use lists. Do not re-read the input file. Avoid using files as a replacement for lists (this restriction became apparent in the discussion). Intent of restrictions Because of the variety of languages on Rosetta Code and the wide variety of concepts used in them, there needs to be a bit of clarification and guidance here to get to the spirit of the challenge and the intent of the restrictions. The basic problem can be solved very conventionally, but that's boring and pedestrian. The original intent here wasn't to unduly frustrate people with interpreting the restrictions, it was to get people to think outside of their particular box and have a bit of fun doing it. The guiding principle here should be to be creative in demonstrating some of the capabilities of the programming language being used. If you need to bend the restrictions a bit, explain why and try to follow the intent. If you think you've implemented a 'cheat', call out the fragment yourself and ask readers if they can spot why. If you absolutely can't get around one of the restrictions, explain why in your description. Now having said that, the restrictions require some elaboration. In general, the restrictions are meant to avoid the explicit use of these features. "No comparison operators may be used" - At some level there must be some test that allows the solution to get at the length and determine if one string is longer. Comparison operators, in particular any less/greater comparison should be avoided. Representing the length of any string as a number should also be avoided. Various approaches allow for detecting the end of a string. Some of these involve implicitly using equal/not-equal; however, explicitly using equal/not-equal should be acceptable. "No arithmetic operations" - Again, at some level something may have to advance through the string. Often there are ways a language can do this implicitly advance a cursor or pointer without explicitly using a +, - , ++, --, add, subtract, etc. The datatype restrictions are amongst the most difficult to reinterpret. In the language of the original challenge strings are atomic datatypes and structured datatypes like lists are quite distinct and have many different operations that apply to them. This becomes a bit fuzzier with languages with a different programming paradigm. The intent would be to avoid using an easy structure to accumulate the longest strings and spit them out. There will be some natural reinterpretation here. To make this a bit more concrete, here are a couple of specific examples: In C, a string is an array of chars, so using a couple of arrays as strings is in the spirit while using a second array in a non-string like fashion would violate the intent. In APL or J, arrays are the core of the language so ruling them out is unfair. Meeting the spirit will come down to how they are used. Please keep in mind these are just examples and you may hit new territory finding a solution. There will be other cases like these. Explain your reasoning. You may want to open a discussion on the talk page as well. The added "No rereading" restriction is for practical reasons, re-reading stdin should be broken. I haven't outright banned the use of other files but I've discouraged them as it is basically another form of a list. Somewhere there may be a language that just sings when doing file manipulation and where that makes sense; however, for most there should be a way to accomplish without resorting to an externality. At the end of the day for the implementer this should be a bit of fun. As an implementer you represent the expertise in your language, the reader may have no knowledge of your language. For the reader it should give them insight into how people think outside the box in other languages. Comments, especially for non-obvious (to the reader) bits will be extremely helpful. While the implementations may be a bit artificial in the context of this task, the general techniques may be useful elsewhere.
#Ada
Ada
with Ada.Text_IO;   procedure Longest_Strings is use Ada.Text_IO;   -- first, in order to strictly use integer, I use integer in -- place of an enumeration type: -1 => not-equal -- 0 => shorter - ignore, no print current string -- 1 => equal - print current and up-stream -- 2 => longer - no print upstream, only current and equal subsequent -- others => null; -- must never happen. -- -- Anything else that is tested or used that is not a string or integer -- is not used explicitly by me, but is a standard part of the language -- as provided in the standard libraries (like boolean "End_Of_File").   function Measure_And_Print_N (O : String := ""; -- original/old string N : String := "" -- next/new string ) return Integer is T1 : String := O; T2 : String := N; L  : Integer := 1; -- Length defaults to the same; function Test_Length (O : in out String; -- original/old string N : in out String) -- new/test-subject string return Integer is function Test_Equal (O : in out String; N : in out String) return Integer is begin O := N; return 1; exception when Constraint_Error => return -1; end; begin case Test_Equal (O, N) is when -1 => O (N'Range) := N; return 0; when 1 => return 1; when others => return -1; end case; exception when Constraint_Error => return 2; end; begin case Test_Length (T1, T2) is when 0 =>   -- N < O, so return "shorter" do not print N   if End_Of_File then return 0; else case Measure_And_Print_N (O, Get_Line) is when 0 => return 0; when 1 => return 0; when 2 => return 2; -- carry up any subsequent canceling of print. when others => raise Numeric_Error; end case; end if; when 1 =>   -- O = N, so return "equal" print N if all subsequent values are -- less than or equal to N   if End_Of_File then Put_Line (N); return 1; else case Measure_And_Print_N (O, Get_Line) is when 0 => Put_Line (N); return 1; when 1 => Put_Line (N); return 1; when 2 => -- carry up the subsequent canceling of print. null; return 2; when others => raise Numeric_Error; end case; end if; when 2 =>   -- N > O, so return "longer" to cancel printing all previous values -- and print N if it is also equal to or greater than descendant -- values.   if End_Of_File then Put_Line (N); return 2; else case Measure_And_Print_N (N, Get_Line) is when 0 => Put_Line (N); return 2; when 1 => Put_Line (N); return 2; when 2 => -- printing N cancelled by subsequent input. null; return 2; when others => raise Numeric_Error; end case; end if; when others =>   -- This should never happen - raise exception   raise Numeric_Error; end case; end; begin if End_Of_File then null; else case Measure_And_Print_N ("", Get_Line) is when 0 => Put_Line (Current_Error, "Error, Somehow the input line is calculated as less than zero!"); when 1 => Put_Line (Current_Error, "All input lines appear to be blank."); when 2 => null; when others => raise Numeric_Error; end case; end if; end;  
http://rosettacode.org/wiki/Longest_increasing_subsequence
Longest increasing subsequence
Calculate and show here a longest increasing subsequence of the list: { 3 , 2 , 6 , 4 , 5 , 1 } {\displaystyle \{3,2,6,4,5,1\}} And of the list: { 0 , 8 , 4 , 12 , 2 , 10 , 6 , 14 , 1 , 9 , 5 , 13 , 3 , 11 , 7 , 15 } {\displaystyle \{0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15\}} Note that a list may have more than one subsequence that is of the maximum length. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet Ref Dynamic Programming #1: Longest Increasing Subsequence on YouTube An efficient solution can be based on Patience sorting.
#Arturo
Arturo
lis: function [d][ l: new [[]] loop d 'num [ x: [] loop l 'seq [ if positive? size seq [ if and? num > last seq (size seq) > size x -> x: seq ] ] 'l ++ @[x ++ @[num]] ] result: [] loop l 'x [ if (size x) > size result -> result: x ] return result ]   loop [ [3 2 6 4 5 1] [0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15] ] 'seq [ print ["LIS of" seq "=>" lis seq] ]
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
#Agena
Agena
for i to 10 do write( i ); if i % 5 = 0 then write( "\n" ) else write( ", " ) fi od
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
#Ada
Ada
with Ada.Text_Io;   procedure Longest_Common_Substring is   function Common (Left, Right: String) return String is Com : array (Left'Range, Right'Range) of Natural := (others => (others => 0)); Longest : Natural := 0; Last  : Natural := 0; begin for L in Left'Range loop for R in Right'Range loop if Left (L) = Right (R) then if L > Left'First and R > Right'First then Com (L, R) := Com (L - 1, R - 1) + 1; else Com (L, R) := 1; end if; if Com (L, R) > Longest then Longest := Com (L, R); Last  := L; end if; end if; end loop; end loop; return Left (Last - Longest + 1 .. Last); end Common;   begin Ada.Text_Io.Put_Line (Common ("thisisatest", "testing123testing")); end Longest_Common_Substring;
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
#Pascal
Pascal
program LoopNested; uses SysUtils; const Ni=10; Nj=20; var tab: array[1..Ni,1..Nj] of Integer; i, j: Integer; label loopend; begin for i := 1 to Ni do for j := 1 to Nj do tab[i,j]:=random(20)+1; for i := 1 to Ni do begin for j := 1 to Nj do begin WriteLn(tab[i,j]); if tab[i,j]=20 then goto loopend end end; loopend: end.
http://rosettacode.org/wiki/Loops/Foreach
Loops/Foreach
Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Racket
Racket
  #lang racket   ;; an example sequence (define sequence '("something" 1 2 "foo"))   ;; works for any sequence (for ([i sequence]) (displayln i))  
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
#Raku
Raku
say $_ for @collection;
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
#Lua
Lua
function luhn(n) n=string.reverse(n) print(n) local s1=0 --sum odd digits for i=1,n:len(),2 do s1=s1+n:sub(i,i) end --evens local s2=0 for i=2,n:len(),2 do local doubled=n:sub(i,i)*2 doubled=string.gsub(doubled,'(%d)(%d)',function(a,b)return a+b end) s2=s2+doubled end print(s1) print(s2) local total=s1+s2 if total%10==0 then return true end return false end   -- Note that this function takes strings, not numbers. -- 16-digit numbers tend to be problematic -- when looking at individual digits. print(luhn'49927398716') print(luhn'49927398717') print(luhn'1234567812345678') print(luhn'1234567812345670')
http://rosettacode.org/wiki/Lucas-Lehmer_test
Lucas-Lehmer test
Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2 − 2 {\displaystyle S(n+1)=(S(n))^{2}-2} , and S ( 1 ) = 4 {\displaystyle S(1)=4} . Task Calculate all Mersenne primes up to the implementation's maximum precision, or the 47th Mersenne prime   (whichever comes first).
#Vlang
Vlang
import math.big const ( primes = [u32(3), 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127]   mersennes = [u32(521), 607, 1279, 2203, 2281, 3217, 4253, 4423, 9689, 9941, 11213, 19937, 21701, 23209, 44497, 86243, 110503, 132049, 216091, 756839, 859433, 1257787, 1398269, 2976221, 3021377, 6972593, 13466917, 20996011, 24036583] )   fn main() { ll_test(primes) println('') ll_test(mersennes) }   fn ll_test(ps []u32) { mut s, mut m := big.zero_int, big.zero_int one := big.one_int two := big.two_int for p in ps { m = one.lshift(p) - one s= big.integer_from_int(4) for i := u32(2); i < p; i++ { s = (s*s - two)%m } if s.bit_len() == 0 { print("M$p ") } } }
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
#Microsoft_Small_Basic
Microsoft Small Basic
  While "True" TextWindow.WriteLine("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
#min
min
(true) ("SPAM" puts!) while
http://rosettacode.org/wiki/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreachbas   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
i = 1024; While[i > 0, Print[i]; i = Floor[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
#MATLAB_.2F_Octave
MATLAB / Octave
for k = 10:-1:0, printf('%d\n',k) 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
#Maxima
Maxima
for i from 10 thru 0 step -1 do print(i);
http://rosettacode.org/wiki/Loops/Do-while
Loops/Do-while
Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges Reference Do while loop Wikipedia.
#Harbour
Harbour
LOCAL n := 0   DO WHILE .T. ? ++n IF n % 6 == 0 EXIT ENDIF ENDDO
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.
#Dyalect
Dyalect
for i in 1..5 { for _ in 1..i { print("*", terminator: "") } print() }
http://rosettacode.org/wiki/Loops/For_with_a_specified_step
Loops/For with a specified step
Task Demonstrate a   for-loop   where the step-value is greater than one. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#hexiscript
hexiscript
for let i 0; i <= 50; let i (i + 5) println i endfor
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
#HicEst
HicEst
DO i = 1, 6, 1.25 ! from 1 to 6 step 1.25 WRITE() i ENDDO
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
#PicoLisp
PicoLisp
(for N 10 (prin N) (T (= N 10)) (prin ", ") )
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
#Pike
Pike
  int main(){ for(int i = 1; i <= 11; i++){ write(sprintf("%d",i)); if(i == 10){ break; } write(", "); } write("\n"); }
http://rosettacode.org/wiki/Longest_string_challenge
Longest string challenge
Background This "longest string challenge" is inspired by a problem that used to be given to students learning Icon. Students were expected to try to solve the problem in Icon and another language with which the student was already familiar. The basic problem is quite simple; the challenge and fun part came through the introduction of restrictions. Experience has shown that the original restrictions required some adjustment to bring out the intent of the challenge and make it suitable for Rosetta Code. Basic problem statement Write a program that reads lines from standard input and, upon end of file, writes the longest line to standard output. If there are ties for the longest line, the program writes out all the lines that tie. If there is no input, the program should produce no output. Task Implement a solution to the basic problem that adheres to the spirit of the restrictions (see below). Describe how you circumvented or got around these 'restrictions' and met the 'spirit' of the challenge. Your supporting description may need to describe any challenges to interpreting the restrictions and how you made this interpretation. You should state any assumptions, warnings, or other relevant points. The central idea here is to make the task a bit more interesting by thinking outside of the box and perhaps by showing off the capabilities of your language in a creative way. Because there is potential for considerable variation between solutions, the description is key to helping others see what you've done. This task is likely to encourage a variety of different types of solutions. They should be substantially different approaches. Given the input: a bb ccc ddd ee f ggg the output should be (possibly rearranged): ccc ddd ggg Original list of restrictions No comparison operators may be used. No arithmetic operations, such as addition and subtraction, may be used. The only datatypes you may use are integer and string. In particular, you may not use lists. Do not re-read the input file. Avoid using files as a replacement for lists (this restriction became apparent in the discussion). Intent of restrictions Because of the variety of languages on Rosetta Code and the wide variety of concepts used in them, there needs to be a bit of clarification and guidance here to get to the spirit of the challenge and the intent of the restrictions. The basic problem can be solved very conventionally, but that's boring and pedestrian. The original intent here wasn't to unduly frustrate people with interpreting the restrictions, it was to get people to think outside of their particular box and have a bit of fun doing it. The guiding principle here should be to be creative in demonstrating some of the capabilities of the programming language being used. If you need to bend the restrictions a bit, explain why and try to follow the intent. If you think you've implemented a 'cheat', call out the fragment yourself and ask readers if they can spot why. If you absolutely can't get around one of the restrictions, explain why in your description. Now having said that, the restrictions require some elaboration. In general, the restrictions are meant to avoid the explicit use of these features. "No comparison operators may be used" - At some level there must be some test that allows the solution to get at the length and determine if one string is longer. Comparison operators, in particular any less/greater comparison should be avoided. Representing the length of any string as a number should also be avoided. Various approaches allow for detecting the end of a string. Some of these involve implicitly using equal/not-equal; however, explicitly using equal/not-equal should be acceptable. "No arithmetic operations" - Again, at some level something may have to advance through the string. Often there are ways a language can do this implicitly advance a cursor or pointer without explicitly using a +, - , ++, --, add, subtract, etc. The datatype restrictions are amongst the most difficult to reinterpret. In the language of the original challenge strings are atomic datatypes and structured datatypes like lists are quite distinct and have many different operations that apply to them. This becomes a bit fuzzier with languages with a different programming paradigm. The intent would be to avoid using an easy structure to accumulate the longest strings and spit them out. There will be some natural reinterpretation here. To make this a bit more concrete, here are a couple of specific examples: In C, a string is an array of chars, so using a couple of arrays as strings is in the spirit while using a second array in a non-string like fashion would violate the intent. In APL or J, arrays are the core of the language so ruling them out is unfair. Meeting the spirit will come down to how they are used. Please keep in mind these are just examples and you may hit new territory finding a solution. There will be other cases like these. Explain your reasoning. You may want to open a discussion on the talk page as well. The added "No rereading" restriction is for practical reasons, re-reading stdin should be broken. I haven't outright banned the use of other files but I've discouraged them as it is basically another form of a list. Somewhere there may be a language that just sings when doing file manipulation and where that makes sense; however, for most there should be a way to accomplish without resorting to an externality. At the end of the day for the implementer this should be a bit of fun. As an implementer you represent the expertise in your language, the reader may have no knowledge of your language. For the reader it should give them insight into how people think outside the box in other languages. Comments, especially for non-obvious (to the reader) bits will be extremely helpful. While the implementations may be a bit artificial in the context of this task, the general techniques may be useful elsewhere.
#ALGOL_68
ALGOL 68
  BEGIN INT bound = 1000000; CO Arbitrary upper limit on string lengths CO INT max; CO Length of longest string CO INT len; CO Length of string under examination CO STRING buffer := ""; CO All characters read from stand in CO STRING mask := bound * "0"; CO High water mark of string length seen so far CO CO Standard boiler plate CO on file end (stand in, (REF FILE f) BOOL: (close (f); GOTO finished)); DO STRING line; read ((line, newline)); buffer PLUSAB line + REPR 10; CO Concatenate string and newline CO mask[UPB line] := "1" CO And set mask where character exists in line CO OD; finished: buffer PLUSAB REPR 10; CO Guarantee there's a zero-length string at the end CO CO Scan backwards through mask looking for highest index used which is equal to the length of the longest string with its terminating newline. CO FOR i FROM bound BY -1 TO 1 DO FROM ABS mask[i] TO ABS "0" DO max := i OD CO Exploit ABS "1" > ABS "0" CO OD; FROM 1 TO UPB buffer DO CO Null loop if buffer is empty CO VOID (char in string (REPR 10, len, buffer)); CO Pedantry and Algol68 Genie extension CO FROM max TO len DO CO Null loop if len < max CO FOR i FROM 1 TO max DO printf (($a$, buffer[i])) CO Print string and newline CO OD OD; buffer := buffer[len : UPB buffer]; CO Step over string CO buffer := buffer[2 : UPB buffer] CO Step over newline CO OD END
http://rosettacode.org/wiki/Longest_increasing_subsequence
Longest increasing subsequence
Calculate and show here a longest increasing subsequence of the list: { 3 , 2 , 6 , 4 , 5 , 1 } {\displaystyle \{3,2,6,4,5,1\}} And of the list: { 0 , 8 , 4 , 12 , 2 , 10 , 6 , 14 , 1 , 9 , 5 , 13 , 3 , 11 , 7 , 15 } {\displaystyle \{0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15\}} Note that a list may have more than one subsequence that is of the maximum length. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet Ref Dynamic Programming #1: Longest Increasing Subsequence on YouTube An efficient solution can be based on Patience sorting.
#AutoHotkey
AutoHotkey
Lists := [[3,2,6,4,5,1], [0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15]]   for k, v in Lists { D := LIS(v) MsgBox, % D[D.I].seq }   LIS(L) { D := [] for i, v in L { D[i, "Length"] := 1, D[i, "Seq"] := v, D[i, "Val"] := v Loop, % i - 1 { if(D[A_Index].Val < v && D[A_Index].Length + 1 > D[i].Length) { D[i].Length := D[A_Index].Length + 1 D[i].Seq := D[A_Index].Seq ", " v if (D[i].Length > MaxLength) MaxLength := D[i].Length, D.I := i } } } return, D }
http://rosettacode.org/wiki/Loops/Continue
Loops/Continue
Task Show the following output using one loop. 1, 2, 3, 4, 5 6, 7, 8, 9, 10 Try to achieve the result by forcing the next iteration within the loop upon a specific condition, if your language allows it. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Aikido
Aikido
foreach i 1..10 { print (i) if ((i % 5) == 0) { println() continue } print (", ") }
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
#ALGOL_60
ALGOL 60
begin integer i; for i:=1 step 1 until 10 do begin outinteger(i); if i=(i div 5)*5 then outimage else outstring(", ") end end
http://rosettacode.org/wiki/Longest_common_substring
Longest common substring
Task Write a function that returns the longest common substring of two strings. Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing". Note that substrings are consecutive characters within a string.   This distinguishes them from subsequences, which is any sequence of characters within a string, even if there are extraneous characters in between them. Hence, the longest common subsequence between "thisisatest" and "testing123testing" is "tsitest", whereas the longest common substring is just "test". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet References Generalize Suffix Tree Ukkonen’s Suffix Tree Construction
#Aime
Aime
void test_string(text &g, v, l) { integer n;   n = prefix(v, l); if (~g < n) { g = cut(l, 0, n); } }   longest(text u, v) { record r; text g, l, s;   while (~u) { r[u] = 0; u = delete(u, 0); } while (~v) { if (rsk_lower(r, v, l)) { test_string(g, v, l); } if (rsk_upper(r, v, l)) { test_string(g, v, l); } v = delete(v, 0); }   g; }
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
#Perl
Perl
my $a = [ map [ map { int(rand(20)) + 1 } 1 .. 10 ], 1 .. 10];   Outer: foreach (@$a) { foreach (@$_) { print " $_"; if ($_ == 20) { last Outer; } } 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
#REBOL
REBOL
rebol [ Title: "Loop/Foreach" URL: http://rosettacode.org/wiki/Loop/Foreach ]   x: [Sork Gun Blues Neds Thirst Fright Catur]   foreach i x [prin rejoin [i "day "]] print ""   ; REBOL also has the 'forall' construct, which provides the rest of ; the list from the current position.   forall x [prin rejoin [x/1 "day "]] print ""
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
#Red
Red
>> blk: ["John" 23 "dave" 30 "bob" 20 "Jeff" 40] >> foreach item blk [print item] John 23 dave 30 bob 20 Jeff 40 >> foreach [name age] blk [print [name "is" age "years old"]] John is 23 years old dave is 30 years old bob is 20 years old Jeff is 40 years old   >> forall blk [print blk] John 23 dave 30 bob 20 Jeff 40 23 dave 30 bob 20 Jeff 40 dave 30 bob 20 Jeff 40 30 bob 20 Jeff 40 bob 20 Jeff 40 20 Jeff 40 Jeff 40 40
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
#M2000_Interpreter
M2000 Interpreter
Module Checkit { Function luhntest(cardnr$) {   cardnr$ = Trim$(cardnr$) ' we don't want spaces if len(cardnr$)=0 then exit Dim Base 0, reverse_nr$(Len(cardnr$)) Def integer i, j, s1, s2, l , l2 Let l=Len(cardnr$)-1, l2=l+1   ' reverse string For i = 0 To l reverse_nr$(i) = mid$(cardnr$,l2-i,1) Next i ' sum odd numbers For i = 0 To l Step 2 s1 = s1 + (Asc(reverse_nr$(i)) - Asc("0")) Next i ' sum even numbers For i = 1 To l Step 2 j = Asc(reverse_nr$(i)) - Asc("0") j = j * 2 If j > 9 Then j = j Mod 10 + 1 s2 = s2 + j Next i   If (s1 + s2) Mod 10 = 0 Then = 1=1 Else = 1=0 End If } Flush Data "49927398716", "49927398717", "1234567812345678", "1234567812345670" while not empty over print letter$;" = ";luhntest(letter$) end while } Checkit
http://rosettacode.org/wiki/Lucas-Lehmer_test
Lucas-Lehmer test
Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2 − 2 {\displaystyle S(n+1)=(S(n))^{2}-2} , and S ( 1 ) = 4 {\displaystyle S(1)=4} . Task Calculate all Mersenne primes up to the implementation's maximum precision, or the 47th Mersenne prime   (whichever comes first).
#Wren
Wren
import "/big" for BigInt import "/math" for Int import "io" for Stdout   var start = System.clock var max = 19 var count = 0 var table = [521, 607, 1279, 2203, 2281, 3217, 4253, 4423] var p = 3 // first odd prime var ix = 0 // index into table for larger primes var one = BigInt.one var two = BigInt.two while (true) { var m = (BigInt.two << (p - 1)) - one var s = BigInt.four for (i in 1..p-2) s = (s.square - two) % m if (s.bitLength == 0) { count = count + 1 System.write("M%(p) ") Stdout.flush() if (count == max) { System.print() break } } // obtain next odd prime or look up in table after 127 if (p < 127) { while (true) { p = p + 2 if (Int.isPrime(p)) break } } else { p = table[ix] ix = ix + 1 } } System.print("\nTook %(System.clock - start) seconds.")
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
#.D0.9C.D0.9A-61.2F52
МК-61/52
1 2 3 4 С/П БП 00
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
#Modula-2
Modula-2
LOOP InOut.WriteString ("SPAM"); InOut.WriteLn 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
#MATLAB_.2F_Octave
MATLAB / Octave
i = 1024; while (i > 0) disp(i); i = floor(i/2); 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
#Maxima
Maxima
block([n], n: 1024, while n > 0 do (print(n), n: quotient(n, 2)));   /* using a C-like loop: divide control variable by two instead of incrementing it */ for n: 1024 next quotient(n, 2) while n > 0 do print(n);
http://rosettacode.org/wiki/Loops/Downward_for
Loops/Downward for
Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#MAXScript
MAXScript
for i in 10 to 0 by -1 do print i
http://rosettacode.org/wiki/Loops/Downward_for
Loops/Downward for
Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Mercury
Mercury
:- module loops_downward_for. :- interface.   :- import_module io. :- pred main(io::di, io::uo) is det.   :- implementation. :- import_module int.   main(!IO) :- Print = (pred(I::in, !.IO::di, !:IO::uo) is det :- io.write_int(I, !IO), io.nl(!IO) ), int.fold_down(Print, 1, 10, !IO).
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.
#Haskell
Haskell
import Data.List import Control.Monad import Control.Arrow   doWhile p f n = (n:) $ takeWhile p $ unfoldr (Just.(id &&& f)) $ succ n
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.
#E
E
for width in 1..5 { for _ in 1..width { print("*") } println() }
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
#HolyC
HolyC
U8 i; for (i = 1; i < 10; i += 2) Print("%d\n", 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
#PL.2FI
PL/I
  do i = 1 to 10; put edit (trim(i)) (a); if i < 10 then put edit (', ') (a); end;  
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
#Plain_English
Plain English
To run: Start up. Write the numbers up to 10 on the console. Wait for the escape key. Shut down.   To write the numbers up to a number on the console: If a counter is past the number, exit. Convert the counter to a string. Write the string on the console without advancing. If the counter is less than the number, write ", " on the console without advancing. Repeat.
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.
#AutoHotkey
AutoHotkey
input = ( a bb ccc ddd ee f ggg ) longestLen := 0, buffer := "" Loop Parse, input, `n { top := SubStr(buffer, 1, InStr(buffer, "`n")) StringReplace, top, top, `n If SubStr(A_LoopField, LongestLen) ; at least as long buffer .= A_LoopField "`n" If !SubStr(top, StrLen(A_LoopField)) ; longer buffer := A_LoopField "`n", LongestLen := StrLen(A_LoopField) } MsgBox % buffer
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.
#C
C
#include <stdio.h> #include <stdlib.h>   struct node { int val, len; struct node *next; };   void lis(int *v, int len) { int i; struct node *p, *n = calloc(len, sizeof *n); for (i = 0; i < len; i++) n[i].val = v[i];   for (i = len; i--; ) { // find longest chain that can follow n[i] for (p = n + i; p++ < n + len; ) { if (p->val > n[i].val && p->len >= n[i].len) { n[i].next = p; n[i].len = p->len + 1; } } }   // find longest chain for (i = 0, p = n; i < len; i++) if (n[i].len > p->len) p = n + i;   do printf(" %d", p->val); while ((p = p->next)); putchar('\n');   free(n); }   int main(void) { int x[] = { 3, 2, 6, 4, 5, 1 }; int y[] = { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 };   lis(x, sizeof(x) / sizeof(int)); lis(y, sizeof(y) / sizeof(int)); return 0; }
http://rosettacode.org/wiki/Loops/Continue
Loops/Continue
Task Show the following output using one loop. 1, 2, 3, 4, 5 6, 7, 8, 9, 10 Try to achieve the result by forcing the next iteration within the loop upon a specific condition, if your language allows it. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#ALGOL_68
ALGOL 68
FOR i FROM 1 TO 10 DO print ((i, IF i MOD 5 = 0 THEN new line ELSE "," FI )) OD
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
#ALGOL_68
ALGOL 68
BEGIN # returns the longest common substring of s and t # PROC longest common substring = ( STRING s, t )STRING: BEGIN STRING s1 = s[ @ 1 ]; # normalise bounds to 1 : ... # STRING s2 = t[ @ 1 ]; STRING result := ""; INT result len := 0; FOR i TO UPB s1 DO FOR j TO UPB s2 DO IF s1[ i ] = s2[ j ] THEN INT k := 1; WHILE INT ik = i + k; INT jk = j + k; IF ik > UPB s1 OR jk > UPB s2 THEN FALSE ELSE s1[ ik ] = s2[ jk ] FI DO k +:= 1 OD; IF k > result len THEN # found a longer substring # result len := k; result := s1[ i : ( i + k ) - 1 ] FI FI OD OD; result END # longest common substring # ;   # task test case # print( ( longest common substring( "thisisatest", "testing123testing" ), newline ) ) END
http://rosettacode.org/wiki/Loops/Nested
Loops/Nested
Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} is met. Specifically, this task also shows how to break out of nested loops. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Phix
Phix
constant s = sq_rand(repeat(repeat(20,20),20)) integer found = 0 for i=1 to 20 do for j=1 to 20 do printf(1,"%d",s[i][j]) if s[i][j]=20 then found = 1 exit end if printf(1,", ") end for printf(1,"\n") if found then exit end if end for
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
#ReScript
ReScript
let fruits = ["apple", "banana", "coconut"]   Js.Array2.forEach(fruits, f => Js.log(f))
http://rosettacode.org/wiki/Loops/Foreach
Loops/Foreach
Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Retro
Retro
# Strings   This will display the ASCII code for each character in a string   ~~~ 'This_is_a_message [ n:put sp ] s:for-each ~~~   # Array   Display each element   ~~~ { #1 #2 #3 } [ n:put sp ] a:for-each ~~~   # Linked List   Using the dictionary as an example, display each name   ~~~ &Dictionary [ d:name s:put sp ] d:for-each ~~~  
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
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
LuhnQ[nb_] := (Mod[Total[(2*ToExpression[#[[2;;All;;2]]]) /. {z_?(Function[v, v>9]) -> z-9}] + Total[ToExpression[#[[1;;All;;2]]]], 10] == 0)& [Characters[StringReverse[ToString[nb]]] ]   LuhnQ /@ {49927398716, 49927398717, 1234567812345678, 1234567812345670} ->{True, False, False, True}
http://rosettacode.org/wiki/Lucas-Lehmer_test
Lucas-Lehmer test
Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2 − 2 {\displaystyle S(n+1)=(S(n))^{2}-2} , and S ( 1 ) = 4 {\displaystyle S(1)=4} . Task Calculate all Mersenne primes up to the implementation's maximum precision, or the 47th Mersenne prime   (whichever comes first).
#Zig
Zig
  const std = @import("std"); const stdout = std.io.getStdOut().outStream(); const assert = std.debug.assert;   pub fn main() !void { const primes = [_]u7{ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, }; try stdout.print("These Mersenne numbers are prime: ", .{}); for (primes) |p| if (isMersennePrime(p)) try stdout.print("M{} ", .{p}); try stdout.print("\n", .{}); }   inline fn M(n: u7) u128 { return (@as(u128, 1) << n) - 1; }   fn isMersennePrime(p: u7) bool { if (p < 3) return p == 2 else { const n = M(p); var s: u128 = 4; var i: u7 = p - 2; while (i > 0) : (i -= 1) { s = modmul(s, s, n); s = if (s >= 2) s - 2 else n - 2 + s; } return s == 0; } }   fn modmul(a0: u128, b0: u128, m: u128) u128 { var r: u128 = 0; var a = a0 % m; var b = b0 % m; while (b > 0) { if (b & 1 == 1) r = if ((m - r) > a) r + a else r + a - m; b >>= 1; if (b > 0) a = if ((m - a) > a) a + a else a + a - m; } return r; }  
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
#Modula-3
Modula-3
LOOP IO.Put("SPAM\n"); END;
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Monte
Monte
  while (true): traceln("SPAM")  
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#MontiLang
MontiLang
WHILE TRUE |SPAM| PRINT . ENDWHILE
http://rosettacode.org/wiki/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreachbas   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#MAXScript
MAXScript
a = 1024 while a > 0 do ( print a a /= 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
#Metafont
Metafont
a := 1024; forever: exitif not (a > 0); show a; a := a div 2; endfor
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
#Metafont
Metafont
for i = 10 step -1 until 0: show i; endfor 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
#min
min
10 :n (n 0 >=) (n puts! n pred @n) while
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.
#Haxe
Haxe
var val = 0;   do { val++; Sys.println(val); } while( val % 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.
#HolyC
HolyC
U8 i = 0; do { i++; Print("%d\n", i); } while (i % 6 != 0);
http://rosettacode.org/wiki/Loops/For
Loops/For
“For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers. Task Show how two loops may be nested within each other, with the number of iterations performed by the inner for loop being controlled by the outer for loop. Specifically print out the following pattern by using one for loop nested in another: * ** *** **** ***** Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges Reference For loop Wikipedia.
#EasyLang
EasyLang
for i range 5 for j range i write "*" . print "" .
http://rosettacode.org/wiki/Loops/For_with_a_specified_step
Loops/For with a specified step
Task Demonstrate a   for-loop   where the step-value is greater than one. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Hy
Hy
(for [i (range 1 10 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
#Pop11
Pop11
lvars i; for i from 1 to 10 do printf(i, '%p'); quitif(i = 10); printf(', ', '%p'); endfor; printf('\n', '%p');
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
#PowerShell
PowerShell
for ($i = 1; $i -le 10; $i++) { Write-Host -NoNewLine $i if ($i -eq 10) { Write-Host break } Write-Host -NoNewLine ", " }
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
#11l
11l
L(x, y, z) zip(‘abc’, ‘ABC’, ‘123’) print(x‘’y‘’z)
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
#11l
11l
L V a = random:(20) print(a) I a == 10 L.break V b = random:(20) print(b)
http://rosettacode.org/wiki/Longest_string_challenge
Longest string challenge
Background This "longest string challenge" is inspired by a problem that used to be given to students learning Icon. Students were expected to try to solve the problem in Icon and another language with which the student was already familiar. The basic problem is quite simple; the challenge and fun part came through the introduction of restrictions. Experience has shown that the original restrictions required some adjustment to bring out the intent of the challenge and make it suitable for Rosetta Code. Basic problem statement Write a program that reads lines from standard input and, upon end of file, writes the longest line to standard output. If there are ties for the longest line, the program writes out all the lines that tie. If there is no input, the program should produce no output. Task Implement a solution to the basic problem that adheres to the spirit of the restrictions (see below). Describe how you circumvented or got around these 'restrictions' and met the 'spirit' of the challenge. Your supporting description may need to describe any challenges to interpreting the restrictions and how you made this interpretation. You should state any assumptions, warnings, or other relevant points. The central idea here is to make the task a bit more interesting by thinking outside of the box and perhaps by showing off the capabilities of your language in a creative way. Because there is potential for considerable variation between solutions, the description is key to helping others see what you've done. This task is likely to encourage a variety of different types of solutions. They should be substantially different approaches. Given the input: a bb ccc ddd ee f ggg the output should be (possibly rearranged): ccc ddd ggg Original list of restrictions No comparison operators may be used. No arithmetic operations, such as addition and subtraction, may be used. The only datatypes you may use are integer and string. In particular, you may not use lists. Do not re-read the input file. Avoid using files as a replacement for lists (this restriction became apparent in the discussion). Intent of restrictions Because of the variety of languages on Rosetta Code and the wide variety of concepts used in them, there needs to be a bit of clarification and guidance here to get to the spirit of the challenge and the intent of the restrictions. The basic problem can be solved very conventionally, but that's boring and pedestrian. The original intent here wasn't to unduly frustrate people with interpreting the restrictions, it was to get people to think outside of their particular box and have a bit of fun doing it. The guiding principle here should be to be creative in demonstrating some of the capabilities of the programming language being used. If you need to bend the restrictions a bit, explain why and try to follow the intent. If you think you've implemented a 'cheat', call out the fragment yourself and ask readers if they can spot why. If you absolutely can't get around one of the restrictions, explain why in your description. Now having said that, the restrictions require some elaboration. In general, the restrictions are meant to avoid the explicit use of these features. "No comparison operators may be used" - At some level there must be some test that allows the solution to get at the length and determine if one string is longer. Comparison operators, in particular any less/greater comparison should be avoided. Representing the length of any string as a number should also be avoided. Various approaches allow for detecting the end of a string. Some of these involve implicitly using equal/not-equal; however, explicitly using equal/not-equal should be acceptable. "No arithmetic operations" - Again, at some level something may have to advance through the string. Often there are ways a language can do this implicitly advance a cursor or pointer without explicitly using a +, - , ++, --, add, subtract, etc. The datatype restrictions are amongst the most difficult to reinterpret. In the language of the original challenge strings are atomic datatypes and structured datatypes like lists are quite distinct and have many different operations that apply to them. This becomes a bit fuzzier with languages with a different programming paradigm. The intent would be to avoid using an easy structure to accumulate the longest strings and spit them out. There will be some natural reinterpretation here. To make this a bit more concrete, here are a couple of specific examples: In C, a string is an array of chars, so using a couple of arrays as strings is in the spirit while using a second array in a non-string like fashion would violate the intent. In APL or J, arrays are the core of the language so ruling them out is unfair. Meeting the spirit will come down to how they are used. Please keep in mind these are just examples and you may hit new territory finding a solution. There will be other cases like these. Explain your reasoning. You may want to open a discussion on the talk page as well. The added "No rereading" restriction is for practical reasons, re-reading stdin should be broken. I haven't outright banned the use of other files but I've discouraged them as it is basically another form of a list. Somewhere there may be a language that just sings when doing file manipulation and where that makes sense; however, for most there should be a way to accomplish without resorting to an externality. At the end of the day for the implementer this should be a bit of fun. As an implementer you represent the expertise in your language, the reader may have no knowledge of your language. For the reader it should give them insight into how people think outside the box in other languages. Comments, especially for non-obvious (to the reader) bits will be extremely helpful. While the implementations may be a bit artificial in the context of this task, the general techniques may be useful elsewhere.
#AWK
AWK
#!/usr/bin/awk -f BEGIN { maxlen = 0; lenList = 0; }   { if (length($0)>maxlen) { lenList = 1; List[lenList] = $0; maxlen = length($0); } else if (length($0)==maxlen) List[++lenList]=$0; }   END { for (k=1; k <= lenList; k++) print List[k]; }
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.
#BASIC
BASIC
  DO READ test$ IF test$ = "~" THEN EXIT DO IF LEN(test$) > LEN(test1$) THEN test1$ = test$ test2$ = test1$ + CHR$(10) ELSEIF LEN(test$) = LEN(test1$) THEN LET test2$ = test2$ + test$ + CHR$(10) END IF LOOP   PRINT (test2$)   DATA "a", "bb", "ccc", "ddd", "ee", "f", "ggg", "~" : ' la tilde es solo para mantener el código compacto  
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.
#C.23
C#
using System; using System.Collections; using System.Collections.Generic; using System.Linq;   public static class LIS { public static IEnumerable<T> FindRec<T>(IList<T> values, IComparer<T> comparer = null) => values == null ? throw new ArgumentNullException() : FindRecImpl(values, Sequence<T>.Empty, 0, comparer ?? Comparer<T>.Default).Reverse();   private static Sequence<T> FindRecImpl<T>(IList<T> values, Sequence<T> current, int index, IComparer<T> comparer) { if (index == values.Count) return current; if (current.Length > 0 && comparer.Compare(values[index], current.Value) <= 0) return FindRecImpl(values, current, index + 1, comparer); return Max( FindRecImpl(values, current, index + 1, comparer), FindRecImpl(values, current + values[index], index + 1, comparer) ); }   private static Sequence<T> Max<T>(Sequence<T> a, Sequence<T> b) => a.Length < b.Length ? b : a;   class Sequence<T> : IEnumerable<T> { public static readonly Sequence<T> Empty = new Sequence<T>(default(T), null);   public Sequence(T value, Sequence<T> tail) { Value = value; Tail = tail; Length = tail == null ? 0 : tail.Length + 1; }   public T Value { get; } public Sequence<T> Tail { get; } public int Length { get; }   public static Sequence<T> operator +(Sequence<T> s, T value) => new Sequence<T>(value, s);   public IEnumerator<T> GetEnumerator() { for (var s = this; s.Length > 0; s = s.Tail) yield return s.Value; }   IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } }
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
#ALGOL_W
ALGOL W
begin i_w := 1; s_w := 0; % set output format % for i := 1 until 10 do begin writeon( i ); if i rem 5 = 0 then write() else writeon( ", " ) end for_i 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
#AppleScript
AppleScript
  set table to {return} repeat with i from 1 to 10 if i < 5 or (i ≥ 6 and i < 10) then set end of table to i & ", " else if i = 5 or i = 10 then set end of table to i & return end if end repeat return table as string  
http://rosettacode.org/wiki/Longest_common_substring
Longest common substring
Task Write a function that returns the longest common substring of two strings. Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing". Note that substrings are consecutive characters within a string.   This distinguishes them from subsequences, which is any sequence of characters within a string, even if there are extraneous characters in between them. Hence, the longest common subsequence between "thisisatest" and "testing123testing" is "tsitest", whereas the longest common substring is just "test". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet References Generalize Suffix Tree Ukkonen’s Suffix Tree Construction
#AppleScript
AppleScript
on LCS(a, b) -- Identify the shorter string. The longest common substring won't be longer than it! set lengthA to a's length set lengthB to b's length if (lengthA < lengthB) then set {shorterString, shorterLength, longerString} to {a, lengthA, b} else set {shorterString, shorterLength, longerString} to {b, lengthB, a} end if   set longestMatches to {} set longestMatchLength to 0 -- Find the longest matching substring starting at each character in the shorter string. repeat with i from 1 to shorterLength repeat with j from shorterLength to i by -1 set thisSubstring to text i thru j of shorterString if (longerString contains thisSubstring) then -- Match found. If it's longer than the previously found match, or a new string of the same length, remember it. set matchLength to j - i + 1 if (matchLength > longestMatchLength) then set longestMatches to {thisSubstring} set longestMatchLength to matchLength else if ((matchLength = longestMatchLength) and (thisSubstring is not in longestMatches)) then set end of longestMatches to thisSubstring end if -- Don't bother with the match's own substrings. exit repeat end if end repeat end repeat   return longestMatches end LCS
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
#PHP
PHP
<?php for ($i = 0; $i < 10; $i++) for ($j = 0; $j < 10; $j++) $a[$i][$j] = rand(1, 20);   foreach ($a as $row) { foreach ($row as $element) { echo " $element"; if ($element == 20) break 2; // 2 is the number of loops we want to break out of } echo "\n"; } echo "\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
#REXX
REXX
days = 'zuntik montik dinstik mitvokh donershtik fraytik shabes'   do j=1 for words(days) /*loop through days of the week. */ say word(days,j) /*display the weekday to screen. */ end /*j*/ /*stick a fork in it, we're done.*/
http://rosettacode.org/wiki/Loops/Foreach
Loops/Foreach
Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Ring
Ring
  aList = "Welcome to the Ring Programming Language" for n in aList see n + nl next  
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
#MATLAB
MATLAB
function passed = luhn(num) if nargin == 0 % evaluate test cases testnum = [49927398716 49927398717 1234567812345678 1234567812345670]; for num = testnum disp([int2str(num) ': ' int2str(luhn(num))]) end return end % luhn function starts here d = int2str(num) - '0'; % convert number into vector of digits m = [2:2:8,1:2:9]; % rule 3: maps 1:9 to [2 4 6 8 1 3 5 7 9] passed = ~mod(sum(d(end:-2:1)) + sum(m(d(end-1:-2:1))), 10); end
http://rosettacode.org/wiki/Lucas-Lehmer_test
Lucas-Lehmer test
Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2 − 2 {\displaystyle S(n+1)=(S(n))^{2}-2} , and S ( 1 ) = 4 {\displaystyle S(1)=4} . Task Calculate all Mersenne primes up to the implementation's maximum precision, or the 47th Mersenne prime   (whichever comes first).
#zkl
zkl
var [const] BN=Import.lib("zklBigNum"); // lib GMP primes:=Utils.Generator(Import("sieve").postponed_sieve); fcn isMersennePrime(p){ if(p==2) return(True); mp:=BN(1).shiftLeft(p) - 1; // 2^p - 1, a BIG number, like 1000s of digits s:=BN(4); do(p-2){ s.mul(s).sub(2).mod(mp) } // the % REALLY cuts down on mem usage return(s==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
#MOO
MOO
while (1) player:tell("SPAM"); endwhile