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/Look-and-say_sequence
Look-and-say sequence
The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequence 1,   11,   21,   1211,   111221?   is sometimes referred to as the Cuckoo's Egg,   from a description of Morris in Clifford Stoll's book   The Cuckoo's Egg. Sequence Definition Take a decimal number Look at the number, visually grouping consecutive runs of the same digit. Say the number, from left to right, group by group; as how many of that digit there are - followed by the digit grouped. This becomes the next number of the sequence. An example: Starting with the number 1,   you have one 1 which produces 11 Starting with 11,   you have two 1's.   I.E.:   21 Starting with 21,   you have one 2, then one 1.   I.E.:   (12)(11) which becomes 1211 Starting with 1211,   you have one 1, one 2, then two 1's.   I.E.:   (11)(12)(21) which becomes 111221 Task Write a program to generate successive members of the look-and-say sequence. Related tasks   Fours is the number of letters in the ...   Number names   Self-describing numbers   Self-referential sequence   Spelling of ordinal numbers See also   Look-and-Say Numbers (feat John Conway), A Numberphile Video.   This task is related to, and an application of, the Run-length encoding task.   Sequence A005150 on The On-Line Encyclopedia of Integer Sequences.
#APL
APL
  ⎕IO←0 d←{(1↓⍵)-¯1↓⍵} f←{m←(0≠d ⍵),1 ⋄ ,(d ¯1,m/⍳⍴⍵),[.5](m/⍵)} {(f⍣⍵) ,1}¨⍳10  
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.
#Haskell
Haskell
  module Main where   import System.Environment   cmp :: String -> String -> Ordering cmp [] [] = EQ cmp [] (_:_) = LT cmp (_:_) [] = GT cmp (_:xs) (_:ys) = cmp xs ys   longest :: String -> String longest = longest' "" "" . lines where longest' acc l [] = acc longest' [] l (x:xs) = longest' x x xs longest' acc l (x:xs) = case cmp l x of LT -> longest' x x xs EQ -> longest' (acc ++ '\n':x) l xs GT -> longest' acc l xs   main :: IO () main = do (file:_) <- getArgs contents <- readFile file putStrLn $ longest contents  
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.
#Icon_and_Unicon
Icon and Unicon
procedure main(arglist) local b # the current buffer (string) local l # the last string local L # a \n delimited accumulation of all the longest strings   while b := read() do { /l := b # primes l on first pass b ? ( move(*l), if move(1) then L := (l := b) || "\n" else if move(0) then L := (\L|"") || b || "\n") # move(*l) - fails if b is not l characters long # move(1) - succeeds/fails if the string is longer and triggers a reset of L }   write(\L) end
http://rosettacode.org/wiki/Longest_increasing_subsequence
Longest increasing subsequence
Calculate and show here a longest increasing subsequence of the list: { 3 , 2 , 6 , 4 , 5 , 1 } {\displaystyle \{3,2,6,4,5,1\}} And of the list: { 0 , 8 , 4 , 12 , 2 , 10 , 6 , 14 , 1 , 9 , 5 , 13 , 3 , 11 , 7 , 15 } {\displaystyle \{0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15\}} Note that a list may have more than one subsequence that is of the maximum length. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet Ref Dynamic Programming #1: Longest Increasing Subsequence on YouTube An efficient solution can be based on Patience sorting.
#Go
Go
package main   import ( "fmt" "sort" )   type Node struct { val int back *Node }   func lis (n []int) (result []int) { var pileTops []*Node // sort into piles for _, x := range n { j := sort.Search(len(pileTops), func (i int) bool { return pileTops[i].val >= x }) node := &Node{ x, nil } if j != 0 { node.back = pileTops[j-1] } if j != len(pileTops) { pileTops[j] = node } else { pileTops = append(pileTops, node) } }   if len(pileTops) == 0 { return []int{} } for node := pileTops[len(pileTops)-1]; node != nil; node = node.back { result = append(result, node.val) } // reverse for i := 0; i < len(result)/2; i++ { result[i], result[len(result)-i-1] = result[len(result)-i-1], result[i] } return }   func main() { for _, d := range [][]int{{3, 2, 6, 4, 5, 1}, {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}} { fmt.Printf("an L.I.S. of %v is %v\n", d, lis(d)) } }
http://rosettacode.org/wiki/Loops/Continue
Loops/Continue
Task Show the following output using one loop. 1, 2, 3, 4, 5 6, 7, 8, 9, 10 Try to achieve the result by forcing the next iteration within the loop upon a specific condition, if your language allows it. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#C.2B.2B
C++
for(int i = 1;i <= 10; i++){ cout << i; if(i % 5 == 0){ cout << endl; continue; } cout << ", "; }
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
#Common_Lisp
Common Lisp
  (defun longest-common-substring (a b) "Return the longest substring common to a and b" ;; Found at https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Longest_common_substring#Common_Lisp (let ((L (make-array (list (length a) (length b)) :initial-element 0)) (z 0) (result '()) ) (dotimes (i (length a)) (dotimes (j (length b)) (when (char= (char a i) (char b j)) (setf (aref L i j) (if (or (zerop i) (zerop j)) 1 (1+ (aref L (1- i) (1- j))) )) (when (> (aref L i j) z) (setf z (aref L i j) result '() )) (when (= (aref L i j) z) (pushnew (subseq a (1+ (- i z)) (1+ i)) result :test #'equal ))))) result ))  
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
#REBOL
REBOL
rebol [ Title: "Loop/Nested" URL: http://rosettacode.org/wiki/Loop/Nested ]   ; Number formatting. zeropad: func [pad n][ n: to-string n insert/dup n "0" (pad - length? n) n]   ; Initialize random number generator from current time. random/seed now   ; Create array and fill with random numbers, range 1..20. soup: array [10 10] repeat row soup [forall row [row/1: random 20]]   print "Loop break using state variable:" done: no for y 1 10 1 [ for x 1 10 1 [ prin rejoin [zeropad 2 soup/:x/:y " "] if 20 = soup/:x/:y [done: yes break] ] prin crlf if done [break] ]   print [crlf "Loop break with catch/throw:"] catch [ for y 1 10 1 [ for x 1 10 1 [ prin rejoin [zeropad 2 soup/:x/:y " "] if 20 = soup/:x/:y [throw 'done] ] prin crlf ] ] prin crlf
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
#Snabel
Snabel
['foo' 'bar' 'baz'] &say 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
#Sparkling
Sparkling
let hash = { "foo": 42, "bar": 1337, "baz": "qux" }; foreach(hash, function(key, val) { print(key, " -> ", val); });
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
#Objective-C
Objective-C
- (NSArray *) toCharArray {   NSMutableArray *characters = [[NSMutableArray alloc] initWithCapacity:[self length]]; for (int i=0; i < [self length]; i++) { NSString *ichar = [NSString stringWithFormat:@"%C", [self characterAtIndex:i]]; [characters addObject:ichar]; }   return characters; }   + (BOOL) luhnCheck:(NSString *)stringToTest {   NSArray *stringAsChars = [stringToTest toCharArray];   BOOL isOdd = YES; int oddSum = 0; int evenSum = 0;   for (int i = [stringToTest length] - 1; i >= 0; i--) {   int digit = [(NSString *)stringAsChars[i] intValue];   if (isOdd) oddSum += digit; else evenSum += digit/5 + (2*digit) % 10;   isOdd = !isOdd; }   return ((oddSum + evenSum) % 10 == 0); }   BOOL test0 = [self luhnCheck:@"49927398716"]; //Result = YES BOOL test1 = [self luhnCheck:@"49927398717"]; //Result = NO BOOL test2 = [self luhnCheck:@"1234567812345678"]; //Result = NO BOOL test3 = [self luhnCheck:@"1234567812345670"]; //Result = YES
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
#Oz
Oz
for do {Show 'SPAM'} 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
#PARI.2FGP
PARI/GP
while(1, print("SPAM") );
http://rosettacode.org/wiki/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreachbas   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Nim
Nim
var n: int = 1024 while n > 0: echo(n) n = n div 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
#NS-HUBASIC
NS-HUBASIC
10 I=1024 20 IF I=0 THEN END 30 PRINT I 40 I=I/2 50 GOTO 20
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
#PARI.2FGP
PARI/GP
forstep(n=10,0,-1,print(n))
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.
#LiveCode
LiveCode
repeat while n mod 6 is not 0 or n is 0 add 1 to n put n end repeat
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.
#Logo
Logo
make "val 0 do.while [make "val :val + 1 print :val] [notequal? 0 modulo :val 6] do.until [make "val :val + 1 print :val] [equal? 0 modulo :val 6]   to my.loop :n make "n :n + 1 print :n if notequal? 0 modulo :n 6 [my.loop :n] end my.loop 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.
#F.23
F#
#light [<EntryPoint>] let main args = for i = 1 to 5 do for j = 1 to i do printf "*" printfn "" 0
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
#LabVIEW
LabVIEW
  {def loops_for_with_a_specified_step {lambda {:a :b :step} {if {>= :a :b} then (end of loop) else :a {loops_for_with_a_specified_step {+ :a :step} :b :step}}}} -> loops_for_with_a_specified_step   {loops_for_with_a_specified_step 0 10 2} -> 0 2 4 6 8 (end of loop)   a more simple way:   {S.map {lambda {:i} :i} {S.serie 0 9 2}} -> 0 2 4 6 8  
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
#Salmon
Salmon
iterate (x; [1...10]) { print(x); if (x == 10) break;; print(", "); }; print("\n");
http://rosettacode.org/wiki/Loops/N_plus_one_half
Loops/N plus one half
Quite often one needs loops which, in the last iteration, execute only part of the loop body. Goal Demonstrate the best way to do this. Task Write a loop which writes the comma-separated list 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 using separate output statements for the number and the comma from within the body of the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Scala
Scala
var i = 1 while ({ print(i) i < 10 }) { print(", ") i += 1 } println()
http://rosettacode.org/wiki/Literals/Floating_point
Literals/Floating point
Programming languages have different ways of expressing floating-point literals. Task Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features. You may want to include a regular expression or BNF/ABNF/EBNF defining allowable formats for your language. Related tasks   Literals/Integer   Extreme floating point values
#11l
11l
// 64-bit floating point literals: 2.3 0.3e+34   // single precision (32-bit) floating point literals: 2.3s 0.3e+34s
http://rosettacode.org/wiki/Long_year
Long year
Most years have 52 weeks, some have 53, according to ISO8601. Task Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
#Arturo
Arturo
longYear?: function [year][ date: to :date .format: "dd/MM/yyyy" ~"01/01/|year|"   or? date\Day = "Thursday" and? leap? year date\Day = "Wednesday" ]   print "Years with 53 weeks between 2000 and 2100:" print select 2000..2100 => longYear?
http://rosettacode.org/wiki/Long_year
Long year
Most years have 52 weeks, some have 53, according to ISO8601. Task Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
#AutoHotkey
AutoHotkey
Long_year(y) { A := Mod(y + floor(y/4) - floor(y/100) + floor(y/400), 7) y--, B := Mod(y + floor(y/4) - floor(y/100) + floor(y/400), 7) return A=4 || B=3 }
http://rosettacode.org/wiki/Long_primes
Long primes
A   long prime   (as defined here)   is a prime number whose reciprocal   (in decimal)   has a   period length   of one less than the prime number. Long primes   are also known as:   base ten cyclic numbers   full reptend primes   golden primes   long period primes   maximal period primes   proper primes Another definition:   primes   p   such that the decimal expansion of   1/p   has period   p-1,   which is the greatest period possible for any integer. Example 7   is the first long prime,   the reciprocal of seven is   1/7,   which is equal to the repeating decimal fraction   0.142857142857··· The length of the   repeating   part of the decimal fraction is six,   (the underlined part)   which is one less than the (decimal) prime number   7. Thus   7   is a long prime. There are other (more) general definitions of a   long prime   which include wording/verbiage for bases other than ten. Task   Show all long primes up to   500   (preferably on one line).   Show the   number   of long primes up to        500   Show the   number   of long primes up to     1,000   Show the   number   of long primes up to     2,000   Show the   number   of long primes up to     4,000   Show the   number   of long primes up to     8,000   Show the   number   of long primes up to   16,000   Show the   number   of long primes up to   32,000   Show the   number   of long primes up to   64,000   (optional)   Show all output here. Also see   Wikipedia: full reptend prime   MathWorld: full reptend prime   OEIS: A001913
#C
C
#include <stdio.h> #include <stdlib.h>   #define TRUE 1 #define FALSE 0   typedef int bool;   void sieve(int limit, int primes[], int *count) { bool *c = calloc(limit + 1, sizeof(bool)); /* composite = TRUE */ /* no need to process even numbers */ int i, p = 3, p2, n = 0; p2 = p * p; while (p2 <= limit) { for (i = p2; i <= limit; i += 2 * p) c[i] = TRUE; do { p += 2; } while (c[p]); p2 = p * p; } for (i = 3; i <= limit; i += 2) { if (!c[i]) primes[n++] = i; } *count = n; free(c); }   /* finds the period of the reciprocal of n */ int findPeriod(int n) { int i, r = 1, rr, period = 0; for (i = 1; i <= n + 1; ++i) { r = (10 * r) % n; } rr = r; do { r = (10 * r) % n; period++; } while (r != rr); return period; }   int main() { int i, prime, count = 0, index = 0, primeCount, longCount = 0, numberCount; int *primes, *longPrimes, *totals; int numbers[] = {500, 1000, 2000, 4000, 8000, 16000, 32000, 64000};   primes = calloc(6500, sizeof(int)); numberCount = sizeof(numbers) / sizeof(int); totals = calloc(numberCount, sizeof(int)); sieve(64000, primes, &primeCount); longPrimes = calloc(primeCount, sizeof(int)); /* Surely longCount < primeCount */ for (i = 0; i < primeCount; ++i) { prime = primes[i]; if (findPeriod(prime) == prime - 1) { longPrimes[longCount++] = prime; } } for (i = 0; i < longCount; ++i, ++count) { if (longPrimes[i] > numbers[index]) { totals[index++] = count; } } totals[numberCount - 1] = count; printf("The long primes up to %d are:\n", numbers[0]); printf("["); for (i = 0; i < totals[0]; ++i) { printf("%d ", longPrimes[i]); } printf("\b]\n");   printf("\nThe number of long primes up to:\n"); for (i = 0; i < 8; ++i) { printf("  %5d is %d\n", numbers[i], totals[i]); } free(totals); free(longPrimes); free(primes); return 0; }
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
#APL
APL
f ← ↓∘⍉∘↑
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
#AutoHotkey
AutoHotkey
Loop { Random, var, 0, 19 output = %output%`n%var% If (var = 10) Break Random, var, 0, 19 output = %output%`n%var% } MsgBox % output
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
#Avail
Avail
rng ::= a pRNG; checked : [0..19]; Do [ checked : = rng's next [0..19]; Print: “checked”; ] while checked ≠ 10 alternate with [ Print: " " ++ “rng's next [0..19]” ++ "\n"; ];
http://rosettacode.org/wiki/Longest_common_subsequence
Longest common subsequence
Introduction Define a subsequence to be any output string obtained by deleting zero or more symbols from an input string. The Longest Common Subsequence (LCS) is a subsequence of maximum length common to two or more strings. Let A ≡ A[0]… A[m - 1] and B ≡ B[0]… B[n - 1], m < n be strings drawn from an alphabet Σ of size s, containing every distinct symbol in A + B. An ordered pair (i, j) will be referred to as a match if A[i] = B[j], where 0 < i ≤ m and 0 < j ≤ n. Define a non-strict product-order (≤) over ordered pairs, such that (i1, j1) ≤ (i2, j2) ⇔ i1 ≤ i2 and j1 ≤ j2. We define (≥) similarly. We say m1, m2 are comparable if either m1 ≤ m2 or m1 ≥ m2 holds. If i1 < i2 and j2 < j1 (or i2 < i1 and j1 < j2) then neither m1 ≤ m2 nor m1 ≥ m2 are possible; and we say m1, m2 are incomparable. We also define the strict product-order (<) over ordered pairs, such that (i1, j1) < (i2, j2) ⇔ i1 < i2 and j1 < j2. We define (>) similarly. Given a set of matches M, a chain C is a subset of M consisting of at least one element m; and where either m1 < m2 or m1 > m2 for every pair of distinct elements m1 and m2. An antichain D is any subset of M in which every pair of distinct elements m1 and m2 are incomparable. The set M represents a relation over match pairs: M[i, j] ⇔ (i, j) ∈ M. A chain C can be visualized as a curve which strictly increases as it passes through each match pair in the m*n coordinate space. Finding an LCS can be restated as the problem of finding a chain of maximum cardinality p over the set of matches M. According to [Dilworth 1950], this cardinality p equals the minimum number of disjoint antichains into which M can be decomposed. Note that such a decomposition into the minimal number p of disjoint antichains may not be unique. Contours Forward Contours FC[k] of class k are defined inductively, as follows: FC[0] consists of those elements m1 for which there exists no element m2 such that m2 < m1. FC[k] consists of those elements m1 for which there exists no element m2 such that m2 < m1; and where neither m1 nor m2 are contained in FC[l] for any class l < k. Reverse Contours RC[k] of class k are defined similarly. Members of the Meet (∧), or Infimum of a Forward Contour are referred to as its Dominant Matches: those m1 for which there exists no m2 such that m2 < m1. Members of the Join (∨), or Supremum of a Reverse Contour are referred to as its Dominant Matches: those m1 for which there exists no m2 such that m2 > m1. Where multiple Dominant Matches exist within a Meet (or within a Join, respectively) the Dominant Matches will be incomparable to each other. Background Where the number of symbols appearing in matches is small relative to the length of the input strings, reuse of the symbols increases; and the number of matches will tend towards quadratic, O(m*n) growth. This occurs, for example, in the Bioinformatics application of nucleotide and protein sequencing. The divide-and-conquer approach of [Hirschberg 1975] limits the space required to O(n). However, this approach requires O(m*n) time even in the best case. This quadratic time dependency may become prohibitive, given very long input strings. Thus, heuristics are often favored over optimal Dynamic Programming solutions. In the application of comparing file revisions, records from the input files form a large symbol space; and the number of symbols approaches the length of the LCS. In this case the number of matches reduces to linear, O(n) growth. A binary search optimization due to [Hunt and Szymanski 1977] can be applied to the basic Dynamic Programming approach, resulting in an expected performance of O(n log m). Performance can degrade to O(m*n log m) time in the worst case, as the number of matches grows to O(m*n). Note [Rick 2000] describes a linear-space algorithm with a time bound of O(n*s + p*min(m, n - p)). Legend A, B are input strings of lengths m, n respectively p is the length of the LCS M is the set of match pairs (i, j) such that A[i] = B[j] r is the magnitude of M s is the magnitude of the alphabet Σ of distinct symbols in A + B References [Dilworth 1950] "A decomposition theorem for partially ordered sets" by Robert P. Dilworth, published January 1950, Annals of Mathematics [Volume 51, Number 1, pp. 161-166] [Goeman and Clausen 2002] "A New Practical Linear Space Algorithm for the Longest Common Subsequence Problem" by Heiko Goeman and Michael Clausen, published 2002, Kybernetika [Volume 38, Issue 1, pp. 45-66] [Hirschberg 1975] "A linear space algorithm for computing maximal common subsequences" by Daniel S. Hirschberg, published June 1975 Communications of the ACM [Volume 18, Number 6, pp. 341-343] [Hunt and McIlroy 1976] "An Algorithm for Differential File Comparison" by James W. Hunt and M. Douglas McIlroy, June 1976 Computing Science Technical Report, Bell Laboratories 41 [Hunt and Szymanski 1977] "A Fast Algorithm for Computing Longest Common Subsequences" by James W. Hunt and Thomas G. Szymanski, published May 1977 Communications of the ACM [Volume 20, Number 5, pp. 350-353] [Rick 2000] "Simple and fast linear space computation of longest common subsequences" by Claus Rick, received 17 March 2000, Information Processing Letters, Elsevier Science [Volume 75, pp. 275–281] Examples The sequences "1234" and "1224533324" have an LCS of "1234": 1234 1224533324 For a string example, consider the sequences "thisisatest" and "testing123testing". An LCS would be "tsitest": thisisatest testing123testing In this puzzle, your code only needs to deal with strings. Write a function which returns an LCS of two strings (case-sensitive). You don't need to show multiple LCS's. For more information on this problem please see Wikipedia. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#BBC_BASIC
BBC BASIC
PRINT FNlcs("1234", "1224533324") PRINT FNlcs("thisisatest", "testing123testing") END   DEF FNlcs(a$, b$) IF a$="" OR b$="" THEN = "" IF RIGHT$(a$) = RIGHT$(b$) THEN = FNlcs(LEFT$(a$), LEFT$(b$)) + RIGHT$(a$) LOCAL x$, y$ x$ = FNlcs(a$, LEFT$(b$)) y$ = FNlcs(LEFT$(a$), b$) IF LEN(y$) > LEN(x$) SWAP x$,y$ = x$
http://rosettacode.org/wiki/Look-and-say_sequence
Look-and-say sequence
The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequence 1,   11,   21,   1211,   111221?   is sometimes referred to as the Cuckoo's Egg,   from a description of Morris in Clifford Stoll's book   The Cuckoo's Egg. Sequence Definition Take a decimal number Look at the number, visually grouping consecutive runs of the same digit. Say the number, from left to right, group by group; as how many of that digit there are - followed by the digit grouped. This becomes the next number of the sequence. An example: Starting with the number 1,   you have one 1 which produces 11 Starting with 11,   you have two 1's.   I.E.:   21 Starting with 21,   you have one 2, then one 1.   I.E.:   (12)(11) which becomes 1211 Starting with 1211,   you have one 1, one 2, then two 1's.   I.E.:   (11)(12)(21) which becomes 111221 Task Write a program to generate successive members of the look-and-say sequence. Related tasks   Fours is the number of letters in the ...   Number names   Self-describing numbers   Self-referential sequence   Spelling of ordinal numbers See also   Look-and-Say Numbers (feat John Conway), A Numberphile Video.   This task is related to, and an application of, the Run-length encoding task.   Sequence A005150 on The On-Line Encyclopedia of Integer Sequences.
#AppleScript
AppleScript
on lookAndSay(startNumber, howMany) if (howMany < 1) then return {}   -- The numbers are handled as lists of digit-value integers for efficiency and output as a list of strings. script o property previousNumber : {} property newNumber : {} property output : {} end script   -- "Digitise" the start number. repeat set beginning of o's newNumber to startNumber mod 10 as integer set startNumber to startNumber div 10 if (startNumber is 0) then exit repeat end repeat -- Add it to the output as text and successively derive the remaining numbers. set astid to AppleScript's text item delimiters set AppleScript's text item delimiters to "" set end of o's output to o's newNumber as text repeat (howMany - 1) times set o's previousNumber to o's newNumber set o's newNumber to {} set i to 1 set previousLength to (o's previousNumber's length) set currentDigit to beginning of o's previousNumber repeat with j from 2 to previousLength set thisDigit to item j of o's previousNumber if (thisDigit is not currentDigit) then set end of o's newNumber to j - i set end of o's newNumber to currentDigit set i to j set currentDigit to thisDigit end if end repeat set end of o's newNumber to previousLength - i + 1 set end of o's newNumber to currentDigit   set end of o's output to o's newNumber as text end repeat set AppleScript's text item delimiters to astid   return o's output end lookAndSay   -- Test code: return lookAndSay(1, 10)
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.
#J
J
isempty =. (0 [ 0&{) :: 1: NB. 0=# compare =. ($:&}.)`((0 1,:_1 0) {~ <@,&isempty)@.(+.&isempty) NB. *@-&# add =. ,`(,:@[)`] @. (compare {:) > add&.>/ (}: , ,:&.>@{:) ;: 'a bb ccc ddd ee f ggg' ccc ddd ggg
http://rosettacode.org/wiki/Longest_string_challenge
Longest string challenge
Background This "longest string challenge" is inspired by a problem that used to be given to students learning Icon. Students were expected to try to solve the problem in Icon and another language with which the student was already familiar. The basic problem is quite simple; the challenge and fun part came through the introduction of restrictions. Experience has shown that the original restrictions required some adjustment to bring out the intent of the challenge and make it suitable for Rosetta Code. Basic problem statement Write a program that reads lines from standard input and, upon end of file, writes the longest line to standard output. If there are ties for the longest line, the program writes out all the lines that tie. If there is no input, the program should produce no output. Task Implement a solution to the basic problem that adheres to the spirit of the restrictions (see below). Describe how you circumvented or got around these 'restrictions' and met the 'spirit' of the challenge. Your supporting description may need to describe any challenges to interpreting the restrictions and how you made this interpretation. You should state any assumptions, warnings, or other relevant points. The central idea here is to make the task a bit more interesting by thinking outside of the box and perhaps by showing off the capabilities of your language in a creative way. Because there is potential for considerable variation between solutions, the description is key to helping others see what you've done. This task is likely to encourage a variety of different types of solutions. They should be substantially different approaches. Given the input: a bb ccc ddd ee f ggg the output should be (possibly rearranged): ccc ddd ggg Original list of restrictions No comparison operators may be used. No arithmetic operations, such as addition and subtraction, may be used. The only datatypes you may use are integer and string. In particular, you may not use lists. Do not re-read the input file. Avoid using files as a replacement for lists (this restriction became apparent in the discussion). Intent of restrictions Because of the variety of languages on Rosetta Code and the wide variety of concepts used in them, there needs to be a bit of clarification and guidance here to get to the spirit of the challenge and the intent of the restrictions. The basic problem can be solved very conventionally, but that's boring and pedestrian. The original intent here wasn't to unduly frustrate people with interpreting the restrictions, it was to get people to think outside of their particular box and have a bit of fun doing it. The guiding principle here should be to be creative in demonstrating some of the capabilities of the programming language being used. If you need to bend the restrictions a bit, explain why and try to follow the intent. If you think you've implemented a 'cheat', call out the fragment yourself and ask readers if they can spot why. If you absolutely can't get around one of the restrictions, explain why in your description. Now having said that, the restrictions require some elaboration. In general, the restrictions are meant to avoid the explicit use of these features. "No comparison operators may be used" - At some level there must be some test that allows the solution to get at the length and determine if one string is longer. Comparison operators, in particular any less/greater comparison should be avoided. Representing the length of any string as a number should also be avoided. Various approaches allow for detecting the end of a string. Some of these involve implicitly using equal/not-equal; however, explicitly using equal/not-equal should be acceptable. "No arithmetic operations" - Again, at some level something may have to advance through the string. Often there are ways a language can do this implicitly advance a cursor or pointer without explicitly using a +, - , ++, --, add, subtract, etc. The datatype restrictions are amongst the most difficult to reinterpret. In the language of the original challenge strings are atomic datatypes and structured datatypes like lists are quite distinct and have many different operations that apply to them. This becomes a bit fuzzier with languages with a different programming paradigm. The intent would be to avoid using an easy structure to accumulate the longest strings and spit them out. There will be some natural reinterpretation here. To make this a bit more concrete, here are a couple of specific examples: In C, a string is an array of chars, so using a couple of arrays as strings is in the spirit while using a second array in a non-string like fashion would violate the intent. In APL or J, arrays are the core of the language so ruling them out is unfair. Meeting the spirit will come down to how they are used. Please keep in mind these are just examples and you may hit new territory finding a solution. There will be other cases like these. Explain your reasoning. You may want to open a discussion on the talk page as well. The added "No rereading" restriction is for practical reasons, re-reading stdin should be broken. I haven't outright banned the use of other files but I've discouraged them as it is basically another form of a list. Somewhere there may be a language that just sings when doing file manipulation and where that makes sense; however, for most there should be a way to accomplish without resorting to an externality. At the end of the day for the implementer this should be a bit of fun. As an implementer you represent the expertise in your language, the reader may have no knowledge of your language. For the reader it should give them insight into how people think outside the box in other languages. Comments, especially for non-obvious (to the reader) bits will be extremely helpful. While the implementations may be a bit artificial in the context of this task, the general techniques may be useful elsewhere.
#Java
Java
import java.io.File; import java.util.Scanner;   public class LongestStringChallenge {   public static void main(String[] args) throws Exception { String lines = "", longest = ""; try (Scanner sc = new Scanner(new File("lines.txt"))) { while(sc.hasNext()) { String line = sc.nextLine(); if (longer(longest, line)) lines = longest = line; else if (!longer(line, longest)) lines = lines.concat("\n").concat(line); } } System.out.println(lines); }   static boolean longer(String a, String b) { try { String dummy = a.substring(b.length()); } catch (StringIndexOutOfBoundsException e) { return true; } return false; } }
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.
#Haskell
Haskell
import Data.Ord ( comparing ) import Data.List ( maximumBy, subsequences ) import Data.List.Ordered ( isSorted, nub )   lis :: Ord a => [a] -> [a] lis = maximumBy (comparing length) . map nub . filter isSorted . subsequences -- longest <-- unique <-- increasing <-- all   main = do print $ lis [3,2,6,4,5,1] print $ lis [0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15] print $ lis [1,1,1,1]
http://rosettacode.org/wiki/Loops/Continue
Loops/Continue
Task Show the following output using one loop. 1, 2, 3, 4, 5 6, 7, 8, 9, 10 Try to achieve the result by forcing the next iteration within the loop upon a specific condition, if your language allows it. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Chapel
Chapel
for i in 1..10 { write(i); if i % 5 == 0 then { writeln(); continue; } write(", "); }
http://rosettacode.org/wiki/Longest_common_substring
Longest common substring
Task Write a function that returns the longest common substring of two strings. Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing". Note that substrings are consecutive characters within a string.   This distinguishes them from subsequences, which is any sequence of characters within a string, even if there are extraneous characters in between them. Hence, the longest common subsequence between "thisisatest" and "testing123testing" is "tsitest", whereas the longest common substring is just "test". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet References Generalize Suffix Tree Ukkonen’s Suffix Tree Construction
#D
D
import std.stdio;   string lcs(string a, string b) { int[][] lengths; lengths.length = a.length; for (int i=0; i<a.length; i++) { lengths[i].length = b.length; }   int greatestLength; string output; for (int i=0; i<a.length; i++) { for (int j=0; j<b.length; j++) { if (a[i]==b[j]) { lengths[i][j] = i==0 || j==0 ? 1 : lengths[i-1][j-1] + 1; if (lengths[i][j] > greatestLength) { greatestLength = lengths[i][j]; int start = i-greatestLength+1; output = a[start..start+greatestLength]; } } else { lengths[i][j] = 0; } } } return output; }   void main() { writeln(lcs("testing123testing", "thisisatest")); }
http://rosettacode.org/wiki/Loops/Nested
Loops/Nested
Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} is met. Specifically, this task also shows how to break out of nested loops. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#ReScript
ReScript
let m = []   for _ in 0 to 9 { let n = [] for _ in 0 to 9 { let _ = Js.Array2.push(n, 1 + Js.Math.random_int(0, 20)) } let _ = Js.Array2.push(m, n) }   try { for i in 0 to 9 { for j in 0 to 9 { Js.log(m[i][j]) if m[i][j] == 20 { raise(Exit) } } } } catch { | Exit => Js.log("stop") }
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
#Standard_ML
Standard ML
app (fn i => print (Int.toString i ^ "\n")) collect_list
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
#Stata
Stata
local a 2 9 4 7 5 3 6 1 8 foreach i in `a' { display "`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
#OCaml
OCaml
let luhn s = let rec g r c = function | 0 -> r | i -> let d = c * ((int_of_char s.[i-1]) - 48) in g (r + (d/10) + (d mod 10)) (3-c) (i-1) in (g 0 1 (String.length s)) mod 10 = 0 ;;
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Pascal
Pascal
while true do writeln('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
#Perl
Perl
while(1){ print "SPAM\n"; }
http://rosettacode.org/wiki/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreachbas   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Oberon-2
Oberon-2
PROCEDURE DivBy2*(); VAR i: INTEGER; BEGIN i := 1024; WHILE i > 0 DO Out.Int(i,0); Out.Ln; i := i DIV 2; END; END DivBy2;
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
#Objeck
Objeck
i := 1024; while(i > 0) { i->PrintLine(); 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
#Pascal
Pascal
for i := 10 downto 0 do writeln(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
#Peloton
Peloton
<@ ITEFORLITLITLITLIT>0|<@ SAYVALFOR>...</@>|10|-1</@>
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.
#Lua
Lua
  i=0 repeat i=i+1 print(i) until i%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.
#M2000_Interpreter
M2000 Interpreter
  Module checkit { x=0 \\ Do or Repeat Do { x++ Print x } Until x mod 6=0   x=0 { \\ when enter to block the loop flag change to false x++ if x mod 6<>0 Then loop ' set loop flag of current block to true \\ when block end check Loop flag and if true execute block again Print X } } Checkit  
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.
#Factor
Factor
5 [1,b] [ [ "*" write ] times nl ] each
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
#Lambdatalk
Lambdatalk
  {def loops_for_with_a_specified_step {lambda {:a :b :step} {if {>= :a :b} then (end of loop) else :a {loops_for_with_a_specified_step {+ :a :step} :b :step}}}} -> loops_for_with_a_specified_step   {loops_for_with_a_specified_step 0 10 2} -> 0 2 4 6 8 (end of loop)   a more simple way:   {S.map {lambda {:i} :i} {S.serie 0 9 2}} -> 0 2 4 6 8  
http://rosettacode.org/wiki/Literals/Integer
Literals/Integer
Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but should be interpreted by the compiler or interpreter as an integer written to a given base. Also show any other ways of expressing literals, e.g. for different types of integers. Related task   Literals/Floating point
#11l
11l
print(255) // decimal literal print(0000'00FF) // hexadecimal literal print(00'FF) // short hexadecimal literal print(F'F) // ultrashort (single-byte) hexadecimal literal print(377o) // octal literal print(1111'1111b) // binary literal print(255'000) // decimal literal
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
#Scheme
Scheme
(call-with-current-continuation (lambda (esc) (do ((i 1 (+ 1 i))) (#f) (display i) (if (= i 10) (esc (newline))) (display ", "))))
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
#Scilab
Scilab
for i=1:10 printf("%2d ",i) if i<10 then printf(", "); end end printf("\n")
http://rosettacode.org/wiki/Literals/Floating_point
Literals/Floating point
Programming languages have different ways of expressing floating-point literals. Task Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features. You may want to include a regular expression or BNF/ABNF/EBNF defining allowable formats for your language. Related tasks   Literals/Integer   Extreme floating point values
#360_Assembly
360 Assembly
XS4 DC E'1.23456E-4' short floating-point   XDPI DC D'3.141592653589793' long floating-point XD1 DC D'0' long floating-point XD2 DC D'1' long floating-point XD3 DC D'-1' long floating-point XD4 DC D'1.2345E-4' long floating-point   XQPI DC L'3.14159265358979323846264338327950' extended   * short floating-point - 32 bits - 4 bytes : 6 decimal digits * long floating-point - 64 bits - 8 bytes : 16 decimal digits * extended floating-point - 128 bits - 16 bytes : 33 decimal digits   * absolute approximate range: 5e-79 to 7e75
http://rosettacode.org/wiki/Literals/Floating_point
Literals/Floating point
Programming languages have different ways of expressing floating-point literals. Task Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features. You may want to include a regular expression or BNF/ABNF/EBNF defining allowable formats for your language. Related tasks   Literals/Integer   Extreme floating point values
#6502_Assembly
6502 Assembly
byte $DB,$0F,$49,$40  ;3.141592654
http://rosettacode.org/wiki/Literals/Floating_point
Literals/Floating point
Programming languages have different ways of expressing floating-point literals. Task Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features. You may want to include a regular expression or BNF/ABNF/EBNF defining allowable formats for your language. Related tasks   Literals/Integer   Extreme floating point values
#Ada
Ada
  3.141_592_6 1.0E-12 0.13  
http://rosettacode.org/wiki/Long_year
Long year
Most years have 52 weeks, some have 53, according to ISO8601. Task Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
#AWK
AWK
  # syntax: GAWK -f LONG_YEAR.AWK BEGIN { for (cc=19; cc<=21; cc++) { printf("%2d00-%2d99: ",cc,cc) for (yy=0; yy<=99; yy++) { ccyy = sprintf("%02d%02d",cc,yy) if (is_long_year(ccyy)) { printf("%4d ",ccyy) } } printf("\n") } # printf("\n%4d-%4d: ",by=1970,ey=2037) for (y=by; y<=ey; y++) { if (strftime("%V",mktime(sprintf("%d 12 28 0 0 0",y))) == 53) { printf("%4d ",y) } } printf("\n") exit(0) } function is_long_year(year, i) { for (i=0; i<=1; i++) { year -= i if ((year + int(year/4) - int(year/100) + int(year/400)) % 7 == 4-i) { return(1) } } return(0) }  
http://rosettacode.org/wiki/Long_primes
Long primes
A   long prime   (as defined here)   is a prime number whose reciprocal   (in decimal)   has a   period length   of one less than the prime number. Long primes   are also known as:   base ten cyclic numbers   full reptend primes   golden primes   long period primes   maximal period primes   proper primes Another definition:   primes   p   such that the decimal expansion of   1/p   has period   p-1,   which is the greatest period possible for any integer. Example 7   is the first long prime,   the reciprocal of seven is   1/7,   which is equal to the repeating decimal fraction   0.142857142857··· The length of the   repeating   part of the decimal fraction is six,   (the underlined part)   which is one less than the (decimal) prime number   7. Thus   7   is a long prime. There are other (more) general definitions of a   long prime   which include wording/verbiage for bases other than ten. Task   Show all long primes up to   500   (preferably on one line).   Show the   number   of long primes up to        500   Show the   number   of long primes up to     1,000   Show the   number   of long primes up to     2,000   Show the   number   of long primes up to     4,000   Show the   number   of long primes up to     8,000   Show the   number   of long primes up to   16,000   Show the   number   of long primes up to   32,000   Show the   number   of long primes up to   64,000   (optional)   Show all output here. Also see   Wikipedia: full reptend prime   MathWorld: full reptend prime   OEIS: A001913
#C.23
C#
using System; using System.Collections.Generic; using System.Linq;   public static class LongPrimes { public static void Main() { var primes = SomePrimeGenerator.Primes(64000).Skip(1).Where(p => Period(p) == p - 1).Append(99999); Console.WriteLine(string.Join(" ", primes.TakeWhile(p => p <= 500))); int count = 0, limit = 500; foreach (int prime in primes) { if (prime > limit) { Console.WriteLine($"There are {count} long primes below {limit}"); limit *= 2; } count++; }   int Period(int n) { int r = 1, rr; for (int i = 0; i <= n; i++) r = 10 * r % n; rr = r; for (int period = 1;; period++) { r = (10 * r) % n; if (r == rr) return period; } } }   }   static class SomePrimeGenerator {   public static IEnumerable<int> Primes(int lim) { bool [] flags = new bool[lim + 1]; int j = 2; for (int d = 3, sq = 4; sq <= lim; j++, sq += d += 2) if (!flags[j]) { yield return j; for (int k = sq; k <= lim; k += j) flags[k] = true; } for (; j<= lim; j++) if (!flags[j]) yield return j; } }
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
#AppleScript
AppleScript
-- ZIP LISTS WITH FUNCTION ---------------------------------------------------   -- zipListsWith :: ([a] -> b) -> [[a]] -> [[b]] on zipListsWith(f, xss) set n to length of xss   script on |λ|(_, i) script on |λ|(xs) item i of xs end |λ| end script   if i ≤ n then apply(f, (map(result, xss))) else {} end if end |λ| end script   if n > 0 then map(result, item 1 of xss) else [] end if end zipListsWith     -- TEST ( zip lists with concat ) ------------------------------------------- on run   intercalate(linefeed, ¬ zipListsWith(concat, ¬ [["a", "b", "c"], ["A", "B", "C"], [1, 2, 3]]))   end run     -- GENERIC FUNCTIONS ---------------------------------------------------------   -- apply (a -> b) -> a -> b on apply(f, a) mReturn(f)'s |λ|(a) end apply   -- concat :: [[a]] -> [a] | [String] -> String on concat(xs) if length of xs > 0 and class of (item 1 of xs) is string then set acc to "" else set acc to {} end if repeat with i from 1 to length of xs set acc to acc & item i of xs end repeat acc end concat   -- intercalate :: Text -> [Text] -> Text on intercalate(strText, lstText) set {dlm, my text item delimiters} to {my text item delimiters, strText} set strJoined to lstText as text set my text item delimiters to dlm return strJoined end intercalate   -- map :: (a -> b) -> [a] -> [b] on map(f, xs) tell mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell end map   -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) if class of f is script then f else script property |λ| : f end script end if end mReturn
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
#AWK
AWK
BEGIN { for (;;) { print n = int(rand() * 20) if (n == 10) break print int(rand() * 20) } }
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
#Axe
Axe
While 1 rand^20→A Disp A▶Dec ReturnIf A=10 rand^20→B Disp B▶Dec,i End
http://rosettacode.org/wiki/Longest_common_subsequence
Longest common subsequence
Introduction Define a subsequence to be any output string obtained by deleting zero or more symbols from an input string. The Longest Common Subsequence (LCS) is a subsequence of maximum length common to two or more strings. Let A ≡ A[0]… A[m - 1] and B ≡ B[0]… B[n - 1], m < n be strings drawn from an alphabet Σ of size s, containing every distinct symbol in A + B. An ordered pair (i, j) will be referred to as a match if A[i] = B[j], where 0 < i ≤ m and 0 < j ≤ n. Define a non-strict product-order (≤) over ordered pairs, such that (i1, j1) ≤ (i2, j2) ⇔ i1 ≤ i2 and j1 ≤ j2. We define (≥) similarly. We say m1, m2 are comparable if either m1 ≤ m2 or m1 ≥ m2 holds. If i1 < i2 and j2 < j1 (or i2 < i1 and j1 < j2) then neither m1 ≤ m2 nor m1 ≥ m2 are possible; and we say m1, m2 are incomparable. We also define the strict product-order (<) over ordered pairs, such that (i1, j1) < (i2, j2) ⇔ i1 < i2 and j1 < j2. We define (>) similarly. Given a set of matches M, a chain C is a subset of M consisting of at least one element m; and where either m1 < m2 or m1 > m2 for every pair of distinct elements m1 and m2. An antichain D is any subset of M in which every pair of distinct elements m1 and m2 are incomparable. The set M represents a relation over match pairs: M[i, j] ⇔ (i, j) ∈ M. A chain C can be visualized as a curve which strictly increases as it passes through each match pair in the m*n coordinate space. Finding an LCS can be restated as the problem of finding a chain of maximum cardinality p over the set of matches M. According to [Dilworth 1950], this cardinality p equals the minimum number of disjoint antichains into which M can be decomposed. Note that such a decomposition into the minimal number p of disjoint antichains may not be unique. Contours Forward Contours FC[k] of class k are defined inductively, as follows: FC[0] consists of those elements m1 for which there exists no element m2 such that m2 < m1. FC[k] consists of those elements m1 for which there exists no element m2 such that m2 < m1; and where neither m1 nor m2 are contained in FC[l] for any class l < k. Reverse Contours RC[k] of class k are defined similarly. Members of the Meet (∧), or Infimum of a Forward Contour are referred to as its Dominant Matches: those m1 for which there exists no m2 such that m2 < m1. Members of the Join (∨), or Supremum of a Reverse Contour are referred to as its Dominant Matches: those m1 for which there exists no m2 such that m2 > m1. Where multiple Dominant Matches exist within a Meet (or within a Join, respectively) the Dominant Matches will be incomparable to each other. Background Where the number of symbols appearing in matches is small relative to the length of the input strings, reuse of the symbols increases; and the number of matches will tend towards quadratic, O(m*n) growth. This occurs, for example, in the Bioinformatics application of nucleotide and protein sequencing. The divide-and-conquer approach of [Hirschberg 1975] limits the space required to O(n). However, this approach requires O(m*n) time even in the best case. This quadratic time dependency may become prohibitive, given very long input strings. Thus, heuristics are often favored over optimal Dynamic Programming solutions. In the application of comparing file revisions, records from the input files form a large symbol space; and the number of symbols approaches the length of the LCS. In this case the number of matches reduces to linear, O(n) growth. A binary search optimization due to [Hunt and Szymanski 1977] can be applied to the basic Dynamic Programming approach, resulting in an expected performance of O(n log m). Performance can degrade to O(m*n log m) time in the worst case, as the number of matches grows to O(m*n). Note [Rick 2000] describes a linear-space algorithm with a time bound of O(n*s + p*min(m, n - p)). Legend A, B are input strings of lengths m, n respectively p is the length of the LCS M is the set of match pairs (i, j) such that A[i] = B[j] r is the magnitude of M s is the magnitude of the alphabet Σ of distinct symbols in A + B References [Dilworth 1950] "A decomposition theorem for partially ordered sets" by Robert P. Dilworth, published January 1950, Annals of Mathematics [Volume 51, Number 1, pp. 161-166] [Goeman and Clausen 2002] "A New Practical Linear Space Algorithm for the Longest Common Subsequence Problem" by Heiko Goeman and Michael Clausen, published 2002, Kybernetika [Volume 38, Issue 1, pp. 45-66] [Hirschberg 1975] "A linear space algorithm for computing maximal common subsequences" by Daniel S. Hirschberg, published June 1975 Communications of the ACM [Volume 18, Number 6, pp. 341-343] [Hunt and McIlroy 1976] "An Algorithm for Differential File Comparison" by James W. Hunt and M. Douglas McIlroy, June 1976 Computing Science Technical Report, Bell Laboratories 41 [Hunt and Szymanski 1977] "A Fast Algorithm for Computing Longest Common Subsequences" by James W. Hunt and Thomas G. Szymanski, published May 1977 Communications of the ACM [Volume 20, Number 5, pp. 350-353] [Rick 2000] "Simple and fast linear space computation of longest common subsequences" by Claus Rick, received 17 March 2000, Information Processing Letters, Elsevier Science [Volume 75, pp. 275–281] Examples The sequences "1234" and "1224533324" have an LCS of "1234": 1234 1224533324 For a string example, consider the sequences "thisisatest" and "testing123testing". An LCS would be "tsitest": thisisatest testing123testing In this puzzle, your code only needs to deal with strings. Write a function which returns an LCS of two strings (case-sensitive). You don't need to show multiple LCS's. For more information on this problem please see Wikipedia. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#BQN
BQN
LCS ← ¯1 ⊑ "" <⊸∾ ""¨∘⊢ ⊣⍟(>○≠){𝕩𝔽¨𝔽`𝕨∾¨""<⊸»𝕩}˝ (=⌜⥊¨⊣)⟜⌽
http://rosettacode.org/wiki/Look-and-say_sequence
Look-and-say sequence
The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequence 1,   11,   21,   1211,   111221?   is sometimes referred to as the Cuckoo's Egg,   from a description of Morris in Clifford Stoll's book   The Cuckoo's Egg. Sequence Definition Take a decimal number Look at the number, visually grouping consecutive runs of the same digit. Say the number, from left to right, group by group; as how many of that digit there are - followed by the digit grouped. This becomes the next number of the sequence. An example: Starting with the number 1,   you have one 1 which produces 11 Starting with 11,   you have two 1's.   I.E.:   21 Starting with 21,   you have one 2, then one 1.   I.E.:   (12)(11) which becomes 1211 Starting with 1211,   you have one 1, one 2, then two 1's.   I.E.:   (11)(12)(21) which becomes 111221 Task Write a program to generate successive members of the look-and-say sequence. Related tasks   Fours is the number of letters in the ...   Number names   Self-describing numbers   Self-referential sequence   Spelling of ordinal numbers See also   Look-and-Say Numbers (feat John Conway), A Numberphile Video.   This task is related to, and an application of, the Run-length encoding task.   Sequence A005150 on The On-Line Encyclopedia of Integer Sequences.
#Arturo
Arturo
lookAndSay: function [n][ if n=0 -> return "1" previous: lookAndSay n-1   result: new "" currentCounter: 0 currentCh: first previous loop previous 'ch [ if? currentCh <> ch [ if not? zero? currentCounter -> 'result ++ (to :string currentCounter) ++ currentCh currentCounter: 1 currentCh: ch ] else -> currentCounter: currentCounter + 1 ] 'result ++ (to :string currentCounter) ++ currentCh return result ]   loop 0..10 'x [ print [x "->" lookAndSay x] ]
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.
#Julia
Julia
function longer(a, b) try b[endof(a)] catch return true end return false end   function printlongest(io::IO) lines = longest = "" while !eof(io) line = readline(io) if longer(line, longest) longest = lines = line elseif !longer(longest, line) lines *= "\n" * line end end println(lines) end printlongest(str::String) = printlongest(IOBuffer(str))   printlongest("a\nbb\nccc\nddd\nee\nf\nggg")
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.
#Kotlin
Kotlin
// version 1.1.0   import java.io.File import java.util.*   fun longer(a: String, b: String): Boolean = try { a.substring(b.length) false } catch (e: StringIndexOutOfBoundsException) { true }   fun main(args: Array<String>) { var lines = "" var longest = "" val sc = Scanner(File("lines.txt")) while(sc.hasNext()) { val line = sc.nextLine() if (longer(longest, line)) { longest = line lines = longest } else if (!longer(line, longest)) lines = lines.plus("\n").plus(line) // using 'plus' to avoid using '+' } sc.close() println(lines); println()   // alternatively (but cheating as library functions will use comparisons and lists under the hood) println(File("lines.txt").readLines().groupBy { it.length }.maxBy { it.key }!!.value.joinToString("\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.
#Icon_and_Unicon
Icon and Unicon
procedure main(A) every writes((!lis(A)||" ") | "\n") end   procedure lis(A) r := [A[1]] | fail every (put(pt := [], [v := !A]), p := !pt) do if put(p, p[-1] < v) then r := (*p > *r, p) else p[-1] := (p[-2] < v) return r 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
#Clipper
Clipper
FOR i := 1 TO 10 ?? i IF i % 5 == 0 ? LOOP ENDIF ?? ", " NEXT
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
#Clojure
Clojure
(doseq [n (range 1 11)] (print n) (if (zero? (rem n 5)) (println) (print ", ")))
http://rosettacode.org/wiki/Longest_common_substring
Longest common substring
Task Write a function that returns the longest common substring of two strings. Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing". Note that substrings are consecutive characters within a string.   This distinguishes them from subsequences, which is any sequence of characters within a string, even if there are extraneous characters in between them. Hence, the longest common subsequence between "thisisatest" and "testing123testing" is "tsitest", whereas the longest common substring is just "test". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet References Generalize Suffix Tree Ukkonen’s Suffix Tree Construction
#Delphi
Delphi
  program Longest_Common_Substring;   {$APPTYPE CONSOLE}   {$R *.res}   uses System.SysUtils;   function lcs(x, y: string): string; var n, m, Alength: Integer; t, common: string; j: Integer; k: Integer; begin   Result := ''; Alength := x.Length;   for j := 0 to Alength - 1 do for k := Alength - j downto 0 do begin common := x.Substring(j, k); if (y.IndexOf(common) > -1) and (common.Length > Result.Length) then Result := common; end; end;   var a, b: string;   begin a := 'thisisatest'; b := 'testing123testing'; if ParamCount = 2 then begin if not ParamStr(1).IsEmpty then a := ParamStr(1); if not ParamStr(2).IsEmpty then b := ParamStr(2); end;   Writeln('string A = ', a); Writeln('string B = ', b); Writeln('LCsubstr = ', lcs(a, b)); readln; 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
#REXX
REXX
/*REXX program loops through a two-dimensional array to search for a '20' (twenty). */ parse arg rows cols targ . /*obtain optional arguments from the CL*/ if rows=='' | rows=="," then rows=60 /*Rows not specified? Then use default*/ if cols=='' | cols=="," then cols=10 /*Cols " " " " " */ if targ=='' | targ=="," then targ=20 /*Targ " " " " " */ w=max(length(rows), length(cols), length(targ)) /*W: used for formatting the output. */ not= 'not' /* [↓] construct the 2─dimension array*/ do row=1 for rows /*ROW is the 1st dimension of array. */ do col=1 for cols /*COL " " 2nd " " " */ @.row.col=random(1, targ) /*create some positive random integers.*/ end /*row*/ end /*col*/   do r=1 for rows /* ◄───────────────── now, search for the target {20}.*/ do c=1 for cols say left('@.'r"."c, 3+w+w) '=' right(@.r.c, w) /*show an array element.*/ if @.r.c==targ then do; not=; leave r; end /*found the targ number?*/ end /*c*/ end /*r*/   say right( space( 'Target' not "found:" ) targ, 33, '─') /*stick a fork in it, we're all 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
#Suneido
Suneido
for i in #(1, 2, 3) 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
#Swift
Swift
for i in [1,2,3] { 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
#SystemVerilog
SystemVerilog
program main; int values[$];   initial begin values = '{ 1, 3, 7, 11 }; foreach (values[i]) begin $display( "%0d --> %0d", i, values[i] ); end end endprogram
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
#Octave
Octave
function y = isluhn(s); if isnumeric(s) s = mat2str(s); end; % make sure s is a string d = s-'0'; % convert string into vector of digits m = [2:2:8,1:2:9]; % rule 3: maps [1:9] -> i y = ~mod(sum(d(end:-2:1)) + sum(m(d(end-1:-2:1))),10); 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
#Phix
Phix
while true do puts(1,"SPAM\n") end while
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
#PHP
PHP
while(1) echo "SPAM\n";
http://rosettacode.org/wiki/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreachbas   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#ObjectIcon
ObjectIcon
import io   procedure main() local n n := 1024 while n := write(0 < n) / 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
#OCaml
OCaml
let n = ref 1024;; while !n > 0 do Printf.printf "%d\n" !n; n := !n / 2 done;;
http://rosettacode.org/wiki/Loops/Downward_for
Loops/Downward for
Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Perl
Perl
foreach (reverse 0..10) { 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
#Phix
Phix
for i=10 to 0 by -1 do ?i end for
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.
#Maple
Maple
val := 0: do val := 1 + val; print( val ); if irem( val, 6 ) = 0 then break end if; end do:
http://rosettacode.org/wiki/Loops/For
Loops/For
“For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers. Task Show how two loops may be nested within each other, with the number of iterations performed by the inner for loop being controlled by the outer for loop. Specifically print out the following pattern by using one for loop nested in another: * ** *** **** ***** Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges Reference For loop Wikipedia.
#FALSE
FALSE
1[$6-][$[$]["*"1-]#%" "1+]#%
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
#Lang5
Lang5
: <range> over iota swap * rot + tuck swap <= select ; : tuck swap over ; : >>say.(*) . ; 1 10 2 <range> >>say.
http://rosettacode.org/wiki/Literals/Integer
Literals/Integer
Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but should be interpreted by the compiler or interpreter as an integer written to a given base. Also show any other ways of expressing literals, e.g. for different types of integers. Related task   Literals/Floating point
#6502_Assembly
6502 Assembly
;These are all equivalent: LDA #$41 LDA #65 LDA #%01000001 LDA #'A'
http://rosettacode.org/wiki/Literals/Integer
Literals/Integer
Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but should be interpreted by the compiler or interpreter as an integer written to a given base. Also show any other ways of expressing literals, e.g. for different types of integers. Related task   Literals/Floating point
#68000_Assembly
68000 Assembly
;These are all equivalent: MOVE.B #$41,D0 MOVE.B #65,D0 MOVE.B #%01000001,D0 MOVE.B #'A',D0
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
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: main is func local var integer: number is 0; begin for number range 1 to 10 do write(number); if number < 10 then write(", ") end if; end for; writeln; end func;
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
#Sidef
Sidef
for (1..10) { |i| print i; i == 10 && break; print ', '; }   print "\n";
http://rosettacode.org/wiki/Literals/Floating_point
Literals/Floating point
Programming languages have different ways of expressing floating-point literals. Task Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features. You may want to include a regular expression or BNF/ABNF/EBNF defining allowable formats for your language. Related tasks   Literals/Integer   Extreme floating point values
#Aime
Aime
3.14 5.0 8r # without the "r"(eal) suffix, "8" would be an integer .125
http://rosettacode.org/wiki/Literals/Floating_point
Literals/Floating point
Programming languages have different ways of expressing floating-point literals. Task Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features. You may want to include a regular expression or BNF/ABNF/EBNF defining allowable formats for your language. Related tasks   Literals/Integer   Extreme floating point values
#ALGOL_68
ALGOL 68
# floating point literals are called REAL denotations in Algol 68 # # They have the following forms: # # 1: a digit sequence followed by "." followed by a digit sequence # # 2: a "." followed by a digit sequence # # 3: forms 1 or 2 followed by "e" followed by an optional sign # # followed by a digit sequence # # 4: a digit sequence follows by "e" followed by an optional sign # # followed by a digit sequence # # # # The "e" indicates the following optionally-signed digit sequence is # # the exponent of the literal. # # If the implementation allows, a "times ten to the power symbol" # # can be used to replace "e" - e.g. a subscript "10" character # # # # spaces can appear anywhere in the denotation # # Examples: # REAL r; r := 1.234; r := .987; r := 4.2e-9; r := .4e+23; r := 1e10; r := 3.142e-23; r := 1 234 567 . 9 e - 4;  
http://rosettacode.org/wiki/Long_year
Long year
Most years have 52 weeks, some have 53, according to ISO8601. Task Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
#BASIC
BASIC
10 DEF FN M7(N) = N - 7 * INT (N / 7) 20 DEF FN WD(Y) = FN M7(Y + INT (Y / 4) - INT (Y / 100) + INT (Y / 400)) 30 DEF FN LY(Y) = (4 = FN WD(Y)) OR (3 = FN WD(Y - 1)) 40 HOME : INVERSE : PRINT "**** LIST OF ISO LONG YEARS ****": NORMAL 50 INPUT "START YEAR? ";S 60 INPUT "END YEAR? ";E 70 PRINT : FOR Y = S TO E 80 IF FN LY(Y) THEN PRINT S$Y;:S$ = " " 90 NEXT Y
http://rosettacode.org/wiki/Long_year
Long year
Most years have 52 weeks, some have 53, according to ISO8601. Task Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
#BCPL
BCPL
get "libhdr"   let p(y) = (y + y/4 - y/100 + y/400) rem 7 let longyear(y) = p(y)=4 | p(y-1)=3   let start() be for y = 2000 to 2100 if longyear(y) do writef("%N*N", y)
http://rosettacode.org/wiki/Long_primes
Long primes
A   long prime   (as defined here)   is a prime number whose reciprocal   (in decimal)   has a   period length   of one less than the prime number. Long primes   are also known as:   base ten cyclic numbers   full reptend primes   golden primes   long period primes   maximal period primes   proper primes Another definition:   primes   p   such that the decimal expansion of   1/p   has period   p-1,   which is the greatest period possible for any integer. Example 7   is the first long prime,   the reciprocal of seven is   1/7,   which is equal to the repeating decimal fraction   0.142857142857··· The length of the   repeating   part of the decimal fraction is six,   (the underlined part)   which is one less than the (decimal) prime number   7. Thus   7   is a long prime. There are other (more) general definitions of a   long prime   which include wording/verbiage for bases other than ten. Task   Show all long primes up to   500   (preferably on one line).   Show the   number   of long primes up to        500   Show the   number   of long primes up to     1,000   Show the   number   of long primes up to     2,000   Show the   number   of long primes up to     4,000   Show the   number   of long primes up to     8,000   Show the   number   of long primes up to   16,000   Show the   number   of long primes up to   32,000   Show the   number   of long primes up to   64,000   (optional)   Show all output here. Also see   Wikipedia: full reptend prime   MathWorld: full reptend prime   OEIS: A001913
#C.2B.2B
C++
  #include <iomanip> #include <iostream> #include <list> using namespace std;   void sieve(int limit, list<int> &primes) { bool *c = new bool[limit + 1]; for (int i = 0; i <= limit; i++) c[i] = false; // No need to process even numbers int p = 3, n = 0; int p2 = p * p; while (p2 <= limit) { for (int i = p2; i <= limit; i += 2 * p) c[i] = true; do p += 2; while (c[p]); p2 = p * p; } for (int i = 3; i <= limit; i += 2) if (!c[i]) primes.push_back(i); delete [] c; }   // Finds the period of the reciprocal of n int findPeriod(int n) { int r = 1, rr, period = 0; for (int i = 1; i <= n + 1; ++i) r = (10 * r) % n; rr = r; do { r = (10 * r) % n; period++; } while (r != rr); return period; }   int main() { int count = 0, index = 0; int numbers[] = {500, 1000, 2000, 4000, 8000, 16000, 32000, 64000}; list<int> primes; list<int> longPrimes; int numberCount = sizeof(numbers) / sizeof(int); int *totals = new int[numberCount]; cout << "Please wait." << endl << endl; sieve(64000, primes); for (list<int>::iterator iterPrime = primes.begin(); iterPrime != primes.end(); iterPrime++) { if (findPeriod(*iterPrime) == *iterPrime - 1) longPrimes.push_back(*iterPrime); }   for (list<int>::iterator iterLongPrime = longPrimes.begin(); iterLongPrime != longPrimes.end(); iterLongPrime++) { if (*iterLongPrime > numbers[index]) totals[index++] = count; ++count; } totals[numberCount - 1] = count; cout << "The long primes up to " << totals[0] << " are:" << endl; cout << "["; int i = 0; for (list<int>::iterator iterLongPrime = longPrimes.begin(); iterLongPrime != longPrimes.end() && i < totals[0]; iterLongPrime++, i++) { cout << *iterLongPrime << " "; } cout << "\b]" << endl; cout << endl << "The number of long primes up to:" << endl; for (int i = 0; i < 8; ++i) cout << " " << setw(5) << numbers[i] << " is " << totals[i] << endl; delete [] totals; }  
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
#Arturo
Arturo
parts: ["abc" "ABC" [1 2 3]]   loop 0..2 'x -> print ~"|parts\0\[x]||parts\1\[x]||parts\2\[x]|"
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
#BASIC
BASIC
FOR I = 0 TO 1 STEP 0 : N = INT(RND(1) * 20) : PRINT " "N; : IF N <> 10 THEN ? ","INT(RND(1) * 20); : NEXT
http://rosettacode.org/wiki/Longest_common_subsequence
Longest common subsequence
Introduction Define a subsequence to be any output string obtained by deleting zero or more symbols from an input string. The Longest Common Subsequence (LCS) is a subsequence of maximum length common to two or more strings. Let A ≡ A[0]… A[m - 1] and B ≡ B[0]… B[n - 1], m < n be strings drawn from an alphabet Σ of size s, containing every distinct symbol in A + B. An ordered pair (i, j) will be referred to as a match if A[i] = B[j], where 0 < i ≤ m and 0 < j ≤ n. Define a non-strict product-order (≤) over ordered pairs, such that (i1, j1) ≤ (i2, j2) ⇔ i1 ≤ i2 and j1 ≤ j2. We define (≥) similarly. We say m1, m2 are comparable if either m1 ≤ m2 or m1 ≥ m2 holds. If i1 < i2 and j2 < j1 (or i2 < i1 and j1 < j2) then neither m1 ≤ m2 nor m1 ≥ m2 are possible; and we say m1, m2 are incomparable. We also define the strict product-order (<) over ordered pairs, such that (i1, j1) < (i2, j2) ⇔ i1 < i2 and j1 < j2. We define (>) similarly. Given a set of matches M, a chain C is a subset of M consisting of at least one element m; and where either m1 < m2 or m1 > m2 for every pair of distinct elements m1 and m2. An antichain D is any subset of M in which every pair of distinct elements m1 and m2 are incomparable. The set M represents a relation over match pairs: M[i, j] ⇔ (i, j) ∈ M. A chain C can be visualized as a curve which strictly increases as it passes through each match pair in the m*n coordinate space. Finding an LCS can be restated as the problem of finding a chain of maximum cardinality p over the set of matches M. According to [Dilworth 1950], this cardinality p equals the minimum number of disjoint antichains into which M can be decomposed. Note that such a decomposition into the minimal number p of disjoint antichains may not be unique. Contours Forward Contours FC[k] of class k are defined inductively, as follows: FC[0] consists of those elements m1 for which there exists no element m2 such that m2 < m1. FC[k] consists of those elements m1 for which there exists no element m2 such that m2 < m1; and where neither m1 nor m2 are contained in FC[l] for any class l < k. Reverse Contours RC[k] of class k are defined similarly. Members of the Meet (∧), or Infimum of a Forward Contour are referred to as its Dominant Matches: those m1 for which there exists no m2 such that m2 < m1. Members of the Join (∨), or Supremum of a Reverse Contour are referred to as its Dominant Matches: those m1 for which there exists no m2 such that m2 > m1. Where multiple Dominant Matches exist within a Meet (or within a Join, respectively) the Dominant Matches will be incomparable to each other. Background Where the number of symbols appearing in matches is small relative to the length of the input strings, reuse of the symbols increases; and the number of matches will tend towards quadratic, O(m*n) growth. This occurs, for example, in the Bioinformatics application of nucleotide and protein sequencing. The divide-and-conquer approach of [Hirschberg 1975] limits the space required to O(n). However, this approach requires O(m*n) time even in the best case. This quadratic time dependency may become prohibitive, given very long input strings. Thus, heuristics are often favored over optimal Dynamic Programming solutions. In the application of comparing file revisions, records from the input files form a large symbol space; and the number of symbols approaches the length of the LCS. In this case the number of matches reduces to linear, O(n) growth. A binary search optimization due to [Hunt and Szymanski 1977] can be applied to the basic Dynamic Programming approach, resulting in an expected performance of O(n log m). Performance can degrade to O(m*n log m) time in the worst case, as the number of matches grows to O(m*n). Note [Rick 2000] describes a linear-space algorithm with a time bound of O(n*s + p*min(m, n - p)). Legend A, B are input strings of lengths m, n respectively p is the length of the LCS M is the set of match pairs (i, j) such that A[i] = B[j] r is the magnitude of M s is the magnitude of the alphabet Σ of distinct symbols in A + B References [Dilworth 1950] "A decomposition theorem for partially ordered sets" by Robert P. Dilworth, published January 1950, Annals of Mathematics [Volume 51, Number 1, pp. 161-166] [Goeman and Clausen 2002] "A New Practical Linear Space Algorithm for the Longest Common Subsequence Problem" by Heiko Goeman and Michael Clausen, published 2002, Kybernetika [Volume 38, Issue 1, pp. 45-66] [Hirschberg 1975] "A linear space algorithm for computing maximal common subsequences" by Daniel S. Hirschberg, published June 1975 Communications of the ACM [Volume 18, Number 6, pp. 341-343] [Hunt and McIlroy 1976] "An Algorithm for Differential File Comparison" by James W. Hunt and M. Douglas McIlroy, June 1976 Computing Science Technical Report, Bell Laboratories 41 [Hunt and Szymanski 1977] "A Fast Algorithm for Computing Longest Common Subsequences" by James W. Hunt and Thomas G. Szymanski, published May 1977 Communications of the ACM [Volume 20, Number 5, pp. 350-353] [Rick 2000] "Simple and fast linear space computation of longest common subsequences" by Claus Rick, received 17 March 2000, Information Processing Letters, Elsevier Science [Volume 75, pp. 275–281] Examples The sequences "1234" and "1224533324" have an LCS of "1234": 1234 1224533324 For a string example, consider the sequences "thisisatest" and "testing123testing". An LCS would be "tsitest": thisisatest testing123testing In this puzzle, your code only needs to deal with strings. Write a function which returns an LCS of two strings (case-sensitive). You don't need to show multiple LCS's. For more information on this problem please see Wikipedia. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Bracmat
Bracmat
( LCS = A a ta B b tb prefix .  !arg:(?prefix.@(?A:%?a ?ta).@(?B:%?b ?tb)) & ( !a:!b&LCS$(!prefix !a.!ta.!tb) | LCS$(!prefix.!A.!tb)&LCS$(!prefix.!ta.!B) ) | !prefix:? ([>!max:[?max):?lcs | ) & 0:?max & :?lcs & LCS$(.thisisatest.testing123testing) & out$(max !max lcs !lcs);
http://rosettacode.org/wiki/Look-and-say_sequence
Look-and-say sequence
The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequence 1,   11,   21,   1211,   111221?   is sometimes referred to as the Cuckoo's Egg,   from a description of Morris in Clifford Stoll's book   The Cuckoo's Egg. Sequence Definition Take a decimal number Look at the number, visually grouping consecutive runs of the same digit. Say the number, from left to right, group by group; as how many of that digit there are - followed by the digit grouped. This becomes the next number of the sequence. An example: Starting with the number 1,   you have one 1 which produces 11 Starting with 11,   you have two 1's.   I.E.:   21 Starting with 21,   you have one 2, then one 1.   I.E.:   (12)(11) which becomes 1211 Starting with 1211,   you have one 1, one 2, then two 1's.   I.E.:   (11)(12)(21) which becomes 111221 Task Write a program to generate successive members of the look-and-say sequence. Related tasks   Fours is the number of letters in the ...   Number names   Self-describing numbers   Self-referential sequence   Spelling of ordinal numbers See also   Look-and-Say Numbers (feat John Conway), A Numberphile Video.   This task is related to, and an application of, the Run-length encoding task.   Sequence A005150 on The On-Line Encyclopedia of Integer Sequences.
#AutoHotkey
AutoHotkey
AutoExecute: Gui, -MinimizeBox Gui, Add, Edit, w500 r20 vInput, 1 Gui, Add, Button, x155 w100 Default, &Calculate Gui, Add, Button, xp+110 yp wp, E&xit Gui, Show,, Look-and-Say sequence Return     ButtonCalculate: Gui, Submit, NoHide GuiControl,, Input, % LookAndSay(Input) Return     GuiClose: ButtonExit: ExitApp Return     ;--------------------------------------------------------------------------- LookAndSay(Input) { ;--------------------------------------------------------------------------- ; credit for this function goes to AutoHotkey forum member Laslo ; http://www.autohotkey.com/forum/topic44657-161.html ;----------------------------------------------------------------------- Loop, Parse, Input ; look at every digit If (A_LoopField = d) ; I've got another one! (of the same value) c += 1 ; Let's count them ... Else { ; No, this one is different! r .= c d ; remember what we've got so far c := 1 ; It is the first one in a row d := A_LoopField ; Which one is it? } Return, r c d }
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.
#Lambdatalk
Lambdatalk
  {def longest_string {def longest_string.r {lambda {:max :s} {if {S.empty? {S.rest :s}} then else {if {= {W.length {S.first :s}} :max} then {br}{S.first :s} else} {longest_string.r :max {S.rest :s}}}}} {lambda {:s} {longest_string.r {max {S.map W.length :s}} :s #}}} -> longest_string   {def words a bb ccc ddd ee f ggg} // it's a sentence, not a list -> words   {longest_string {words}} -> ccc ddd ggg  
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.
#J
J
increasing=: (-: /:~)@#~"1 #:@i.@^~&2@# longestinc=: ] #~ [: (#~ ([: (= >./) +/"1)) #:@I.@increasing
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
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. loop-continue.   DATA DIVISION. WORKING-STORAGE SECTION. 01 i PIC 99.   PROCEDURE DIVISION. PERFORM VARYING i FROM 1 BY 1 UNTIL 10 < i DISPLAY i WITH NO ADVANCING   IF FUNCTION MOD(i, 5) = 0 DISPLAY SPACE EXIT PERFORM CYCLE END-IF   DISPLAY ", " WITH NO ADVANCING END-PERFORM   GOBACK .
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
#Dyalect
Dyalect
func lComSubStr(w1, w2) { var (len, end) = (0, 0) var mat = Array.Empty(w1.Length() + 1, () => Array.Empty(w2.Length() + 1, 0)) var (i, j) = (0, 0)   for sLett in w1 { for tLett in w2 { if tLett == sLett { let curLen = mat[i][j] + 1 mat[i + 1][j + 1] = curLen if curLen > len { len = curLen end = i } } j += 1 } j = 0 i += 1 } String(values: w1).Substring((end + 1) - len, len) }   func comSubStr(w1, w2) { return String(lComSubStr(w1.Iterate().ToArray(), w2.Iterate().ToArray())) }   comSubStr("thisisatest", "testing123testing") // "test"
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
#Elixir
Elixir
defmodule LCS do def longest_common_substring(a,b) do alist = to_charlist(a) |> Enum.with_index blist = to_charlist(b) |> Enum.with_index lengths = for i <- 0..length(alist)-1, j <- 0..length(blist), into: %{}, do: {{i,j},0} Enum.reduce(alist, {lengths,0,""}, fn {x,i},acc -> Enum.reduce(blist, acc, fn {y,j},{map,gleng,lcs} -> if x==y do len = if i==0 or j==0, do: 1, else: map[{i-1,j-1}]+1 map = %{map | {i,j} => len} if len > gleng, do: {map, len, String.slice(a, i - len + 1, len)}, else: {map, gleng, lcs} else {map, gleng, lcs} end end) end) |> elem(2) end end   IO.puts LCS.longest_common_substring("thisisatest", "testing123testing")