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/Magic_8-ball
Magic 8-ball
Task Create Magic 8-Ball. See details at:   Magic 8-Ball. 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
#JavaScript
JavaScript
  //console var answers = [ "It is certain", "It is decidedly so", "Without a doubt", "Yes, definitely", "You may rely on it", "As I see it, yes", "Most likely", "Outlook good", "Signs point to yes", "Yes", "Reply hazy, try again", "Ask again later", "Better not tell you now", "Cannot predict now", "Concentrate and ask again", "Don't bet on it", "My reply is no", "My sources say no", "Outlook not so good", "Very doubtful"])   console.log("ASK ANY QUESTION TO THE MAGIC 8-BALL AND YOU SHALL RECEIVE AN ANSWER!")   for(;;){ var answer = prompt("question:") console.log(answer) console.log(answers[Math.floor(Math.random()*answers.length)]); }  
http://rosettacode.org/wiki/Magic_8-ball
Magic 8-ball
Task Create Magic 8-Ball. See details at:   Magic 8-Ball. 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
#Julia
Julia
const responses = ["It is certain", "It is decidedly so", "Without a doubt", "Yes, definitely", "You may rely on it", "As I see it, yes", "Most likely", "Outlook good", "Signs point to yes", "Yes", "Reply hazy, try again", "Ask again later", "Better not tell you now", "Cannot predict now", "Concentrate and ask again", "Don't bet on it", "My reply is no", "My sources say no", "Outlook not so good", "Very doubtful"]   while true println("Ask a question (blank to exit):") if !occursin(r"[a-zA-Z]", readline(stdin)) break end println(rand(responses)) end  
http://rosettacode.org/wiki/Machine_code
Machine code
The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language. For example, the following assembly language program is given for x86 (32 bit) architectures: mov EAX, [ESP+4] add EAX, [ESP+8] ret This would translate into the following opcode bytes: 139 68 36 4 3 68 36 8 195 Or in hexadecimal: 8B 44 24 04 03 44 24 08 C3 Task If different than 32-bit x86, specify the target architecture of the machine code for your example. It may be helpful to also include an assembly version of the machine code for others to reference and understand what is being executed. Then, implement the following in your favorite programming language: Poke the necessary opcodes into a memory location. Provide a means to pass two values to the machine code. Execute the machine code with the following arguments: unsigned-byte argument of value 7; unsigned-byte argument of value 12; The result would be 19. Perform any clean up actions that are appropriate for your chosen language (free the pointer or memory allocations, etc.)
#XPL0
XPL0
func Sum(A, B); \Return sum of A+B char A, B; [asm { ldrb r0, A ldrb r1, B add r0, r1 strb r0, A } return A; ];   IntOut(0, Sum(7, 12))
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#SequenceL
SequenceL
import <Utilities/Complex.sl>; import <Utilities/Sequence.sl>; import <Utilities/Math.sl>;   COLOR_STRUCT ::= (R: int(0), G: int(0), B: int(0)); rgb(r(0), g(0), b(0)) := (R: r, G: g, B: b);   RESULT_STRUCT ::= (FinalValue: Complex(0), Iterations: int(0)); makeResult(val(0), iters(0)) := (FinalValue: val, Iterations: iters);   zSquaredOperation(startingNum(0), currentNum(0)) := complexAdd(startingNum, complexMultiply(currentNum, currentNum));   zSquared(minX(0), maxX(0), resolutionX(0), minY(0), maxY(0), resolutionY(0), maxMagnitude(0), maxIters(0))[Y,X] := let stepX := (maxX - minX) / resolutionX; stepY := (maxY - minY) / resolutionY;   currentX := X * stepX + minX; currentY := Y * stepY + minY;   in operateUntil(zSquaredOperation, makeComplex(currentX, currentY), makeComplex(currentX, currentY), maxMagnitude, 0, maxIters) foreach Y within 0 ... (resolutionY - 1), X within 0 ... (resolutionX - 1);   operateUntil(operation(0), startingNum(0), currentNum(0), maxMagnitude(0), currentIters(0), maxIters(0)) := let operated := operation(startingNum, currentNum); in makeResult(currentNum, maxIters) when currentIters >= maxIters else makeResult(currentNum, currentIters) when complexMagnitude(currentNum) >= maxMagnitude else operateUntil(operation, startingNum, operated, maxMagnitude, currentIters + 1, maxIters);   //region Smooth Coloring   COLOR_COUNT := size(colorSelections);   colorRange := range(0, 255, 1);   colors := let first[i] := rgb(0, 0, i) foreach i within colorRange; second[i] := rgb(i, i, 255) foreach i within colorRange; third[i] := rgb(255, 255, i) foreach i within reverse(colorRange); fourth[i] := rgb(255, i, 0) foreach i within reverse(colorRange); fifth[i] := rgb(i, 0, 0) foreach i within reverse(colorRange);   red[i] := rgb(i, 0, 0) foreach i within colorRange; redR[i] := rgb(i, 0, 0) foreach i within reverse(colorRange); green[i] := rgb(0, i, 0) foreach i within colorRange; greenR[i] :=rgb(0, i, 0) foreach i within reverse(colorRange); blue[i] := rgb(0, 0, i) foreach i within colorRange; blueR[i] := rgb(0, 0, i) foreach i within reverse(colorRange);   in //red ++ redR ++ green ++ greenR ++ blue ++ blueR; first ++ second ++ third ++ fourth ++ fifth; //first ++ fourth;   colorSelections := range(1, size(colors), 30);   getSmoothColorings(zSquaredResult(2), maxIters(0))[Y,X] := let current := zSquaredResult[Y,X];   zn := complexMagnitude(current.FinalValue); nu := ln(ln(zn) / ln(2)) / ln(2);   result := abs(current.Iterations + 1 - nu);   index := floor(result); rem := result - index;   color1 := colorSelections[(index mod COLOR_COUNT) + 1]; color2 := colorSelections[((index + 1) mod COLOR_COUNT) + 1]; in rgb(0, 0, 0) when current.Iterations = maxIters else colors[color1] when color2 < color1 else colors[floor(linearInterpolate(color1, color2, rem))];   linearInterpolate(v0(0), v1(0), t(0)) := (1 - t) * v0 + t * v1;   //endregion
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#XSLT_1.0
XSLT 1.0
<?xml-stylesheet href="matmul.templ.xsl" type="text/xsl"?> <mult> <A> <r><c>1</c><c>2</c></r> <r><c>3</c><c>4</c></r> <r><c>5</c><c>6</c></r> <r><c>7</c><c>8</c></r> </A> <B> <r><c>1</c><c>2</c><c>3</c></r> <r><c>4</c><c>5</c><c>6</c></r> </B> </mult>
http://rosettacode.org/wiki/Mad_Libs
Mad Libs
This page uses content from Wikipedia. The original article was at Mad Libs. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Mad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results. Task; Write a program to create a Mad Libs like story. The program should read an arbitrary multiline story from input. The story will be terminated with a blank line. Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements. Stop when there are none left and print the final story. The input should be an arbitrary story in the form: <name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home. Given this example, it should then ask for a name, a he or she and a noun (<name> gets replaced both times with the same value). Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Aime
Aime
file f; data b; list l; record r;   f.stdin;   o_text("Enter the blank line terminated story:\n");   while (0 < f.b_line(b)) { l.append(b); }   for (, b in l) { integer p, q; text s, t;   while ((p = b.place('<')) ^ -1) { q = b.probe(p, '>'); if (q ^ -1) { s = bq_string(b, p + 1, q - 1); b.erase(p, q); if (!r.key(s)) { o_("Replacement for `", s, "':\n"); f.line(t); r.put(s, t); } b.paste(p, r[s]); } } }   l.ucall(o_, 0, "\n");
http://rosettacode.org/wiki/Ludic_numbers
Ludic numbers
Ludic numbers   are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers. The first ludic number is   1. To generate succeeding ludic numbers create an array of increasing integers starting from   2. 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... (Loop) Take the first member of the resultant array as the next ludic number   2. Remove every   2nd   indexed item from the array (including the first). 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... (Unrolling a few loops...) Take the first member of the resultant array as the next ludic number   3. Remove every   3rd   indexed item from the array (including the first). 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 ... Take the first member of the resultant array as the next ludic number   5. Remove every   5th   indexed item from the array (including the first). 5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 ... Take the first member of the resultant array as the next ludic number   7. Remove every   7th   indexed item from the array (including the first). 7 11 13 17 23 25 29 31 37 41 43 47 53 55 59 61 67 71 73 77 83 85 89 91 97 ... ... Take the first member of the current array as the next ludic number   L. Remove every   Lth   indexed item from the array (including the first). ... Task Generate and show here the first 25 ludic numbers. How many ludic numbers are there less than or equal to 1000? Show the 2000..2005th ludic numbers. Stretch goal Show all triplets of ludic numbers < 250. A triplet is any three numbers     x , {\displaystyle x,}   x + 2 , {\displaystyle x+2,}   x + 6 {\displaystyle x+6}     where all three numbers are also ludic numbers.
#AppleScript
AppleScript
-- Generate a list of the ludic numbers up to and including n. on ludicsTo(n) if (n < 1) then return {} -- Start with an array of numbers from 2 to n and a ludic collection already containing 1. script o property array : {} property ludics : {1} end script repeat with i from 2 to n set end of o's array to i end repeat -- Collect ludics and sieve the array until a ludic matches or exceeds the remaining -- array length, at which point the array contains just the remaining ludics. set thisLudic to 2 set arrayLength to n - 1 repeat while (thisLudic < arrayLength) set end of o's ludics to thisLudic repeat with i from 1 to arrayLength by thisLudic set item i of o's array to missing value end repeat set o's array to o's array's numbers set thisLudic to beginning of o's array set arrayLength to (count o's array) end repeat   return (o's ludics) & (o's array) end ludicsTo   on doTask() script o property ludics : ludicsTo(22000) end script   set output to {} set astid to AppleScript's text item delimiters set AppleScript's text item delimiters to ", " set end of output to "First 25 ludic numbers:" set end of output to (items 1 thru 25 of o's ludics) as text repeat with i from 1 to (count o's ludics) if (item i of o's ludics > 1000) then exit repeat end repeat set end of output to "There are " & (i - 1) & " ludic numbers ≤ 1000." set end of output to "2000th-2005th ludic numbers:" set end of output to (items 2000 thru 2005 of o's ludics) as text set end of output to "Triplets < 250:" set triplets to {} repeat with x in o's ludics set x to x's contents if (x > 243) then exit repeat if ((x + 2) is in o's ludics) and ((x + 6) is in o's ludics) then set end of triplets to "{" & {x, x + 2, x + 6} & "}" end if end repeat set end of output to triplets as text set AppleScript's text item delimiters to linefeed set output to output as text set AppleScript's text item delimiters to astid   return output end doTask   return doTask()
http://rosettacode.org/wiki/Magic_8-ball
Magic 8-ball
Task Create Magic 8-Ball. See details at:   Magic 8-Ball. 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
#Kotlin
Kotlin
// Version 1.2.40   import java.util.Random   fun main(args: Array<String>) { val answers = listOf( "It is certain", "It is decidedly so", "Without a doubt", "Yes, definitely", "You may rely on it", "As I see it, yes", "Most likely", "Outlook good", "Signs point to yes", "Yes", "Reply hazy, try again", "Ask again later", "Better not tell you now", "Cannot predict now", "Concentrate and ask again", "Don't bet on it", "My reply is no", "My sources say no", "Outlook not so good", "Very doubtful" ) val rand = Random() println("Please enter your question or a blank line to quit.") while (true) { print("\n? : ") val question = readLine()!! if (question.trim() == "") return val answer = answers[rand.nextInt(20)] println("\n$answer") } }
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#Sidef
Sidef
func mandelbrot(z) { var c = z { z = (z*z + c) z.abs > 2 && return true } * 20 return false }   for y range(1, -1, -0.05) { for x in range(-2, 0.5, 0.0315) { print(mandelbrot(x + y.i) ? ' ' : '#') } print "\n" }
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#Yabasic
Yabasic
dim a(4, 2) a(0, 0) = 1 : a(0, 1) = 2 a(1, 0) = 3 : a(1, 1) = 4 a(2, 0) = 5 : a(2, 1) = 6 a(3, 0) = 7 : a(3, 1) = 8 dim b(2, 3) b(0, 0) = 1 : b(0, 1) = 2 : b(0, 2) = 3 b(1, 0) = 4 : b(1, 1) = 5 : b(1, 2) = 6 dim prod(arraysize(a(),1), arraysize(b(),2))   if (arraysize(a(),2) = arraysize(b(),1)) then for i = 0 to arraysize(a(),1) for j = 0 to arraysize(b(),2) for k = 0 to arraysize(a(),2) prod(i, j) = prod(i, j) + (a(i, k) * b(k, j)) next k next j next i   for i = 0 to arraysize(prod(),1)-1 for j = 0 to arraysize(prod(),2)-1 print prod(i, j), next j print next i else print "invalid dimensions" end if end
http://rosettacode.org/wiki/Mad_Libs
Mad Libs
This page uses content from Wikipedia. The original article was at Mad Libs. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Mad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results. Task; Write a program to create a Mad Libs like story. The program should read an arbitrary multiline story from input. The story will be terminated with a blank line. Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements. Stop when there are none left and print the final story. The input should be an arbitrary story in the form: <name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home. Given this example, it should then ask for a name, a he or she and a noun (<name> gets replaced both times with the same value). Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#ALGOL_68
ALGOL 68
# Mad Libs style story generation #   # gets the story template from the file f. The template terminates with # # a blank line # # The user is then promoted for the replacements for the <word> markers # # and the story is printed with the substitutions made # PROC story = ( REF FILE f )VOID: BEGIN   # a linked list of strings, used to hold the story template # MODE STRINGLIST = STRUCT( STRING text, REF STRINGLIST next );   # a linked list of pairs of strings, used to hold the replacements # MODE REPLACEMENTLIST = STRUCT( STRING word , STRING replacement , REF REPLACEMENTLIST next );   # NIL reference for marking the end of a STRINGLIST # REF STRINGLIST nil stringlist = NIL;   # NIL reference for marking the end of a REPLACEMENTLIST # REF REPLACEMENTLIST nil replacementlist = NIL;     # returns "text" with trailing spaces removed # OP RTRIM = ( STRING text )STRING: BEGIN INT trim pos := UPB text; FOR text pos FROM UPB text BY -1 TO LWB text WHILE text[ text pos ] = " " DO trim pos := text pos - 1 OD;   text[ LWB text : trim pos ] END; # RTRIM #   # looks for word in the dictionary. If it is found, replacement is # # set to its replacement and TRUE is returned. If word not present, # # FALSE is returned - uses recursion # PROC find replacement = ( STRING word , REF STRING replacement , REF REPLACEMENTLIST dictionary )BOOL: IF dictionary IS nil replacementlist THEN FALSE ELIF word OF dictionary = word THEN replacement := replacement OF dictionary; TRUE ELSE find replacement( word, replacement, next OF dictionary ) FI; # find replacement #     # read the story template #   # the result has a dummy element so "next OF next" is always valid # REF STRINGLIST story := HEAP STRINGLIST := ( "dummy", nil stringlist ); REF REF STRINGLIST next := story;   # read the story template, terminates with a blank line #   WHILE STRING text; get( f, ( text, newline ) ); text := RTRIM text; text /= "" DO # add the line to the end of the list # next := ( next OF next ) := HEAP STRINGLIST := ( text, nil stringlist ) OD;   # find the <word> markers in the story and replace them with the # # user's chosen text - we ignore the dummy element at the start #   REF REPLACEMENTLIST dictionary := nil replacementlist; REF STRINGLIST line := story;   WHILE line := next OF line; line ISNT nil stringlist DO # have a line of text - replace all the <word> markers in it # STRING word, replacement; INT start pos, end pos; WHILE char in string( "<", start pos, text OF line ) AND char in string( ">", end pos, text OF line ) DO # have a marker, get it from the line # word := ( text OF line )[ start pos : end pos ]; # get its replacement # IF NOT find replacement( word, replacement, dictionary ) THEN # we don't already have a replacement for word # # get one from the user and add it to the dictionary # print( ( "What should replace ", word, "? " ) ); read( ( replacement, newline ) ); dictionary := HEAP REPLACEMENTLIST := ( word, replacement, dictionary ) FI; # replace <word> with the replacement # text OF line := ( text OF line )[ : start pos - 1 ] + replacement + ( text OF line )[ end pos + 1 : ] OD OD;   # print the story, ignoring the dummy element at the start #   line := story;   WHILE line := next OF line; line ISNT nil stringlist DO print( ( text OF line, newline ) ) OD   END; # story #   main:(   # we read the template from stand in (the keyboard unless it's been # # redirected) we could prompt the user for a template file name, # # open it and read that instead... # print( ( "Please Enter the story template terminated by a blank line", newline ) ); story( stand in )   )
http://rosettacode.org/wiki/Ludic_numbers
Ludic numbers
Ludic numbers   are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers. The first ludic number is   1. To generate succeeding ludic numbers create an array of increasing integers starting from   2. 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... (Loop) Take the first member of the resultant array as the next ludic number   2. Remove every   2nd   indexed item from the array (including the first). 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... (Unrolling a few loops...) Take the first member of the resultant array as the next ludic number   3. Remove every   3rd   indexed item from the array (including the first). 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 ... Take the first member of the resultant array as the next ludic number   5. Remove every   5th   indexed item from the array (including the first). 5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 ... Take the first member of the resultant array as the next ludic number   7. Remove every   7th   indexed item from the array (including the first). 7 11 13 17 23 25 29 31 37 41 43 47 53 55 59 61 67 71 73 77 83 85 89 91 97 ... ... Take the first member of the current array as the next ludic number   L. Remove every   Lth   indexed item from the array (including the first). ... Task Generate and show here the first 25 ludic numbers. How many ludic numbers are there less than or equal to 1000? Show the 2000..2005th ludic numbers. Stretch goal Show all triplets of ludic numbers < 250. A triplet is any three numbers     x , {\displaystyle x,}   x + 2 , {\displaystyle x+2,}   x + 6 {\displaystyle x+6}     where all three numbers are also ludic numbers.
#Arturo
Arturo
ludicGen: function [nmax][ result: [1] lst: new 2..nmax+1 i: 0 worked: false while [and? [not? empty? lst] [i < size lst]][ item: lst\[i] result: result ++ item del: 0 worked: false while [del < size lst][ worked: true remove 'lst .index del del: dec del + item ] if not? worked -> i: i + 1 ] return result ]   ludics: ludicGen 25000   print "The first 25 ludic numbers:" print first.n: 25 ludics   leThan1000: select ludics => [& =< 1000] print ["\nThere are" size leThan1000 "ludic numbers less than/or equal to 1000\n"]   print ["The ludic numbers from 2000th to 2005th are:" slice ludics 1999 2004 "\n"]   print "The triplets of ludic numbers less than 250 are:" print map select ludics 'x [ all? @[ x < 250 contains? ludics x+2 contains? ludics x+6 ] ] 't -> @[t, t+2, t+6]
http://rosettacode.org/wiki/Magic_8-ball
Magic 8-ball
Task Create Magic 8-Ball. See details at:   Magic 8-Ball. 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
#Liberty_BASIC
Liberty BASIC
data "It is certain","It is decidedly so","Without a doubt","Yes - definitely",_ "You may rely on it","As I see it, yes","Most likely","Outlook good","Yes",_ "Signs point to yes","Reply hazy, try again","Ask again later","Better not tell you now",_ "Cannot predict now","Concentrate and ask again","Don't count on it","My reply is no",_ "My sources say no","Outlook not so good","Very doubtful"   dim c$(20) for a = 1 to 20 read b$ c$(a) = b$ next a   [loop] input "Type your question: ";a$ if a$="" then end d=int(rnd(1)*20)+1 print "Answer: ";c$(d) goto [loop]  
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#Simula
Simula
BEGIN REAL XCENTRE, YCENTRE, WIDTH, RMAX, XOFFSET, YOFFSET, PIXELSIZE; INTEGER N, IMAX, JMAX, COLOURMAX; TEXT FILENAME;   CLASS COMPLEX(RE,IM); REAL RE,IM;;   REF(COMPLEX) PROCEDURE ADD(A,B); REF(COMPLEX) A,B; ADD :- NEW COMPLEX(A.RE + B.RE, A.IM + B.IM);   REF(COMPLEX) PROCEDURE SUB(A,B); REF(COMPLEX) A,B; SUB :- NEW COMPLEX(A.RE - B.RE, A.IM - B.IM);   REF(COMPLEX) PROCEDURE MUL(A,B); REF(COMPLEX) A,B; MUL :- NEW COMPLEX(A.RE * B.RE - A.IM * B.IM, A.RE * B.IM + A.IM * B.RE);   REF(COMPLEX) PROCEDURE DIV(A,B); REF(COMPLEX) A,B; BEGIN REAL TMP; TMP := B.RE * B.RE + B.IM * B.IM; DIV :- NEW COMPLEX((A.RE * B.RE + A.IM * B.IM) / TMP, (A.IM * B.RE - A.RE * B.IM) / TMP); END DIV;   REF(COMPLEX) PROCEDURE RECTANGULAR(RE,IM); REAL RE,IM; RECTANGULAR :- NEW COMPLEX(RE,IM);   REAL PROCEDURE MAGNITUDE(CX); REF(COMPLEX) CX; MAGNITUDE := SQRT(CX.RE**2 + CX.IM**2);   BOOLEAN PROCEDURE INSIDEP(Z); REF(COMPLEX) Z; BEGIN BOOLEAN PROCEDURE INSIDE(Z0,Z,N); REAL N; REF(COMPLEX) Z,Z0; INSIDE := MAGNITUDE(Z) < RMAX AND THEN N = 0 OR ELSE INSIDE(Z0, ADD(Z0,MUL(Z,Z)), N-1); INSIDEP := INSIDE(Z, NEW COMPLEX(0,0), N); END INSIDEP;   INTEGER PROCEDURE BOOL2INT(B); BOOLEAN B; BOOL2INT := IF B THEN COLOURMAX ELSE 0;   INTEGER PROCEDURE PIXEL(I,J); INTEGER I,J; PIXEL := BOOL2INT(INSIDEP(RECTANGULAR(XOFFSET + PIXELSIZE * I, YOFFSET - PIXELSIZE * J))); PROCEDURE PLOT; BEGIN REF (OUTFILE) OUTF; INTEGER J,I; OUTF :- NEW OUTFILE(FILENAME); OUTF.OPEN(BLANKS(132)); OUTF.OUTTEXT("P2"); OUTF.OUTIMAGE; OUTF.OUTINT(IMAX,0); OUTF.OUTIMAGE; OUTF.OUTINT(JMAX,0); OUTF.OUTIMAGE; OUTF.OUTINT(COLOURMAX,0); OUTF.OUTIMAGE; FOR J := 1 STEP 1 UNTIL JMAX DO BEGIN FOR I := 1 STEP 1 UNTIL IMAX DO BEGIN OUTF.OUTINT(PIXEL(I,J),0); OUTF.OUTIMAGE; END; END; OUTF.CLOSE; END PLOT;   XCENTRE := -0.5; YCENTRE := 0.0; WIDTH := 4.0; IMAX := 800; JMAX := 600; N := 100; RMAX := 2.0; FILENAME :- "out.pgm"; COLOURMAX := 255; PIXELSIZE := WIDTH / IMAX; XOFFSET := XCENTRE - (0.5 * PIXELSIZE * (IMAX + 1)); YOFFSET := YCENTRE + (0.5 * PIXELSIZE * (JMAX + 1));   OUTTEXT("OUTPUT WILL BE WRITTEN TO "); OUTTEXT(FILENAME); OUTIMAGE;   PLOT; END;
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#zkl
zkl
var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library) A:=GSL.Matrix(4,2).set(1,2, 3,4, 5,6, 7,8); B:=GSL.Matrix(2,3).set(1,2,3, 4,5,6); (A*B).format().println(); // creates a new matrix
http://rosettacode.org/wiki/Mad_Libs
Mad Libs
This page uses content from Wikipedia. The original article was at Mad Libs. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Mad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results. Task; Write a program to create a Mad Libs like story. The program should read an arbitrary multiline story from input. The story will be terminated with a blank line. Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements. Stop when there are none left and print the final story. The input should be an arbitrary story in the form: <name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home. Given this example, it should then ask for a name, a he or she and a noun (<name> gets replaced both times with the same value). 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
#AppleScript
AppleScript
    set theNoun to the text returned of (display dialog "What is your noun?" default answer "")   set thePerson to the text returned of (display dialog "What is the person's name?" default answer "")   set theGender to the text returned of (display dialog "He or she? Please capitalize." default answer "")   display dialog thePerson & " went for a walk in the park. " & theGender & " found a " & theNoun & ". " & thePerson & " decided to take it home."    
http://rosettacode.org/wiki/Ludic_numbers
Ludic numbers
Ludic numbers   are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers. The first ludic number is   1. To generate succeeding ludic numbers create an array of increasing integers starting from   2. 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... (Loop) Take the first member of the resultant array as the next ludic number   2. Remove every   2nd   indexed item from the array (including the first). 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... (Unrolling a few loops...) Take the first member of the resultant array as the next ludic number   3. Remove every   3rd   indexed item from the array (including the first). 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 ... Take the first member of the resultant array as the next ludic number   5. Remove every   5th   indexed item from the array (including the first). 5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 ... Take the first member of the resultant array as the next ludic number   7. Remove every   7th   indexed item from the array (including the first). 7 11 13 17 23 25 29 31 37 41 43 47 53 55 59 61 67 71 73 77 83 85 89 91 97 ... ... Take the first member of the current array as the next ludic number   L. Remove every   Lth   indexed item from the array (including the first). ... Task Generate and show here the first 25 ludic numbers. How many ludic numbers are there less than or equal to 1000? Show the 2000..2005th ludic numbers. Stretch goal Show all triplets of ludic numbers < 250. A triplet is any three numbers     x , {\displaystyle x,}   x + 2 , {\displaystyle x+2,}   x + 6 {\displaystyle x+6}     where all three numbers are also ludic numbers.
#AutoHotkey
AutoHotkey
#NoEnv SetBatchLines, -1 Ludic := LudicSieve(22000)   Loop, 25 ; the first 25 ludic numbers Task1 .= Ludic[A_Index] " "   for i, Val in Ludic ; the number of ludic numbers less than or equal to 1000 if (Val <= 1000) Task2++ else break   Loop, 6 ; the 2000..2005'th ludic numbers Task3 .= Ludic[1999 + A_Index] " "   for i, Val in Ludic { ; all triplets of ludic numbers < 250 if (Val + 6 > 249) break if (Ludic[i + 1] = Val + 2 && Ludic[i + 2] = Val + 6 || i = 1) Task4 .= "(" Val " " Val + 2 " " Val + 6 ") " }   MsgBox, % "First 25:`t`t" Task1 . "`nLudics below 1000:`t" Task2 . "`nLudic 2000 to 2005:`t" Task3 . "`nTriples below 250:`t" Task4 return   LudicSieve(Limit) { Arr := [], Ludic := [] Loop, % Limit Arr.Insert(A_Index) Ludic.Insert(Arr.Remove(1)) while Arr.MaxIndex() != 1 { Ludic.Insert(n := Arr.Remove(1)) , Removed := 0 Loop, % Arr.MaxIndex() // n { Arr.Remove(A_Index * n - Removed) , Removed++ } } Ludic.Insert(Arr[1]) return Ludic }
http://rosettacode.org/wiki/Lychrel_numbers
Lychrel numbers
  Take an integer n, greater than zero.   Form the next n of its series by reversing the digits of the current n and adding the result to the current n.   Stop when n becomes palindromic - i.e. the digits of n in reverse order == n. The above recurrence relation when applied to most starting numbers n = 1, 2, ... terminates in a palindrome quite quickly. Example If n0 = 12 we get 12 12 + 21 = 33, a palindrome! And if n0 = 55 we get 55 55 + 55 = 110 110 + 011 = 121, a palindrome! Notice that the check for a palindrome happens   after   an addition. Some starting numbers seem to go on forever; the recurrence relation for 196 has been calculated for millions of repetitions forming numbers with millions of digits, without forming a palindrome. These numbers that do not end in a palindrome are called Lychrel numbers. For the purposes of this task a Lychrel number is any starting number that does not form a palindrome within 500 (or more) iterations. Seed and related Lychrel numbers Any integer produced in the sequence of a Lychrel number is also a Lychrel number. In general, any sequence from one Lychrel number might converge to join the sequence from a prior Lychrel number candidate; for example the sequences for the numbers 196 and then 689 begin: 196 196 + 691 = 887 887 + 788 = 1675 1675 + 5761 = 7436 7436 + 6347 = 13783 13783 + 38731 = 52514 52514 + 41525 = 94039 ... 689 689 + 986 = 1675 1675 + 5761 = 7436 ... So we see that the sequence starting with 689 converges to, and continues with the same numbers as that for 196. Because of this we can further split the Lychrel numbers into true Seed Lychrel number candidates, and Related numbers that produce no palindromes but have integers in their sequence seen as part of the sequence generated from a lower Lychrel number. Task   Find the number of seed Lychrel number candidates and related numbers for n in the range 1..10000 inclusive. (With that iteration limit of 500).   Print the number of seed Lychrels found; the actual seed Lychrels; and just the number of relateds found.   Print any seed Lychrel or related number that is itself a palindrome. Show all output here. References   What's special about 196? Numberphile video.   A023108 Positive integers which apparently never result in a palindrome under repeated applications of the function f(x) = x + (x with digits reversed).   Status of the 196 conjecture? Mathoverflow.
#11l
11l
F rev(n) R BigInt(reversed(String(n)))   [BigInt = (Bool, BigInt)] cache   F lychrel(BigInt =n) I n C :cache R :cache[n]   V r = rev(n) V res = (1B, n) [BigInt] seen L(i) 1000 n += r r = rev(n) I n == r res = (0B, BigInt(0)) L.break I n C :cache res = :cache[n] L.break seen [+]= n   L(x) seen  :cache[x] = res R res   [Int] seeds, related, palin   L(i) 1..9999 V tf_s = lychrel(i) I !tf_s[0] L.continue I BigInt(i) == tf_s[1] seeds [+]= i E related [+]= i I BigInt(i) == rev(i) palin [+]= i   print(seeds.len‘ Lychrel seeds: ’seeds) print(related.len‘ Lychrel related’) print(palin.len‘ Lychrel palindromes: ’palin)
http://rosettacode.org/wiki/Magic_8-ball
Magic 8-ball
Task Create Magic 8-Ball. See details at:   Magic 8-Ball. 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
#Locomotive_Basic
Locomotive Basic
10 mode 2:defint a-z:randomize time 20 input "Your question (hit Return to quit)";i$ 30 if i$="" then print "Goodbye!":end 40 q=1+19*rnd 50 on q gosub 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250, 260, 270, 280, 290 60 goto 20 100 print "It is certain":return 110 print "It is decidedly so":return 120 print "Without a doubt":return 130 print "Yes, definitely":return 140 print "You may rely on it":return 150 print "As I see it, yes":return 160 print "Most likely":return 170 print "Outlook good":return 180 print "Signs point to yes":return 190 print "Yes":return 200 print "Reply hazy, try again":return 210 print "Ask again later":return 220 print "Better not tell you now":return 230 print "Cannot predict now":return 240 print "Concentrate and ask again":return 250 print "Don't bet on it":return 260 print "My reply is no":return 270 print "My sources say no":return 280 print "Outlook not so good":return 290 print "Very doubtful":return
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#Spin
Spin
con _clkmode = xtal1+pll16x _clkfreq = 80_000_000   xmin=-8601 ' int(-2.1*4096) xmax=2867 ' int( 0.7*4096)   ymin=-4915 ' int(-1.2*4096) ymax=4915 ' int( 1.2*4096)   maxiter=25   obj ser : "FullDuplexSerial"   pub main | c,cx,cy,dx,dy,x,y,x2,y2,iter   ser.start(31, 30, 0, 115200)   dx:=(xmax-xmin)/79 dy:=(ymax-ymin)/24   cy:=ymin repeat while cy=<ymax cx:=xmin repeat while cx=<xmax x:=0 y:=0 x2:=0 y2:=0 iter:=0 repeat while iter=<maxiter and x2+y2=<16384 y:=((x*y)~>11)+cy x:=x2-y2+cx iter+=1 x2:=(x*x)~>12 y2:=(y*y)~>12 cx+=dx ser.tx(iter+32) cy+=dy ser.str(string(13,10))   waitcnt(_clkfreq+cnt) ser.stop
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#zonnon
zonnon
  module MatrixOps; type Matrix = array {math} *,* of integer;     procedure WriteMatrix(x: array {math} *,* of integer); var i,j: integer; begin for i := 0 to len(x,0) - 1 do for j := 0 to len(x,1) - 1 do write(x[i,j]); end; writeln; end end WriteMatrix;   procedure Multiplication; var a,b: Matrix; begin a := [[1,2],[3,4],[5,6],[7,8]]; b := [[1,2,3],[4,5,6]]; WriteMatrix(a * b); end Multiplication;   begin Multiplication; end MatrixOps.  
http://rosettacode.org/wiki/Mad_Libs
Mad Libs
This page uses content from Wikipedia. The original article was at Mad Libs. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Mad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results. Task; Write a program to create a Mad Libs like story. The program should read an arbitrary multiline story from input. The story will be terminated with a blank line. Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements. Stop when there are none left and print the final story. The input should be an arbitrary story in the form: <name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home. Given this example, it should then ask for a name, a he or she and a noun (<name> gets replaced both times with the same value). 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
#Applesoft_BASIC
Applesoft BASIC
100 DIM L$(100),W$(50),T$(50) 110 LET M$ = CHR$ (13) 120 FOR L = 1 TO 1E9 130 READ L$(L) 140 IF LEN (L$(L)) THEN NEXT L 150 FOR I = 1 TO L 160 LET M = 0 170 LET N$(0) = "" 180 FOR J = 1 TO LEN (L$(I)) 190 LET C$ = MID$ (L$(I),J,1) 200 IF C$ = "<" AND NOT M THEN M = 1:C$ = "":N$(M) = "" 210 IF C$ = ">" AND M THEN GOSUB 300:M = 0:C$ = W$(Z) 220 LET N$(M) = N$(M) + C$ 230 NEXT J 240 LET L$(I) = N$(0) 250 NEXT I 260 FOR I = 1 TO L 270 PRINT M$L$(I); 280 NEXT 290 END 300 FOR Z = 0 TO T 310 IF T$(Z) = N$(M) THEN RETURN 320 NEXT Z 330 LET T = Z 340 LET T$(Z) = N$(M) 350 PRINT M$"ENTER A "T$(Z); 360 INPUT "? ";W$(Z) 370 RETURN 380 DATA "<NAME> WENT FOR A WALK IN THE PARK. <HE OR SHE>" 390 DATA "FOUND A <NOUN>. <NAME> DECIDED TO TAKE IT HOME." 990 DATA
http://rosettacode.org/wiki/Ludic_numbers
Ludic numbers
Ludic numbers   are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers. The first ludic number is   1. To generate succeeding ludic numbers create an array of increasing integers starting from   2. 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... (Loop) Take the first member of the resultant array as the next ludic number   2. Remove every   2nd   indexed item from the array (including the first). 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... (Unrolling a few loops...) Take the first member of the resultant array as the next ludic number   3. Remove every   3rd   indexed item from the array (including the first). 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 ... Take the first member of the resultant array as the next ludic number   5. Remove every   5th   indexed item from the array (including the first). 5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 ... Take the first member of the resultant array as the next ludic number   7. Remove every   7th   indexed item from the array (including the first). 7 11 13 17 23 25 29 31 37 41 43 47 53 55 59 61 67 71 73 77 83 85 89 91 97 ... ... Take the first member of the current array as the next ludic number   L. Remove every   Lth   indexed item from the array (including the first). ... Task Generate and show here the first 25 ludic numbers. How many ludic numbers are there less than or equal to 1000? Show the 2000..2005th ludic numbers. Stretch goal Show all triplets of ludic numbers < 250. A triplet is any three numbers     x , {\displaystyle x,}   x + 2 , {\displaystyle x+2,}   x + 6 {\displaystyle x+6}     where all three numbers are also ludic numbers.
#C
C
#include <stdio.h> #include <stdlib.h>   typedef unsigned uint; typedef struct { uint i, v; } filt_t;   // ludics with at least so many elements and reach at least such value uint* ludic(uint min_len, uint min_val, uint *len) { uint cap, i, v, active = 1, nf = 0; filt_t *f = calloc(cap = 2, sizeof(*f)); f[1].i = 4;   for (v = 1; ; ++v) { for (i = 1; i < active && --f[i].i; i++);   if (i < active) f[i].i = f[i].v; else if (nf == f[i].i) f[i].i = f[i].v, ++active; // enable one more filter else { if (nf >= cap) f = realloc(f, sizeof(*f) * (cap*=2)); f[nf] = (filt_t){ v + nf, v }; if (++nf >= min_len && v >= min_val) break; } }   // pack the sequence into a uint[] // filt_t struct was used earlier for cache locality in loops uint *x = (void*) f; for (i = 0; i < nf; i++) x[i] = f[i].v; x = realloc(x, sizeof(*x) * nf);   *len = nf; return x; }   int find(uint *a, uint v) { uint i; for (i = 0; a[i] <= v; i++) if (v == a[i]) return 1; return 0; }   int main(void) { uint len, i, *x = ludic(2005, 1000, &len);   printf("First 25:"); for (i = 0; i < 25; i++) printf(" %u", x[i]); putchar('\n');   for (i = 0; x[i] <= 1000; i++); printf("Ludics below 1000: %u\n", i);   printf("Ludic 2000 to 2005:"); for (i = 2000; i <= 2005; i++) printf(" %u", x[i - 1]); putchar('\n');   printf("Triples below 250:"); for (i = 0; x[i] + 6 <= 250; i++) if (find(x, x[i] + 2) && find(x, x[i] + 6)) printf(" (%u %u %u)", x[i], x[i] + 2, x[i] + 6);   putchar('\n');   free(x); return 0; }
http://rosettacode.org/wiki/Lychrel_numbers
Lychrel numbers
  Take an integer n, greater than zero.   Form the next n of its series by reversing the digits of the current n and adding the result to the current n.   Stop when n becomes palindromic - i.e. the digits of n in reverse order == n. The above recurrence relation when applied to most starting numbers n = 1, 2, ... terminates in a palindrome quite quickly. Example If n0 = 12 we get 12 12 + 21 = 33, a palindrome! And if n0 = 55 we get 55 55 + 55 = 110 110 + 011 = 121, a palindrome! Notice that the check for a palindrome happens   after   an addition. Some starting numbers seem to go on forever; the recurrence relation for 196 has been calculated for millions of repetitions forming numbers with millions of digits, without forming a palindrome. These numbers that do not end in a palindrome are called Lychrel numbers. For the purposes of this task a Lychrel number is any starting number that does not form a palindrome within 500 (or more) iterations. Seed and related Lychrel numbers Any integer produced in the sequence of a Lychrel number is also a Lychrel number. In general, any sequence from one Lychrel number might converge to join the sequence from a prior Lychrel number candidate; for example the sequences for the numbers 196 and then 689 begin: 196 196 + 691 = 887 887 + 788 = 1675 1675 + 5761 = 7436 7436 + 6347 = 13783 13783 + 38731 = 52514 52514 + 41525 = 94039 ... 689 689 + 986 = 1675 1675 + 5761 = 7436 ... So we see that the sequence starting with 689 converges to, and continues with the same numbers as that for 196. Because of this we can further split the Lychrel numbers into true Seed Lychrel number candidates, and Related numbers that produce no palindromes but have integers in their sequence seen as part of the sequence generated from a lower Lychrel number. Task   Find the number of seed Lychrel number candidates and related numbers for n in the range 1..10000 inclusive. (With that iteration limit of 500).   Print the number of seed Lychrels found; the actual seed Lychrels; and just the number of relateds found.   Print any seed Lychrel or related number that is itself a palindrome. Show all output here. References   What's special about 196? Numberphile video.   A023108 Positive integers which apparently never result in a palindrome under repeated applications of the function f(x) = x + (x with digits reversed).   Status of the 196 conjecture? Mathoverflow.
#ALGOL_68
ALGOL 68
PR read "aArray.a68" PR   # number of additions to attempt before deciding the number is Lychrel # INT max additions = 500;   # buffer to hold number during testing # # addition of two equal sized numbers can produce a number of at most # # one additional digit, so for 500 additions of numbers up to 10 000 # # we need a bit over 500 digits... # [ 512 ]CHAR number; FOR c TO UPB number DO number[ c ] := "0" OD; # count of used digits in number # INT digits := 0;   # sets the number buffer to the specified positive value # PROC set number = ( INT value )VOID: BEGIN digits := 0; INT v := ABS value; WHILE digits +:= 1; number[ digits ] := REPR ( ABS "0" + v MOD 10 ); v OVERAB 10; v > 0 DO SKIP OD END # set number # ;   # adds the reverse of number to itself # PROC add reverse = VOID: BEGIN [ digits + 1 ]CHAR result; INT carry := 0; INT r pos := digits; FOR d pos TO digits DO INT sum = ( ( ABS number[ d pos ] + ABS number[ r pos ] + carry ) - ( 2 * ABS "0" ) ); IF sum < 10 THEN # no carry required # result[ d pos ] := REPR( sum + ABS "0" ); carry := 0 ELSE # need to carry # result[ d pos ] := REPR ( ( sum - 10 ) + ABS "0" ); carry := 1 FI; r pos -:= 1 OD; IF carry /= 0 THEN # need another digit # digits +:= 1; result[ digits ] := REPR ( ABS "0" + carry ) FI; number[ : digits ] := result[ : digits ] END # add reverse # ;   # returns TRUE if number is a palindrome, FALSE otherwise # PROC is palindromic = BOOL: BEGIN BOOL result := TRUE; INT d pos := 1; INT r pos := digits; WHILE IF d pos >= r pos THEN FALSE ELSE result := ( number[ d pos ] = number[ r pos ] ) FI DO d pos +:= 1; r pos -:= 1 OD; result END # is palindromic # ;   # associative array of numbers that are not palindromic after 500 # # iterations # REF AARRAY related := INIT HEAP AARRAY;   # adds the elements of the specified path to the related numbers # PROC add related numbers = ( REF AARRAY path )VOID: BEGIN REF AAELEMENT r := FIRST path; WHILE r ISNT nil element DO related // key OF r := "Y"; r := NEXT path OD END # add related numbers # ;   # Lychrel number results # # lychrel[n] is: # # not lychrel if n becomes palidromic before 500 additions # # lychrel seed if n is a seed lychrel number # # lychrel related if n is a related lychrel number # # untested if n hasn't been tested yet # INT not lychrel = 0; INT lychrel seed = 1; INT lychrel related = 2; INT untested = 3; INT max number = 10 000; [ max number ]INT lychrel; FOR n TO UPB lychrel DO lychrel[ n ] := untested OD; [ UPB lychrel ]BOOL palindromic; FOR n TO UPB palindromic DO palindromic[ n ] := FALSE OD; INT seed count := 0; INT related count := 0; INT palindrome count := 0;   # set the lychrel array to the values listed above # FOR n TO UPB lychrel DO # classify this number # set number( n ); palindromic[ n ] := is palindromic; add reverse; REF AARRAY path := INIT HEAP AARRAY; BOOL continue searching := TRUE; TO max additions WHILE continue searching := IF related CONTAINSKEY number[ : digits ] THEN # this number is already known to be lychrel # lychrel[ n ] := lychrel related; add related numbers( path ); related count +:= 1; FALSE ELIF is palindromic THEN # have reached a palindrome # lychrel[ n ] := not lychrel; FALSE ELSE # not palindromic - try another iteration # path // number[ : digits ] := "Y"; add reverse; TRUE FI DO SKIP OD; IF continue searching THEN # we have a lychrel seed # add related numbers( path ); lychrel[ n ] := lychrel seed; seed count +:= 1 FI; IF palindromic[ n ] AND ( lychrel[ n ] = lychrel seed OR lychrel[ n ] = lychrel related ) THEN # have a palindromic related or seed lychrel number # palindrome count +:= 1 FI OD;   # print the lychrel numbers up to max number # print( ( "There are " , whole( seed count, 0 ), " seed Lychrel numbers and " , whole( related count, 0 ), " related Lychrel numbers up to " , whole( UPB lychrel, 0 ) , newline ) ); # shpw the seeds # print( ( "Seed Lychrel numbers up to ", whole( UPB lychrel, 0 ), ":" ) ); FOR n TO UPB lychrel DO IF lychrel[ n ] = lychrel seed THEN print( ( " ", whole( n, 0 ) ) ) FI OD; print( ( newline ) ); # show the Lychrel numbers that are palindromic # print( ( "There are " , whole( palindrome count, 0 ) , " palindromic Lychrel numbers up to " , whole( UPB lychrel, 0 ) , ":" ) ); FOR n TO UPB lychrel DO IF ( lychrel[ n ] = lychrel seed OR lychrel[ n ] = lychrel related ) AND palindromic[ n ] THEN print( ( " ", whole( n, 0 ) ) ) FI OD; print( ( newline ) )  
http://rosettacode.org/wiki/Magic_8-ball
Magic 8-ball
Task Create Magic 8-Ball. See details at:   Magic 8-Ball. 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
#Lua
Lua
math.randomseed(os.time()) answers = { "It is certain.", "It is decidedly so.", "Without a doubt.", "Yes, definitely.", "You may rely on it.", "As I see it, yes.", "Most likely.", "Outlook good.", "Signs point to yes.", "Yes.", "Reply hazy, try again.", "Ask again later.", "Better not tell you now.", "Cannot predict now.", "Concentrate and ask again.", "Don't bet on it.", "My reply is no.", "My sources say no.", "Outlook not so good.", "Very doubtful." } while true do io.write("Q: ") question = io.read() print("A: "..answers[math.random(#answers)]) end
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#SPL
SPL
w,h = #.scrsize() sfx = -2.5; sfy = -2*h/w; fs = 4/w #.aaoff() > y, 1...h > x, 1...w fx = sfx + x*fs; fy = sfy + y*fs #.drawpoint(x,y,color(fx,fy):3) < < color(x,y)= zr = x; zi = y; n = 0; maxn = 150 > zr*zr+zi*zi<4 & n<maxn zrn = zr*zr-zi*zi+x; zin = 2*zr*zi+y zr = zrn; zi = zin; n += 1 <  ? n=maxn, <= 0,0,0 <= #.hsv2rgb(n/maxn*360,1,1):3 .
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#ZPL
ZPL
  program matmultSUMMA;   prototype GetSingleDim(infile:file):integer; prototype GetInnerDim(infile1:file; infile2:file):integer;   config var Afilename: string = ""; Bfilename: string = "";   Afile: file = open(Afilename,file_read); Bfile: file = open(Bfilename,file_read);   default_size:integer = 4; m:integer = GetSingleDim(Afile); n:integer = GetInnerDim(Afile,Bfile); p:integer = GetSingleDim(Bfile);   iters: integer = 1;   printinput: boolean = false; verbose: boolean = true; dotiming: boolean = false;   region RA = [1..m,1..n]; RB = [1..n,1..p]; RC = [1..m,1..p]; FCol = [1..m,*]; FRow = [*,1..p];   var A : [RA] double; B : [RB] double; C : [RC] double; Aflood : [FCol] double; Bflood : [FRow] double;     procedure ReadA(); var step:double; [RA] begin if (Afile != znull) then read(Afile,A); else step := 1.0/(m*n); A := ((Index1-1)*n + Index2)*step + 1.0; end; end;     procedure ReadB(); var step:double; [RB] begin if (Bfile != znull) then read(Bfile,B); else step := 1.0/(n*p); B := ((Index1-1)*p + Index2)*step + 1.0; end; end;     procedure matmultSUMMA(); var i: integer; it: integer; runtime: double; [RC] begin ReadA(); ReadB();   if (printinput) then [RA] writeln("A is:\n",A); [RB] writeln("B is:\n",B); end;   ResetTimer();   for it := 1 to iters do   C := 0.0; -- zero C   for i := 1 to n do [FCol] Aflood := >>[,i] A; -- flood A col [FRow] Bflood := >>[i,] B; -- flood B row   C += (Aflood * Bflood); -- multiply end; end;   runtime := CheckTimer();   if (verbose) then writeln("C is:\n",C); end;   if (dotiming) then writeln("total runtime = %12.6f":runtime); writeln("actual runtime = %12.6f":runtime/iters); end; end;     procedure GetSingleDim(infile:file):integer; var dim:integer; begin if (infile != znull) then read(infile,dim); else dim := default_size; end; return dim; end;     procedure GetInnerDim(infile1:file; infile2:file):integer; var col:integer; row:integer; retval:integer; begin retval := -1; if (infile1 != znull) then read(infile1,col); retval := col; end; if (infile2 != znull) then read(infile2,row); if (retval = -1) then retval := row; else if (row != col) then halt("ERROR: Inner dimensions don't match"); end; end; end; if (retval = -1) then retval := default_size; end; return retval; end;  
http://rosettacode.org/wiki/Mad_Libs
Mad Libs
This page uses content from Wikipedia. The original article was at Mad Libs. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Mad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results. Task; Write a program to create a Mad Libs like story. The program should read an arbitrary multiline story from input. The story will be terminated with a blank line. Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements. Stop when there are none left and print the final story. The input should be an arbitrary story in the form: <name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home. Given this example, it should then ask for a name, a he or she and a noun (<name> gets replaced both times with the same value). Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Arturo
Arturo
story: strip input "Enter a story: " vars: unique map match story {/\|([^\|]+)\|/} 'v -> replace v "|" ""   i: 0 while [i < size vars].import [ let vars\[i] input ~"Enter value for <|vars\[i]|>: " i: i + 1 ]   print ~story
http://rosettacode.org/wiki/Ludic_numbers
Ludic numbers
Ludic numbers   are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers. The first ludic number is   1. To generate succeeding ludic numbers create an array of increasing integers starting from   2. 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... (Loop) Take the first member of the resultant array as the next ludic number   2. Remove every   2nd   indexed item from the array (including the first). 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... (Unrolling a few loops...) Take the first member of the resultant array as the next ludic number   3. Remove every   3rd   indexed item from the array (including the first). 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 ... Take the first member of the resultant array as the next ludic number   5. Remove every   5th   indexed item from the array (including the first). 5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 ... Take the first member of the resultant array as the next ludic number   7. Remove every   7th   indexed item from the array (including the first). 7 11 13 17 23 25 29 31 37 41 43 47 53 55 59 61 67 71 73 77 83 85 89 91 97 ... ... Take the first member of the current array as the next ludic number   L. Remove every   Lth   indexed item from the array (including the first). ... Task Generate and show here the first 25 ludic numbers. How many ludic numbers are there less than or equal to 1000? Show the 2000..2005th ludic numbers. Stretch goal Show all triplets of ludic numbers < 250. A triplet is any three numbers     x , {\displaystyle x,}   x + 2 , {\displaystyle x+2,}   x + 6 {\displaystyle x+6}     where all three numbers are also ludic numbers.
#C.23
C#
using System; using System.Linq; using System.Collections.Generic;   public class Program { public static void Main() { Console.WriteLine("First 25 ludic numbers:"); Console.WriteLine(string.Join(", ", LudicNumbers(150).Take(25))); Console.WriteLine();   Console.WriteLine($"There are {LudicNumbers(1001).Count()} ludic numbers below 1000"); Console.WriteLine();   foreach (var ludic in LudicNumbers(22000).Skip(1999).Take(6) .Select((n, i) => $"#{i+2000} = {n}")) { Console.WriteLine(ludic); } Console.WriteLine();   Console.WriteLine("Triplets below 250:"); var queue = new Queue<int>(5); foreach (int x in LudicNumbers(255)) { if (queue.Count == 5) queue.Dequeue(); queue.Enqueue(x); if (x - 6 < 250 && queue.Contains(x - 6) && queue.Contains(x - 4)) { Console.WriteLine($"{x-6}, {x-4}, {x}"); } } }   public static IEnumerable<int> LudicNumbers(int limit) { yield return 1; //Like a linked list, but with value types. //Create 2 extra entries at the start to avoid ugly index calculations //and another at the end to avoid checking for index-out-of-bounds. Entry[] values = Enumerable.Range(0, limit + 1).Select(n => new Entry(n)).ToArray(); for (int i = 2; i < limit; i = values[i].Next) { yield return values[i].N; int start = i; while (start < limit) { Unlink(values, start); for (int step = 0; step < i && start < limit; step++) start = values[start].Next; } } }   static void Unlink(Entry[] values, int index) { values[values[index].Prev].Next = values[index].Next; values[values[index].Next].Prev = values[index].Prev; }   }   struct Entry { public Entry(int n) : this() { N = n; Prev = n - 1; Next = n + 1; }   public int N { get; } public int Prev { get; set; } public int Next { get; set; } }
http://rosettacode.org/wiki/Lychrel_numbers
Lychrel numbers
  Take an integer n, greater than zero.   Form the next n of its series by reversing the digits of the current n and adding the result to the current n.   Stop when n becomes palindromic - i.e. the digits of n in reverse order == n. The above recurrence relation when applied to most starting numbers n = 1, 2, ... terminates in a palindrome quite quickly. Example If n0 = 12 we get 12 12 + 21 = 33, a palindrome! And if n0 = 55 we get 55 55 + 55 = 110 110 + 011 = 121, a palindrome! Notice that the check for a palindrome happens   after   an addition. Some starting numbers seem to go on forever; the recurrence relation for 196 has been calculated for millions of repetitions forming numbers with millions of digits, without forming a palindrome. These numbers that do not end in a palindrome are called Lychrel numbers. For the purposes of this task a Lychrel number is any starting number that does not form a palindrome within 500 (or more) iterations. Seed and related Lychrel numbers Any integer produced in the sequence of a Lychrel number is also a Lychrel number. In general, any sequence from one Lychrel number might converge to join the sequence from a prior Lychrel number candidate; for example the sequences for the numbers 196 and then 689 begin: 196 196 + 691 = 887 887 + 788 = 1675 1675 + 5761 = 7436 7436 + 6347 = 13783 13783 + 38731 = 52514 52514 + 41525 = 94039 ... 689 689 + 986 = 1675 1675 + 5761 = 7436 ... So we see that the sequence starting with 689 converges to, and continues with the same numbers as that for 196. Because of this we can further split the Lychrel numbers into true Seed Lychrel number candidates, and Related numbers that produce no palindromes but have integers in their sequence seen as part of the sequence generated from a lower Lychrel number. Task   Find the number of seed Lychrel number candidates and related numbers for n in the range 1..10000 inclusive. (With that iteration limit of 500).   Print the number of seed Lychrels found; the actual seed Lychrels; and just the number of relateds found.   Print any seed Lychrel or related number that is itself a palindrome. Show all output here. References   What's special about 196? Numberphile video.   A023108 Positive integers which apparently never result in a palindrome under repeated applications of the function f(x) = x + (x with digits reversed).   Status of the 196 conjecture? Mathoverflow.
#AppleScript
AppleScript
on Lychrels(numberLimit, iterationLimit) script o property digits : missing value -- Digits of the current startNumber or a derived sum. property stigid : missing value -- Reverse thereof. property digitLists : missing value -- Copies of the digit lists in the current sequence. -- The digit lists from earlier Lychrel sequences, grouped into 1000 sublists -- indexed by their last three digits (+ 1) to speed up searches for them. property earlierDigitLists : listOfLists(1000) property subgroup : missing value -- Sublist picked from earlierDigitLists. -- Lychrel output. property seeds : {} property relateds : {} property palindromics : {}   -- Subhandler: Has the current list of digits come up in the sequence for an earlier Lychrel? on isRelated() -- Unless it only has one digit, look for it in the appropriate subgroup of earlierDigitLists. set digitCount to (count my digits) if (digitCount > 1) then set i to (item -2 of my digits) * 10 + (end of my digits) + 1 if (digitCount > 2) then set i to i + (item -3 of my digits) * 100 set subgroup to item i of my earlierDigitLists -- It's faster to test this using a repeat than with 'is in'! repeat with i from 1 to (count my subgroup) if (item i of my subgroup = digits) then return true end repeat end if return false end isRelated end script   repeat with startNumber from 1 to numberLimit -- Get the number's digits and their reverse. set o's digits to {} set temp to startNumber repeat until (temp = 0) set beginning of o's digits to temp mod 10 set temp to temp div 10 end repeat set o's stigid to reverse of o's digits -- Note if the number itself is palindromic. set startNumberIsPalindrome to (o's digits = o's stigid)   if (o's isRelated()) then -- It(s digits) occurred in the sequence for an earlier Lychrel, so it's a related Lychrel. set end of o's relateds to startNumber else -- Otherwise run its sequence. set o's digitLists to {} set digitCount to (count o's digits)   -- Sequence loop. repeat iterationLimit times -- Add the reversed digits to those of the current number. set carry to 0 repeat with i from digitCount to 1 by -1 set d to (item i of o's digits) + (item i of o's stigid) + carry set item i of o's digits to d mod 10 set carry to d div 10 end repeat if (carry > 0) then set beginning of o's digits to carry set digitCount to digitCount + 1 end if   -- If the sum's digits are palindromic, the start number's not a Lychrel. set o's stigid to reverse of o's digits set sumIsPalindrome to (o's digits = o's stigid) if (sumIsPalindrome) then exit repeat -- Otherwise, if the digits occurred in an earlier Lychrel sequence, the start number's a related Lychrel. set startNumberIsRelated to (o's isRelated()) if (startNumberIsRelated) then set sumIsPalindrome to false exit repeat end if -- Otherwise keep a copy of the digits and go for the next number in the sequence. copy o's digits to end of o's digitLists end repeat   if (not sumIsPalindrome) then -- No palindrome other than the start number occurred in the sequence, -- so the number's a Lychrel. Store it as the relevant type. if (startNumberIsRelated) then set end of o's relateds to startNumber else set end of o's seeds to startNumber end if if (startNumberIsPalindrome) then set end of o's palindromics to startNumber -- Store this sequence's digit lists based on their last three digits. There won't be any -- single-digit lists (they're palindromes), but there may be some with only two digits. repeat with thisList in o's digitLists set i to (item -2 of thisList) * 10 + (end of thisList) + 1 set digitCount to (count thisList) if (digitCount > 2) then set i to i + (item -3 of thisList) * 100 set end of item i of o's earlierDigitLists to thisList's contents end repeat end if end if end repeat   return {seeds:o's seeds, relateds:o's relateds, palindromics:o's palindromics} end Lychrels   on listOfLists(len) script o property lst : {} end script repeat len times set end of o's lst to {} end repeat return o's lst end listOfLists   on join(lst, delim) set astid to AppleScript's text item delimiters set AppleScript's text item delimiters to delim set txt to lst as text set AppleScript's text item delimiters to astid return txt end join   on task() set numberLimit to 10000 set iterationLimit to 500 set {seeds:seeds, relateds:relateds, palindromics:palindromics} to Lychrels(numberLimit, iterationLimit) set output to {"Lychrel numbers between 1 and " & numberLimit & ":", ""} set end of output to ((count seeds) as text) & " seed Lychrels: " & join(seeds, ", ") set end of output to ((count relateds) as text) & " related Lychrels" set end of output to ((count palindromics) as text) & " palindromic Lychrels: " & join(palindromics, ", ") return join(output, linefeed) end task   task()
http://rosettacode.org/wiki/Magic_8-ball
Magic 8-ball
Task Create Magic 8-Ball. See details at:   Magic 8-Ball. 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
#M2000_Interpreter
M2000 Interpreter
  Module Magic.8.Ball { answers=("It is certain", "It is decidedly so", "Without a doubt", "Yes, definitely", "You may rely on it", "As I see it, yes", "Most likely", "Outlook good", "Signs point to yes", "Yes", "Reply hazy, try again", "Ask again later", "Better not tell you now", "Cannot predict now", "Concentrate and ask again", "Don't bet on it", "My reply is no", "My sources say no", "Outlook not so good", "Very doubtful") Print "Please enter your question or a blank line to quit." { Line Input A$ Print A$=trim$(A$) If A$="" Then Exit Print Array$(answers, Random(0, 19)) Loop } } Magic.8.Ball  
http://rosettacode.org/wiki/Magic_8-ball
Magic 8-ball
Task Create Magic 8-Ball. See details at:   Magic 8-Ball. 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
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
answers = {"It is certain.", "It is decidedly so.", "Without a doubt.", "Yes - definitely.", "You may rely on it.", "As I see it, yes.", "Most likely.", "Outlook good.", "Yes.", "Signs point to yes.", "Reply hazy, try again.", "Ask again later.", "Better not tell you now.", "Cannot predict now.", "Concentrate and ask again.", "Don't count on it.", "My reply is no.", "My sources say no.", "Outlook not so good.", "Very doubtful."}; q = Input["Please enter your question"]; SeedRandom[Hash[q]]; Print[RandomChoice[answers]]
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#Swift
Swift
import Foundation import Numerics import QDBMP   public typealias Color = (red: UInt8, green: UInt8, blue: UInt8)   public class BitmapDrawer { public let imageHeight: Int public let imageWidth: Int   var grid: [[Color?]]   private let bmp: OpaquePointer   public init(height: Int, width: Int) { self.imageHeight = height self.imageWidth = width self.grid = [[Color?]](repeating: [Color?](repeating: nil, count: height), count: width) self.bmp = BMP_Create(UInt(width), UInt(height), 24)   checkError() }   deinit { BMP_Free(bmp) }   private func checkError() { let err = BMP_GetError()   guard err == BMP_STATUS(0) else { fatalError("\(err)") } }   public func save(to path: String = "~/Desktop/out.bmp") { for x in 0..<imageWidth { for y in 0..<imageHeight { guard let color = grid[x][y] else { continue }   BMP_SetPixelRGB(bmp, UInt(x), UInt(y), color.red, color.green, color.blue) checkError() } }   (path as NSString).expandingTildeInPath.withCString {s in BMP_WriteFile(bmp, s) } }   public func setPixel(x: Int, y: Int, to color: Color?) { grid[x][y] = color } }   let imageSize = 10_000 let canvas = BitmapDrawer(height: imageSize, width: imageSize) let maxIterations = 256 let cxMin = -2.0 let cxMax = 1.0 let cyMin = -1.5 let cyMax = 1.5 let scaleX = (cxMax - cxMin) / Double(imageSize) let scaleY = (cyMax - cyMin) / Double(imageSize)   for x in 0..<imageSize { for y in 0..<imageSize { let cx = cxMin + Double(x) * scaleX let cy = cyMin + Double(y) * scaleY   let c = Complex(cx, cy) var z = Complex(0.0, 0.0) var i = 0   for t in 0..<maxIterations { if z.magnitude > 2 { break }   z = z * z + c i = t }   canvas.setPixel(x: x, y: y, to: Color(red: UInt8(i), green: UInt8(i), blue: UInt8(i))) } }   canvas.save()
http://rosettacode.org/wiki/Mad_Libs
Mad Libs
This page uses content from Wikipedia. The original article was at Mad Libs. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Mad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results. Task; Write a program to create a Mad Libs like story. The program should read an arbitrary multiline story from input. The story will be terminated with a blank line. Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements. Stop when there are none left and print the final story. The input should be an arbitrary story in the form: <name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home. Given this example, it should then ask for a name, a he or she and a noun (<name> gets replaced both times with the same value). Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#AutoHotkey
AutoHotkey
FileSelectFile, filename, , %A_ScriptDir%, Select a Mad Libs template, *.txt If ErrorLevel ExitApp ; the user canceled the file selection FileRead, contents, %filename% pos := match := 0 While pos := RegExMatch(contents, "<[^>]+>", match, pos+strLen(match)) { InputBox, repl, Mad Libs, Enter a replacement for %match%: If ErrorLevel ; cancelled inputbox ExitApp StringReplace, contents, contents, %match%, %repl%, All } MsgBox % contents
http://rosettacode.org/wiki/Ludic_numbers
Ludic numbers
Ludic numbers   are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers. The first ludic number is   1. To generate succeeding ludic numbers create an array of increasing integers starting from   2. 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... (Loop) Take the first member of the resultant array as the next ludic number   2. Remove every   2nd   indexed item from the array (including the first). 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... (Unrolling a few loops...) Take the first member of the resultant array as the next ludic number   3. Remove every   3rd   indexed item from the array (including the first). 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 ... Take the first member of the resultant array as the next ludic number   5. Remove every   5th   indexed item from the array (including the first). 5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 ... Take the first member of the resultant array as the next ludic number   7. Remove every   7th   indexed item from the array (including the first). 7 11 13 17 23 25 29 31 37 41 43 47 53 55 59 61 67 71 73 77 83 85 89 91 97 ... ... Take the first member of the current array as the next ludic number   L. Remove every   Lth   indexed item from the array (including the first). ... Task Generate and show here the first 25 ludic numbers. How many ludic numbers are there less than or equal to 1000? Show the 2000..2005th ludic numbers. Stretch goal Show all triplets of ludic numbers < 250. A triplet is any three numbers     x , {\displaystyle x,}   x + 2 , {\displaystyle x+2,}   x + 6 {\displaystyle x+6}     where all three numbers are also ludic numbers.
#C.2B.2B
C++
  #include <vector> #include <iostream> using namespace std;   class ludic { public: void ludicList() { _list.push_back( 1 );   vector<int> v; for( int x = 2; x < 22000; x++ ) v.push_back( x );   while( true ) { vector<int>::iterator i = v.begin(); int z = *i; _list.push_back( z );   while( true ) { i = v.erase( i ); if( distance( i, v.end() ) <= z - 1 ) break; advance( i, z - 1 ); } if( v.size() < 1 ) return; } }   void show( int s, int e ) { for( int x = s; x < e; x++ ) cout << _list[x] << " "; }   void findTriplets( int e ) { int lu, x = 0; while( _list[x] < e ) { lu = _list[x]; if( inList( lu + 2 ) && inList( lu + 6 ) ) cout << "(" << lu << " " << lu + 2 << " " << lu + 6 << ")\n"; x++; } }   int count( int e ) { int x = 0, c = 0; while( _list[x++] <= 1000 ) c++; return c; }   private: bool inList( int lu ) { for( int x = 0; x < 250; x++ ) if( _list[x] == lu ) return true; return false; }   vector<int> _list; };   int main( int argc, char* argv[] ) { ludic l; l.ludicList(); cout << "first 25 ludic numbers:" << "\n"; l.show( 0, 25 ); cout << "\n\nThere are " << l.count( 1000 ) << " ludic numbers <= 1000" << "\n"; cout << "\n2000 to 2005'th ludic numbers:" << "\n"; l.show( 1999, 2005 ); cout << "\n\nall triplets of ludic numbers < 250:" << "\n"; l.findTriplets( 250 ); cout << "\n\n"; return system( "pause" ); }  
http://rosettacode.org/wiki/Lychrel_numbers
Lychrel numbers
  Take an integer n, greater than zero.   Form the next n of its series by reversing the digits of the current n and adding the result to the current n.   Stop when n becomes palindromic - i.e. the digits of n in reverse order == n. The above recurrence relation when applied to most starting numbers n = 1, 2, ... terminates in a palindrome quite quickly. Example If n0 = 12 we get 12 12 + 21 = 33, a palindrome! And if n0 = 55 we get 55 55 + 55 = 110 110 + 011 = 121, a palindrome! Notice that the check for a palindrome happens   after   an addition. Some starting numbers seem to go on forever; the recurrence relation for 196 has been calculated for millions of repetitions forming numbers with millions of digits, without forming a palindrome. These numbers that do not end in a palindrome are called Lychrel numbers. For the purposes of this task a Lychrel number is any starting number that does not form a palindrome within 500 (or more) iterations. Seed and related Lychrel numbers Any integer produced in the sequence of a Lychrel number is also a Lychrel number. In general, any sequence from one Lychrel number might converge to join the sequence from a prior Lychrel number candidate; for example the sequences for the numbers 196 and then 689 begin: 196 196 + 691 = 887 887 + 788 = 1675 1675 + 5761 = 7436 7436 + 6347 = 13783 13783 + 38731 = 52514 52514 + 41525 = 94039 ... 689 689 + 986 = 1675 1675 + 5761 = 7436 ... So we see that the sequence starting with 689 converges to, and continues with the same numbers as that for 196. Because of this we can further split the Lychrel numbers into true Seed Lychrel number candidates, and Related numbers that produce no palindromes but have integers in their sequence seen as part of the sequence generated from a lower Lychrel number. Task   Find the number of seed Lychrel number candidates and related numbers for n in the range 1..10000 inclusive. (With that iteration limit of 500).   Print the number of seed Lychrels found; the actual seed Lychrels; and just the number of relateds found.   Print any seed Lychrel or related number that is itself a palindrome. Show all output here. References   What's special about 196? Numberphile video.   A023108 Positive integers which apparently never result in a palindrome under repeated applications of the function f(x) = x + (x with digits reversed).   Status of the 196 conjecture? Mathoverflow.
#BASIC
BASIC
  ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' Lychrel Numbers V1.0 ' ' ' ' Developed by A. David Garza Marín in QB64 for ' ' RosettaCode. December 2, 2016. ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '   OPTION _EXPLICIT ' Change to OPTION EXPLICIT in VB-DOS or PDS 7.1. Remove in QB and QBASIC   ' SUBs and FUNCTIONs DECLARE SUB doAddLychrel (WhichNumber AS LONG) DECLARE SUB doAddRelated (WhichNumber AS LONG) DECLARE SUB doFindLychrelPalyndromes () DECLARE FUNCTION CalculateMaxRes& (WhichNumber AS LONG) DECLARE FUNCTION IsLychrel% (WhichNumber AS LONG) DECLARE FUNCTION Reverse$ (WhatToReverse AS STRING) DECLARE FUNCTION Sum$ (N1 AS STRING, N2 AS STRING)   ' Var DIM sN1 AS STRING, sN2 AS STRING, sLychrel AS STRING DIM i AS LONG, iLychrel AS INTEGER, iCount AS INTEGER, l AS INTEGER DIM c1 AS INTEGER, l1 AS INTEGER, c2 AS INTEGER, l2 AS INTEGER DIM lMC AS LONG, lT AS LONG DIM lLC AS LONG, lRL AS LONG, lPN AS LONG CONST MaxNumbers = 10000, MaxIterations = 500, False = 0, True = NOT False   ' Init REDIM lLC(1, 0) AS LONG, lRL(0) AS LONG, lPN(0) AS LONG lMC = CalculateMaxRes&(MaxNumbers) lT = TIMER   ' ------------------ Main program ----------------------------------------- CLS PRINT "Lychrel Numbers 1.0" PRINT PRINT "Calculating numbers from 1 to"; MaxNumbers; c1 = POS(1) l1 = CSRLIN COLOR 7 + 16: PRINT "...": PRINT COLOR 7 c2 = POS(1) l2 = CSRLIN FOR i = 1 TO MaxNumbers sN1 = LTRIM$(STR$(i)) sN2 = Reverse$(sN1) iCount = 0 LOCATE l2, 1: PRINT "Analyzing number"; i; COLOR 7 + 16: PRINT "...": COLOR 7 DO iCount = iCount + 1 sN1 = Sum$(sN1, sN2) sN2 = Reverse$(sN1) LOOP UNTIL iCount >= MaxIterations OR sN1 = sN2   IF sN1 <> sN2 THEN IF IsLychrel%(i) THEN doAddLychrel i ELSE doAddRelated i END IF PRINT "Potential Lychrel numbers:"; UBOUND(lLC, 2); "{"; FOR l = 1 TO UBOUND(lLC, 2) PRINT lLC(1, l); NEXT PRINT "}"   IF UBOUND(lRL) > 0 THEN PRINT "Kin Lychrel numbers found:"; UBOUND(lRL) END IF END IF NEXT i   ' Look for palyndromes IF UBOUND(lLC, 2) > 0 THEN doFindLychrelPalyndromes END IF   ' Shows the results CLS PRINT "Lychrel numbers 1.0 in QB64" PRINT PRINT "Lychrel numbers found: "; UBOUND(lLC, 2) PRINT "Lychrel numbers: {"; FOR i = 1 TO UBOUND(lLC, 2) PRINT lLC(1, i); NEXT PRINT "}" PRINT PRINT "Kin numbers found: "; UBOUND(lRL) ' You can uncomment the following lines if you want to see the ' Kin or Related numbers found. 'PRINT "Kin numbers: {"; 'FOR i = 1 TO UBOUND(lRL) ' PRINT lRL(i); 'NEXT i 'PRINT "}" PRINT PRINT "Palyndrome Lychrel numbers found:"; UBOUND(lPN); "{"; FOR i = 1 TO UBOUND(lPN) PRINT lPN(i); NEXT i PRINT "}" lT = TIMER - lT PRINT PRINT USING "Calculation took ##:## seconds."; FIX(lT / 60), (lT MOD 60) PRINT "End of program." ' ------------------ End of Main program -------------------------------------- END   FUNCTION CalculateMaxRes& (WhichNumber AS LONG) ' Var IF (WhichNumber MOD 10) <> 0 THEN CalculateMaxRes& = WhichNumber + VAL(Reverse$(LTRIM$(STR$(WhichNumber)))) ELSE CalculateMaxRes& = (WhichNumber - 1) + VAL(Reverse$(LTRIM$(STR$(WhichNumber - 1)))) END IF END FUNCTION   SUB doAddLychrel (WhichNumber AS LONG) ' Var DIM iMaxC AS INTEGER, iMaxR AS INTEGER DIM lRes AS LONG, iRow AS INTEGER DIM sN1 AS STRING, sN2 AS STRING DIM lNum(1 TO 10) AS LONG SHARED lLC() AS LONG, lMC AS LONG   ' lNum(1) = WhichNumber iRow = 1 iMaxR = 10 lRes = WhichNumber DO iRow = iRow + 1 IF iRow > iMaxR THEN ' Change to REDIM PRESERVE for VB-DOS, QB, QBASIC and PDS 7.1 REDIM _PRESERVE lNum(1 TO iMaxR + 10) AS LONG END IF sN1 = LTRIM$(STR$(lRes)) sN2 = Reverse$(sN1) lRes = VAL(Sum$(sN1, sN2)) lNum(iRow) = lRes LOOP UNTIL lRes > lMC   ' Change to REDIM PRESERVE for VB-DOS, QB, QBASIC and PDS 7.1 REDIM _PRESERVE lNum(1 TO iRow) AS LONG   ' Now, Gathers the size of the lLC table iMaxC = UBOUND(lLC, 2) + 1 IF iMaxC = 1 THEN ERASE lLC iMaxR = iRow ELSE iMaxR = UBOUND(lLC, 1) END IF   IF iMaxC = 1 THEN REDIM lLC(1 TO iMaxR, 1 TO iMaxC) AS LONG ELSE ' Change to REDIM PRESERVE for VB-DOS, QB, QBASIC and PDS 7.1 REDIM _PRESERVE lLC(1 TO iMaxR, 1 TO iMaxC) AS LONG END IF   ' Assigns the result to the table FOR lRes = 1 TO iRow lLC(lRes, iMaxC) = lNum(lRes) NEXT lRes   ERASE lNum END SUB   SUB doAddRelated (WhichNumber AS LONG) ' Var DIM iMax AS INTEGER SHARED lRL() AS LONG   iMax = UBOUND(lRL) + 1 IF iMax = 1 THEN ERASE lRL END IF ' Change to REDIM PRESERVE for VB-DOS, QB, QBASIC and PDS 7.1 REDIM _PRESERVE lRL(1 TO iMax) AS LONG lRL(iMax) = WhichNumber END SUB   SUB doFindLychrelPalyndromes () ' Var DIM iMaxC AS INTEGER, i AS INTEGER, iCount AS INTEGER DIM sN1 AS STRING, sN2 AS STRING SHARED lLC() AS LONG, lRL() AS LONG, lPN() AS LONG   ' Verify seeds iMaxC = UBOUND(lLC, 2) FOR i = 1 TO iMaxC IF lLC(1, i) > 0 THEN sN1 = LTRIM$(STR$(lLC(1, i))) sN2 = Reverse$(sN1) IF sN1 = sN2 THEN iCount = iCount + 1 GOSUB AddSpaceForItem lPN(iCount) = VAL(sN1) END IF END IF NEXT i   ' Verify Kins iMaxC = UBOUND(lRL) FOR i = 1 TO iMaxC IF lRL(i) > 0 THEN sN1 = LTRIM$(STR$(lRL(i))) sN2 = Reverse$(sN1) IF sN1 = sN2 THEN iCount = iCount + 1 GOSUB AddSpaceForItem lPN(iCount) = VAL(sN1) END IF END IF NEXT i   ' Change to REDIM PRESERVE for VB-DOS, QB, QBASIC and PDS 7.1 REDIM _PRESERVE lPN(1 TO iCount) AS LONG   EXIT SUB   AddSpaceForItem: IF UBOUND(lPN) < iCount THEN IF UBOUND(lPN) = 0 THEN ERASE lPN END IF ' Change to REDIM PRESERVE for VB-DOS, QB, QBASIC and PDS 7.1 REDIM _PRESERVE lPN(1 TO iCount + 9) AS LONG END IF RETURN     END SUB   FUNCTION IsLychrel% (WhichNumber AS LONG) ' Var DIM iMaxC AS INTEGER, iMaxR AS INTEGER DIM iCol AS INTEGER, iRow AS INTEGER DIM lToCompare AS LONG DIM YesItIs AS INTEGER DIM sN1 AS STRING, sN2 AS STRING SHARED lLC() AS LONG, lMC AS LONG   iMaxC = UBOUND(lLC, 2) iMaxR = UBOUND(lLC, 1) lToCompare = WhichNumber IF iMaxC > 0 THEN DO sN1 = LTRIM$(STR$(lToCompare)) sN2 = Reverse$(sN1) lToCompare = VAL(Sum$(sN1, sN2)) iCol = 0 DO iCol = iCol + 1 iRow = 0 DO iRow = iRow + 1 LOOP UNTIL iRow = iMaxR OR lToCompare = lLC(iRow, iCol) LOOP UNTIL iCol = iMaxC OR lToCompare = lLC(iRow, iCol) LOOP UNTIL lToCompare >= lMC OR lToCompare = lLC(iRow, iCol) YesItIs = (lToCompare <> lLC(iRow, iCol)) ELSE YesItIs = True END IF   IsLychrel = YesItIs   END FUNCTION   FUNCTION Reverse$ (WhatToReverse AS STRING) ' Var DIM sChar AS STRING DIM sRes AS STRING DIM i AS INTEGER, l AS INTEGER   l = LEN(WhatToReverse) sRes = "" FOR i = 1 TO l sRes = MID$(WhatToReverse, i, 1) + sRes NEXT i   Reverse$ = sRes END FUNCTION   FUNCTION Sum$ (N1 AS STRING, N2 AS STRING) ' Var DIM iN1 AS INTEGER, iN2 AS INTEGER, iSum AS INTEGER DIM i AS INTEGER, l AS INTEGER, iCarry AS INTEGER, lM AS LONG DIM sRes AS STRING   IF LEN(N1) > LEN(N2) THEN l = LEN(N1) ELSE l = LEN(N2) END IF lM = 2147483647 / 2   ' Add trailing zeroes (uncomment in case strings have not equal number of digits) ' N1 = STRING$(l - LEN(N1), 48) + N1 ' N2 = STRING$(l - LEN(N2), 48) + N2   ' Hace la suma IF VAL(N1) < lM THEN sRes = LTRIM$(STR$(VAL(N1) + VAL(N2))) ELSE   FOR i = l TO 1 STEP -1 iN1 = VAL(MID$(N1, i, 1)) iN2 = VAL(MID$(N2, i, 1))   iSum = iN1 + iN2 + iCarry   iCarry = FIX(iSum / 10) iSum = iSum MOD 10   sRes = LTRIM$(STR$(iSum)) + sRes NEXT i IF iCarry > 0 THEN sRes = LTRIM$(STR$(iCarry)) + sRes END IF   Sum$ = sRes   END FUNCTION  
http://rosettacode.org/wiki/Magic_8-ball
Magic 8-ball
Task Create Magic 8-Ball. See details at:   Magic 8-Ball. 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
#min
min
randomize  ; Seed the RNG with current timestamp.   ( "It is certain" "It is decidedly so" "Without a doubt" "Yes, definitely" "You may rely on it" "As I see it, yes" "Most likely" "Outlook good" "Signs point to yes" "Yes" "Reply hazy, try again" "Ask again later" "Better not tell you now" "Cannot predict now" "Concentrate and ask again" "Don't bet on it" "My reply is no" "My sources say no" "Outlook not so good" "Very doubtful" ) =phrases   (phrases dup size pred random get puts!) :answer   (true) ("Ask a question" ask answer) while
http://rosettacode.org/wiki/Magic_8-ball
Magic 8-ball
Task Create Magic 8-Ball. See details at:   Magic 8-Ball. 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
#MiniScript
MiniScript
answers = ["It is certain", "It is decidedly so", "Without a doubt", "Yes, definitely", "You may rely on it", "As I see it, yes", "Most likely", "Outlook good", "Signs point to yes", "Yes", "Reply hazy, try again", "Ask again later", "Better not tell you now", "Cannot predict now", "Concentrate and ask again", "Don't bet on it", "My reply is no", "My sources say no", "Outlook not so good", "Very doubtful"] print "Ask your question and the Magic 8 Ball will give you the answer!" input "What is your question?" print answers[rnd * answers.len]
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#Tcl
Tcl
package require Tk   proc mandelIters {cx cy} { set x [set y 0.0] for {set count 0} {hypot($x,$y) < 2 && $count < 255} {incr count} { set x1 [expr {$x*$x - $y*$y + $cx}] set y1 [expr {2*$x*$y + $cy}] set x $x1; set y $y1 } return $count } proc mandelColor {iter} { set r [expr {16*($iter % 15)}] set g [expr {32*($iter % 7)}] set b [expr {8*($iter % 31)}] format "#%02x%02x%02x" $r $g $b } image create photo mandel -width 300 -height 300 # Build picture in strips, updating as we go so we have "progress" monitoring # Also set the cursor to tell the user to wait while we work. pack [label .mandel -image mandel -cursor watch] update for {set x 0} {$x < 300} {incr x} { for {set y 0} {$y < 300} {incr y} { set i [mandelIters [expr {($x-220)/100.}] [expr {($y-150)/90.}]] mandel put [mandelColor $i] -to $x $y } update } .mandel configure -cursor {}
http://rosettacode.org/wiki/Mad_Libs
Mad Libs
This page uses content from Wikipedia. The original article was at Mad Libs. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Mad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results. Task; Write a program to create a Mad Libs like story. The program should read an arbitrary multiline story from input. The story will be terminated with a blank line. Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements. Stop when there are none left and print the final story. The input should be an arbitrary story in the form: <name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home. Given this example, it should then ask for a name, a he or she and a noun (<name> gets replaced both times with the same value). Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#AWK
AWK
  # syntax: GAWK -f MAD_LIBS.AWK BEGIN { print("enter story:") } { story_arr[++nr] = $0 if ($0 ~ /^ *$/) { exit } while ($0 ~ /[<>]/) { L = index($0,"<") R = index($0,">") changes_arr[substr($0,L,R-L+1)] = "" sub(/</,"",$0) sub(/>/,"",$0) } } END { PROCINFO["sorted_in"] = "@ind_str_asc" print("enter values for:") for (i in changes_arr) { # prompt for replacement values printf("%s ",i) getline rec sub(/ +$/,"",rec) changes_arr[i] = rec } printf("\nrevised story:\n") for (i=1; i<=nr; i++) { # print the story for (j in changes_arr) { gsub(j,changes_arr[j],story_arr[i]) } printf("%s\n",story_arr[i]) } exit(0) }  
http://rosettacode.org/wiki/Ludic_numbers
Ludic numbers
Ludic numbers   are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers. The first ludic number is   1. To generate succeeding ludic numbers create an array of increasing integers starting from   2. 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... (Loop) Take the first member of the resultant array as the next ludic number   2. Remove every   2nd   indexed item from the array (including the first). 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... (Unrolling a few loops...) Take the first member of the resultant array as the next ludic number   3. Remove every   3rd   indexed item from the array (including the first). 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 ... Take the first member of the resultant array as the next ludic number   5. Remove every   5th   indexed item from the array (including the first). 5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 ... Take the first member of the resultant array as the next ludic number   7. Remove every   7th   indexed item from the array (including the first). 7 11 13 17 23 25 29 31 37 41 43 47 53 55 59 61 67 71 73 77 83 85 89 91 97 ... ... Take the first member of the current array as the next ludic number   L. Remove every   Lth   indexed item from the array (including the first). ... Task Generate and show here the first 25 ludic numbers. How many ludic numbers are there less than or equal to 1000? Show the 2000..2005th ludic numbers. Stretch goal Show all triplets of ludic numbers < 250. A triplet is any three numbers     x , {\displaystyle x,}   x + 2 , {\displaystyle x+2,}   x + 6 {\displaystyle x+6}     where all three numbers are also ludic numbers.
#Clojure
Clojure
(defn ints-from [n] (cons n (lazy-seq (ints-from (inc n)))))   (defn drop-nth [n seq] (cond (zero? n) seq (empty? seq) []  :else (concat (take (dec n) seq) (lazy-seq (drop-nth n (drop n seq))))))   (def ludic ((fn ludic ([] (ludic 1)) ([n] (ludic n (ints-from (inc n)))) ([n [f & r]] (cons n (lazy-seq (ludic f (drop-nth f r))))))))   (defn ludic? [n] (= (first (filter (partial <= n) ludic)) n))   (print "First 25: ") (println (take 25 ludic)) (print "Count below 1000: ") (println (count (take-while (partial > 1000) ludic))) (print "2000th through 2005th: ") (println (map (partial nth ludic) (range 1999 2005))) (print "Triplets < 250: ") (println (filter (partial every? ludic?) (for [i (range 250)] (list i (+ i 2) (+ i 6)))))
http://rosettacode.org/wiki/Lychrel_numbers
Lychrel numbers
  Take an integer n, greater than zero.   Form the next n of its series by reversing the digits of the current n and adding the result to the current n.   Stop when n becomes palindromic - i.e. the digits of n in reverse order == n. The above recurrence relation when applied to most starting numbers n = 1, 2, ... terminates in a palindrome quite quickly. Example If n0 = 12 we get 12 12 + 21 = 33, a palindrome! And if n0 = 55 we get 55 55 + 55 = 110 110 + 011 = 121, a palindrome! Notice that the check for a palindrome happens   after   an addition. Some starting numbers seem to go on forever; the recurrence relation for 196 has been calculated for millions of repetitions forming numbers with millions of digits, without forming a palindrome. These numbers that do not end in a palindrome are called Lychrel numbers. For the purposes of this task a Lychrel number is any starting number that does not form a palindrome within 500 (or more) iterations. Seed and related Lychrel numbers Any integer produced in the sequence of a Lychrel number is also a Lychrel number. In general, any sequence from one Lychrel number might converge to join the sequence from a prior Lychrel number candidate; for example the sequences for the numbers 196 and then 689 begin: 196 196 + 691 = 887 887 + 788 = 1675 1675 + 5761 = 7436 7436 + 6347 = 13783 13783 + 38731 = 52514 52514 + 41525 = 94039 ... 689 689 + 986 = 1675 1675 + 5761 = 7436 ... So we see that the sequence starting with 689 converges to, and continues with the same numbers as that for 196. Because of this we can further split the Lychrel numbers into true Seed Lychrel number candidates, and Related numbers that produce no palindromes but have integers in their sequence seen as part of the sequence generated from a lower Lychrel number. Task   Find the number of seed Lychrel number candidates and related numbers for n in the range 1..10000 inclusive. (With that iteration limit of 500).   Print the number of seed Lychrels found; the actual seed Lychrels; and just the number of relateds found.   Print any seed Lychrel or related number that is itself a palindrome. Show all output here. References   What's special about 196? Numberphile video.   A023108 Positive integers which apparently never result in a palindrome under repeated applications of the function f(x) = x + (x with digits reversed).   Status of the 196 conjecture? Mathoverflow.
#C.2B.2B
C++
#include <iostream> #include <map> #include <vector> #include <gmpxx.h>   using integer = mpz_class;   integer reverse(integer n) { integer rev = 0; while (n > 0) { rev = rev * 10 + (n % 10); n /= 10; } return rev; }   void print_vector(const std::vector<integer>& vec) { if (vec.empty()) return; auto i = vec.begin(); std::cout << *i++; for (; i != vec.end(); ++i) std::cout << ", " << *i; std::cout << '\n'; }   int main() { std::map<integer, std::pair<bool, integer>> cache; std::vector<integer> seeds, related, palindromes; for (integer n = 1; n <= 10000; ++n) { std::pair<bool, integer> p(true, n); std::vector<integer> seen; integer rev = reverse(n); integer sum = n; for (int i = 0; i < 500; ++i) { sum += rev; rev = reverse(sum); if (rev == sum) { p.first = false; p.second = 0; break; } auto iter = cache.find(sum); if (iter != cache.end()) { p = iter->second; break; } seen.push_back(sum); } for (integer s : seen) cache.emplace(s, p); if (!p.first) continue; if (p.second == n) seeds.push_back(n); else related.push_back(n); if (n == reverse(n)) palindromes.push_back(n); } std::cout << "number of seeds: " << seeds.size() << '\n'; std::cout << "seeds: "; print_vector(seeds); std::cout << "number of related: " << related.size() << '\n'; std::cout << "palindromes: "; print_vector(palindromes); return 0; }
http://rosettacode.org/wiki/Magic_8-ball
Magic 8-ball
Task Create Magic 8-Ball. See details at:   Magic 8-Ball. 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
#Nim
Nim
import random, strutils   const Answers = ["It is certain", "It is decidedly so", "Without a doubt", "Yes, definitely", "You may rely on it", "As I see it, yes", "Most likely", "Outlook good", "Signs point to yes", "Yes", "Reply hazy, try again", "Ask again later", "Better not tell you now", "Cannot predict now", "Concentrate and ask again", "Don't bet on it", "My reply is no", "My sources say no", "Outlook not so good", "Very doubtful"]   proc exit() = echo "Bye." quit QuitSuccess   randomize()   try: while true: echo "Type your question or an empty line to quit." stdout.write "? " let question = stdin.readLine() if question.strip().len == 0: exit() echo Answers[rand(19)], ".\n" except EOFError: exit()
http://rosettacode.org/wiki/Magic_8-ball
Magic 8-ball
Task Create Magic 8-Ball. See details at:   Magic 8-Ball. 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
#ooRexx
ooRexx
  /* REXX */ a=.array~of("It is certain", "It is decidedly so", "Without a doubt",, "Yes, definitely", "You may rely on it", "As I see it, yes",, "Most likely", "Outlook good", "Signs point to yes", "Yes",, "Reply hazy, try again", "Ask again later",, "Better not tell you now", "Cannot predict now",, "Concentrate and ask again", "Don't bet on it",, "My reply is no", "My sources say no", "Outlook not so good",, "Very doubtful") Do Forever Say 'your question:' Parse Pull q If q='' Then Leave Say a[random(1,20)] Say '' End
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#Plain_TeX
Plain TeX
\input pst-fractal \psfractal[type=Mandel,xWidth=14cm,yWidth=12cm,maxIter=30,dIter=20] (-2.5,-1.5)(1,1.5) \end
http://rosettacode.org/wiki/Mad_Libs
Mad Libs
This page uses content from Wikipedia. The original article was at Mad Libs. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Mad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results. Task; Write a program to create a Mad Libs like story. The program should read an arbitrary multiline story from input. The story will be terminated with a blank line. Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements. Stop when there are none left and print the final story. The input should be an arbitrary story in the form: <name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home. Given this example, it should then ask for a name, a he or she and a noun (<name> gets replaced both times with the same value). Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#BASIC256
BASIC256
  cadena = "<name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home." k = instr(cadena, "<")   print "La historia: " : print cadena : print while k reemplaza = mid(cadena, k, instr(cadena, ">") - k + 1) print "What should replace "; reemplaza; : input " ", con while k cadena = left(cadena, k-1) + con + mid(cadena, k + length(reemplaza), length(cadena)) k = instr(cadena, reemplaza, k) end while k = instr(cadena, "<", length(reemplaza)) end while print : print "La historia final: " : print cadena end  
http://rosettacode.org/wiki/Ludic_numbers
Ludic numbers
Ludic numbers   are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers. The first ludic number is   1. To generate succeeding ludic numbers create an array of increasing integers starting from   2. 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... (Loop) Take the first member of the resultant array as the next ludic number   2. Remove every   2nd   indexed item from the array (including the first). 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... (Unrolling a few loops...) Take the first member of the resultant array as the next ludic number   3. Remove every   3rd   indexed item from the array (including the first). 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 ... Take the first member of the resultant array as the next ludic number   5. Remove every   5th   indexed item from the array (including the first). 5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 ... Take the first member of the resultant array as the next ludic number   7. Remove every   7th   indexed item from the array (including the first). 7 11 13 17 23 25 29 31 37 41 43 47 53 55 59 61 67 71 73 77 83 85 89 91 97 ... ... Take the first member of the current array as the next ludic number   L. Remove every   Lth   indexed item from the array (including the first). ... Task Generate and show here the first 25 ludic numbers. How many ludic numbers are there less than or equal to 1000? Show the 2000..2005th ludic numbers. Stretch goal Show all triplets of ludic numbers < 250. A triplet is any three numbers     x , {\displaystyle x,}   x + 2 , {\displaystyle x+2,}   x + 6 {\displaystyle x+6}     where all three numbers are also ludic numbers.
#Common_Lisp
Common Lisp
(defun ludic-numbers (max &optional n) (loop with numbers = (make-array (1+ max) :element-type 'boolean :initial-element t) for i from 2 to max until (and n (= num-results (1- n))) ; 1 will be added at the end when (aref numbers i) collect i into results and count t into num-results and do (loop for j from i to max count (aref numbers j) into counter when (= (mod counter i) 1) do (setf (aref numbers j) nil)) finally (return (cons 1 results))))   (defun main () (format t "First 25 ludic numbers:~%") (format t "~{~D~^ ~}~%" (ludic-numbers 100 25)) (terpri) (format t "How many ludic numbers <= 1000?~%") (format t "~D~%" (length (ludic-numbers 1000))) (terpri) (let ((numbers (ludic-numbers 30000 2005))) (format t "~{#~D: ~D~%~}" (mapcan #'list '(2000 2001 2002 2003 2004 2005) (nthcdr 1999 numbers)))) (terpri) (loop with numbers = (ludic-numbers 250) initially (format t "Triplets:~%") for x in numbers when (and (find (+ x 2) numbers) (find (+ x 6) numbers)) do (format t "~3D ~3D ~3D~%" x (+ x 2) (+ x 6))))
http://rosettacode.org/wiki/Lychrel_numbers
Lychrel numbers
  Take an integer n, greater than zero.   Form the next n of its series by reversing the digits of the current n and adding the result to the current n.   Stop when n becomes palindromic - i.e. the digits of n in reverse order == n. The above recurrence relation when applied to most starting numbers n = 1, 2, ... terminates in a palindrome quite quickly. Example If n0 = 12 we get 12 12 + 21 = 33, a palindrome! And if n0 = 55 we get 55 55 + 55 = 110 110 + 011 = 121, a palindrome! Notice that the check for a palindrome happens   after   an addition. Some starting numbers seem to go on forever; the recurrence relation for 196 has been calculated for millions of repetitions forming numbers with millions of digits, without forming a palindrome. These numbers that do not end in a palindrome are called Lychrel numbers. For the purposes of this task a Lychrel number is any starting number that does not form a palindrome within 500 (or more) iterations. Seed and related Lychrel numbers Any integer produced in the sequence of a Lychrel number is also a Lychrel number. In general, any sequence from one Lychrel number might converge to join the sequence from a prior Lychrel number candidate; for example the sequences for the numbers 196 and then 689 begin: 196 196 + 691 = 887 887 + 788 = 1675 1675 + 5761 = 7436 7436 + 6347 = 13783 13783 + 38731 = 52514 52514 + 41525 = 94039 ... 689 689 + 986 = 1675 1675 + 5761 = 7436 ... So we see that the sequence starting with 689 converges to, and continues with the same numbers as that for 196. Because of this we can further split the Lychrel numbers into true Seed Lychrel number candidates, and Related numbers that produce no palindromes but have integers in their sequence seen as part of the sequence generated from a lower Lychrel number. Task   Find the number of seed Lychrel number candidates and related numbers for n in the range 1..10000 inclusive. (With that iteration limit of 500).   Print the number of seed Lychrels found; the actual seed Lychrels; and just the number of relateds found.   Print any seed Lychrel or related number that is itself a palindrome. Show all output here. References   What's special about 196? Numberphile video.   A023108 Positive integers which apparently never result in a palindrome under repeated applications of the function f(x) = x + (x with digits reversed).   Status of the 196 conjecture? Mathoverflow.
#Clojure
Clojure
(ns lychrel.core (require [clojure.string :as s]) (require [clojure.set :as set-op]) (:gen-class))   (defn palindrome? "Returns true if given number is a palindrome (number on base 10)" [number] (let [number-str (str number)] (= number-str (s/reverse number-str))))   (defn delete-leading-zeros "Delete leading zeros so that you can read the string" [number-str] (read-string (re-find (re-pattern "[1-9]\\d*") number-str)) )   (defn lychrel "Returns T if number is a candidate Lychrel (up to max iterations), and a second value with the sequence of sums" ([number] (lychrel number 500)) ([number depth] (let [next-number (+' number (delete-leading-zeros (s/reverse (str number)))) depth (- depth 1)] (if (palindrome? next-number) (conj [next-number] number) (if (not= depth 0) (conj (lychrel next-number depth) number) (conj [] nil)) ) )))   (defn lychrel? "Test if number is a possible lychrel number" [number] (= nil (first (lychrel number 500))))   (defn lychrel-up-to-n "Get all lychrels up to N" [N] (filter lychrel? (range 1 N)))   (defn make-kin "Removes the starting number of the list, the starting number" [kin] (rest (butlast kin)))   (defn calc-seed "The seeding" [] (let [kin-set (atom #{}) seed-set (atom #{})] (fn [n] (let [lychrel-seed (set #{(last n)}) kins (set (butlast n))] (if (= kins (clojure.set/difference kins @kin-set)) (do (swap! kin-set clojure.set/union kins) (swap! seed-set clojure.set/union lychrel-seed) @kin-set)) @seed-set ))))   (defn filter-seeds "Filtering the seed through the paths" [] (let [calc-f (calc-seed) all-lychrels (for [lychrel-list (filter lychrel? (range 1 10000))] (filter (fn [x] (> 1000001 x)) (rest (lychrel lychrel-list))))] (last (for [ll all-lychrels] (do (calc-f ll))))))   (defn -main "Here we do the three tasks: Get all possible Lychrel numbers up to 10000 Count them Reduce all possible numbers to seed"   [& args] (let [lychrels-n (filter-seeds) count-lychrels (count lychrels-n) related-n (- (count (filter lychrel? (range 1 10000))) count-lychrels) palindrom-n (filter palindrome? (filter lychrel? (range 1 10000))) count-palindromes (count palindrom-n) ] (println count-lychrels "Lychrel seeds:" lychrels-n) (println related-n "Lychrel related.") (println count-palindromes "Lychrel palindromes found:" palindrom-n)) )  
http://rosettacode.org/wiki/Magic_8-ball
Magic 8-ball
Task Create Magic 8-Ball. See details at:   Magic 8-Ball. 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
#Perl
Perl
@a = ('It is certain', 'It is decidedly so', 'Without a doubt', 'Yes, definitely', 'You may rely on it', 'As I see it, yes', 'Most likely', 'Outlook good', 'Signs point to yes', 'Yes', 'Reply hazy, try again', 'Ask again later', 'Better not tell you now', 'Cannot predict now', 'Concentrate and ask again', "Don't bet on it", 'My reply is no', 'My sources say no', 'Outlook not so good', 'Very doubtful');   while () { print 'Enter your question:'; last unless <> =~ /\w/; print @a[int rand @a], "\n"; }
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#LaTeX
LaTeX
\documentclass{minimal} \usepackage{tikz} \usetikzlibrary{shadings} \begin{document} \begin{tikzpicture} \shade[shading=Mandelbrot set] (0,0) rectangle (4,4); \end{tikzpicture} \end{document}
http://rosettacode.org/wiki/Mad_Libs
Mad Libs
This page uses content from Wikipedia. The original article was at Mad Libs. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Mad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results. Task; Write a program to create a Mad Libs like story. The program should read an arbitrary multiline story from input. The story will be terminated with a blank line. Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements. Stop when there are none left and print the final story. The input should be an arbitrary story in the form: <name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home. Given this example, it should then ask for a name, a he or she and a noun (<name> gets replaced both times with the same value). Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#C
C
  #include <stdio.h> #include <stdlib.h> #include <string.h>   #define err(...) fprintf(stderr, ## __VA_ARGS__), exit(1)   /* We create a dynamic string with a few functions which make modifying * the string and growing a bit easier */ typedef struct { char *data; size_t alloc; size_t length; } dstr;   inline int dstr_space(dstr *s, size_t grow_amount) { return s->length + grow_amount < s->alloc; }   int dstr_grow(dstr *s) { s->alloc *= 2; char *attempt = realloc(s->data, s->alloc);   if (!attempt) return 0; else s->data = attempt;   return 1; }   dstr* dstr_init(const size_t to_allocate) { dstr *s = malloc(sizeof(dstr)); if (!s) goto failure;   s->length = 0; s->alloc = to_allocate; s->data = malloc(s->alloc);   if (!s->data) goto failure;   return s;   failure: if (s->data) free(s->data); if (s) free(s); return NULL; }   void dstr_delete(dstr *s) { if (s->data) free(s->data); if (s) free(s); }   dstr* readinput(FILE *fd) { static const size_t buffer_size = 4096; char buffer[buffer_size];   dstr *s = dstr_init(buffer_size); if (!s) goto failure;   while (fgets(buffer, buffer_size, fd)) { while (!dstr_space(s, buffer_size)) if (!dstr_grow(s)) goto failure;   strncpy(s->data + s->length, buffer, buffer_size); s->length += strlen(buffer); }   return s;   failure: dstr_delete(s); return NULL; }   void dstr_replace_all(dstr *story, const char *replace, const char *insert) { const size_t replace_l = strlen(replace); const size_t insert_l = strlen(insert); char *start = story->data;   while ((start = strstr(start, replace))) { if (!dstr_space(story, insert_l - replace_l)) if (!dstr_grow(story)) err("Failed to allocate memory");   if (insert_l != replace_l) { memmove(start + insert_l, start + replace_l, story->length - (start + replace_l - story->data));   /* Remember to null terminate the data so we can utilize it * as we normally would */ story->length += insert_l - replace_l; story->data[story->length] = 0; }   memmove(start, insert, insert_l); } }   void madlibs(dstr *story) { static const size_t buffer_size = 128; char insert[buffer_size]; char replace[buffer_size];   char *start, *end = story->data;   while (start = strchr(end, '<')) { if (!(end = strchr(start, '>'))) err("Malformed brackets in input");   /* One extra for current char and another for nul byte */ strncpy(replace, start, end - start + 1); replace[end - start + 1] = '\0';   printf("Enter value for field %s: ", replace);   fgets(insert, buffer_size, stdin); const size_t il = strlen(insert) - 1; if (insert[il] == '\n') insert[il] = '\0';   dstr_replace_all(story, replace, insert); } printf("\n"); }   int main(int argc, char *argv[]) { if (argc < 2) return 0;   FILE *fd = fopen(argv[1], "r"); if (!fd) err("Could not open file: '%s\n", argv[1]);   dstr *story = readinput(fd); fclose(fd); if (!story) err("Failed to allocate memory");   madlibs(story); printf("%s\n", story->data); dstr_delete(story); return 0; }  
http://rosettacode.org/wiki/Ludic_numbers
Ludic numbers
Ludic numbers   are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers. The first ludic number is   1. To generate succeeding ludic numbers create an array of increasing integers starting from   2. 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... (Loop) Take the first member of the resultant array as the next ludic number   2. Remove every   2nd   indexed item from the array (including the first). 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... (Unrolling a few loops...) Take the first member of the resultant array as the next ludic number   3. Remove every   3rd   indexed item from the array (including the first). 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 ... Take the first member of the resultant array as the next ludic number   5. Remove every   5th   indexed item from the array (including the first). 5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 ... Take the first member of the resultant array as the next ludic number   7. Remove every   7th   indexed item from the array (including the first). 7 11 13 17 23 25 29 31 37 41 43 47 53 55 59 61 67 71 73 77 83 85 89 91 97 ... ... Take the first member of the current array as the next ludic number   L. Remove every   Lth   indexed item from the array (including the first). ... Task Generate and show here the first 25 ludic numbers. How many ludic numbers are there less than or equal to 1000? Show the 2000..2005th ludic numbers. Stretch goal Show all triplets of ludic numbers < 250. A triplet is any three numbers     x , {\displaystyle x,}   x + 2 , {\displaystyle x+2,}   x + 6 {\displaystyle x+6}     where all three numbers are also ludic numbers.
#D
D
struct Ludics(T) { int opApply(int delegate(in ref T) dg) { int result; T[] rotor, taken = [T(1)]; result = dg(taken[0]); if (result) return result;   for (T i = 2; ; i++) { // Shoud be stopped if T has a max. size_t j = 0; for (; j < rotor.length; j++) if (!--rotor[j]) break;   if (j < rotor.length) { rotor[j] = taken[j + 1]; } else { result = dg(i); if (result) return result; taken ~= i; rotor ~= taken[j + 1]; } } } }   void main() { import std.stdio, std.range, std.algorithm;   // std.algorithm.take can't be used here. uint[] L; foreach (const x; Ludics!uint()) if (L.length < 2005) L ~= x; else break;   writeln("First 25 ludic primes:\n", L.take(25)); writefln("\nThere are %d ludic numbers <= 1000.", L.until!q{ a > 1000 }.walkLength);   writeln("\n2000'th .. 2005'th ludic primes:\n", L[1999 .. 2005]);   enum m = 250; const triplets = L.filter!(x => x + 6 < m && L.canFind(x + 2) && L.canFind(x + 6)) // Ugly output: //.map!(x => tuple(x, x + 2, x + 6)).array; .map!(x => [x, x + 2, x + 6]).array; writefln("\nThere are %d triplets less than %d:\n%s", triplets.length, m, triplets); }
http://rosettacode.org/wiki/Lucas-Lehmer_test
Lucas-Lehmer test
Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2 − 2 {\displaystyle S(n+1)=(S(n))^{2}-2} , and S ( 1 ) = 4 {\displaystyle S(1)=4} . Task Calculate all Mersenne primes up to the implementation's maximum precision, or the 47th Mersenne prime   (whichever comes first).
#11l
11l
F isPrime(p) I p < 2 | p % 2 == 0 R p == 2 L(i) 3..Int(sqrt(p)) I p % i == 0 R 0B R 1B   F isMersennePrime(p) I !isPrime(p) R 0B I p == 2 R 1B V mp = BigInt(2) ^ p - 1 V s = BigInt(4) L 3..p s = (s ^ 2 - 2) % mp R s == 0   L(p) 2..2299 I isMersennePrime(p) print(‘M’p, end' ‘ ’)
http://rosettacode.org/wiki/Lychrel_numbers
Lychrel numbers
  Take an integer n, greater than zero.   Form the next n of its series by reversing the digits of the current n and adding the result to the current n.   Stop when n becomes palindromic - i.e. the digits of n in reverse order == n. The above recurrence relation when applied to most starting numbers n = 1, 2, ... terminates in a palindrome quite quickly. Example If n0 = 12 we get 12 12 + 21 = 33, a palindrome! And if n0 = 55 we get 55 55 + 55 = 110 110 + 011 = 121, a palindrome! Notice that the check for a palindrome happens   after   an addition. Some starting numbers seem to go on forever; the recurrence relation for 196 has been calculated for millions of repetitions forming numbers with millions of digits, without forming a palindrome. These numbers that do not end in a palindrome are called Lychrel numbers. For the purposes of this task a Lychrel number is any starting number that does not form a palindrome within 500 (or more) iterations. Seed and related Lychrel numbers Any integer produced in the sequence of a Lychrel number is also a Lychrel number. In general, any sequence from one Lychrel number might converge to join the sequence from a prior Lychrel number candidate; for example the sequences for the numbers 196 and then 689 begin: 196 196 + 691 = 887 887 + 788 = 1675 1675 + 5761 = 7436 7436 + 6347 = 13783 13783 + 38731 = 52514 52514 + 41525 = 94039 ... 689 689 + 986 = 1675 1675 + 5761 = 7436 ... So we see that the sequence starting with 689 converges to, and continues with the same numbers as that for 196. Because of this we can further split the Lychrel numbers into true Seed Lychrel number candidates, and Related numbers that produce no palindromes but have integers in their sequence seen as part of the sequence generated from a lower Lychrel number. Task   Find the number of seed Lychrel number candidates and related numbers for n in the range 1..10000 inclusive. (With that iteration limit of 500).   Print the number of seed Lychrels found; the actual seed Lychrels; and just the number of relateds found.   Print any seed Lychrel or related number that is itself a palindrome. Show all output here. References   What's special about 196? Numberphile video.   A023108 Positive integers which apparently never result in a palindrome under repeated applications of the function f(x) = x + (x with digits reversed).   Status of the 196 conjecture? Mathoverflow.
#Common_Lisp
Common Lisp
(defun Lychrel (number &optional (max 500)) "Returns T if number is a candidate Lychrel (up to max iterations), and a second value with the sequence of sums" (do* ((n number (+ n (parse-integer rev-str))) (n-str (write-to-string n) (write-to-string n)) (rev-str (reverse n-str) (reverse n-str)) (i 0 (1+ i)) (list (list n) (cons n list)) ) ((or (> i max) (and (string= n-str rev-str) (> i 0))) (values (not (string= n-str rev-str)) (nreverse list)))))     (defun Lychrel-test (n &optional (max 500)) "Tests the first n numbers up to max number of iterations" (let ((seeds nil) (related 0) (palyndromes nil) ) (dotimes (i (1+ n)) (multiple-value-bind (Lychrel-p seq) (Lychrel i max) (when Lychrel-p (if (find seq seeds :test #'intersection :key #'cdr) (incf related) (push (cons i seq) seeds) ) (when (= i (parse-integer (reverse (write-to-string i)))) (push i palyndromes) )))) (format T "Testing numbers: 1 to ~D~%Iteration maximum: ~D~%~%Number of Lychrel seeds found: ~d => ~a~%~ Number of related found: ~D~%Palyndrome Lychrel numbers: ~D => ~a~%" n max (length seeds) (nreverse (mapcar #'car seeds)) related (length palyndromes) (nreverse palyndromes)) ))  
http://rosettacode.org/wiki/Magic_8-ball
Magic 8-ball
Task Create Magic 8-Ball. See details at:   Magic 8-Ball. 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
#Phix
Phix
with javascript_semantics constant answers = {"As I see it, yes", "Ask again later", "You may rely on it", "Without a doubt", "Don't bet on it", "Outlook not so good", "Signs point to yes", "It is decidedly so", "It is certain", "Better not tell you now", "My reply is no", "Outlook good", "Concentrate and ask again", "Reply hazy, try again", "Yes", "Most likely", "Cannot predict now", "My sources say maybe", "My sources say no", "Yes, definitely", "Yes, probably not", "Very doubtful", "Your question has already been answered"} include pGUI.e Ihandle dlg, vbox, question, answer sequence answered = {} bool clearkey = false function key_cb(Ihandle /*dlg*/, atom c) if c=K_ESC then return IUP_CLOSE end if -- (standard practice for me) if c=K_F5 then return IUP_DEFAULT end if -- (let browser reload work) if c=K_CR then string q = IupGetAttribute(question,"VALUE"), reply if length(q) then if find(q,answered) then reply = "Your question has already been answered" else answered = append(answered,q) reply = answers[rand(length(answers))] end if IupSetStrAttribute(answer,"TITLE",reply) clearkey = true end if elsif clearkey then IupSetAttribute(question,"VALUE","") clearkey = false end if return IUP_CONTINUE end function IupOpen() question = IupText("EXPAND=HORIZONTAL") answer = IupLabel("","EXPAND=HORIZONTAL") vbox = IupVbox({question,answer},`MARGIN=40x40`) dlg = IupDialog(vbox,`TITLE="Magic 8-ball",SIZE=250x100`) IupSetCallback(dlg,"KEY_CB",Icallback("key_cb")) IupShow(dlg) if platform()!=JS then IupMainLoop() IupHide(dlg) end if
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#LuaTeX
LuaTeX
PROGRAM:MANDELBR :Input "ITER. ",D :For(A,Xmin,Xmax,ΔX) :For(B,Ymin,Ymax,ΔY) :0→X :0→Y :0→I :D→M :While X^2+Y^2≤4 and I<M :X^2-Y^2+A→R :2XY+B→Y :R→X :I+1→I :End :If I≠M :Then :I→C :Else :0→C :End :If C<1 :Pt-On(A,B) :End :End :End  
http://rosettacode.org/wiki/Mad_Libs
Mad Libs
This page uses content from Wikipedia. The original article was at Mad Libs. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Mad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results. Task; Write a program to create a Mad Libs like story. The program should read an arbitrary multiline story from input. The story will be terminated with a blank line. Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements. Stop when there are none left and print the final story. The input should be an arbitrary story in the form: <name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home. Given this example, it should then ask for a name, a he or she and a noun (<name> gets replaced both times with the same value). Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#C.2B.2B
C++
#include <iostream> #include <string> using namespace std;   int main() { string story, input;   //Loop while(true) { //Get a line from the user getline(cin, input);   //If it's blank, break this loop if(input == "\r") break;   //Add the line to the story story += input; }   //While there is a '<' in the story int begin; while((begin = story.find("<")) != string::npos) { //Get the category from between '<' and '>' int end = story.find(">"); string cat = story.substr(begin + 1, end - begin - 1);   //Ask the user for a replacement cout << "Give me a " << cat << ": "; cin >> input;   //While there's a matching category //in the story while((begin = story.find("<" + cat + ">")) != string::npos) { //Replace it with the user's replacement story.replace(begin, cat.length()+2, input); } }   //Output the final story cout << endl << story;   return 0; }
http://rosettacode.org/wiki/Ludic_numbers
Ludic numbers
Ludic numbers   are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers. The first ludic number is   1. To generate succeeding ludic numbers create an array of increasing integers starting from   2. 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... (Loop) Take the first member of the resultant array as the next ludic number   2. Remove every   2nd   indexed item from the array (including the first). 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... (Unrolling a few loops...) Take the first member of the resultant array as the next ludic number   3. Remove every   3rd   indexed item from the array (including the first). 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 ... Take the first member of the resultant array as the next ludic number   5. Remove every   5th   indexed item from the array (including the first). 5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 ... Take the first member of the resultant array as the next ludic number   7. Remove every   7th   indexed item from the array (including the first). 7 11 13 17 23 25 29 31 37 41 43 47 53 55 59 61 67 71 73 77 83 85 89 91 97 ... ... Take the first member of the current array as the next ludic number   L. Remove every   Lth   indexed item from the array (including the first). ... Task Generate and show here the first 25 ludic numbers. How many ludic numbers are there less than or equal to 1000? Show the 2000..2005th ludic numbers. Stretch goal Show all triplets of ludic numbers < 250. A triplet is any three numbers     x , {\displaystyle x,}   x + 2 , {\displaystyle x+2,}   x + 6 {\displaystyle x+6}     where all three numbers are also ludic numbers.
#Delphi
Delphi
  class LUDIC_NUMBERS   create make   feature   make (n: INTEGER) -- Initialized arrays for find_ludic_numbers. require n_positive: n > 0 local i: INTEGER do create initial.make_filled (0, 1, n - 1) create ludic_numbers.make_filled (1, 1, 1) from i := 2 until i > n loop initial.put (i, i - 1) i := i + 1 end find_ludic_numbers end   ludic_numbers: ARRAY [INTEGER]   feature {NONE}   initial: ARRAY [INTEGER]   find_ludic_numbers -- Ludic numbers in array ludic_numbers. local count: INTEGER new_array: ARRAY [INTEGER] last: INTEGER do create new_array.make_from_array (initial) last := initial.count from count := 1 until count > last loop if ludic_numbers [ludic_numbers.count] /= new_array [1] then ludic_numbers.force (new_array [1], count + 1) end new_array := delete_i_elements (new_array) count := count + 1 end end   delete_i_elements (ar: ARRAY [INTEGER]): ARRAY [INTEGER] --- Array with all multiples of 'ar[1]' deleted. require ar_not_empty: ar.count > 0 local s_array: ARRAY [INTEGER] i, k: INTEGER length: INTEGER do create s_array.make_empty length := ar.count from i := 0 k := 1 until i = length loop if (i) \\ (ar [1]) /= 0 then s_array.force (ar [i + 1], k) k := k + 1 end i := i + 1 end if s_array.count = 0 then Result := ar else Result := s_array end ensure not_empty: not Result.is_empty end   end  
http://rosettacode.org/wiki/Lucas-Lehmer_test
Lucas-Lehmer test
Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2 − 2 {\displaystyle S(n+1)=(S(n))^{2}-2} , and S ( 1 ) = 4 {\displaystyle S(1)=4} . Task Calculate all Mersenne primes up to the implementation's maximum precision, or the 47th Mersenne prime   (whichever comes first).
#360_Assembly
360 Assembly
* Lucas-Lehmer test LUCASLEH CSECT USING LUCASLEH,R12 SAVEARA B STM-SAVEARA(R15) DC 17F'0' DC CL8'LUCASLEH' STM STM R14,R12,12(R13) save calling context ST R13,4(R15) ST R15,8(R13) LR R12,R15 set addessability * ---- CODE LA R2,2 R2=2 LA R11,0 R11:N' BCTR R11,0 N':=X'FFFFFFFF' LA R10,1 R10:N N=1 LA R4,1 R4:IEXP LA R6,1 step LH R7,IEXPMAX R7:IEXPMAX limit LOOPE BXH R4,R6,ENDLOOPE do iexp=2 to iexpmax SR R3,R3 R3:S S=0 CR R4,R2 if iexp=2 then S=0 BE OKS LA R3,4 else S=4 OKS EQU * SLDA R10,1 n=(n+1)*2-1 LA R5,0 I LA R8,1 step LR R9,R4 IEXP SR R9,R2 IEXP-2 limit LOOPI BXH R5,R8,ENDLOOPI do i=1 to iexp-2 * ---- compute s=(s*s-2) MOD n SR R14,R14 R14=0 LR R15,R3 R15=S MR R14,R3 R{14-15}=S*S SLR R15,R2 R15=R15-2=S*S-2 BNM *+6 skip next if no borrow BCTR R14,0 perform borrow DR R14,R10 R10=N LR R3,R14 R14=MOD B LOOPI ENDLOOPI EQU * LTR R3,R3 BNZ NOPRT if s<>0 then no print CVD R4,P store to packed P UNPK Z,P Z=P MVC C,Z C=Z OI C+L'C-1,X'F0' zap sign MVC WTOBUF(4),C+12 MVI WTOBUF,C'M' WTO MF=(E,WTOMSG) NOPRT EQU * B LOOPE ENDLOOPE EQU * * ---- END CODE RETURN EQU * LM R14,R12,12(R13) XR R15,R15 BR R14 * ---- DATA IEXPMAX DC H'31' I DS H IEXP DS H S DS F N DS F P DS PL8 packed Z DS ZL16 zoned C DS CL16 character WTOMSG DS 0F DC H'80',XL2'0000' WTOBUF DC 80C' ' LTORG YREGS END LUCASLEH
http://rosettacode.org/wiki/Lucky_and_even_lucky_numbers
Lucky and even lucky numbers
Note that in the following explanation list indices are assumed to start at one. Definition of lucky numbers Lucky numbers are positive integers that are formed by: Form a list of all the positive odd integers > 0 1 , 3 , 5 , 7 , 9 , 11 , 13 , 15 , 17 , 19 , 21 , 23 , 25 , 27 , 29 , 31 , 33 , 35 , 37 , 39... {\displaystyle 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39...} Return the first number from the list (which is 1). (Loop begins here) Note then return the second number from the list (which is 3). Discard every third, (as noted), number from the list to form the new list 1 , 3 , 7 , 9 , 13 , 15 , 19 , 21 , 25 , 27 , 31 , 33 , 37 , 39 , 43 , 45 , 49 , 51 , 55 , 57... {\displaystyle 1,3,7,9,13,15,19,21,25,27,31,33,37,39,43,45,49,51,55,57...} (Expanding the loop a few more times...) Note then return the third number from the list (which is 7). Discard every 7th, (as noted), number from the list to form the new list 1 , 3 , 7 , 9 , 13 , 15 , 21 , 25 , 27 , 31 , 33 , 37 , 43 , 45 , 49 , 51 , 55 , 57 , 63 , 67... {\displaystyle 1,3,7,9,13,15,21,25,27,31,33,37,43,45,49,51,55,57,63,67...} Note then return the 4th number from the list (which is 9). Discard every 9th, (as noted), number from the list to form the new list 1 , 3 , 7 , 9 , 13 , 15 , 21 , 25 , 31 , 33 , 37 , 43 , 45 , 49 , 51 , 55 , 63 , 67 , 69 , 73... {\displaystyle 1,3,7,9,13,15,21,25,31,33,37,43,45,49,51,55,63,67,69,73...} Take the 5th, i.e. 13. Remove every 13th. Take the 6th, i.e. 15. Remove every 15th. Take the 7th, i.e. 21. Remove every 21th. Take the 8th, i.e. 25. Remove every 25th. (Rule for the loop) Note the n {\displaystyle n} th, which is m {\displaystyle m} . Remove every m {\displaystyle m} th. Increment n {\displaystyle n} . Definition of even lucky numbers This follows the same rules as the definition of lucky numbers above except for the very first step: Form a list of all the positive even integers > 0 2 , 4 , 6 , 8 , 10 , 12 , 14 , 16 , 18 , 20 , 22 , 24 , 26 , 28 , 30 , 32 , 34 , 36 , 38 , 40... {\displaystyle 2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40...} Return the first number from the list (which is 2). (Loop begins here) Note then return the second number from the list (which is 4). Discard every 4th, (as noted), number from the list to form the new list 2 , 4 , 6 , 10 , 12 , 14 , 18 , 20 , 22 , 26 , 28 , 30 , 34 , 36 , 38 , 42 , 44 , 46 , 50 , 52... {\displaystyle 2,4,6,10,12,14,18,20,22,26,28,30,34,36,38,42,44,46,50,52...} (Expanding the loop a few more times...) Note then return the third number from the list (which is 6). Discard every 6th, (as noted), number from the list to form the new list 2 , 4 , 6 , 10 , 12 , 18 , 20 , 22 , 26 , 28 , 34 , 36 , 38 , 42 , 44 , 50 , 52 , 54 , 58 , 60... {\displaystyle 2,4,6,10,12,18,20,22,26,28,34,36,38,42,44,50,52,54,58,60...} Take the 4th, i.e. 10. Remove every 10th. Take the 5th, i.e. 12. Remove every 12th. (Rule for the loop) Note the n {\displaystyle n} th, which is m {\displaystyle m} . Remove every m {\displaystyle m} th. Increment n {\displaystyle n} . Task requirements Write one or two subroutines (functions) to generate lucky numbers and even lucky numbers Write a command-line interface to allow selection of which kind of numbers and which number(s). Since input is from the command line, tests should be made for the common errors: missing arguments too many arguments number (or numbers) aren't legal misspelled argument (lucky or evenLucky) The command line handling should: support mixed case handling of the (non-numeric) arguments support printing a particular number support printing a range of numbers by their index support printing a range of numbers by their values The resulting list of numbers should be printed on a single line. The program should support the arguments: what is displayed (on a single line) argument(s) (optional verbiage is encouraged) ╔═══════════════════╦════════════════════════════════════════════════════╗ ║ j ║ Jth lucky number ║ ║ j , lucky ║ Jth lucky number ║ ║ j , evenLucky ║ Jth even lucky number ║ ║ ║ ║ ║ j k ║ Jth through Kth (inclusive) lucky numbers ║ ║ j k lucky ║ Jth through Kth (inclusive) lucky numbers ║ ║ j k evenLucky ║ Jth through Kth (inclusive) even lucky numbers ║ ║ ║ ║ ║ j -k ║ all lucky numbers in the range j ──► |k| ║ ║ j -k lucky ║ all lucky numbers in the range j ──► |k| ║ ║ j -k evenLucky ║ all even lucky numbers in the range j ──► |k| ║ ╚═══════════════════╩════════════════════════════════════════════════════╝ where |k| is the absolute value of k Demonstrate the program by: showing the first twenty lucky numbers showing the first twenty even lucky numbers showing all lucky numbers between 6,000 and 6,100 (inclusive) showing all even lucky numbers in the same range as above showing the 10,000th lucky number (extra credit) showing the 10,000th even lucky number (extra credit) See also This task is related to the Sieve of Eratosthenes task. OEIS Wiki Lucky numbers. Sequence A000959 lucky numbers on The On-Line Encyclopedia of Integer Sequences. Sequence A045954 even lucky numbers or ELN on The On-Line Encyclopedia of Integer Sequences. Entry lucky numbers on The Eric Weisstein's World of Mathematics.
#11l
11l
-V NoValue = 0   F initLuckyNumbers(nelems, evenlucky, limit = -1) [Int] result L(i) 0 .< nelems V k = i L(j) (result.len - 1 .< 0).step(-1) k = k * result[j] I/ (result[j] - 1) V n = 2 * k + 1 + evenlucky I limit != -1 & n > limit L.break result.append(n) R result   F name(evenlucky) R [‘Lucky’, ‘Even lucky’][evenlucky]   F printSingle(j, evenlucky) V luckySeq = initLuckyNumbers(j, evenlucky) print(name(evenlucky)‘ number at index ’j‘ is ’luckySeq[j - 1])   F printRange(j, k, evenlucky) V luckySeq = initLuckyNumbers(k, evenlucky) print(name(evenlucky)‘ numbers at indexes ’j‘ to ’k‘ are: ’, end' ‘’) L(idx) j - 1 .< k I idx != j - 1 print(‘, ’, end' ‘’) print(luckySeq[idx], end' ‘’) print()   F printInRange(j, k, evenlucky) V luckySeq = initLuckyNumbers(k, evenlucky, k) print(name(evenlucky)‘ numbers between ’j‘ to ’k‘ are: ’, end' ‘’) V first = 1B L(val) luckySeq I val > j I first first = 0B E print(‘, ’, end' ‘’) print(val, end' ‘’) print()   F process_args(args) assert(args.len C 1..3, ‘Wrong number of arguments’)   // First argument: "j" value. V j = Int(args[0])   V k = NoValue // Second argument: "k" value or a comma. I args.len > 1 I args[1] == ‘,’ // Must be followed by the kind of lucky number. assert(args.len == 3, ‘Missing kind argument’) E k = Int(args[1]) assert(k != 0, ‘Expected a non null number’)   V evenlucky = 0 // Third argument: number kind. I args.len == 3 V kind = args[2].lowercase() assert(kind C (‘lucky’, ‘evenlucky’), ‘Wrong kind’) I kind == ‘evenlucky’ evenlucky = 1   I k == NoValue // Print jth value. printSingle(j, evenlucky) E I k > 0 // Print jth to kth values. printRange(j, k, evenlucky) E // Print values in range j..(-k). printInRange(j, -k, evenlucky)   :start: I 1B L(args) [‘1 20’, ‘1 20 evenlucky’, ‘6000 -6100’, ‘6000 -6100 evenlucky’, ‘10000’, ‘10000 , lucky’, ‘10000 , evenlucky’] print(‘Command line arguments: ’args) process_args(args.split(‘ ’)) print() E process_args(:argv[1..])
http://rosettacode.org/wiki/LZW_compression
LZW compression
The Lempel-Ziv-Welch (LZW) algorithm provides loss-less data compression. You can read a complete description of it in the   Wikipedia article   on the subject.   It was patented, but it entered the public domain in 2004.
#11l
11l
F compress(uncompressed) V dict_size = 256 V dictionary = Dict((0 .< dict_size).map(i -> (String(Char(code' i)), i))) V w = ‘’ [Int] result L(c) uncompressed V wc = w‘’c I wc C dictionary w = wc E result.append(dictionary[w]) dictionary[wc] = dict_size dict_size++ w = c   I !w.empty result.append(dictionary[w])   R result   F decompress([Int] &compressed) V dict_size = 256 V dictionary = Dict((0 .< dict_size).map(i -> (i, String(Char(code' i))))) V result = ‘’ V w = String(Char(code' compressed.pop(0))) result ‘’= w L(k) compressed V entry = ‘’ I k C dictionary entry = dictionary[k] E I k == dict_size entry = w‘’w[0] E exit(‘Bad compressed k: ’k) result ‘’= entry dictionary[dict_size] = w‘’entry[0] dict_size++ w = entry   R result   V compressed = compress(‘TOBEORNOTTOBEORTOBEORNOT’) print(compressed) print(decompress(&compressed))
http://rosettacode.org/wiki/LU_decomposition
LU decomposition
Every square matrix A {\displaystyle A} can be decomposed into a product of a lower triangular matrix L {\displaystyle L} and a upper triangular matrix U {\displaystyle U} , as described in LU decomposition. A = L U {\displaystyle A=LU} It is a modified form of Gaussian elimination. While the Cholesky decomposition only works for symmetric, positive definite matrices, the more general LU decomposition works for any square matrix. There are several algorithms for calculating L and U. To derive Crout's algorithm for a 3x3 example, we have to solve the following system: A = ( a 11 a 12 a 13 a 21 a 22 a 23 a 31 a 32 a 33 ) = ( l 11 0 0 l 21 l 22 0 l 31 l 32 l 33 ) ( u 11 u 12 u 13 0 u 22 u 23 0 0 u 33 ) = L U {\displaystyle A={\begin{pmatrix}a_{11}&a_{12}&a_{13}\\a_{21}&a_{22}&a_{23}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}={\begin{pmatrix}l_{11}&0&0\\l_{21}&l_{22}&0\\l_{31}&l_{32}&l_{33}\\\end{pmatrix}}{\begin{pmatrix}u_{11}&u_{12}&u_{13}\\0&u_{22}&u_{23}\\0&0&u_{33}\end{pmatrix}}=LU} We now would have to solve 9 equations with 12 unknowns. To make the system uniquely solvable, usually the diagonal elements of L {\displaystyle L} are set to 1 l 11 = 1 {\displaystyle l_{11}=1} l 22 = 1 {\displaystyle l_{22}=1} l 33 = 1 {\displaystyle l_{33}=1} so we get a solvable system of 9 unknowns and 9 equations. A = ( a 11 a 12 a 13 a 21 a 22 a 23 a 31 a 32 a 33 ) = ( 1 0 0 l 21 1 0 l 31 l 32 1 ) ( u 11 u 12 u 13 0 u 22 u 23 0 0 u 33 ) = ( u 11 u 12 u 13 u 11 l 21 u 12 l 21 + u 22 u 13 l 21 + u 23 u 11 l 31 u 12 l 31 + u 22 l 32 u 13 l 31 + u 23 l 32 + u 33 ) = L U {\displaystyle A={\begin{pmatrix}a_{11}&a_{12}&a_{13}\\a_{21}&a_{22}&a_{23}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}={\begin{pmatrix}1&0&0\\l_{21}&1&0\\l_{31}&l_{32}&1\\\end{pmatrix}}{\begin{pmatrix}u_{11}&u_{12}&u_{13}\\0&u_{22}&u_{23}\\0&0&u_{33}\end{pmatrix}}={\begin{pmatrix}u_{11}&u_{12}&u_{13}\\u_{11}l_{21}&u_{12}l_{21}+u_{22}&u_{13}l_{21}+u_{23}\\u_{11}l_{31}&u_{12}l_{31}+u_{22}l_{32}&u_{13}l_{31}+u_{23}l_{32}+u_{33}\end{pmatrix}}=LU} Solving for the other l {\displaystyle l} and u {\displaystyle u} , we get the following equations: u 11 = a 11 {\displaystyle u_{11}=a_{11}} u 12 = a 12 {\displaystyle u_{12}=a_{12}} u 13 = a 13 {\displaystyle u_{13}=a_{13}} u 22 = a 22 − u 12 l 21 {\displaystyle u_{22}=a_{22}-u_{12}l_{21}} u 23 = a 23 − u 13 l 21 {\displaystyle u_{23}=a_{23}-u_{13}l_{21}} u 33 = a 33 − ( u 13 l 31 + u 23 l 32 ) {\displaystyle u_{33}=a_{33}-(u_{13}l_{31}+u_{23}l_{32})} and for l {\displaystyle l} : l 21 = 1 u 11 a 21 {\displaystyle l_{21}={\frac {1}{u_{11}}}a_{21}} l 31 = 1 u 11 a 31 {\displaystyle l_{31}={\frac {1}{u_{11}}}a_{31}} l 32 = 1 u 22 ( a 32 − u 12 l 31 ) {\displaystyle l_{32}={\frac {1}{u_{22}}}(a_{32}-u_{12}l_{31})} We see that there is a calculation pattern, which can be expressed as the following formulas, first for U {\displaystyle U} u i j = a i j − ∑ k = 1 i − 1 u k j l i k {\displaystyle u_{ij}=a_{ij}-\sum _{k=1}^{i-1}u_{kj}l_{ik}} and then for L {\displaystyle L} l i j = 1 u j j ( a i j − ∑ k = 1 j − 1 u k j l i k ) {\displaystyle l_{ij}={\frac {1}{u_{jj}}}(a_{ij}-\sum _{k=1}^{j-1}u_{kj}l_{ik})} We see in the second formula that to get the l i j {\displaystyle l_{ij}} below the diagonal, we have to divide by the diagonal element (pivot) u j j {\displaystyle u_{jj}} , so we get problems when u j j {\displaystyle u_{jj}} is either 0 or very small, which leads to numerical instability. The solution to this problem is pivoting A {\displaystyle A} , which means rearranging the rows of A {\displaystyle A} , prior to the L U {\displaystyle LU} decomposition, in a way that the largest element of each column gets onto the diagonal of A {\displaystyle A} . Rearranging the rows means to multiply A {\displaystyle A} by a permutation matrix P {\displaystyle P} : P A ⇒ A ′ {\displaystyle PA\Rightarrow A'} Example: ( 0 1 1 0 ) ( 1 4 2 3 ) ⇒ ( 2 3 1 4 ) {\displaystyle {\begin{pmatrix}0&1\\1&0\end{pmatrix}}{\begin{pmatrix}1&4\\2&3\end{pmatrix}}\Rightarrow {\begin{pmatrix}2&3\\1&4\end{pmatrix}}} The decomposition algorithm is then applied on the rearranged matrix so that P A = L U {\displaystyle PA=LU} Task description The task is to implement a routine which will take a square nxn matrix A {\displaystyle A} and return a lower triangular matrix L {\displaystyle L} , a upper triangular matrix U {\displaystyle U} and a permutation matrix P {\displaystyle P} , so that the above equation is fulfilled. You should then test it on the following two examples and include your output. Example 1 A 1 3 5 2 4 7 1 1 0 L 1.00000 0.00000 0.00000 0.50000 1.00000 0.00000 0.50000 -1.00000 1.00000 U 2.00000 4.00000 7.00000 0.00000 1.00000 1.50000 0.00000 0.00000 -2.00000 P 0 1 0 1 0 0 0 0 1 Example 2 A 11 9 24 2 1 5 2 6 3 17 18 1 2 5 7 1 L 1.00000 0.00000 0.00000 0.00000 0.27273 1.00000 0.00000 0.00000 0.09091 0.28750 1.00000 0.00000 0.18182 0.23125 0.00360 1.00000 U 11.00000 9.00000 24.00000 2.00000 0.00000 14.54545 11.45455 0.45455 0.00000 0.00000 -3.47500 5.68750 0.00000 0.00000 0.00000 0.51079 P 1 0 0 0 0 0 1 0 0 1 0 0 0 0 0 1
#11l
11l
F pprint(m) L(row) m print(row)   F matrix_mul(a, b) V result = [[0.0] * a.len] * a.len L(j) 0 .< a.len L(i) 0 .< a.len V r = 0.0 L(k) 0 .< a.len r += a[i][k] * b[k][j] result[i][j] = r R result   F pivotize(m) ‘Creates the pivoting matrix for m.’ V n = m.len V ID = (0 .< n).map(j -> (0 .< @n).map(i -> Float(i == @j))) L(j) 0 .< n V row = max(j .< n, key' i -> abs(@m[i][@j])) I j != row swap(&ID[j], &ID[row]) R ID   F lu(A) ‘Decomposes a nxn matrix A by PA=lU and returns l, U and P.’ V n = A.len V l = [[0.0] * n] * n V U = [[0.0] * n] * n V P = pivotize(A) V A2 = matrix_mul(P, A) L(j) 0 .< n l[j][j] = 1.0 L(i) 0 .. j V s1 = sum((0 .< i).map(k -> @U[k][@j] * @l[@i][k])) U[i][j] = A2[i][j] - s1 L(i) j .< n V s2 = sum((0 .< j).map(k -> @U[k][@j] * @l[@i][k])) l[i][j] = (A2[i][j] - s2) / U[j][j] R (l, U, P)   V a = [[1, 3, 5], [2, 4, 7], [1, 1, 0]] L(part) lu(a) pprint(part) print() print() V b = [[11, 9, 24, 2], [1, 5, 2, 6], [3, 17, 18, 1], [2, 5, 7, 1]] L(part) lu(b) pprint(part) print()
http://rosettacode.org/wiki/Lychrel_numbers
Lychrel numbers
  Take an integer n, greater than zero.   Form the next n of its series by reversing the digits of the current n and adding the result to the current n.   Stop when n becomes palindromic - i.e. the digits of n in reverse order == n. The above recurrence relation when applied to most starting numbers n = 1, 2, ... terminates in a palindrome quite quickly. Example If n0 = 12 we get 12 12 + 21 = 33, a palindrome! And if n0 = 55 we get 55 55 + 55 = 110 110 + 011 = 121, a palindrome! Notice that the check for a palindrome happens   after   an addition. Some starting numbers seem to go on forever; the recurrence relation for 196 has been calculated for millions of repetitions forming numbers with millions of digits, without forming a palindrome. These numbers that do not end in a palindrome are called Lychrel numbers. For the purposes of this task a Lychrel number is any starting number that does not form a palindrome within 500 (or more) iterations. Seed and related Lychrel numbers Any integer produced in the sequence of a Lychrel number is also a Lychrel number. In general, any sequence from one Lychrel number might converge to join the sequence from a prior Lychrel number candidate; for example the sequences for the numbers 196 and then 689 begin: 196 196 + 691 = 887 887 + 788 = 1675 1675 + 5761 = 7436 7436 + 6347 = 13783 13783 + 38731 = 52514 52514 + 41525 = 94039 ... 689 689 + 986 = 1675 1675 + 5761 = 7436 ... So we see that the sequence starting with 689 converges to, and continues with the same numbers as that for 196. Because of this we can further split the Lychrel numbers into true Seed Lychrel number candidates, and Related numbers that produce no palindromes but have integers in their sequence seen as part of the sequence generated from a lower Lychrel number. Task   Find the number of seed Lychrel number candidates and related numbers for n in the range 1..10000 inclusive. (With that iteration limit of 500).   Print the number of seed Lychrels found; the actual seed Lychrels; and just the number of relateds found.   Print any seed Lychrel or related number that is itself a palindrome. Show all output here. References   What's special about 196? Numberphile video.   A023108 Positive integers which apparently never result in a palindrome under repeated applications of the function f(x) = x + (x with digits reversed).   Status of the 196 conjecture? Mathoverflow.
#Crystal
Crystal
require "set" require "big"   def add_reverse(num, max_iter=1000) num = num.to_big_i nums = [] of BigInt (1..max_iter).each_with_object(Set.new([num])) do |_, nums| num += reverse_int(num) nums << num return nums if palindrome?(num) end end   def palindrome?(num) num == reverse_int(num) end   def reverse_int(num) num.to_s.reverse.to_big_i end   def split_roots_from_relateds(roots_and_relateds) roots = roots_and_relateds.dup i = 1 while i < roots.size this = roots[i] if roots[0...i].any?{ |prev| this.intersects?(prev) } roots.delete_at(i) else i += 1 end end root = roots.map{ |each_set| each_set.min } related = roots_and_relateds.map{ |each_set| each_set.min } related = related.reject{ |n| root.includes?(n) } return root, related end   def find_lychrel(maxn, max_reversions) series = (1..maxn).map{ |n| add_reverse(n, max_reversions*2) } roots_and_relateds = series.select{ |s| s.size > max_reversions } split_roots_from_relateds(roots_and_relateds) end   maxn, reversion_limit = 10000, 500 puts "Calculations using n = 1..#{maxn} and limiting each search to 2*#{reversion_limit} reverse-digits-and-adds" lychrel, l_related = find_lychrel(maxn, reversion_limit) puts " Number of Lychrel numbers: #{lychrel.size}" puts " Lychrel numbers: #{lychrel}" puts " Number of Lychrel related: #{l_related.size}" pals = (lychrel + l_related).select{|x| palindrome?(x)}.sort puts " Number of Lychrel palindromes: #{pals.size}" puts " Lychrel palindromes: #{pals}"
http://rosettacode.org/wiki/Magic_8-ball
Magic 8-ball
Task Create Magic 8-Ball. See details at:   Magic 8-Ball. 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
#PHP
PHP
<?php   $fortunes = array( "It is certain", "It is decidedly so", "Without a doubt", "Yes, definitely", "You may rely on it", "As I see it, yes", "Most likely", "Outlook good", "Signs point to yes", "Yes", "Reply hazy, try again", "Ask again later", "Better not tell you now", "Cannot predict now", "Concentrate and ask again", "Don't bet on it", "My reply is no", "My sources say no", "Outlook not so good", "Very doubtful" );   /* * Prompt the user at the CLI for the command */ function cli_prompt( $prompt='> ', $default=false ) {   // keep asking until a non-empty response is given do { // display the prompt echo $prompt;   // read input and remove CRLF $cmd = chop( fgets( STDIN ) );   } while ( empty( $default ) and empty( $cmd ) );   return $cmd ?: $default;   }   $question = cli_prompt( 'What is your question? ' );   echo 'Q: ', $question, PHP_EOL;   echo 'A: ', $fortunes[ array_rand( $fortunes ) ], PHP_EOL;  
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#TI-83_BASIC
TI-83 BASIC
PROGRAM:MANDELBR :Input "ITER. ",D :For(A,Xmin,Xmax,ΔX) :For(B,Ymin,Ymax,ΔY) :0→X :0→Y :0→I :D→M :While X^2+Y^2≤4 and I<M :X^2-Y^2+A→R :2XY+B→Y :R→X :I+1→I :End :If I≠M :Then :I→C :Else :0→C :End :If C<1 :Pt-On(A,B) :End :End :End  
http://rosettacode.org/wiki/Mad_Libs
Mad Libs
This page uses content from Wikipedia. The original article was at Mad Libs. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Mad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results. Task; Write a program to create a Mad Libs like story. The program should read an arbitrary multiline story from input. The story will be terminated with a blank line. Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements. Stop when there are none left and print the final story. The input should be an arbitrary story in the form: <name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home. Given this example, it should then ask for a name, a he or she and a noun (<name> gets replaced both times with the same value). Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#C.23
C#
using System; using System.Linq; using System.Text; using System.Text.RegularExpressions;   namespace MadLibs_RosettaCode { class Program { static void Main(string[] args) { string madLibs = @"Write a program to create a Mad Libs like story. The program should read an arbitrary multiline story from input. The story will be terminated with a blank line. Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements. Stop when there are none left and print the final story. The input should be an arbitrary story in the form: <name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home. Given this example, it should then ask for a name, a he or she and a noun (<name> gets replaced both times with the same value).";   StringBuilder sb = new StringBuilder(); Regex pattern = new Regex(@"\<(.*?)\>"); string storyLine; string replacement;   Console.WriteLine(madLibs + Environment.NewLine + Environment.NewLine); Console.WriteLine("Enter a story: ");   // Continue to get input while empty line hasn't been entered. do { storyLine = Console.ReadLine(); sb.Append(storyLine + Environment.NewLine); } while (!string.IsNullOrEmpty(storyLine) && !string.IsNullOrWhiteSpace(storyLine));   // Retrieve only the unique regex matches from the user entered story. Match nameMatch = pattern.Matches(sb.ToString()).OfType<Match>().Where(x => x.Value.Equals("<name>")).Select(x => x.Value).Distinct() as Match; if(nameMatch != null) { do { Console.WriteLine("Enter value for: " + nameMatch.Value); replacement = Console.ReadLine(); } while (string.IsNullOrEmpty(replacement) || string.IsNullOrWhiteSpace(replacement)); sb.Replace(nameMatch.Value, replacement); }   foreach (Match match in pattern.Matches(sb.ToString())) { replacement = string.Empty; // Guarantee we get a non-whitespace value for the replacement do { Console.WriteLine("Enter value for: " + match.Value); replacement = Console.ReadLine(); } while (string.IsNullOrEmpty(replacement) || string.IsNullOrWhiteSpace(replacement));   int location = sb.ToString().IndexOf(match.Value); sb.Remove(location, match.Value.Length).Insert(location, replacement); }   Console.WriteLine(Environment.NewLine + Environment.NewLine + "--[ Here's your story! ]--"); Console.WriteLine(sb.ToString()); } } }  
http://rosettacode.org/wiki/Ludic_numbers
Ludic numbers
Ludic numbers   are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers. The first ludic number is   1. To generate succeeding ludic numbers create an array of increasing integers starting from   2. 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... (Loop) Take the first member of the resultant array as the next ludic number   2. Remove every   2nd   indexed item from the array (including the first). 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... (Unrolling a few loops...) Take the first member of the resultant array as the next ludic number   3. Remove every   3rd   indexed item from the array (including the first). 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 ... Take the first member of the resultant array as the next ludic number   5. Remove every   5th   indexed item from the array (including the first). 5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 ... Take the first member of the resultant array as the next ludic number   7. Remove every   7th   indexed item from the array (including the first). 7 11 13 17 23 25 29 31 37 41 43 47 53 55 59 61 67 71 73 77 83 85 89 91 97 ... ... Take the first member of the current array as the next ludic number   L. Remove every   Lth   indexed item from the array (including the first). ... Task Generate and show here the first 25 ludic numbers. How many ludic numbers are there less than or equal to 1000? Show the 2000..2005th ludic numbers. Stretch goal Show all triplets of ludic numbers < 250. A triplet is any three numbers     x , {\displaystyle x,}   x + 2 , {\displaystyle x+2,}   x + 6 {\displaystyle x+6}     where all three numbers are also ludic numbers.
#Eiffel
Eiffel
  class LUDIC_NUMBERS   create make   feature   make (n: INTEGER) -- Initialized arrays for find_ludic_numbers. require n_positive: n > 0 local i: INTEGER do create initial.make_filled (0, 1, n - 1) create ludic_numbers.make_filled (1, 1, 1) from i := 2 until i > n loop initial.put (i, i - 1) i := i + 1 end find_ludic_numbers end   ludic_numbers: ARRAY [INTEGER]   feature {NONE}   initial: ARRAY [INTEGER]   find_ludic_numbers -- Ludic numbers in array ludic_numbers. local count: INTEGER new_array: ARRAY [INTEGER] last: INTEGER do create new_array.make_from_array (initial) last := initial.count from count := 1 until count > last loop if ludic_numbers [ludic_numbers.count] /= new_array [1] then ludic_numbers.force (new_array [1], count + 1) end new_array := delete_i_elements (new_array) count := count + 1 end end   delete_i_elements (ar: ARRAY [INTEGER]): ARRAY [INTEGER] --- Array with all multiples of 'ar[1]' deleted. require ar_not_empty: ar.count > 0 local s_array: ARRAY [INTEGER] i, k: INTEGER length: INTEGER do create s_array.make_empty length := ar.count from i := 0 k := 1 until i = length loop if (i) \\ (ar [1]) /= 0 then s_array.force (ar [i + 1], k) k := k + 1 end i := i + 1 end if s_array.count = 0 then Result := ar else Result := s_array end ensure not_empty: not Result.is_empty end   end  
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
Luhn test of credit card numbers
The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of the digits in the number. Take the first, third, ... and every other odd digit in the reversed digits and sum them to form the partial sum s1 Taking the second, fourth ... and every other even digit in the reversed digits: Multiply each digit by two and sum the digits if the answer is greater than nine to form partial sums for the even digits Sum the partial sums of the even digits to form s2 If s1 + s2 ends in zero then the original number is in the form of a valid credit card number as verified by the Luhn test. For example, if the trial number is 49927398716: Reverse the digits: 61789372994 Sum the odd digits: 6 + 7 + 9 + 7 + 9 + 4 = 42 = s1 The even digits: 1, 8, 3, 2, 9 Two times each even digit: 2, 16, 6, 4, 18 Sum the digits of each multiplication: 2, 7, 6, 4, 9 Sum the last: 2 + 7 + 6 + 4 + 9 = 28 = s2 s1 + s2 = 70 which ends in zero which means that 49927398716 passes the Luhn test Task Write a function/method/procedure/subroutine that will validate a number with the Luhn test, and use it to validate the following numbers: 49927398716 49927398717 1234567812345678 1234567812345670 Related tasks   SEDOL   ISIN
#11l
11l
F luhn(n) V ch = String(n) V sum = 0 V chParity = ch.len % 2 L(i) (ch.len-1 .. 0).step(-1) V j = Int(ch[i]) I (i + 1) % 2 != chParity j *= 2 I j > 9 j -= 9 sum += j R sum % 10 == 0   L(n) (49927398716, 49927398717, 1234567812345678, 1234567812345670) print(luhn(n))
http://rosettacode.org/wiki/Lucas-Lehmer_test
Lucas-Lehmer test
Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2 − 2 {\displaystyle S(n+1)=(S(n))^{2}-2} , and S ( 1 ) = 4 {\displaystyle S(1)=4} . Task Calculate all Mersenne primes up to the implementation's maximum precision, or the 47th Mersenne prime   (whichever comes first).
#Ada
Ada
with Ada.Text_Io; use Ada.Text_Io; with Ada.Integer_Text_Io; use Ada.Integer_Text_Io;   procedure Lucas_Lehmer_Test is type Ull is mod 2**64; function Mersenne(Item : Integer) return Boolean is S : Ull := 4; MP : Ull := 2**Item - 1; begin if Item = 2 then return True; else for I in 3..Item loop S := (S * S - 2) mod MP; end loop; return S = 0; end if; end Mersenne; Upper_Bound : constant Integer := 64; begin Put_Line(" Mersenne primes:"); for P in 2..Upper_Bound loop if Mersenne(P) then Put(" M"); Put(Item => P, Width => 1); end if; end loop; end Lucas_Lehmer_Test;
http://rosettacode.org/wiki/Lucky_and_even_lucky_numbers
Lucky and even lucky numbers
Note that in the following explanation list indices are assumed to start at one. Definition of lucky numbers Lucky numbers are positive integers that are formed by: Form a list of all the positive odd integers > 0 1 , 3 , 5 , 7 , 9 , 11 , 13 , 15 , 17 , 19 , 21 , 23 , 25 , 27 , 29 , 31 , 33 , 35 , 37 , 39... {\displaystyle 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39...} Return the first number from the list (which is 1). (Loop begins here) Note then return the second number from the list (which is 3). Discard every third, (as noted), number from the list to form the new list 1 , 3 , 7 , 9 , 13 , 15 , 19 , 21 , 25 , 27 , 31 , 33 , 37 , 39 , 43 , 45 , 49 , 51 , 55 , 57... {\displaystyle 1,3,7,9,13,15,19,21,25,27,31,33,37,39,43,45,49,51,55,57...} (Expanding the loop a few more times...) Note then return the third number from the list (which is 7). Discard every 7th, (as noted), number from the list to form the new list 1 , 3 , 7 , 9 , 13 , 15 , 21 , 25 , 27 , 31 , 33 , 37 , 43 , 45 , 49 , 51 , 55 , 57 , 63 , 67... {\displaystyle 1,3,7,9,13,15,21,25,27,31,33,37,43,45,49,51,55,57,63,67...} Note then return the 4th number from the list (which is 9). Discard every 9th, (as noted), number from the list to form the new list 1 , 3 , 7 , 9 , 13 , 15 , 21 , 25 , 31 , 33 , 37 , 43 , 45 , 49 , 51 , 55 , 63 , 67 , 69 , 73... {\displaystyle 1,3,7,9,13,15,21,25,31,33,37,43,45,49,51,55,63,67,69,73...} Take the 5th, i.e. 13. Remove every 13th. Take the 6th, i.e. 15. Remove every 15th. Take the 7th, i.e. 21. Remove every 21th. Take the 8th, i.e. 25. Remove every 25th. (Rule for the loop) Note the n {\displaystyle n} th, which is m {\displaystyle m} . Remove every m {\displaystyle m} th. Increment n {\displaystyle n} . Definition of even lucky numbers This follows the same rules as the definition of lucky numbers above except for the very first step: Form a list of all the positive even integers > 0 2 , 4 , 6 , 8 , 10 , 12 , 14 , 16 , 18 , 20 , 22 , 24 , 26 , 28 , 30 , 32 , 34 , 36 , 38 , 40... {\displaystyle 2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40...} Return the first number from the list (which is 2). (Loop begins here) Note then return the second number from the list (which is 4). Discard every 4th, (as noted), number from the list to form the new list 2 , 4 , 6 , 10 , 12 , 14 , 18 , 20 , 22 , 26 , 28 , 30 , 34 , 36 , 38 , 42 , 44 , 46 , 50 , 52... {\displaystyle 2,4,6,10,12,14,18,20,22,26,28,30,34,36,38,42,44,46,50,52...} (Expanding the loop a few more times...) Note then return the third number from the list (which is 6). Discard every 6th, (as noted), number from the list to form the new list 2 , 4 , 6 , 10 , 12 , 18 , 20 , 22 , 26 , 28 , 34 , 36 , 38 , 42 , 44 , 50 , 52 , 54 , 58 , 60... {\displaystyle 2,4,6,10,12,18,20,22,26,28,34,36,38,42,44,50,52,54,58,60...} Take the 4th, i.e. 10. Remove every 10th. Take the 5th, i.e. 12. Remove every 12th. (Rule for the loop) Note the n {\displaystyle n} th, which is m {\displaystyle m} . Remove every m {\displaystyle m} th. Increment n {\displaystyle n} . Task requirements Write one or two subroutines (functions) to generate lucky numbers and even lucky numbers Write a command-line interface to allow selection of which kind of numbers and which number(s). Since input is from the command line, tests should be made for the common errors: missing arguments too many arguments number (or numbers) aren't legal misspelled argument (lucky or evenLucky) The command line handling should: support mixed case handling of the (non-numeric) arguments support printing a particular number support printing a range of numbers by their index support printing a range of numbers by their values The resulting list of numbers should be printed on a single line. The program should support the arguments: what is displayed (on a single line) argument(s) (optional verbiage is encouraged) ╔═══════════════════╦════════════════════════════════════════════════════╗ ║ j ║ Jth lucky number ║ ║ j , lucky ║ Jth lucky number ║ ║ j , evenLucky ║ Jth even lucky number ║ ║ ║ ║ ║ j k ║ Jth through Kth (inclusive) lucky numbers ║ ║ j k lucky ║ Jth through Kth (inclusive) lucky numbers ║ ║ j k evenLucky ║ Jth through Kth (inclusive) even lucky numbers ║ ║ ║ ║ ║ j -k ║ all lucky numbers in the range j ──► |k| ║ ║ j -k lucky ║ all lucky numbers in the range j ──► |k| ║ ║ j -k evenLucky ║ all even lucky numbers in the range j ──► |k| ║ ╚═══════════════════╩════════════════════════════════════════════════════╝ where |k| is the absolute value of k Demonstrate the program by: showing the first twenty lucky numbers showing the first twenty even lucky numbers showing all lucky numbers between 6,000 and 6,100 (inclusive) showing all even lucky numbers in the same range as above showing the 10,000th lucky number (extra credit) showing the 10,000th even lucky number (extra credit) See also This task is related to the Sieve of Eratosthenes task. OEIS Wiki Lucky numbers. Sequence A000959 lucky numbers on The On-Line Encyclopedia of Integer Sequences. Sequence A045954 even lucky numbers or ELN on The On-Line Encyclopedia of Integer Sequences. Entry lucky numbers on The Eric Weisstein's World of Mathematics.
#C
C
#include <stdbool.h> #include <stdio.h> #include <stdlib.h>   #define LUCKY_SIZE 60000 int luckyOdd[LUCKY_SIZE]; int luckyEven[LUCKY_SIZE];   void compactLucky(int luckyArray[]) { int i, j, k;   for (i = 0; i < LUCKY_SIZE; i++) { if (luckyArray[i] == 0) { j = i; break; } }   for (j = i + 1; j < LUCKY_SIZE; j++) { if (luckyArray[j] > 0) { luckyArray[i++] = luckyArray[j]; } }   for (; i < LUCKY_SIZE; i++) { luckyArray[i] = 0; } }   void initialize() { int i, j;   // unfiltered for (i = 0; i < LUCKY_SIZE; i++) { luckyEven[i] = 2 * i + 2; luckyOdd[i] = 2 * i + 1; }   // odd filter for (i = 1; i < LUCKY_SIZE; i++) { if (luckyOdd[i] > 0) { for (j = luckyOdd[i] - 1; j < LUCKY_SIZE; j += luckyOdd[i]) { luckyOdd[j] = 0; } compactLucky(luckyOdd); } }   // even filter for (i = 1; i < LUCKY_SIZE; i++) { if (luckyEven[i] > 0) { for (j = luckyEven[i] - 1; j < LUCKY_SIZE; j += luckyEven[i]) { luckyEven[j] = 0; } compactLucky(luckyEven); } } }   void printBetween(size_t j, size_t k, bool even) { int i;   if (even) { if (luckyEven[j] == 0 || luckyEven[k] == 0) { fprintf(stderr, "At least one argument is too large\n"); exit(EXIT_FAILURE); } printf("Lucky even numbers between %d and %d are:", j, k); for (i = 0; luckyEven[i] != 0; i++) { if (luckyEven[i] > k) { break; } if (luckyEven[i] > j) { printf(" %d", luckyEven[i]); } } } else { if (luckyOdd[j] == 0 || luckyOdd[k] == 0) { fprintf(stderr, "At least one argument is too large\n"); exit(EXIT_FAILURE); } printf("Lucky numbers between %d and %d are:", j, k); for (i = 0; luckyOdd[i] != 0; i++) { if (luckyOdd[i] > k) { break; } if (luckyOdd[i] > j) { printf(" %d", luckyOdd[i]); } } } printf("\n"); }   void printRange(size_t j, size_t k, bool even) { int i;   if (even) { if (luckyEven[k] == 0) { fprintf(stderr, "The argument is too large\n"); exit(EXIT_FAILURE); } printf("Lucky even numbers %d to %d are:", j, k); for (i = j - 1; i < k; i++) { printf(" %d", luckyEven[i]); } } else { if (luckyOdd[k] == 0) { fprintf(stderr, "The argument is too large\n"); exit(EXIT_FAILURE); } printf("Lucky numbers %d to %d are:", j, k); for (i = j - 1; i < k; i++) { printf(" %d", luckyOdd[i]); } } printf("\n"); }   void printSingle(size_t j, bool even) { if (even) { if (luckyEven[j] == 0) { fprintf(stderr, "The argument is too large\n"); exit(EXIT_FAILURE); } printf("Lucky even number %d=%d\n", j, luckyEven[j - 1]); } else { if (luckyOdd[j] == 0) { fprintf(stderr, "The argument is too large\n"); exit(EXIT_FAILURE); } printf("Lucky number %d=%d\n", j, luckyOdd[j - 1]); } }   void help() { printf("./lucky j [k] [--lucky|--evenLucky]\n"); printf("\n"); printf(" argument(s) | what is displayed\n"); printf("==============================================\n"); printf("-j=m | mth lucky number\n"); printf("-j=m --lucky | mth lucky number\n"); printf("-j=m --evenLucky | mth even lucky number\n"); printf("-j=m -k=n | mth through nth (inclusive) lucky numbers\n"); printf("-j=m -k=n --lucky | mth through nth (inclusive) lucky numbers\n"); printf("-j=m -k=n --evenLucky | mth through nth (inclusive) even lucky numbers\n"); printf("-j=m -k=-n | all lucky numbers in the range [m, n]\n"); printf("-j=m -k=-n --lucky | all lucky numbers in the range [m, n]\n"); printf("-j=m -k=-n --evenLucky | all even lucky numbers in the range [m, n]\n"); }   void process(int argc, char *argv[]) { bool evenLucky = false; int j = 0; int k = 0;   bool good = false; int i;   for (i = 1; i < argc; ++i) { if ('-' == argv[i][0]) { if ('-' == argv[i][1]) { // long args if (0 == strcmp("--lucky", argv[i])) { evenLucky = false; } else if (0 == strcmp("--evenLucky", argv[i])) { evenLucky = true; } else { fprintf(stderr, "Unknown long argument: [%s]\n", argv[i]); exit(EXIT_FAILURE); } } else { // short args if ('j' == argv[i][1] && '=' == argv[i][2] && argv[i][3] != 0) { good = true; j = atoi(&argv[i][3]); } else if ('k' == argv[i][1] && '=' == argv[i][2]) { k = atoi(&argv[i][3]); } else { fprintf(stderr, "Unknown short argument: [%s]\n", argv[i]); exit(EXIT_FAILURE); } } } else { fprintf(stderr, "Unknown argument: [%s]\n", argv[i]); exit(EXIT_FAILURE); } }   if (!good) { help(); exit(EXIT_FAILURE); }   if (k > 0) { printRange(j, k, evenLucky); } else if (k < 0) { printBetween(j, -k, evenLucky); } else { printSingle(j, evenLucky); } }   void test() { printRange(1, 20, false); printRange(1, 20, true);   printBetween(6000, 6100, false); printBetween(6000, 6100, true);   printSingle(10000, false); printSingle(10000, true); }   int main(int argc, char *argv[]) { initialize();   //test();   if (argc < 2) { help(); return 1; } process(argc, argv);   return 0; }
http://rosettacode.org/wiki/LZW_compression
LZW compression
The Lempel-Ziv-Welch (LZW) algorithm provides loss-less data compression. You can read a complete description of it in the   Wikipedia article   on the subject.   It was patented, but it entered the public domain in 2004.
#Ada
Ada
package LZW is   MAX_CODE : constant := 4095;   type Codes is new Natural range 0 .. MAX_CODE; type Compressed_Data is array (Positive range <>) of Codes;   function Compress (Cleartext : in String) return Compressed_Data; function Decompress (Data : in Compressed_Data) return String;   end LZW;
http://rosettacode.org/wiki/LU_decomposition
LU decomposition
Every square matrix A {\displaystyle A} can be decomposed into a product of a lower triangular matrix L {\displaystyle L} and a upper triangular matrix U {\displaystyle U} , as described in LU decomposition. A = L U {\displaystyle A=LU} It is a modified form of Gaussian elimination. While the Cholesky decomposition only works for symmetric, positive definite matrices, the more general LU decomposition works for any square matrix. There are several algorithms for calculating L and U. To derive Crout's algorithm for a 3x3 example, we have to solve the following system: A = ( a 11 a 12 a 13 a 21 a 22 a 23 a 31 a 32 a 33 ) = ( l 11 0 0 l 21 l 22 0 l 31 l 32 l 33 ) ( u 11 u 12 u 13 0 u 22 u 23 0 0 u 33 ) = L U {\displaystyle A={\begin{pmatrix}a_{11}&a_{12}&a_{13}\\a_{21}&a_{22}&a_{23}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}={\begin{pmatrix}l_{11}&0&0\\l_{21}&l_{22}&0\\l_{31}&l_{32}&l_{33}\\\end{pmatrix}}{\begin{pmatrix}u_{11}&u_{12}&u_{13}\\0&u_{22}&u_{23}\\0&0&u_{33}\end{pmatrix}}=LU} We now would have to solve 9 equations with 12 unknowns. To make the system uniquely solvable, usually the diagonal elements of L {\displaystyle L} are set to 1 l 11 = 1 {\displaystyle l_{11}=1} l 22 = 1 {\displaystyle l_{22}=1} l 33 = 1 {\displaystyle l_{33}=1} so we get a solvable system of 9 unknowns and 9 equations. A = ( a 11 a 12 a 13 a 21 a 22 a 23 a 31 a 32 a 33 ) = ( 1 0 0 l 21 1 0 l 31 l 32 1 ) ( u 11 u 12 u 13 0 u 22 u 23 0 0 u 33 ) = ( u 11 u 12 u 13 u 11 l 21 u 12 l 21 + u 22 u 13 l 21 + u 23 u 11 l 31 u 12 l 31 + u 22 l 32 u 13 l 31 + u 23 l 32 + u 33 ) = L U {\displaystyle A={\begin{pmatrix}a_{11}&a_{12}&a_{13}\\a_{21}&a_{22}&a_{23}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}={\begin{pmatrix}1&0&0\\l_{21}&1&0\\l_{31}&l_{32}&1\\\end{pmatrix}}{\begin{pmatrix}u_{11}&u_{12}&u_{13}\\0&u_{22}&u_{23}\\0&0&u_{33}\end{pmatrix}}={\begin{pmatrix}u_{11}&u_{12}&u_{13}\\u_{11}l_{21}&u_{12}l_{21}+u_{22}&u_{13}l_{21}+u_{23}\\u_{11}l_{31}&u_{12}l_{31}+u_{22}l_{32}&u_{13}l_{31}+u_{23}l_{32}+u_{33}\end{pmatrix}}=LU} Solving for the other l {\displaystyle l} and u {\displaystyle u} , we get the following equations: u 11 = a 11 {\displaystyle u_{11}=a_{11}} u 12 = a 12 {\displaystyle u_{12}=a_{12}} u 13 = a 13 {\displaystyle u_{13}=a_{13}} u 22 = a 22 − u 12 l 21 {\displaystyle u_{22}=a_{22}-u_{12}l_{21}} u 23 = a 23 − u 13 l 21 {\displaystyle u_{23}=a_{23}-u_{13}l_{21}} u 33 = a 33 − ( u 13 l 31 + u 23 l 32 ) {\displaystyle u_{33}=a_{33}-(u_{13}l_{31}+u_{23}l_{32})} and for l {\displaystyle l} : l 21 = 1 u 11 a 21 {\displaystyle l_{21}={\frac {1}{u_{11}}}a_{21}} l 31 = 1 u 11 a 31 {\displaystyle l_{31}={\frac {1}{u_{11}}}a_{31}} l 32 = 1 u 22 ( a 32 − u 12 l 31 ) {\displaystyle l_{32}={\frac {1}{u_{22}}}(a_{32}-u_{12}l_{31})} We see that there is a calculation pattern, which can be expressed as the following formulas, first for U {\displaystyle U} u i j = a i j − ∑ k = 1 i − 1 u k j l i k {\displaystyle u_{ij}=a_{ij}-\sum _{k=1}^{i-1}u_{kj}l_{ik}} and then for L {\displaystyle L} l i j = 1 u j j ( a i j − ∑ k = 1 j − 1 u k j l i k ) {\displaystyle l_{ij}={\frac {1}{u_{jj}}}(a_{ij}-\sum _{k=1}^{j-1}u_{kj}l_{ik})} We see in the second formula that to get the l i j {\displaystyle l_{ij}} below the diagonal, we have to divide by the diagonal element (pivot) u j j {\displaystyle u_{jj}} , so we get problems when u j j {\displaystyle u_{jj}} is either 0 or very small, which leads to numerical instability. The solution to this problem is pivoting A {\displaystyle A} , which means rearranging the rows of A {\displaystyle A} , prior to the L U {\displaystyle LU} decomposition, in a way that the largest element of each column gets onto the diagonal of A {\displaystyle A} . Rearranging the rows means to multiply A {\displaystyle A} by a permutation matrix P {\displaystyle P} : P A ⇒ A ′ {\displaystyle PA\Rightarrow A'} Example: ( 0 1 1 0 ) ( 1 4 2 3 ) ⇒ ( 2 3 1 4 ) {\displaystyle {\begin{pmatrix}0&1\\1&0\end{pmatrix}}{\begin{pmatrix}1&4\\2&3\end{pmatrix}}\Rightarrow {\begin{pmatrix}2&3\\1&4\end{pmatrix}}} The decomposition algorithm is then applied on the rearranged matrix so that P A = L U {\displaystyle PA=LU} Task description The task is to implement a routine which will take a square nxn matrix A {\displaystyle A} and return a lower triangular matrix L {\displaystyle L} , a upper triangular matrix U {\displaystyle U} and a permutation matrix P {\displaystyle P} , so that the above equation is fulfilled. You should then test it on the following two examples and include your output. Example 1 A 1 3 5 2 4 7 1 1 0 L 1.00000 0.00000 0.00000 0.50000 1.00000 0.00000 0.50000 -1.00000 1.00000 U 2.00000 4.00000 7.00000 0.00000 1.00000 1.50000 0.00000 0.00000 -2.00000 P 0 1 0 1 0 0 0 0 1 Example 2 A 11 9 24 2 1 5 2 6 3 17 18 1 2 5 7 1 L 1.00000 0.00000 0.00000 0.00000 0.27273 1.00000 0.00000 0.00000 0.09091 0.28750 1.00000 0.00000 0.18182 0.23125 0.00360 1.00000 U 11.00000 9.00000 24.00000 2.00000 0.00000 14.54545 11.45455 0.45455 0.00000 0.00000 -3.47500 5.68750 0.00000 0.00000 0.00000 0.51079 P 1 0 0 0 0 0 1 0 0 1 0 0 0 0 0 1
#Ada
Ada
with Ada.Numerics.Generic_Real_Arrays; generic with package Matrix is new Ada.Numerics.Generic_Real_Arrays (<>); package Decomposition is   -- decompose a square matrix A by PA = LU procedure Decompose (A : Matrix.Real_Matrix; P, L, U : out Matrix.Real_Matrix);   end Decomposition;
http://rosettacode.org/wiki/Lychrel_numbers
Lychrel numbers
  Take an integer n, greater than zero.   Form the next n of its series by reversing the digits of the current n and adding the result to the current n.   Stop when n becomes palindromic - i.e. the digits of n in reverse order == n. The above recurrence relation when applied to most starting numbers n = 1, 2, ... terminates in a palindrome quite quickly. Example If n0 = 12 we get 12 12 + 21 = 33, a palindrome! And if n0 = 55 we get 55 55 + 55 = 110 110 + 011 = 121, a palindrome! Notice that the check for a palindrome happens   after   an addition. Some starting numbers seem to go on forever; the recurrence relation for 196 has been calculated for millions of repetitions forming numbers with millions of digits, without forming a palindrome. These numbers that do not end in a palindrome are called Lychrel numbers. For the purposes of this task a Lychrel number is any starting number that does not form a palindrome within 500 (or more) iterations. Seed and related Lychrel numbers Any integer produced in the sequence of a Lychrel number is also a Lychrel number. In general, any sequence from one Lychrel number might converge to join the sequence from a prior Lychrel number candidate; for example the sequences for the numbers 196 and then 689 begin: 196 196 + 691 = 887 887 + 788 = 1675 1675 + 5761 = 7436 7436 + 6347 = 13783 13783 + 38731 = 52514 52514 + 41525 = 94039 ... 689 689 + 986 = 1675 1675 + 5761 = 7436 ... So we see that the sequence starting with 689 converges to, and continues with the same numbers as that for 196. Because of this we can further split the Lychrel numbers into true Seed Lychrel number candidates, and Related numbers that produce no palindromes but have integers in their sequence seen as part of the sequence generated from a lower Lychrel number. Task   Find the number of seed Lychrel number candidates and related numbers for n in the range 1..10000 inclusive. (With that iteration limit of 500).   Print the number of seed Lychrels found; the actual seed Lychrels; and just the number of relateds found.   Print any seed Lychrel or related number that is itself a palindrome. Show all output here. References   What's special about 196? Numberphile video.   A023108 Positive integers which apparently never result in a palindrome under repeated applications of the function f(x) = x + (x with digits reversed).   Status of the 196 conjecture? Mathoverflow.
#D
D
import std.stdio, std.conv, std.range, std.typecons, std.bigInt;   auto rev(in BigInt n) { return n.text.retro.text.BigInt; }   alias Res = Tuple!(bool, BigInt);   Res lychrel(BigInt n) { static Res[BigInt] cache; if (n in cache) return cache[n];   auto r = n.rev; auto res = Res(true, n); immutable(BigInt)[] seen; foreach (immutable i; 0 .. 1_000) { n += r; r = n.rev; if (n == r) { res = Res(false, BigInt(0)); break; } if (n in cache) { res = cache[n]; break; } seen ~= n; }   foreach (x; seen) cache[x] = res; return res; }   void main() { BigInt[] seeds, related, palin;   foreach (immutable i; BigInt(1) .. BigInt(10_000)) { // 1_000_000 const tf_s = i.lychrel; if (!tf_s[0]) continue; (i == tf_s[1] ? seeds : related) ~= i; if (i == i.rev) palin ~= i; }   writeln(seeds.length, " Lychrel seeds: ", seeds); writeln(related.length, " Lychrel related"); writeln(palin.length, " Lychrel palindromes: ", palin); }
http://rosettacode.org/wiki/Magic_8-ball
Magic 8-ball
Task Create Magic 8-Ball. See details at:   Magic 8-Ball. 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
#PureBasic
PureBasic
Define.s Magic8="● It is certain."+#LF$+ "● It is decidedly so."+#LF$+ "● Without a doubt."+#LF$+ "● Yes – definitely."+#LF$+ "● You may rely on it."+#LF$+ "● As I see it, yes."+#LF$+ "● Most likely."+#LF$+ "● Outlook good."+#LF$+ "● Yes."+#LF$+ "● Signs point To yes."+#LF$+ "● Reply hazy, try again."+#LF$+ "● Ask again later."+#LF$+ "● Better Not tell you now."+#LF$+ "● Cannot predict now."+#LF$+ "● Concentrate And ask again."+#LF$+ "● Don't count on it."+#LF$+ "● My reply is no."+#LF$+ "● My sources say no."+#LF$+ "● Outlook Not so good."+#LF$+ "● Very doubtful."+#LF$   OpenConsole()   Repeat Print("MAGIC8: What would you like To know? "): q$=Input() If Len(q$)=0 : End : EndIf PrintN(StringField(Magic8,Random(CountString(Magic8,#LF$),1),#LF$)) ForEver
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#TXR
TXR
(defvar x-centre -0.5) (defvar y-centre 0.0) (defvar width 4.0) (defvar i-max 800) (defvar j-max 600) (defvar n 100) (defvar r-max 2.0) (defvar file "mandelbrot.pgm") (defvar colour-max 255) (defvar pixel-size (/ width i-max)) (defvar x-offset (- x-centre (* 0.5 pixel-size (+ i-max 1)))) (defvar y-offset (+ y-centre (* 0.5 pixel-size (+ j-max 1))))   ;; with-output-to-file macro (defmacro with-output-to-file (name . body) ^(let ((*stdout* (open-file ,name "w"))) (unwind-protect (progn ,*body) (close-stream *stdout*))))   ;; complex number library (defmacro cplx (x y) ^(cons ,x ,y)) (defmacro re (c) ^(car ,c)) (defmacro im (c) ^(cdr ,c))   (defsymacro c0 '(0 . 0))   (macro-time (defun with-cplx-expand (specs body) (tree-case specs (((re im expr) . rest) ^(tree-bind (,re . ,im) ,expr ,(with-cplx-expand rest body))) (() (tree-case body ((a b . rest) ^(progn ,a ,b ,*rest)) ((a) a) (x (error "with-cplx: invalid body ~s" body)))) (x (error "with-cplx: bad args ~s" x)))))   (defmacro with-cplx (specs . body) (with-cplx-expand specs body))   (defun c+ (x y) (with-cplx ((a b x) (c d y)) (cplx (+ a c) (+ b d))))   (defun c* (x y) (with-cplx ((a b x) (c d y)) (cplx (- (* a c) (* b d)) (+ (* b c) (* a d)))))   (defun modulus (z) (with-cplx ((a b z)) (sqrt (+ (* a a) (* b b)))))   ;; Mandelbrot routines (defun inside-p (z0 : (z c0) (n n)) (and (< (modulus z) r-max) (or (zerop n) (inside-p z0 (c+ (c* z z) z0) (- n 1)))))   (defmacro int-bool (b) ^(if ,b colour-max 0))   (defun pixel (i j) (int-bool (inside-p (cplx (+ x-offset (* pixel-size i)) (- y-offset (* pixel-size j))))))   ;; Mandelbrot loop and output (defun plot () (with-output-to-file file (format t "P2\n~s\n~s\n~s\n" i-max j-max colour-max) (each ((j (range 1 j-max))) (each ((i (range 1 i-max))) (format *stdout* "~s " (pixel i j))) (put-line "" *stdout*))))   (plot)
http://rosettacode.org/wiki/Mad_Libs
Mad Libs
This page uses content from Wikipedia. The original article was at Mad Libs. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Mad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results. Task; Write a program to create a Mad Libs like story. The program should read an arbitrary multiline story from input. The story will be terminated with a blank line. Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements. Stop when there are none left and print the final story. The input should be an arbitrary story in the form: <name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home. Given this example, it should then ask for a name, a he or she and a noun (<name> gets replaced both times with the same value). Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Clojure
Clojure
(ns magic.rosetta (:require [clojure.string :as str]))   (defn mad-libs "Write a program to create a Mad Libs like story. The program should read an arbitrary multiline story from input. The story will be terminated with a blank line. Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements. Stop when there are none left and print the final story. The input should be an arbitrary story in the form: <name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home. Given this example, it should then ask for a name, a he or she and a noun (<name> gets replaced both times with the same value). " [] (let [story (do (println "Please enter story:") (loop [story []] (let [line (read-line)] (if (empty? line) (str/join "\n" story) (recur (conj story line)))))) tokens (set (re-seq #"<[^<>]+>" story)) story-completed (reduce (fn [s t] (str/replace s t (do (println (str "Substitute " t ":")) (read-line)))) story tokens)] (println (str "Here is your story:\n" "------------------------------------\n" story-completed)))) ; Sample run at REPL: ; ; user=> (magic.rosetta/mad-libs) ; Please enter story: ; One day <who> wake up at <where>. ; <who> decided to <do something>. ; While <who> <do something>, strange man ; appears and gave <who> a <thing>.   ; Substitute <where>: ; Sweden ; Substitute <thing>: ; Nobel prize ; Substitute <who>: ; Bob Dylan ; Substitute <do something>: ; walk ; Here is your story: ; ------------------------------------ ; One day Bob Dylan wake up at Sweden. ; Bob Dylan decided to walk. ; While Bob Dylan walk, strange man ; appears and gave Bob Dylan a Nobel prize.  
http://rosettacode.org/wiki/Ludic_numbers
Ludic numbers
Ludic numbers   are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers. The first ludic number is   1. To generate succeeding ludic numbers create an array of increasing integers starting from   2. 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... (Loop) Take the first member of the resultant array as the next ludic number   2. Remove every   2nd   indexed item from the array (including the first). 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... (Unrolling a few loops...) Take the first member of the resultant array as the next ludic number   3. Remove every   3rd   indexed item from the array (including the first). 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 ... Take the first member of the resultant array as the next ludic number   5. Remove every   5th   indexed item from the array (including the first). 5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 ... Take the first member of the resultant array as the next ludic number   7. Remove every   7th   indexed item from the array (including the first). 7 11 13 17 23 25 29 31 37 41 43 47 53 55 59 61 67 71 73 77 83 85 89 91 97 ... ... Take the first member of the current array as the next ludic number   L. Remove every   Lth   indexed item from the array (including the first). ... Task Generate and show here the first 25 ludic numbers. How many ludic numbers are there less than or equal to 1000? Show the 2000..2005th ludic numbers. Stretch goal Show all triplets of ludic numbers < 250. A triplet is any three numbers     x , {\displaystyle x,}   x + 2 , {\displaystyle x+2,}   x + 6 {\displaystyle x+6}     where all three numbers are also ludic numbers.
#Elixir
Elixir
defmodule Ludic do def numbers(n \\ 100000) do [h|t] = Enum.to_list(1..n) numbers(t, [h]) end   defp numbers(list, nums) when length(list) < hd(list), do: Enum.reverse(nums, list) defp numbers([h|_]=list, nums) do Enum.drop_every(list, h) |> numbers([h | nums]) end   def task do IO.puts "First 25 : #{inspect numbers(200) |> Enum.take(25)}" IO.puts "Below 1000: #{length(numbers(1000))}" tuple = numbers(25000) |> List.to_tuple IO.puts "2000..2005th: #{ inspect for i <- 1999..2004, do: elem(tuple, i) }" ludic = numbers(250) triple = for x <- ludic, x+2 in ludic, x+6 in ludic, do: [x, x+2, x+6] IO.puts "Triples below 250: #{inspect triple, char_lists: :as_lists}" end end   Ludic.task
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
#360_Assembly
360 Assembly
* Luhn test of credit card numbers 22/05/2016 LUHNTEST CSECT USING LUHNTEST,R13 base register B 72(R15) skip savearea DC 17F'0' savearea STM R14,R12,12(R13) prolog ST R13,4(R15) " ST R15,8(R13) " LR R13,R15 " LA R9,T @t(k) LA R8,N for n LOOPK EQU * for k=1 to n LR R4,R9 @t(k),@s[1] LA R6,1 from i=1 LA R7,M to m LOOPI1 CR R6,R7 for i=1 to m BH ELOOPI1 leave i CLI 0(R4),C' ' if mid(s,i,1)=" " BNE ITERI1 then BCTR R6,0 i-1 ST R6,L l=i-1 B ELOOPI1 exit for * end if ITERI1 LA R4,1(R4) next @s[i] LA R6,1(R6) i=i+1 B LOOPI1 next i ELOOPI1 EQU * out of loop i MVC W,BLANK w=" " LA R4,W iw=@w LR R5,R9 is=@s A R5,L is=@s+l BCTR R5,0 is=s+l-1 L R6,L i=l LA R7,1 to 1 LOOPI2 CR R6,R7 for i=l to 1 by -1 BL ELOOPI2 leave i MVC 0(1,R4),0(R5) mid(w,iw,1)=mid(s,is,1) LA R4,1(R4) iw=iw+1 BCTR R5,0 is=is-1 BCTR R6,0 i=i-1 B LOOPI2 next i ELOOPI2 EQU * out of loop i LA R11,0 s1=0 LA R12,0 s2=0 LA R6,1 i=1 L R7,L to l LOOPI3 CR R6,R7 for i=1 to l BH ELOOPI3 leave i LA R2,W-1 @w-1 AR R2,R6 w[i] MVC CI,0(R2) ci=mid(w,i,1) NI CI,X'0F' zap upper half byte LR R4,R6 i SRDA R4,32 >>32 D R4,=F'2' i/2 LTR R4,R4 if mod(i,2)>0 BNH NOTMOD then XR R2,R2 clear IC R2,CI z=cint(mid(w,i,1)) AR R11,R2 s1=s1+cint(mid(w,i,1)) B EIFMOD else NOTMOD XR R2,R2 clear IC R2,CI cint(mid(w,i,1)) SLA R2,1 *2 ST R2,Z z=cint(mid(w,i,1))*2 C R2,=F'10' if z<10 BNL GE10 then A R12,Z s2=s2+z B EIF10 else GE10 L R2,Z z CVD R2,PL8 binary to packed UNPK CL16,PL8 packed to zoned OI CL16+15,X'F0' zoned to char (zap sign) MVC X(1),CL16+15 x=right(cstr(z),1) NI X,X'0F' zap upper half byte XR R2,R2 r2=0 IC R2,X r2=cint(right(cstr(z),1)) AR R12,R2 s2=s2+r2 LA R12,1(R12) s2=s2+cint(right(cstr(z),1))+1 EIF10 EQU * end if EIFMOD EQU * end if LA R6,1(R6) i=i+1 B LOOPI3 next i ELOOPI3 EQU * out of loop i LR R1,R11 s1 AR R1,R12 s1+s2 CVD R1,PL8 binary to packed UNPK CL16,PL8 packed to zoned CLI CL16+15,X'C0' if right(cstr(s1+s2),1)="0" BNE NOTZERO then MVC R,=CL8'Valid' r="Valid" B ECLI else NOTZERO MVC R,=CL8'Invalid' r="Invalid" ECLI EQU * end if MVC PG(M),0(R9) t(k) MVC PG+M+1(L'R),R r XPRNT PG,L'PG print buffer LA R9,M(R9) at=at+m BCT R8,LOOPK next k L R13,4(0,R13) epilog LM R14,R12,12(R13) " XR R15,R15 " BR R14 exit N EQU (TEND-T)/L'T M EQU 20 T DC CL(M)'49927398716 ' DC CL(M)'49927398717 ' DC CL(M)'1234567812345678 ' DC CL(M)'1234567812345670 ' TEND DS 0C W DS CL(M) BLANK DC CL(M)' ' L DS F Z DS F PL8 DS PL8 CL16 DS CL16 CI DS C X DS C R DS CL8 PG DC CL80' ' buffer YREGS END LUHNTEST
http://rosettacode.org/wiki/Lucas-Lehmer_test
Lucas-Lehmer test
Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2 − 2 {\displaystyle S(n+1)=(S(n))^{2}-2} , and S ( 1 ) = 4 {\displaystyle S(1)=4} . Task Calculate all Mersenne primes up to the implementation's maximum precision, or the 47th Mersenne prime   (whichever comes first).
#Agena
Agena
readlib 'mapm';   mapm.xdigits(100);   mersenne := proc(p::number) is local s, m; s := 4; m := mapm.xnumber(2^p) - 1; if p = 2 then return true else for i from 3 to p do s := (mapm.xnumber(s)^2 - 2) % m od; return mapm.xtoNumber(s) = 0 fi end;   for i from 3 to 64 do if mersenne(i) then write('M' & i & ' ') fi od;
http://rosettacode.org/wiki/Lucky_and_even_lucky_numbers
Lucky and even lucky numbers
Note that in the following explanation list indices are assumed to start at one. Definition of lucky numbers Lucky numbers are positive integers that are formed by: Form a list of all the positive odd integers > 0 1 , 3 , 5 , 7 , 9 , 11 , 13 , 15 , 17 , 19 , 21 , 23 , 25 , 27 , 29 , 31 , 33 , 35 , 37 , 39... {\displaystyle 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39...} Return the first number from the list (which is 1). (Loop begins here) Note then return the second number from the list (which is 3). Discard every third, (as noted), number from the list to form the new list 1 , 3 , 7 , 9 , 13 , 15 , 19 , 21 , 25 , 27 , 31 , 33 , 37 , 39 , 43 , 45 , 49 , 51 , 55 , 57... {\displaystyle 1,3,7,9,13,15,19,21,25,27,31,33,37,39,43,45,49,51,55,57...} (Expanding the loop a few more times...) Note then return the third number from the list (which is 7). Discard every 7th, (as noted), number from the list to form the new list 1 , 3 , 7 , 9 , 13 , 15 , 21 , 25 , 27 , 31 , 33 , 37 , 43 , 45 , 49 , 51 , 55 , 57 , 63 , 67... {\displaystyle 1,3,7,9,13,15,21,25,27,31,33,37,43,45,49,51,55,57,63,67...} Note then return the 4th number from the list (which is 9). Discard every 9th, (as noted), number from the list to form the new list 1 , 3 , 7 , 9 , 13 , 15 , 21 , 25 , 31 , 33 , 37 , 43 , 45 , 49 , 51 , 55 , 63 , 67 , 69 , 73... {\displaystyle 1,3,7,9,13,15,21,25,31,33,37,43,45,49,51,55,63,67,69,73...} Take the 5th, i.e. 13. Remove every 13th. Take the 6th, i.e. 15. Remove every 15th. Take the 7th, i.e. 21. Remove every 21th. Take the 8th, i.e. 25. Remove every 25th. (Rule for the loop) Note the n {\displaystyle n} th, which is m {\displaystyle m} . Remove every m {\displaystyle m} th. Increment n {\displaystyle n} . Definition of even lucky numbers This follows the same rules as the definition of lucky numbers above except for the very first step: Form a list of all the positive even integers > 0 2 , 4 , 6 , 8 , 10 , 12 , 14 , 16 , 18 , 20 , 22 , 24 , 26 , 28 , 30 , 32 , 34 , 36 , 38 , 40... {\displaystyle 2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40...} Return the first number from the list (which is 2). (Loop begins here) Note then return the second number from the list (which is 4). Discard every 4th, (as noted), number from the list to form the new list 2 , 4 , 6 , 10 , 12 , 14 , 18 , 20 , 22 , 26 , 28 , 30 , 34 , 36 , 38 , 42 , 44 , 46 , 50 , 52... {\displaystyle 2,4,6,10,12,14,18,20,22,26,28,30,34,36,38,42,44,46,50,52...} (Expanding the loop a few more times...) Note then return the third number from the list (which is 6). Discard every 6th, (as noted), number from the list to form the new list 2 , 4 , 6 , 10 , 12 , 18 , 20 , 22 , 26 , 28 , 34 , 36 , 38 , 42 , 44 , 50 , 52 , 54 , 58 , 60... {\displaystyle 2,4,6,10,12,18,20,22,26,28,34,36,38,42,44,50,52,54,58,60...} Take the 4th, i.e. 10. Remove every 10th. Take the 5th, i.e. 12. Remove every 12th. (Rule for the loop) Note the n {\displaystyle n} th, which is m {\displaystyle m} . Remove every m {\displaystyle m} th. Increment n {\displaystyle n} . Task requirements Write one or two subroutines (functions) to generate lucky numbers and even lucky numbers Write a command-line interface to allow selection of which kind of numbers and which number(s). Since input is from the command line, tests should be made for the common errors: missing arguments too many arguments number (or numbers) aren't legal misspelled argument (lucky or evenLucky) The command line handling should: support mixed case handling of the (non-numeric) arguments support printing a particular number support printing a range of numbers by their index support printing a range of numbers by their values The resulting list of numbers should be printed on a single line. The program should support the arguments: what is displayed (on a single line) argument(s) (optional verbiage is encouraged) ╔═══════════════════╦════════════════════════════════════════════════════╗ ║ j ║ Jth lucky number ║ ║ j , lucky ║ Jth lucky number ║ ║ j , evenLucky ║ Jth even lucky number ║ ║ ║ ║ ║ j k ║ Jth through Kth (inclusive) lucky numbers ║ ║ j k lucky ║ Jth through Kth (inclusive) lucky numbers ║ ║ j k evenLucky ║ Jth through Kth (inclusive) even lucky numbers ║ ║ ║ ║ ║ j -k ║ all lucky numbers in the range j ──► |k| ║ ║ j -k lucky ║ all lucky numbers in the range j ──► |k| ║ ║ j -k evenLucky ║ all even lucky numbers in the range j ──► |k| ║ ╚═══════════════════╩════════════════════════════════════════════════════╝ where |k| is the absolute value of k Demonstrate the program by: showing the first twenty lucky numbers showing the first twenty even lucky numbers showing all lucky numbers between 6,000 and 6,100 (inclusive) showing all even lucky numbers in the same range as above showing the 10,000th lucky number (extra credit) showing the 10,000th even lucky number (extra credit) See also This task is related to the Sieve of Eratosthenes task. OEIS Wiki Lucky numbers. Sequence A000959 lucky numbers on The On-Line Encyclopedia of Integer Sequences. Sequence A045954 even lucky numbers or ELN on The On-Line Encyclopedia of Integer Sequences. Entry lucky numbers on The Eric Weisstein's World of Mathematics.
#C.2B.2B
C++
#include <algorithm> #include <iostream> #include <iterator> #include <vector>   const int luckySize = 60000; std::vector<int> luckyEven(luckySize); std::vector<int> luckyOdd(luckySize);   void init() { for (int i = 0; i < luckySize; ++i) { luckyEven[i] = i * 2 + 2; luckyOdd[i] = i * 2 + 1; } }   void filterLuckyEven() { for (size_t n = 2; n < luckyEven.size(); ++n) { int m = luckyEven[n - 1]; int end = (luckyEven.size() / m) * m - 1; for (int j = end; j >= m - 1; j -= m) { std::copy(luckyEven.begin() + j + 1, luckyEven.end(), luckyEven.begin() + j); luckyEven.pop_back(); } } }   void filterLuckyOdd() { for (size_t n = 2; n < luckyOdd.size(); ++n) { int m = luckyOdd[n - 1]; int end = (luckyOdd.size() / m) * m - 1; for (int j = end; j >= m - 1; j -= m) { std::copy(luckyOdd.begin() + j + 1, luckyOdd.end(), luckyOdd.begin() + j); luckyOdd.pop_back(); } } }   void printBetween(size_t j, size_t k, bool even) { std::ostream_iterator<int> out_it{ std::cout, ", " };   if (even) { size_t max = luckyEven.back(); if (j > max || k > max) { std::cerr << "At least one are is too big\n"; exit(EXIT_FAILURE); }   std::cout << "Lucky even numbers between " << j << " and " << k << " are: "; std::copy_if(luckyEven.begin(), luckyEven.end(), out_it, [j, k](size_t n) { return j <= n && n <= k; }); } else { size_t max = luckyOdd.back(); if (j > max || k > max) { std::cerr << "At least one are is too big\n"; exit(EXIT_FAILURE); }   std::cout << "Lucky numbers between " << j << " and " << k << " are: "; std::copy_if(luckyOdd.begin(), luckyOdd.end(), out_it, [j, k](size_t n) { return j <= n && n <= k; }); } std::cout << '\n'; }   void printRange(size_t j, size_t k, bool even) { std::ostream_iterator<int> out_it{ std::cout, ", " }; if (even) { if (k >= luckyEven.size()) { std::cerr << "The argument is too large\n"; exit(EXIT_FAILURE); } std::cout << "Lucky even numbers " << j << " to " << k << " are: "; std::copy(luckyEven.begin() + j - 1, luckyEven.begin() + k, out_it); } else { if (k >= luckyOdd.size()) { std::cerr << "The argument is too large\n"; exit(EXIT_FAILURE); } std::cout << "Lucky numbers " << j << " to " << k << " are: "; std::copy(luckyOdd.begin() + j - 1, luckyOdd.begin() + k, out_it); } }   void printSingle(size_t j, bool even) { if (even) { if (j >= luckyEven.size()) { std::cerr << "The argument is too large\n"; exit(EXIT_FAILURE); } std::cout << "Lucky even number " << j << "=" << luckyEven[j - 1] << '\n'; } else { if (j >= luckyOdd.size()) { std::cerr << "The argument is too large\n"; exit(EXIT_FAILURE); } std::cout << "Lucky number " << j << "=" << luckyOdd[j - 1] << '\n'; } }   void help() { std::cout << "./lucky j [k] [--lucky|--evenLucky]\n"; std::cout << "\n"; std::cout << " argument(s) | what is displayed\n"; std::cout << "==============================================\n"; std::cout << "-j=m | mth lucky number\n"; std::cout << "-j=m --lucky | mth lucky number\n"; std::cout << "-j=m --evenLucky | mth even lucky number\n"; std::cout << "-j=m -k=n | mth through nth (inclusive) lucky numbers\n"; std::cout << "-j=m -k=n --lucky | mth through nth (inclusive) lucky numbers\n"; std::cout << "-j=m -k=n --evenLucky | mth through nth (inclusive) even lucky numbers\n"; std::cout << "-j=m -k=-n | all lucky numbers in the range [m, n]\n"; std::cout << "-j=m -k=-n --lucky | all lucky numbers in the range [m, n]\n"; std::cout << "-j=m -k=-n --evenLucky | all even lucky numbers in the range [m, n]\n"; }   int main(int argc, char **argv) { bool evenLucky = false; int j = 0; int k = 0;   // skip arg 0, because that is just the executable name if (argc < 2) { help(); exit(EXIT_FAILURE); }   bool good = false; for (int i = 1; i < argc; ++i) { if ('-' == argv[i][0]) { if ('-' == argv[i][1]) { // long args if (0 == strcmp("--lucky", argv[i])) { evenLucky = false; } else if (0 == strcmp("--evenLucky", argv[i])) { evenLucky = true; } else { std::cerr << "Unknown long argument: [" << argv[i] << "]\n"; exit(EXIT_FAILURE); } } else { // short args if ('j' == argv[i][1] && '=' == argv[i][2] && argv[i][3] != 0) { good = true; j = atoi(&argv[i][3]); } else if ('k' == argv[i][1] && '=' == argv[i][2]) { k = atoi(&argv[i][3]); } else { std::cerr << "Unknown short argument: " << argv[i] << '\n'; exit(EXIT_FAILURE); } } } else { std::cerr << "Unknown argument: " << argv[i] << '\n'; exit(EXIT_FAILURE); } } if (!good) { help(); exit(EXIT_FAILURE); }   init(); filterLuckyEven(); filterLuckyOdd(); if (k > 0) { printRange(j, k, evenLucky); } else if (k < 0) { printBetween(j, -k, evenLucky); } else { printSingle(j, evenLucky); }   return 0; }
http://rosettacode.org/wiki/LZW_compression
LZW compression
The Lempel-Ziv-Welch (LZW) algorithm provides loss-less data compression. You can read a complete description of it in the   Wikipedia article   on the subject.   It was patented, but it entered the public domain in 2004.
#Arturo
Arturo
compress: function [str][ dict: #[] loop 0..255 'i -> dict\[to :char i]: i   w: "" result: new [] loop str 'c [ wc: w ++ c if? key? dict wc -> w: wc else [ 'result ++ dict\[w] dict\[wc]: size dict w: to :string c ] ]   if 0 < size w -> 'result ++ dict\[w] return result ]     decompress: function [compressed][ dict: #[] arr: new compressed loop 0..255 'i -> dict\[i]: to :string to :char i   w: dict\[first arr] remove 'arr .index 0   result: w loop arr 'k [ entry: "" if? key? dict k -> entry: dict\[k] else [ if? k = size dict -> entry: w ++ first w else -> panic ~"Error with compressed: |k|" ] 'result ++ entry dict\[size dict]: w ++ first entry w: entry ] return result ]   compressed: compress "TOBEORNOTTOBEORTOBEORNOT" print "Compressed:" print compressed print ""   decompressed: decompress compressed print "Decompressed:" print decompressed
http://rosettacode.org/wiki/LU_decomposition
LU decomposition
Every square matrix A {\displaystyle A} can be decomposed into a product of a lower triangular matrix L {\displaystyle L} and a upper triangular matrix U {\displaystyle U} , as described in LU decomposition. A = L U {\displaystyle A=LU} It is a modified form of Gaussian elimination. While the Cholesky decomposition only works for symmetric, positive definite matrices, the more general LU decomposition works for any square matrix. There are several algorithms for calculating L and U. To derive Crout's algorithm for a 3x3 example, we have to solve the following system: A = ( a 11 a 12 a 13 a 21 a 22 a 23 a 31 a 32 a 33 ) = ( l 11 0 0 l 21 l 22 0 l 31 l 32 l 33 ) ( u 11 u 12 u 13 0 u 22 u 23 0 0 u 33 ) = L U {\displaystyle A={\begin{pmatrix}a_{11}&a_{12}&a_{13}\\a_{21}&a_{22}&a_{23}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}={\begin{pmatrix}l_{11}&0&0\\l_{21}&l_{22}&0\\l_{31}&l_{32}&l_{33}\\\end{pmatrix}}{\begin{pmatrix}u_{11}&u_{12}&u_{13}\\0&u_{22}&u_{23}\\0&0&u_{33}\end{pmatrix}}=LU} We now would have to solve 9 equations with 12 unknowns. To make the system uniquely solvable, usually the diagonal elements of L {\displaystyle L} are set to 1 l 11 = 1 {\displaystyle l_{11}=1} l 22 = 1 {\displaystyle l_{22}=1} l 33 = 1 {\displaystyle l_{33}=1} so we get a solvable system of 9 unknowns and 9 equations. A = ( a 11 a 12 a 13 a 21 a 22 a 23 a 31 a 32 a 33 ) = ( 1 0 0 l 21 1 0 l 31 l 32 1 ) ( u 11 u 12 u 13 0 u 22 u 23 0 0 u 33 ) = ( u 11 u 12 u 13 u 11 l 21 u 12 l 21 + u 22 u 13 l 21 + u 23 u 11 l 31 u 12 l 31 + u 22 l 32 u 13 l 31 + u 23 l 32 + u 33 ) = L U {\displaystyle A={\begin{pmatrix}a_{11}&a_{12}&a_{13}\\a_{21}&a_{22}&a_{23}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}={\begin{pmatrix}1&0&0\\l_{21}&1&0\\l_{31}&l_{32}&1\\\end{pmatrix}}{\begin{pmatrix}u_{11}&u_{12}&u_{13}\\0&u_{22}&u_{23}\\0&0&u_{33}\end{pmatrix}}={\begin{pmatrix}u_{11}&u_{12}&u_{13}\\u_{11}l_{21}&u_{12}l_{21}+u_{22}&u_{13}l_{21}+u_{23}\\u_{11}l_{31}&u_{12}l_{31}+u_{22}l_{32}&u_{13}l_{31}+u_{23}l_{32}+u_{33}\end{pmatrix}}=LU} Solving for the other l {\displaystyle l} and u {\displaystyle u} , we get the following equations: u 11 = a 11 {\displaystyle u_{11}=a_{11}} u 12 = a 12 {\displaystyle u_{12}=a_{12}} u 13 = a 13 {\displaystyle u_{13}=a_{13}} u 22 = a 22 − u 12 l 21 {\displaystyle u_{22}=a_{22}-u_{12}l_{21}} u 23 = a 23 − u 13 l 21 {\displaystyle u_{23}=a_{23}-u_{13}l_{21}} u 33 = a 33 − ( u 13 l 31 + u 23 l 32 ) {\displaystyle u_{33}=a_{33}-(u_{13}l_{31}+u_{23}l_{32})} and for l {\displaystyle l} : l 21 = 1 u 11 a 21 {\displaystyle l_{21}={\frac {1}{u_{11}}}a_{21}} l 31 = 1 u 11 a 31 {\displaystyle l_{31}={\frac {1}{u_{11}}}a_{31}} l 32 = 1 u 22 ( a 32 − u 12 l 31 ) {\displaystyle l_{32}={\frac {1}{u_{22}}}(a_{32}-u_{12}l_{31})} We see that there is a calculation pattern, which can be expressed as the following formulas, first for U {\displaystyle U} u i j = a i j − ∑ k = 1 i − 1 u k j l i k {\displaystyle u_{ij}=a_{ij}-\sum _{k=1}^{i-1}u_{kj}l_{ik}} and then for L {\displaystyle L} l i j = 1 u j j ( a i j − ∑ k = 1 j − 1 u k j l i k ) {\displaystyle l_{ij}={\frac {1}{u_{jj}}}(a_{ij}-\sum _{k=1}^{j-1}u_{kj}l_{ik})} We see in the second formula that to get the l i j {\displaystyle l_{ij}} below the diagonal, we have to divide by the diagonal element (pivot) u j j {\displaystyle u_{jj}} , so we get problems when u j j {\displaystyle u_{jj}} is either 0 or very small, which leads to numerical instability. The solution to this problem is pivoting A {\displaystyle A} , which means rearranging the rows of A {\displaystyle A} , prior to the L U {\displaystyle LU} decomposition, in a way that the largest element of each column gets onto the diagonal of A {\displaystyle A} . Rearranging the rows means to multiply A {\displaystyle A} by a permutation matrix P {\displaystyle P} : P A ⇒ A ′ {\displaystyle PA\Rightarrow A'} Example: ( 0 1 1 0 ) ( 1 4 2 3 ) ⇒ ( 2 3 1 4 ) {\displaystyle {\begin{pmatrix}0&1\\1&0\end{pmatrix}}{\begin{pmatrix}1&4\\2&3\end{pmatrix}}\Rightarrow {\begin{pmatrix}2&3\\1&4\end{pmatrix}}} The decomposition algorithm is then applied on the rearranged matrix so that P A = L U {\displaystyle PA=LU} Task description The task is to implement a routine which will take a square nxn matrix A {\displaystyle A} and return a lower triangular matrix L {\displaystyle L} , a upper triangular matrix U {\displaystyle U} and a permutation matrix P {\displaystyle P} , so that the above equation is fulfilled. You should then test it on the following two examples and include your output. Example 1 A 1 3 5 2 4 7 1 1 0 L 1.00000 0.00000 0.00000 0.50000 1.00000 0.00000 0.50000 -1.00000 1.00000 U 2.00000 4.00000 7.00000 0.00000 1.00000 1.50000 0.00000 0.00000 -2.00000 P 0 1 0 1 0 0 0 0 1 Example 2 A 11 9 24 2 1 5 2 6 3 17 18 1 2 5 7 1 L 1.00000 0.00000 0.00000 0.00000 0.27273 1.00000 0.00000 0.00000 0.09091 0.28750 1.00000 0.00000 0.18182 0.23125 0.00360 1.00000 U 11.00000 9.00000 24.00000 2.00000 0.00000 14.54545 11.45455 0.45455 0.00000 0.00000 -3.47500 5.68750 0.00000 0.00000 0.00000 0.51079 P 1 0 0 0 0 0 1 0 0 1 0 0 0 0 0 1
#AutoHotkey
AutoHotkey
;-------------------------- LU_decomposition(A){ P := Pivot(A) A_ := Multiply_Matrix(P, A)   U := [], L := [], n := A_.Count() loop % n { i := A_Index loop % n { j := A_Index   Sigma := 0, k := 1 while (k <= i-1) Sigma += (U[k, j] * L[i, k]), k++ U[i, j] := A_[i, j] - Sigma   Sigma := 0, k := 1 while (k <= j-1) Sigma += (U[k, j] * L[i, k]), k++ L[i, j] := (A_[i, j] - Sigma) / U[j, j] } } return [L, U, P] } ;-------------------------- Pivot(M){ n := M.Count(), P := [], i := 0 while (i++ < n){ P.push([]) j := 0 while (j++ < n) P[i].push(i=j ? 1 : 0) } i := 0 while (i++ < n){ maxm := M[i, i], row := i, j := i while (j++ < n) if (M[j, i] > maxm) maxm := M[j, i], row := j if (i != row) tmp := P[i], P[i] := P[row], P[row] := tmp } return P } ;-------------------------- Multiply_Matrix(A,B){ if (A[1].Count() <> B.Count()) return RCols := A[1].Count()>B[1].Count()?A[1].Count():B[1].Count() RRows := A.Count()>B.Count()?A.Count():B.Count(), R := [] Loop, % RRows { RRow:=A_Index loop, % RCols { RCol:=A_Index, v := 0 loop % A[1].Count() col := A_Index, v += A[RRow, col] * B[col,RCol] R[RRow,RCol] := v } } return R } ;-------------------------- ShowMatrix(L, f:=3){ for r, obj in L{ row := "" for c, v in obj row .= Format("{:." f "f}", v) ", " output .= "[" trim(row, ", ") "]`n," } return "[" Trim(output, "`n,") "]" } ;--------------------------
http://rosettacode.org/wiki/Lychrel_numbers
Lychrel numbers
  Take an integer n, greater than zero.   Form the next n of its series by reversing the digits of the current n and adding the result to the current n.   Stop when n becomes palindromic - i.e. the digits of n in reverse order == n. The above recurrence relation when applied to most starting numbers n = 1, 2, ... terminates in a palindrome quite quickly. Example If n0 = 12 we get 12 12 + 21 = 33, a palindrome! And if n0 = 55 we get 55 55 + 55 = 110 110 + 011 = 121, a palindrome! Notice that the check for a palindrome happens   after   an addition. Some starting numbers seem to go on forever; the recurrence relation for 196 has been calculated for millions of repetitions forming numbers with millions of digits, without forming a palindrome. These numbers that do not end in a palindrome are called Lychrel numbers. For the purposes of this task a Lychrel number is any starting number that does not form a palindrome within 500 (or more) iterations. Seed and related Lychrel numbers Any integer produced in the sequence of a Lychrel number is also a Lychrel number. In general, any sequence from one Lychrel number might converge to join the sequence from a prior Lychrel number candidate; for example the sequences for the numbers 196 and then 689 begin: 196 196 + 691 = 887 887 + 788 = 1675 1675 + 5761 = 7436 7436 + 6347 = 13783 13783 + 38731 = 52514 52514 + 41525 = 94039 ... 689 689 + 986 = 1675 1675 + 5761 = 7436 ... So we see that the sequence starting with 689 converges to, and continues with the same numbers as that for 196. Because of this we can further split the Lychrel numbers into true Seed Lychrel number candidates, and Related numbers that produce no palindromes but have integers in their sequence seen as part of the sequence generated from a lower Lychrel number. Task   Find the number of seed Lychrel number candidates and related numbers for n in the range 1..10000 inclusive. (With that iteration limit of 500).   Print the number of seed Lychrels found; the actual seed Lychrels; and just the number of relateds found.   Print any seed Lychrel or related number that is itself a palindrome. Show all output here. References   What's special about 196? Numberphile video.   A023108 Positive integers which apparently never result in a palindrome under repeated applications of the function f(x) = x + (x with digits reversed).   Status of the 196 conjecture? Mathoverflow.
#Fortran
Fortran
  SUBROUTINE CROAK(GASP) !A dying message. CHARACTER*(*) GASP !The message. WRITE (6,*) "Oh dear! ",GASP !The gasp. STOP "Alas." !The death. END !Goodbye, cruel world.   MODULE LYCHREL SEARCH !Assistants for the pursuit of Lychrel numbers. INTEGER LOTSADIGITS,BASE !Parameters. PARAMETER (LOTSADIGITS = 1000, BASE = 10) !This should do. TYPE BIGINT !Can't use an element zero as the count, as lots of digits are needed. INTEGER LDIGIT !Count in use. INTEGER*1 DIGIT(LOTSADIGITS) !Stored in increasing powers of BASE. END TYPE BIGINT !No fractional parts. INTEGER MSTASH !Now for my stash. PARAMETER (MSTASH = 66666) !This should be enough. TYPE(BIGINT) STASH(MSTASH) !The work area. INTEGER AVAILS(0:MSTASH) !A list of available STASH entries. INTEGER PLIST(0:MSTASH) !These strings of fingers INTEGER LLIST(0:MSTASH) !Each starting with a count INTEGER LYCHREL(0:MSTASH)!Finger BIGINTs in the STASH INTEGER L0P(0:MSTASH) !Without the body of the BIGINT being copied. INTEGER LONGESTNUMBER !Keep track out of curiosity. DATA LONGESTNUMBER/0/ !No digits so far. CONTAINS !A miscellany. Commence with some STASH service. If problems were to arise, better error messages would be in order. SUBROUTINE PREPARESTASH !Since fancy usage is involved, fancy initialisation is needed. INTEGER I !A stepper. AVAILS(0) = MSTASH !All are available. FORALL (I = 1:MSTASH) AVAILS(I) = MSTASH + 1 - I !Will be used stack style. STASH.LDIGIT = -666 !This will cause trouble! END SUBROUTINE PREPARESTASH !Simple enough. SUBROUTINE GRABSTASH(X) !Finger an available STASH. INTEGER X !The finger. INTEGER L !The last. L = AVAILS(0) !Pick on the last in the list. IF (L .LE. 0) CALL CROAK("Run out of stashes!") !Hopefully not. X = AVAILS(L) !Select some element or other. AVAILS(L) = 0 !Might as well unfinger. AVAILS(0) = L - 1 !As well as drop off the list. END SUBROUTINE GRABSTASH!Can't be bothered making this a function. Sudden death instead. SUBROUTINE FREESTASH(X) !Unhand a STASH. INTEGER X !The finger. IF (X.EQ.0) RETURN !A non-finger. IF (X.LT.0) CALL CROAK("Unhanding a non-stash!") !Paranoia. IF (X.GT.MSTASH) CALL CROAK("Not a stash!") !I don't expect any of these. IF (AVAILS(0).GE.MSTASH) CALL CROAK("Over subscribed!") !But on principle... AVAILS(0) = AVAILS(0) + 1 !So, append to the list of available entries. AVAILS(AVAILS(0)) = X !Thus. X = 0 !The finger is amputated. END SUBROUTINE FREESTASH !Last out, first in. Etc.   SUBROUTINE BIGWRITE(T,N)!Reveal an annotated bignumber. CHARACTER*(*) T !The text of its name. TYPE(BIGINT) N !The value of its name. WRITE (6,1) T,N.LDIGIT,N.DIGIT(N.LDIGIT:1:-1) !Roll! 1 FORMAT (A,"(1:",I0,") = ",(300I1)) !This should do. END SUBROUTINE BIGWRITE !Perhaps bigger than Integer*8.   SUBROUTINE SHOWLIST(BLAH,LIST) !One can become confused. INTEGER LIST(0:MSTASH) !Explicit bounds prevents confusion. CHARACTER*(*) BLAH !An identifying message. CHARACTER*4 ZOT !Scratchpad. INTEGER I,IT !Stepper. c REAL*8 V,P !For logarithmic output. c INTEGER J !Another stepper needed. WRITE (6,1) BLAH,LIST(0) !A heading. 1 FORMAT ("The count for ",A," is ",I0) !Ah, layout. DO I = 1,LIST(0) !Work through the list. WRITE(ZOT,"('#',I3)") I !Prepare an annotation. IT = LIST(I) !Finger the stash. CALL BIGWRITE(ZOT,STASH(IT)) !Show. c V = 0 !Convert the BIGINT to a floating-point number. c P = 1 !Tracking the powers of BASE, presumed ten. c PP:DO J = STASH(IT).LDIGIT,1,-1 !Start with the highest power. c V = V + STASH(IT).DIGIT(J)/P !Deem it a units digit. c P = P*10 !The next digit will have a lesser power. c IF (P.GT.1000000) EXIT PP !This will do. c END DO PP !On to the next digit. c V = STASH(IT).LDIGIT - 1 + LOG10(V) !Convert. LOG10(196) = 2.29225607135648 c WRITE (6,*) I,V !Reveal. END DO !On to the next. END SUBROUTINE SHOWLIST !Adrift in indirection.   SUBROUTINE BIGLOAD(A,NUM) !Shatters a proper number into its digits. Can't overflow, because the biggest normal integer has far fewer than LOTSADIGITS digits. TYPE(BIGINT) A !The bignumber. INTEGER NUM !The normal integer to put in it. INTEGER L,N !Assistants. N = NUM !A copy that I can damage. A.DIGIT = 0 !Scrub, against a future carry.. L = 0 !No digits so far. DO WHILE(N .GT. 0) !Some number remaining? L = L + 1 !Yes. Count another digit. A.DIGIT(L) = MOD(N,BASE) !Place it. N = N/BASE !Reduce the number. END DO !And try again. A.LDIGIT = MAX(1,L) !Zero will have one digit, a zero. END SUBROUTINE BIGLOAD !A small service.   Continue with routines for doing the work. SUBROUTINE ADVANCE(A,B) !Advance A, giving B. C Experiment shows that for 196, log10(v) = 0·43328*step + 2·1616, or, each advance increases by a factor of ~2·7. TYPE(BIGINT) A,B !To be twiddled. INTEGER D !An assistant for carrying. INTEGER I !A stepper. B.LDIGIT = A.LDIGIT !Same size, so far. FORALL(I = 1:A.LDIGIT) !Do these in any order, even in parallel! 1 B.DIGIT(I) = A.DIGIT(I) !Add each digit 2 + A.DIGIT(A.LDIGIT - I + 1) ! to its other-end partner. B.DIGIT(B.LDIGIT + 1) = 0 !Perhaps another digit will be needed shortly. DO I = 1,B.LDIGIT !Now slow down and taste the carry. D = B.DIGIT(I) - BASE !Allowable digits are 0:BASE - 1. IF (D.GE.0) THEN !So, has this digit overflowed? B.DIGIT(I) = D !Yes. Only addition, so no div and mod stuff. B.DIGIT(I + 1) = B.DIGIT(I + 1) + 1 !Carry one up, corresponding to subtracting one BASE down. END IF !So much for that digit. END DO !On to the next digit, of higher power. IF (D.GE.0) THEN !A carry from the highest digit? IF (B.LDIGIT .GE. LOTSADIGITS) CALL CROAK("Overflow!") !Oh dear. B.LDIGIT = B.LDIGIT + 1 !NB! Always there is room left for ONE more digit. LONGESTNUMBER = MAX(B.LDIGIT,LONGESTNUMBER) !Perhaps a surprise awaits. END IF !Avoids overflow testing for every carry above. END SUBROUTINE ADVANCE !That was fun!   LOGICAL FUNCTION PALINDROME(N) !Perhaps a surprise property? Calls a one-digit number palindromic through the execution of vacuous logic. TYPE(BIGINT) N !The big number to inspect. PALINDROME = ALL(N.DIGIT(1:N.LDIGIT/2) !Compare each digit in the first half... 1 .EQ.N.DIGIT(N.LDIGIT:N.LDIGIT/2 + 1:-1)) !To its opposite digit in the second. Whee! END FUNCTION PALINDROME !If an odd number of digits, ignores the middle digit.   INTEGER FUNCTION ORDER(A,B) !Does B follow A? TYPE(BIGINT) A,B !The two numbers. INTEGER I !A stepper. IF (A.LDIGIT - B.LDIGIT) 1,10,2 !First, compare the lengths. 1 ORDER = +1 !B has more digits. RETURN !So, A must be smaller: in order. 2 ORDER = -1 !A has more digits. RETURN !So B must be smaller: reverse order. Compare the digits of the two numbers, known to be of equal length. 10 DO 11 I = A.LDIGIT,1,-1 !The last digit has the highest power. IF (A.DIGIT(I) - B.DIGIT(I)) 1,11,2 !Compare the digits. 11 CONTINUE !If they match, continue with the next digit. ORDER = 0 !If all match, A = B. END FUNCTION ORDER !Ah, three-way tests...   SUBROUTINE COMBSORT(XNDX) !Sort according to STASH(XNDX)) by reordering XNDX. Crank up a Comb sort of array STASH as indexed by XNDX. INTEGER XNDX(0:),T !The index to be rearranged. INTEGER I,H !Tools. H ought not be a small integer. LOGICAL CURSE !Annoyance. H = XNDX(0) - 1 !Last - First, and not +1. IF (H.LE.0) GO TO 999 !Ha ha. 1 H = MAX(1,H*10/13) !The special feature. IF (H.EQ.9 .OR. H.EQ.10) H = 11 !A twiddle. CURSE = .FALSE. !So far, so good. DO I = XNDX(0) - H,1,-1 !If H = 1, this is a BubbleSort. IF (ORDER(STASH(XNDX(I)),STASH(XNDX(I + H))) .LT. 0) THEN !One compare. T=XNDX(I); XNDX(I)=XNDX(I+H); XNDX(I+H)=T !One swap. CURSE = .TRUE. !One curse. END IF !One test. END DO !One loop. IF (CURSE .OR. H.GT.1) GO TO 1!Work remains? 999 RETURN !If not, we're done. END SUBROUTINE COMBSORT !Good performance, and simple.   SUBROUTINE INSERTIONSORT(XNDX) !Adjust XNDX according to STASH(XNDX) Crank up an Insertion sort of array STASH as indexed by XNDX. INTEGER XNDX(0:),IT !The index to be prepared, and a safe place. INTEGER I,L !Fingers. DO L = 2,XNDX(0) !Step along the array. IF (ORDER(STASH(XNDX(L - 1)),STASH(XNDX(L))) .LT. 0) THEN !Disorder? I = L !Yes. Element L belongs earlier. IT = XNDX(L) !Save it so that others can be shifted up one. 1 XNDX(I) = XNDX(I - 1) !Shift one. I = I - 1 !The next candidate back. IF (I.GT.1 .AND. ORDER(STASH(XNDX(I - 1)), !Do I have to go further back? 1 STASH(IT)).LT.0) GO TO 1 !Yes. XNDX(I) = IT !Done. Place it in the space created. END IF !So much for that comparison. END DO !On to the next. END SUBROUTINE INSERTIONSORT !Swift only if the array is nearly in order.   INTEGER FUNCTION FOUNDIN(XNDX,X) !Search STASH(XNDX) for X. Crank up a binary serach. This uses EXCLUSIVE bounds. INTEGER XNDX(0:) !The list of elements. TYPE(BIGINT) X !The value to be sought. INTEGER L,P,R !Fingers for the binary search. L = 0 !Establish outer bounds. R = XNDX(0) + 1 !One before, and one after, the first and last. 1 P = (R - L)/2 !Probe point offset. Beware integer overflow with (L + R)/2. IF (P.LE.0) THEN !Is the search span exhausted? FOUNDIN = -L !Alas. X should follow position L but doesn't. RETURN !Nothing more to search. END IF !Otherwise, STASH(XNDX(L + 1)) <= X <= STASH(XNDX(R - 1)) P = L + P !Convert from offset to probe point. IF (ORDER(X,STASH(XNDX(P)))) 2,4,3 !Compare X to the probe point's value. 2 L = P !STASH(XNDX(P)) < X: advance L to P. GO TO 1 !Try again. 3 R = P !X < STASH(XNDX(P)): retract R to P. GO TO 1 !Try again. Caught it! X = STASH(XNDX(P)) - the result indexes XNDX, not STASH. 4 FOUNDIN = P !So, X is found, here! *Not* at P, but at XNDX(P). END FUNCTION FOUNDIN !Hopefully, without array copy-in, copy-out.   SUBROUTINE INSPECT(S1,S2,ENUFF) !Follow the Lychrel protocol. Careful! A march is stopped on encountering a palindrome, BUT, the starting value is not itself checked. INTEGER S1,S2 !Start and stop values. INTEGER ENUFF !An infinite trail can't be followed. INTEGER STEP,SEED !Counts the advances along the long march. INTEGER START !The first value of a march has special treatment. INTEGER MARCH(0:ENUFF) !The waypoints of a long march. INTEGER DEJAVU !Some may prove to be junctions. INTEGER LP,NP,LL,NL !Counters for various odd outcomes. NP = 0 !No palindromic stops. LP = 0 !Nor any that head for one. NL = 0 !No neverending sequences seen. LL = 0 !Nor any that head for one. WRITE (6,10) S1,S2,ENUFF !Announce the plan. 10 FORMAT ("Starting values ",I0," to ",I0,"; step limit ",I0) C For each try, steps (but not the START) are saved in MARCH, and those steps end up in one list or another. C Thus, there is no removal of their entries from the working STASH. If a plaindrome is found, or a step's value is c noticed in the PLIST or LYCHREL list, the last STEP is not saved (being in that list, as a different entry in STASH) c and its redundant value in STASH is unhanded via CALL FREESTASH(MARCH(STEP)). c But if instead the MARCH is to be added to the LYCHREL list, the last value is included. c Since tries are made in increasing order, and ADVANCE always produces a bigger number, there is no point c in saving the START value in STASH, except, some START values turn out to be notable and being saved in L0P c or LLIST, their entry in STASH must not be rugpulled, thus the START = 0 to note this and prevent FREESTASH. TRY:DO SEED = S1,S2 !Here we go. CALL GRABSTASH(START) !Ask for a starting space. CALL BIGLOAD(STASH(START),SEED) !The starting value. c CALL BIGWRITE("N0",STASH(START)) !Show it. c IF (FOUNDIN(LYCHREL,STASH(START)) .GT. 0) THEN! Have we been here during a long march? c WRITE (6,*) SEED,"Falls in!" !Yes! c CYCLE TRY !Nothing will be learnt by continuing. c END IF !Otherwise, we're not discouraged. STEP = 1 !Even the longest journey stars with its first step. MARCH(0) = STEP !And I'm remembering every step. CALL GRABSTASH(MARCH(STEP)) !A place for my first footfall. CALL ADVANCE(STASH(START),STASH(MARCH(STEP))) !Start the stomping. Contemplate the current step. 100 CONTINUE !Can't label a blank line... c CALL BIGWRITE("N1",STASH(MARCH(STEP))) !Progress may be of interest. DEJAVU = FOUNDIN(PLIST,STASH(MARCH(STEP))) !A value known to later become a palindrome? IF (DEJAVU .GT. 0) THEN !It being amongst those stashed for that cause. c WRITE (6,*) SEED,STEP,"Deja vu! List#",DEJAVU LP = LP + 1 !Count a late starter. CALL FREESTASH(MARCH(STEP)) !The last step is already known. CALL SLURP(PLIST) !Add the MARCH to the palindrome starters. GO TO 110 !And we're finished with this try. END IF !So much for prospective palindromes. IF (PALINDROME(STASH(MARCH(STEP)))) THEN !Attained an actual palindrome? c WRITE (6,*) SEED,STEP,"Palindrome!" !Yes! NP = NP + 1 !Count a proper palendrome. CALL FREESTASH(MARCH(STEP)) !The last step is a palindrome. CALL SLURP(PLIST) !So remember only those non-palindromes before it. GO TO 110 !This is a pretext for ending. END IF !Since one could advance past a palindrome, and then find another. DEJAVU = FOUNDIN(LYCHREL,STASH(MARCH(STEP))) !A value known to later pass ENUFF? IF (DEJAVU .GT. 0) THEN !If so, there is no need to follow that march again. c WRITE (6,*) SEED,STEP,"Latecomer! List#",DEJAVU !So this starter has been preempted. c CALL BIGWRITE("Latecomer!",STASH(LYCHREL(DEJAVU))) !Or, STASH(MARCH(STEP)), they being equal. LLIST(0) = LLIST(0) + 1 !Count another latecomer. LLIST(LLIST(0)) = START !This was its starting value's finger. IF (PALINDROME(STASH(START))) THEN !Perhaps its starting value was also already a palindrome? L0P(0) = L0P(0) + 1 !Yes! Count another such. L0P(L0P(0)) = START !Using a finger, rather than copying a BIGINT. END IF !A Lychrel number whose zeroth step is palindromic. START = 0 !This is not to be unfingered! LL = LL + 1 !Anyway, this path has joined a known long march. CALL FREESTASH(MARCH(STEP)) !This value is already fingered in a list. CALL SLURP(LYCHREL) !So, all its steps do so also, including the last. GO TO 110 !Even though its later start might find a palindrome within ENUFF steps. END IF !So much for discoveries at each step. IF (STEP.LT.ENUFF) THEN !Are we there yet? STEP = STEP + 1 !It seems there is no reason to stop. MARCH(0) = STEP !So, the long march extends. CALL GRABSTASH(MARCH(STEP)) !Another step. CALL ADVANCE(STASH(MARCH(STEP - 1)),STASH(MARCH(STEP))) !Lurch forwards. GO TO 100 !And see what happens here. END IF !The end of the loop. Chase completed, having reached STEP = ENUFF with no decision. WRITE (6,*) SEED,"retains Lychrel potential." !Since a palindrome has not been reached. IF (PALINDROME(STASH(START))) THEN !Perhaps it started as a palindrome? L0P(0) = L0P(0) + 1 !It did! L0P(L0P(0)) = START !So remember it. START = 0 !And don't unhand this entry, a finger to it being saved. END IF !Enough shades of classification. NL = NL + 1 !Count another at the end of a long march. CALL SLURP(LYCHREL) !And save the lot, including the final value. 110 IF (START.GT.0) CALL FREESTASH(START) !The starting value was not held as a part of the MARCH. END DO TRY !Start another. Cast forth a summary. WRITE (6,*) WRITE (6,11) NL,ENUFF,LL,LYCHREL(0) 11 FORMAT (I8," starters attained step ",I0," and ", 1 I0," joined a long march. " 2 I0," waypoints stashed.") c CALL SHOWLIST("starters that joined a Long March",LLIST) CALL SHOWLIST("Long Marchers starting as palindromes",L0P) WRITE (6,12) NP,LP,PLIST(0) 12 FORMAT (I8," starters ended as a palindrome, ", 1 I0," joined a route leading to a palindrome. ", 2 I0," waypoints stashed.") CONTAINS !An assistant. SUBROUTINE SLURP(LIST) !Adds the elements in MARCH to LIST. C Entries in LIST are such that STASH(LIST(~)) is ordered. Because I arrange this. C Entries MARCH are also in increasing order as they are successive values from ADVANCE. C Accordingly, if only a few entries are to be added, a binary search can be used to find the C location for insertion, and then existing entries can be shifted up to make room for the new entry. C This is the basic task of Insertionsort, however, this shift can be conducted without invoking ORDER C to determine its bounds, as is done by Insertionsort, and ORDER takes a lot of time to decide. C In other words, the binary search makes only a few calls to ORDER and then the moves follow, in one go, C whereas the Insertionsort makes as many calls to ORDER as it makes moves, and does so stepwise. C When many entries are to be added, they could be appended to LIST and then COMBSORT invoked. C This is infrequent as few numbers evoke a lengthy march, so that method is adequate. C But since both lists are in order, a merge of the two lists would be more stylish, if encoded clunkily. C It turns out that the incoming set may finger a value that is already in LIST, c so equal values may appear. With the binary search method, such incomers can simply be skipped, c but with the merge it is a bit more messy. In the event, the new value is discarded and the c old one retained. C For instance, 5 -> 10 -> 11 so fingers for 5 and 10 are added to PLIST. C Later on, 10 -> 11 and a finger for 10 is to be added to PLIST, because the starting value is not checked. C However, a later version refrains from adding the (unchecked) starting value, and then, no worries. INTEGER LIST(0:MSTASH) !Some string of numbers. INTEGER MIST(0:MSTASH) !LIST(0) is the upper bound, but risks stack overflow. INTEGER I,S,L !A stepper. Check for annoying nullities. 1 IF (MARCH(0).LE.0) RETURN !An empty march already! IF (MARCH(MARCH(0)).LE.0) THEN !Otherwise, look at the last step. MARCH(0) = MARCH(0) - 1 !It was boring. GO TO 1 !So, go back one and look afresh. END IF !Having snipped off trailing nullities, what remains means effort. Can't escape some work. IF (MARCH(0) .LE. 6) THEN !If we have a few only, DO I = 1,MARCH(0) !Work through them one by one, S = MARCH(I) !The finger for this step of the march. IF (S.LE.0) CYCLE !A stump? L = FOUNDIN(LIST,STASH(S)) !Using a binary search to find the proper place. IF (L.GT.0) THEN !If already present, CALL FREESTASH(S) !Its entry is no longer needed. CYCLE !So skip this. END IF !But if not found, a place must be made. L = 1 - L !Finger where the missing element should be. LIST(LIST(0) + 1:L + 1:-1) = LIST(LIST(0):L:-1) !Shift followers up to make space. LIST(0) = LIST(0) + 1 !Count another. LIST(L) = S !Place it. END DO !On to the next. ELSE !But if there are many to add, merge the two lists... Both are ordered. MIST(0:LIST(0)) = LIST(0:LIST(0)) !Copy the source list. LIST(0) = 0 !It is to be reformed by the merge. L = 1 !Start with the first in MIST. DO I = 1,MARCH(0) !And work along the long MARCH. S = MARCH(I) !So, a step from the long march. IF (S.LE.0) CYCLE !And if not an empty step, we have one. 11 LIST(0) = LIST(0) + 1 !Count in another for this list. IF (L.LE.MIST(0)) THEN !Still have suppliers from what had been LIST? IF (ORDER(STASH(MIST(L)),STASH(S))) 14,13,12 !Yes, Which is to be selected? 12 LIST(LIST(0)) = MIST(L) !STASH(MIST(L)) precedes STASH(S), so take it. L = L + 1 !Advance to the next MIST entry. GO TO 11 !And look again. 13 CALL FREESTASH(S) !Equal. Discard the new entry. S = MIST(L) !And pefer the established entry. L = L + 1 !Advance past the MIST(L) entry. END IF !Thus, MIST entries have been rolled until a MARCH entry was due. 14 LIST(LIST(0)) = S !Save the finger - which may have come from MIST... END DO !On to the next MARCH. S = MIST(0) - L + 1 !The number of MIST entries still waiting. IF (S .GT. 0) THEN !Are there any? LIST(LIST(0) + 1:LIST(0) + S) = MIST(L:MIST(0)) !Yes. Append them. LIST(0) = LIST(0) + S !And count them in. END IF !So much for the merge. END IF !Otherwise, a COMBSORT would do. END SUBROUTINE SLURP !Can't overflow, because each LIST has room for MSTASH entries. END SUBROUTINE INSPECT !That was fun. END MODULE LYCHREL SEARCH !Enough of that.   PROGRAM TEST USE LYCHREL SEARCH CALL PREPARESTASH Clear my lists. LYCHREL = 0 !No Lychrel candidates. LLIST = 0 !No latecomers to a Lychrel candidacy sequence. PLIST = 0 !No numbers leading to a palindrome. L0P = 0 !No Lychrel/latecomers starting as a palindrome.   CALL INSPECT(1,10000,500) !Whee!   WRITE (6,*) "Longest digit string =",LONGESTNUMBER WRITE (6,*) "Unused STASH entries =",AVAILS(0) END  
http://rosettacode.org/wiki/Magic_8-ball
Magic 8-ball
Task Create Magic 8-Ball. See details at:   Magic 8-Ball. 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
#Python
Python
import random   s = ('It is certain', 'It is decidedly so', 'Without a doubt', 'Yes, definitely', 'You may rely on it', 'As I see it, yes', 'Most likely', 'Outlook good', 'Signs point to yes', 'Yes', 'Reply hazy, try again', 'Ask again later', 'Better not tell you now', 'Cannot predict now', 'Concentrate and ask again', "Don't bet on it", 'My reply is no', 'My sources say no', 'Outlook not so good', 'Very doubtful')   q_and_a = {}   while True: question = input('Ask your question:') if len(question) == 0: break   if question in q_and_a: print('Your question has already been answered') else: answer = random.choice(s) q_and_a[question] = answer print(answer)
http://rosettacode.org/wiki/Magic_8-ball
Magic 8-ball
Task Create Magic 8-Ball. See details at:   Magic 8-Ball. 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
#Quackery
Quackery
[ 20 random [ table $ "Concentrate and ask again." $ "Yes." $ "Better not tell you now." $ "Most likely." $ "Reply hazy, try again." $ "Outlook good." $ "Outlook not so good." $ "It is certain." $ "Cannot predict now." $ "Very doubtful." $ "Signs point to yes." $ "My reply is no." $ "It is decidedly so." $ "Ask again later." $ "You may rely on it." $ "Without a doubt." $ "Don't count on it." $ "Yes - definitely." $ "My sources say no." $ "As I see it, yes." ] do echo$ cr ] is 8-ball ( --> )
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#uBasic.2F4tH
uBasic/4tH
A =-21000 ' Left Edge = -2.1 B = 15000 ' Right Edge = 1.5 C = 15000 ' Top Edge = 1.5 D =-15000 ' Bottom Edge = -1.5 E = 200 ' Max Iteration Depth F = 350 ' X Step Size G = 750 ' Y Step Size   For L = C To D Step -G ' Y0 For K = A To B-1 Step F ' X0 V = 0 ' Y U = 0 ' X I = 32 ' Char To Be Displayed For O = 0 To E-1 ' Iteration X = (U/10 * U) / 1000 ' X*X Y = (V/10 * V) / 1000 ' Y*Y If (X + Y > 40000) I = 48 + O ' Print Digit 0...9 If (O > 9) ' If Iteration Count > 9, I = 64 ' Print '@' Endif Break Endif Z = X - Y + K ' Temp = X*X - Y*Y + X0 V = (U/10 * V) / 500 + L ' Y = 2*X*Y + Y0 U = Z ' X = Temp Next Gosub I ' Ins_char(I) Next Print Next   End ' Translate number to ASCII 32 Print " "; : Return 48 Print "0"; : Return 49 Print "1"; : Return 50 Print "2"; : Return 51 Print "3"; : Return 52 Print "4"; : Return 53 Print "5"; : Return 54 Print "6"; : Return 55 Print "7"; : Return 56 Print "8"; : Return 57 Print "9"; : Return 64 Print "@"; : Return
http://rosettacode.org/wiki/Mad_Libs
Mad Libs
This page uses content from Wikipedia. The original article was at Mad Libs. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Mad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results. Task; Write a program to create a Mad Libs like story. The program should read an arbitrary multiline story from input. The story will be terminated with a blank line. Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements. Stop when there are none left and print the final story. The input should be an arbitrary story in the form: <name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home. Given this example, it should then ask for a name, a he or she and a noun (<name> gets replaced both times with the same value). 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
#Commodore_BASIC
Commodore BASIC
10 rem mad lib for rosetta code 15 dim bf$(100),wd$(50),tg$(50):tb=49152 20 print chr$(147);chr$(14);"Mad Lib Processor":print 25 gosub 1000 30 gosub 100:gosub 250:gosub 300:gosub 400 40 print:print:print "Again? ";:gosub 500:print k$ 45 if k$<>"y" then end 50 goto 20 100 tg=1:for i=1 to bp:n$="":mo=0 105 t$=bf$(i) 110 for j=1 to len(t$) 115 ch$=mid$(t$,j,1) 120 if ch$="<" then mo=1:goto 140 125 if ch$=">" then mo=0:gosub 200:n$=n$+wd$:tg$="":goto 140 130 if mo=0 then n$=n$+ch$ 135 if mo=1 then tg$=tg$+ch$ 140 next j 145 bf$(i)=n$ 150 next i 155 return 200 for z=1 to tg 205 if tg$(z)=tg$ then wd$=wd$(z):return 210 next z 215 tg=tg+1:tg$(tg)=tg$ 220 print "Enter a ";tg$(tg);:input wd$ 225 wd$(tg)=wd$ 230 return 250 print chr$(147):print "Processing...":print 255 m=tb:os=0:ns=0:for i=1 to bp-1 260 t$=bf$(i) 265 for c=1 to len(t$):ch$=mid$(t$,c,1) 270 poke m,asc(ch$+chr$(0)):m=m+1:next c 275 next i:rem poke m,32:m=m+1 280 m=m-1:return 300 rem insert cr for word wrap 310 pt=tb:sz=0:ll=0 320 if peek(pt)=32 then gosub 350:if(ll+sz>39) then poke pt,13:ll=-1:sz=0 325 if peek(pt)=13 then ll=-1 330 if pt<>m then pt=pt+1:ll=ll+1:goto 320 340 return 350 rem look ahead to next space 355 nx=pt+1:sz=1 360 if peek(nx)=32 or peek(nx)=13 then return 365 nx=nx+1:sz=sz+1 370 if nx=m then return 375 goto 360 400 rem output memory buffer 401 ln=0:print chr$(147); 410 for i=tb to m:c=peek(i) 420 if c=13 then ln=ln+1 425 print chr$(c); 430 if ln=23 then ln=0:print:gosub 550 440 next i 450 return 500 rem clear buffer, wait for a key 501 get k$:if k$<>"" then 501 505 get k$:if k$="" then 505 510 return 550 rem pause prompt 560 print"[Pause]{CRSR-LEFT 7}"; 565 gosub 500 570 print"{SPACE 7}{CRSR-LEFT 7}{CRSR-UP}"; 575 return 1000 rem load file 1005 bp=1 1010 print:input "Enter name of file: ";fi$ 1020 open 7,8,7,"0:"+fi$+",s,r" 1025 rem gosub 2000 1030 rem if er<>0 then print:gosub 2100:return 1035 get#7,a$ 1036 ifa$=chr$(13)thenbf$(bp)=t$+a$:print" ";:t$="":bp=bp+1:goto 1040 1038 t$=t$+a$ 1040 if (st and 64)=0 then goto 1035 1049 close 7:gosub 2000 1050 if er=0 then printchr$(147):return 1055 gosub 2100 1060 if er<>0 then goto 1000 1080 return 2000 rem check disk error 2001 open 15,8,15:input#15,er,en$,et$,es$:close15 2010 return 2100 rem print pretty error 2101 ca$=left$(en$,1):ca$=chr$(asc(ca$)+128):en$=ca$+right$(en$,len(en$)-1) 2105 print:print er;"- ";en$;" at .:";et$;" .:";es$ 2110 print:print "Press a key.":gosub 500 2115 return
http://rosettacode.org/wiki/Ludic_numbers
Ludic numbers
Ludic numbers   are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers. The first ludic number is   1. To generate succeeding ludic numbers create an array of increasing integers starting from   2. 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... (Loop) Take the first member of the resultant array as the next ludic number   2. Remove every   2nd   indexed item from the array (including the first). 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... (Unrolling a few loops...) Take the first member of the resultant array as the next ludic number   3. Remove every   3rd   indexed item from the array (including the first). 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 ... Take the first member of the resultant array as the next ludic number   5. Remove every   5th   indexed item from the array (including the first). 5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 ... Take the first member of the resultant array as the next ludic number   7. Remove every   7th   indexed item from the array (including the first). 7 11 13 17 23 25 29 31 37 41 43 47 53 55 59 61 67 71 73 77 83 85 89 91 97 ... ... Take the first member of the current array as the next ludic number   L. Remove every   Lth   indexed item from the array (including the first). ... Task Generate and show here the first 25 ludic numbers. How many ludic numbers are there less than or equal to 1000? Show the 2000..2005th ludic numbers. Stretch goal Show all triplets of ludic numbers < 250. A triplet is any three numbers     x , {\displaystyle x,}   x + 2 , {\displaystyle x+2,}   x + 6 {\displaystyle x+6}     where all three numbers are also ludic numbers.
#Factor
Factor
USING: formatting fry kernel make math math.ranges namespaces prettyprint.config sequences sequences.extras ; IN: rosetta-code.ludic-numbers   : next-ludic ( seq -- seq' ) dup first '[ nip _ mod zero? not ] filter-index ;   : ludics-upto-2005 ( -- a ) 22,000 2 swap [a,b] [ ! 22k suffices to produce 2005 ludics 1 , [ building get length 2005 = ] [ dup first , next-ludic ] until drop ] { } make ;   : ludic-demo ( -- ) 100 margin set ludics-upto-2005 [ 6 tail* ] [ [ 1000 < ] count ] [ 25 head ] tri "First 25 ludic numbers:\n%u\n\n" "Count of ludic numbers less than 1000:\n%d\n\n" "Ludic numbers 2000 to 2005:\n%u\n" [ printf ] tri@ ;   MAIN: ludic-demo
http://rosettacode.org/wiki/Loops/Wrong_ranges
Loops/Wrong ranges
Loops/Wrong ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment. The purpose of this task is to select the range syntax/function that would generate at least two increasing numbers when given a stop value more than the start value and a positive increment of less than half the difference.   You are then to use that same syntax/function but with different parameters; and show, here, what would happen. Use these values if possible: start stop increment Comment -2 2 1 Normal -2 2 0 Zero increment -2 2 -1 Increments away from stop value -2 2 10 First increment is beyond stop value 2 -2 1 Start more than stop: positive increment 2 2 1 Start equal stop: positive increment 2 2 -1 Start equal stop: negative increment 2 2 0 Start equal stop: zero increment 0 0 0 Start equal stop equal zero: zero increment Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#11l
11l
F displayRange(first, last, step) print(‘(#2, #2, #2): ’.format(first, last, step), end' ‘’) I step == 0 print(‘not allowed.’) E print(Array((first..last).step(step)))   L(f, l, s) [(-2, 2, 1), (-2, 2, 0), (-2, 2, -1), (-2, 2, 10), (2, -2, 1), ( 2, 2, 1), ( 2, 2, -1), (2, 2, 0), ( 0, 0, 0)] displayRange(f, l, s)
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
#8080_Assembly
8080 Assembly
org 100h jmp demo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Check if the 0-terminated string at HL passes the Luhn test. ;;; Returns with carry clear if the string passes, carry set ;;; if the string fails. luhn: mvi b,0 ; Counter mov d,b ; D = S1+S2 (we don't need to keep them separate) lscan: mov a,m ; Get byte inx h ; Increment pointer inr b ; Increment counter ana a ; Is it 0? jnz lscan ; If not, try next byte dcx h ; Go to the byte before the 0 dcx h dcr b ; Decrement counter rz ; If 0, the string was empty, return. lloop: mvi c,'0' ; ASCII zero mov a,d ; Add odd digit to the total add m sub c ; Subtract ASCII zero mov d,a dcr b ; If last digit, we're done jz ldone dcx h ; Go back one byte mov a,m ; Get even digit sub c ; Subtract ASCII zero add a ; Multiply by two mvi c,9 ; 10-1, compensate for extra subtraction loop ldiv: inr c ; Find two digits using trial subtraction sui 10 jnc ldiv add c ; Add the possible second digit in add d ; Add it to the total mov d,a dcx h ; Go back one byte dcr b ; Done yet? jnz lloop ldone: mov a,d ; See if total is divisible by 10 mvi b,10 lchk: sub b ; Trial subtraction, subtract 10 rz ; If zero, it is divisible, return (carry clear) rc ; If carry, it is not divisible, return (carry set) jmp lchk ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Run the routine on the argument given on the CP/M command line demo: lxi h,80h ; Zero-terminate the command line argument mov a,m add l mov l,a inr l mvi m,0 mvi l,82h ; Run the 'luhn' subroutine call luhn mvi c,9 lxi d,pass ; Carry clear = print 'Pass' jnc 5 lxi d,fail ; Carry set = print 'Fail' jmp 5 pass: db 'Pass$' fail: db 'Fail$'
http://rosettacode.org/wiki/Lucas-Lehmer_test
Lucas-Lehmer test
Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2 − 2 {\displaystyle S(n+1)=(S(n))^{2}-2} , and S ( 1 ) = 4 {\displaystyle S(1)=4} . Task Calculate all Mersenne primes up to the implementation's maximum precision, or the 47th Mersenne prime   (whichever comes first).
#ALGOL_68
ALGOL 68
PRAGMAT stack=1M precision=20000 PRAGMAT   PROC is prime = ( INT p )BOOL: IF p = 2 THEN TRUE ELIF p <= 1 OR p MOD 2 = 0 THEN FALSE ELSE BOOL prime := TRUE; FOR i FROM 3 BY 2 TO ENTIER sqrt(p) WHILE prime := p MOD i /= 0 DO SKIP OD; prime FI;   PROC is mersenne prime = ( INT p )BOOL: IF p = 2 THEN TRUE ELSE LONG LONG INT m p := LONG LONG 2 ** p - 1, s := 4; FROM 3 TO p DO s := (s ** 2 - 2) MOD m p OD; s = 0 FI;   test:( INT upb prime = ( long long bits width - 1 ) OVER 2; # no unsigned # INT upb count = 45; # find 45 mprimes if INT has enough bits #   printf(($" Finding Mersenne primes in M[2.."g(0)"]: "l$,upb prime));   INT count:=0; FOR p FROM 2 TO upb prime WHILE IF is prime(p) THEN IF is mersenne prime(p) THEN printf (($" M"g(0)$,p)); count +:= 1 FI FI; count <= upb count DO SKIP OD )
http://rosettacode.org/wiki/Lucky_and_even_lucky_numbers
Lucky and even lucky numbers
Note that in the following explanation list indices are assumed to start at one. Definition of lucky numbers Lucky numbers are positive integers that are formed by: Form a list of all the positive odd integers > 0 1 , 3 , 5 , 7 , 9 , 11 , 13 , 15 , 17 , 19 , 21 , 23 , 25 , 27 , 29 , 31 , 33 , 35 , 37 , 39... {\displaystyle 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39...} Return the first number from the list (which is 1). (Loop begins here) Note then return the second number from the list (which is 3). Discard every third, (as noted), number from the list to form the new list 1 , 3 , 7 , 9 , 13 , 15 , 19 , 21 , 25 , 27 , 31 , 33 , 37 , 39 , 43 , 45 , 49 , 51 , 55 , 57... {\displaystyle 1,3,7,9,13,15,19,21,25,27,31,33,37,39,43,45,49,51,55,57...} (Expanding the loop a few more times...) Note then return the third number from the list (which is 7). Discard every 7th, (as noted), number from the list to form the new list 1 , 3 , 7 , 9 , 13 , 15 , 21 , 25 , 27 , 31 , 33 , 37 , 43 , 45 , 49 , 51 , 55 , 57 , 63 , 67... {\displaystyle 1,3,7,9,13,15,21,25,27,31,33,37,43,45,49,51,55,57,63,67...} Note then return the 4th number from the list (which is 9). Discard every 9th, (as noted), number from the list to form the new list 1 , 3 , 7 , 9 , 13 , 15 , 21 , 25 , 31 , 33 , 37 , 43 , 45 , 49 , 51 , 55 , 63 , 67 , 69 , 73... {\displaystyle 1,3,7,9,13,15,21,25,31,33,37,43,45,49,51,55,63,67,69,73...} Take the 5th, i.e. 13. Remove every 13th. Take the 6th, i.e. 15. Remove every 15th. Take the 7th, i.e. 21. Remove every 21th. Take the 8th, i.e. 25. Remove every 25th. (Rule for the loop) Note the n {\displaystyle n} th, which is m {\displaystyle m} . Remove every m {\displaystyle m} th. Increment n {\displaystyle n} . Definition of even lucky numbers This follows the same rules as the definition of lucky numbers above except for the very first step: Form a list of all the positive even integers > 0 2 , 4 , 6 , 8 , 10 , 12 , 14 , 16 , 18 , 20 , 22 , 24 , 26 , 28 , 30 , 32 , 34 , 36 , 38 , 40... {\displaystyle 2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40...} Return the first number from the list (which is 2). (Loop begins here) Note then return the second number from the list (which is 4). Discard every 4th, (as noted), number from the list to form the new list 2 , 4 , 6 , 10 , 12 , 14 , 18 , 20 , 22 , 26 , 28 , 30 , 34 , 36 , 38 , 42 , 44 , 46 , 50 , 52... {\displaystyle 2,4,6,10,12,14,18,20,22,26,28,30,34,36,38,42,44,46,50,52...} (Expanding the loop a few more times...) Note then return the third number from the list (which is 6). Discard every 6th, (as noted), number from the list to form the new list 2 , 4 , 6 , 10 , 12 , 18 , 20 , 22 , 26 , 28 , 34 , 36 , 38 , 42 , 44 , 50 , 52 , 54 , 58 , 60... {\displaystyle 2,4,6,10,12,18,20,22,26,28,34,36,38,42,44,50,52,54,58,60...} Take the 4th, i.e. 10. Remove every 10th. Take the 5th, i.e. 12. Remove every 12th. (Rule for the loop) Note the n {\displaystyle n} th, which is m {\displaystyle m} . Remove every m {\displaystyle m} th. Increment n {\displaystyle n} . Task requirements Write one or two subroutines (functions) to generate lucky numbers and even lucky numbers Write a command-line interface to allow selection of which kind of numbers and which number(s). Since input is from the command line, tests should be made for the common errors: missing arguments too many arguments number (or numbers) aren't legal misspelled argument (lucky or evenLucky) The command line handling should: support mixed case handling of the (non-numeric) arguments support printing a particular number support printing a range of numbers by their index support printing a range of numbers by their values The resulting list of numbers should be printed on a single line. The program should support the arguments: what is displayed (on a single line) argument(s) (optional verbiage is encouraged) ╔═══════════════════╦════════════════════════════════════════════════════╗ ║ j ║ Jth lucky number ║ ║ j , lucky ║ Jth lucky number ║ ║ j , evenLucky ║ Jth even lucky number ║ ║ ║ ║ ║ j k ║ Jth through Kth (inclusive) lucky numbers ║ ║ j k lucky ║ Jth through Kth (inclusive) lucky numbers ║ ║ j k evenLucky ║ Jth through Kth (inclusive) even lucky numbers ║ ║ ║ ║ ║ j -k ║ all lucky numbers in the range j ──► |k| ║ ║ j -k lucky ║ all lucky numbers in the range j ──► |k| ║ ║ j -k evenLucky ║ all even lucky numbers in the range j ──► |k| ║ ╚═══════════════════╩════════════════════════════════════════════════════╝ where |k| is the absolute value of k Demonstrate the program by: showing the first twenty lucky numbers showing the first twenty even lucky numbers showing all lucky numbers between 6,000 and 6,100 (inclusive) showing all even lucky numbers in the same range as above showing the 10,000th lucky number (extra credit) showing the 10,000th even lucky number (extra credit) See also This task is related to the Sieve of Eratosthenes task. OEIS Wiki Lucky numbers. Sequence A000959 lucky numbers on The On-Line Encyclopedia of Integer Sequences. Sequence A045954 even lucky numbers or ELN on The On-Line Encyclopedia of Integer Sequences. Entry lucky numbers on The Eric Weisstein's World of Mathematics.
#D
D
import std.algorithm; import std.concurrency; import std.conv; import std.getopt; import std.range; import std.stdio;   auto lucky(bool even, int nmax=200_000) { import std.container.array;   int start = even ? 2 : 1;   return new Generator!int({ auto ln = make!(Array!int)(iota(start,nmax,2));   // yield the first number yield(ln[0]);   int n=1; for(; n<ln.length/2+1; n++) { yield(ln[n]);   int step = ln[n]-1;   // remove the non-lucky numbers related to the current lucky number for (int i=step; i<ln.length; i+=step) { ln.linearRemove(ln[].drop(i).take(1)); } }   // yield all remaining values foreach(val; ln[n..$]) { yield(val); } }); }   void help(Option[] opt) { defaultGetoptPrinter("./lucky j [k] [--lucky|--evenLucky]", opt);   writeln; writeln(" argument(s) | what is displayed"); writeln("=============================================="); writeln("-j=m | mth lucky number"); writeln("-j=m --lucky | mth lucky number"); writeln("-j=m --evenLucky | mth even lucky number"); writeln("-j=m -k=n | mth through nth (inclusive) lucky numbers"); writeln("-j=m -k=n --lucky | mth through nth (inclusive) lucky numbers"); writeln("-j=m -k=n --evenLucky | mth through nth (inclusive) even lucky numbers"); writeln("-j=m -k=-n | all lucky numbers in the range [m, n]"); writeln("-j=m -k=-n --lucky | all lucky numbers in the range [m, n]"); writeln("-j=m -k=-n --evenLucky | all even lucky numbers in the range [m, n]"); }   void main(string[] args) { int j; int k; bool evenLucky = false;   void luckyOpt() { evenLucky = false; } auto helpInformation = getopt( args, std.getopt.config.passThrough, std.getopt.config.required, "j", "The starting point to generate lucky numbers", &j, "k", "The ending point for generating lucky numbers", &k, "lucky", "Specify to generate a list of lucky numbers", &luckyOpt, "evenLucky", "Specify to generate a list of even lucky numbers", &evenLucky );   if (helpInformation.helpWanted) { help(helpInformation.options); return; }   if (k>0) { lucky(evenLucky).drop(j-1).take(k-j+1).writeln; } else if (k<0) { auto f = (int a) => j<=a && a<=-k; lucky(evenLucky, -k).filter!f.writeln; } else { lucky(evenLucky).drop(j-1).take(1).writeln; } }
http://rosettacode.org/wiki/LZW_compression
LZW compression
The Lempel-Ziv-Welch (LZW) algorithm provides loss-less data compression. You can read a complete description of it in the   Wikipedia article   on the subject.   It was patented, but it entered the public domain in 2004.
#BaCon
BaCon
CONST lzw_data$ = "TOBEORNOTTOBEORTOBEORNOT"   PRINT "LZWData: ", lzw_data$ encoded$ = Encode_LZW$(lzw_data$) PRINT "Encoded: ", encoded$ PRINT "Decoded: ", Decode_LZW$(encoded$)   '----------------------------------------------------------   FUNCTION Encode_LZW$(sample$)   LOCAL dict ASSOC int LOCAL ch$, buf$, result$ LOCAL nr, x   FOR nr = 0 TO 255 dict(CHR$(nr)) = nr NEXT   FOR x = 1 TO LEN(sample$)   ch$ = MID$(sample$, x, 1)   IF dict(buf$ & ch$) THEN buf$ = buf$ & ch$ ELSE result$ = APPEND$(result$, 0, STR$(dict(buf$))) dict(buf$ & ch$) = nr INCR nr buf$ = ch$ END IF NEXT   result$ = APPEND$(result$, 0, STR$(dict(buf$)))   RETURN result$   END FUNCTION   '----------------------------------------------------------   FUNCTION Decode_LZW$(sample$)   LOCAL list$ ASSOC STRING LOCAL old$, ch$, x$, out$, result$ LOCAL nr   FOR nr = 0 TO 255 list$(STR$(nr)) = CHR$(nr) NEXT   old$ = TOKEN$(sample$, 1)   ch$ = list$(old$) result$ = ch$   FOR x$ IN LAST$(sample$, 1)   IF NOT(LEN(list$(x$))) THEN out$ = list$(old$) out$ = out$ & ch$ ELSE out$ = list$(x$) END IF   result$ = result$ & out$ ch$ = LEFT$(out$, 1) list$(STR$(nr)) = list$(old$) & ch$   INCR nr old$ = x$ NEXT   RETURN result$   END FUNCTION
http://rosettacode.org/wiki/LU_decomposition
LU decomposition
Every square matrix A {\displaystyle A} can be decomposed into a product of a lower triangular matrix L {\displaystyle L} and a upper triangular matrix U {\displaystyle U} , as described in LU decomposition. A = L U {\displaystyle A=LU} It is a modified form of Gaussian elimination. While the Cholesky decomposition only works for symmetric, positive definite matrices, the more general LU decomposition works for any square matrix. There are several algorithms for calculating L and U. To derive Crout's algorithm for a 3x3 example, we have to solve the following system: A = ( a 11 a 12 a 13 a 21 a 22 a 23 a 31 a 32 a 33 ) = ( l 11 0 0 l 21 l 22 0 l 31 l 32 l 33 ) ( u 11 u 12 u 13 0 u 22 u 23 0 0 u 33 ) = L U {\displaystyle A={\begin{pmatrix}a_{11}&a_{12}&a_{13}\\a_{21}&a_{22}&a_{23}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}={\begin{pmatrix}l_{11}&0&0\\l_{21}&l_{22}&0\\l_{31}&l_{32}&l_{33}\\\end{pmatrix}}{\begin{pmatrix}u_{11}&u_{12}&u_{13}\\0&u_{22}&u_{23}\\0&0&u_{33}\end{pmatrix}}=LU} We now would have to solve 9 equations with 12 unknowns. To make the system uniquely solvable, usually the diagonal elements of L {\displaystyle L} are set to 1 l 11 = 1 {\displaystyle l_{11}=1} l 22 = 1 {\displaystyle l_{22}=1} l 33 = 1 {\displaystyle l_{33}=1} so we get a solvable system of 9 unknowns and 9 equations. A = ( a 11 a 12 a 13 a 21 a 22 a 23 a 31 a 32 a 33 ) = ( 1 0 0 l 21 1 0 l 31 l 32 1 ) ( u 11 u 12 u 13 0 u 22 u 23 0 0 u 33 ) = ( u 11 u 12 u 13 u 11 l 21 u 12 l 21 + u 22 u 13 l 21 + u 23 u 11 l 31 u 12 l 31 + u 22 l 32 u 13 l 31 + u 23 l 32 + u 33 ) = L U {\displaystyle A={\begin{pmatrix}a_{11}&a_{12}&a_{13}\\a_{21}&a_{22}&a_{23}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}={\begin{pmatrix}1&0&0\\l_{21}&1&0\\l_{31}&l_{32}&1\\\end{pmatrix}}{\begin{pmatrix}u_{11}&u_{12}&u_{13}\\0&u_{22}&u_{23}\\0&0&u_{33}\end{pmatrix}}={\begin{pmatrix}u_{11}&u_{12}&u_{13}\\u_{11}l_{21}&u_{12}l_{21}+u_{22}&u_{13}l_{21}+u_{23}\\u_{11}l_{31}&u_{12}l_{31}+u_{22}l_{32}&u_{13}l_{31}+u_{23}l_{32}+u_{33}\end{pmatrix}}=LU} Solving for the other l {\displaystyle l} and u {\displaystyle u} , we get the following equations: u 11 = a 11 {\displaystyle u_{11}=a_{11}} u 12 = a 12 {\displaystyle u_{12}=a_{12}} u 13 = a 13 {\displaystyle u_{13}=a_{13}} u 22 = a 22 − u 12 l 21 {\displaystyle u_{22}=a_{22}-u_{12}l_{21}} u 23 = a 23 − u 13 l 21 {\displaystyle u_{23}=a_{23}-u_{13}l_{21}} u 33 = a 33 − ( u 13 l 31 + u 23 l 32 ) {\displaystyle u_{33}=a_{33}-(u_{13}l_{31}+u_{23}l_{32})} and for l {\displaystyle l} : l 21 = 1 u 11 a 21 {\displaystyle l_{21}={\frac {1}{u_{11}}}a_{21}} l 31 = 1 u 11 a 31 {\displaystyle l_{31}={\frac {1}{u_{11}}}a_{31}} l 32 = 1 u 22 ( a 32 − u 12 l 31 ) {\displaystyle l_{32}={\frac {1}{u_{22}}}(a_{32}-u_{12}l_{31})} We see that there is a calculation pattern, which can be expressed as the following formulas, first for U {\displaystyle U} u i j = a i j − ∑ k = 1 i − 1 u k j l i k {\displaystyle u_{ij}=a_{ij}-\sum _{k=1}^{i-1}u_{kj}l_{ik}} and then for L {\displaystyle L} l i j = 1 u j j ( a i j − ∑ k = 1 j − 1 u k j l i k ) {\displaystyle l_{ij}={\frac {1}{u_{jj}}}(a_{ij}-\sum _{k=1}^{j-1}u_{kj}l_{ik})} We see in the second formula that to get the l i j {\displaystyle l_{ij}} below the diagonal, we have to divide by the diagonal element (pivot) u j j {\displaystyle u_{jj}} , so we get problems when u j j {\displaystyle u_{jj}} is either 0 or very small, which leads to numerical instability. The solution to this problem is pivoting A {\displaystyle A} , which means rearranging the rows of A {\displaystyle A} , prior to the L U {\displaystyle LU} decomposition, in a way that the largest element of each column gets onto the diagonal of A {\displaystyle A} . Rearranging the rows means to multiply A {\displaystyle A} by a permutation matrix P {\displaystyle P} : P A ⇒ A ′ {\displaystyle PA\Rightarrow A'} Example: ( 0 1 1 0 ) ( 1 4 2 3 ) ⇒ ( 2 3 1 4 ) {\displaystyle {\begin{pmatrix}0&1\\1&0\end{pmatrix}}{\begin{pmatrix}1&4\\2&3\end{pmatrix}}\Rightarrow {\begin{pmatrix}2&3\\1&4\end{pmatrix}}} The decomposition algorithm is then applied on the rearranged matrix so that P A = L U {\displaystyle PA=LU} Task description The task is to implement a routine which will take a square nxn matrix A {\displaystyle A} and return a lower triangular matrix L {\displaystyle L} , a upper triangular matrix U {\displaystyle U} and a permutation matrix P {\displaystyle P} , so that the above equation is fulfilled. You should then test it on the following two examples and include your output. Example 1 A 1 3 5 2 4 7 1 1 0 L 1.00000 0.00000 0.00000 0.50000 1.00000 0.00000 0.50000 -1.00000 1.00000 U 2.00000 4.00000 7.00000 0.00000 1.00000 1.50000 0.00000 0.00000 -2.00000 P 0 1 0 1 0 0 0 0 1 Example 2 A 11 9 24 2 1 5 2 6 3 17 18 1 2 5 7 1 L 1.00000 0.00000 0.00000 0.00000 0.27273 1.00000 0.00000 0.00000 0.09091 0.28750 1.00000 0.00000 0.18182 0.23125 0.00360 1.00000 U 11.00000 9.00000 24.00000 2.00000 0.00000 14.54545 11.45455 0.45455 0.00000 0.00000 -3.47500 5.68750 0.00000 0.00000 0.00000 0.51079 P 1 0 0 0 0 0 1 0 0 1 0 0 0 0 0 1
#BBC_BASIC
BBC BASIC
DIM A1(2,2) A1() = 1, 3, 5, 2, 4, 7, 1, 1, 0 PROCLUdecomposition(A1(), L1(), U1(), P1()) PRINT "L1:" ' FNshowmatrix(L1()) PRINT "U1:" ' FNshowmatrix(U1()) PRINT "P1:" ' FNshowmatrix(P1())   DIM A2(3,3) A2() = 11, 9, 24, 2, 1, 5, 2, 6, 3, 17, 18, 1, 2, 5, 7, 1 PROCLUdecomposition(A2(), L2(), U2(), P2()) PRINT "L2:" ' FNshowmatrix(L2()) PRINT "U2:" ' FNshowmatrix(U2()) PRINT "P2:" ' FNshowmatrix(P2()) END   DEF PROCLUdecomposition(a(), RETURN l(), RETURN u(), RETURN p()) LOCAL i%, j%, k%, n%, s, b() : n% = DIM(a(),2) DIM l(n%,n%), u(n%,n%), b(n%,n%) PROCpivot(a(), p()) b() = p() . a() FOR j% = 0 TO n% l(j%,j%) = 1 FOR i% = 0 TO j% s = 0 FOR k% = 0 TO i% : s += u(k%,j%) * l(i%,k%) : NEXT u(i%,j%) = b(i%,j%) - s NEXT FOR i% = j% TO n% s = 0 FOR k% = 0 TO j% : s += u(k%,j%) * l(i%,k%) : NEXT IF i%<>j% l(i%,j%) = (b(i%,j%) - s) / u(j%,j%) NEXT NEXT j% ENDPROC   DEF PROCpivot(a(), RETURN p()) LOCAL i%, j%, m%, n%, r% : n% = DIM(a(),2) DIM p(n%,n%) : FOR i% = 0 TO n% : p(i%,i%) = 1 : NEXT FOR i% = 0 TO n% m% = a(i%,i%) r% = i% FOR j% = i% TO n% IF a(j%,i%) > m% m% = a(j%,i%) : r% = j% NEXT IF i%<>r% THEN FOR j% = 0 TO n% : SWAP p(i%,j%),p(r%,j%) : NEXT ENDIF NEXT i% ENDPROC   DEF FNshowmatrix(a()) LOCAL @%, i%, j%, a$ @% = &102050A FOR i% = 0 TO DIM(a(),1) FOR j% = 0 TO DIM(a(),2) a$ += STR$(a(i%,j%)) + ", " NEXT a$ = LEFT$(LEFT$(a$)) + CHR$(13) + CHR$(10) NEXT i% = a$
http://rosettacode.org/wiki/Lychrel_numbers
Lychrel numbers
  Take an integer n, greater than zero.   Form the next n of its series by reversing the digits of the current n and adding the result to the current n.   Stop when n becomes palindromic - i.e. the digits of n in reverse order == n. The above recurrence relation when applied to most starting numbers n = 1, 2, ... terminates in a palindrome quite quickly. Example If n0 = 12 we get 12 12 + 21 = 33, a palindrome! And if n0 = 55 we get 55 55 + 55 = 110 110 + 011 = 121, a palindrome! Notice that the check for a palindrome happens   after   an addition. Some starting numbers seem to go on forever; the recurrence relation for 196 has been calculated for millions of repetitions forming numbers with millions of digits, without forming a palindrome. These numbers that do not end in a palindrome are called Lychrel numbers. For the purposes of this task a Lychrel number is any starting number that does not form a palindrome within 500 (or more) iterations. Seed and related Lychrel numbers Any integer produced in the sequence of a Lychrel number is also a Lychrel number. In general, any sequence from one Lychrel number might converge to join the sequence from a prior Lychrel number candidate; for example the sequences for the numbers 196 and then 689 begin: 196 196 + 691 = 887 887 + 788 = 1675 1675 + 5761 = 7436 7436 + 6347 = 13783 13783 + 38731 = 52514 52514 + 41525 = 94039 ... 689 689 + 986 = 1675 1675 + 5761 = 7436 ... So we see that the sequence starting with 689 converges to, and continues with the same numbers as that for 196. Because of this we can further split the Lychrel numbers into true Seed Lychrel number candidates, and Related numbers that produce no palindromes but have integers in their sequence seen as part of the sequence generated from a lower Lychrel number. Task   Find the number of seed Lychrel number candidates and related numbers for n in the range 1..10000 inclusive. (With that iteration limit of 500).   Print the number of seed Lychrels found; the actual seed Lychrels; and just the number of relateds found.   Print any seed Lychrel or related number that is itself a palindrome. Show all output here. References   What's special about 196? Numberphile video.   A023108 Positive integers which apparently never result in a palindrome under repeated applications of the function f(x) = x + (x with digits reversed).   Status of the 196 conjecture? Mathoverflow.
#FreeBASIC
FreeBASIC
' version 13-09-2015 ' compile with: fbc -s console   ' iteration limit #Define max_it 500 ' the highest number to be tested #Define max_number_to_test 10000   Dim As String num, rev Dim As String temp(), store()   Dim As Integer x, x1, palindrome Dim As UInteger it, s, carry, sum, match, seed, related Dim As UInteger num2test, p_count, lychrel_palindrome()   For num2test = 1 To max_number_to_test num = Str(num2test) rev = num : s = Len(num) - 1 For x = 0 To s rev[s - x] = num[x] Next ' if num = rev then palindrome = -1 else palindrome = 0 ' palindrome is set to the result of the compare of num and rev palindrome = (num = rev) it = 0 ReDim temp(1 To max_it) Do carry = 0 For x = s To 0 Step -1 'add the two numbers sum = num[x] + rev[x] + carry If sum > (9 + 48 + 48) Then num[x] = sum - 10 - 48 carry = 1 Else num[x] = sum - 48 carry = 0 End If Next If carry = 1 Then num = "1" + num it = it + 1 : temp(it) = num rev = num : s = Len(num) - 1 For x = 0 To s rev[s - x] = num[x] Next Loop Until num = rev OrElse it = max_it If it = max_it Then match = 0 ' if it's palindrome then save the number If palindrome <> 0 Then p_count = p_count + 1 ReDim Preserve lychrel_palindrome(1 To p_count) lychrel_palindrome(p_count) = num2test End If For x = 1 To seed ' check against previous found seed(s) For x1 = max_it To 1 Step -1 If store(x, 1) = temp(x1) Then match = 1 related = related + 1 Exit For, For Else If Len(store(x,1)) > Len(temp(x1)) Then Exit For End If End If Next Next ' no match found then it's a new seed, store it If match = 0 Then seed = seed + 1 ReDim Preserve store(seed, 1) store(seed, 0) = Str(num2test) store(seed, 1) = temp(max_it) End If End If Next   Print Print " Testing numbers: 1 to "; Str(max_number_to_test) Print " Iteration maximum: ";Str(max_it) Print Print " Number of Lychrel seeds: "; seed Print " Lychrel number: "; For x = 1 To seed : Print store(x,0); " "; : Next : Print Print " Number of relateds found: "; related Print " Lychrel numbers that are palindromes: "; p_count Print " Lychrel palindromes: "; For x = 1 To p_count : Print lychrel_palindrome(x); " "; : Next : Print Print   ' empty keyboard buffer While Inkey <> "" : Wend Print : Print "hit any key to end program" Sleep End
http://rosettacode.org/wiki/Magic_8-ball
Magic 8-ball
Task Create Magic 8-Ball. See details at:   Magic 8-Ball. 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
#R
R
eight_ball <- function() { responses <- c("It is certain", "It is decidedly so", "Without a doubt", "Yes, definitely", "You may rely on it", "As I see it, yes", "Most likely", "Outlook good", "Signs point to yes", "Yes", "Reply hazy, try again", "Ask again later", "Better not tell you now", "Cannot predict now", "Concentrate and ask again", "Don't bet on it", "My reply is no", "My sources say no", "Outlook not so good", "Very doubtful")   question <- ""   cat("Welcome to 8 ball!\n\n", "Please ask yes/no questions to get answers.", " Type 'quit' to exit the program\n\n")   while(TRUE) { question <- readline(prompt="Enter Question: ") if(question == 'quit') { break } randint <- runif(1, 1, 20) cat("Response: ", responses[randint], "\n") } }   if(!interactive()) { eight_ball() }
http://rosettacode.org/wiki/Magic_8-ball
Magic 8-ball
Task Create Magic 8-Ball. See details at:   Magic 8-Ball. 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
#Racket
Racket
(define eight-ball-responses (list "It is certain" "It is decidedly so" "Without a doubt" "Yes definitely" "You may rely on it" "As I see it, yes" "Most likely" "Outlook good" "Yes" "Signs point to yes" "Reply hazy try again" "Ask again later" "Better not tell you now" "Cannot predict now" "Concentrate and ask again" "Don't count on it" "My reply is no" "My sources say no" "Outlook not so good" "Very doubtful"))   (define ((answer-picker answers)) (sequence-ref answers (random (sequence-length answers))))   (define magic-eightball (answer-picker eight-ball-responses))   (module+ main (let loop () (display "What do you want to know\n?") (read-line) (displayln (magic-eightball)) (loop)))
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#UNIX_Shell
UNIX Shell
((xmin=-8601)) # int(-2.1*4096) ((xmax=2867)) # int( 0.7*4096)   ((ymin=-4915)) # int(-1.2*4096) ((ymax=4915)) # int( 1.2*4096)   ((maxiter=30))   ((dx=(xmax-xmin)/72)) ((dy=(ymax-ymin)/24))   C='0123456789' ((lC=${#C}))   for((cy=ymax;cy>=ymin;cy-=dy)) ; do for((cx=xmin;cx<=xmax;cx+=dx)) ; do ((x=0,y=0,x2=0,y2=0)) for((iter=0;iter<maxiter && x2+y2<=16384;iter++)) ; do ((y=((x*y)>>11)+cy,x=x2-y2+cx,x2=(x*x)>>12,y2=(y*y)>>12)) done ((c=iter%lC)) echo -n ${C:$c:1} done echo done
http://rosettacode.org/wiki/Mad_Libs
Mad Libs
This page uses content from Wikipedia. The original article was at Mad Libs. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Mad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results. Task; Write a program to create a Mad Libs like story. The program should read an arbitrary multiline story from input. The story will be terminated with a blank line. Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements. Stop when there are none left and print the final story. The input should be an arbitrary story in the form: <name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home. Given this example, it should then ask for a name, a he or she and a noun (<name> gets replaced both times with the same value). 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
#D
D
import std.stdio, std.regex, std.algorithm, std.string, std.array;   void main() { writeln("Enter a story template, terminated by an empty line:"); string story; while (true) { auto line = stdin.readln().strip(); if (line.empty) break; story ~= line ~ "\n"; }   auto re = regex("<.+?>", "g"); auto fields = story.match(re).map!q{a.hit}().array().sort().uniq(); foreach (field; fields) { writef("Enter a value for '%s': ", field[1 .. $ - 1]); story = story.replace(field, stdin.readln().strip()); }   writeln("\nThe story becomes:\n", story); }
http://rosettacode.org/wiki/Ludic_numbers
Ludic numbers
Ludic numbers   are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers. The first ludic number is   1. To generate succeeding ludic numbers create an array of increasing integers starting from   2. 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... (Loop) Take the first member of the resultant array as the next ludic number   2. Remove every   2nd   indexed item from the array (including the first). 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... (Unrolling a few loops...) Take the first member of the resultant array as the next ludic number   3. Remove every   3rd   indexed item from the array (including the first). 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 ... Take the first member of the resultant array as the next ludic number   5. Remove every   5th   indexed item from the array (including the first). 5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 ... Take the first member of the resultant array as the next ludic number   7. Remove every   7th   indexed item from the array (including the first). 7 11 13 17 23 25 29 31 37 41 43 47 53 55 59 61 67 71 73 77 83 85 89 91 97 ... ... Take the first member of the current array as the next ludic number   L. Remove every   Lth   indexed item from the array (including the first). ... Task Generate and show here the first 25 ludic numbers. How many ludic numbers are there less than or equal to 1000? Show the 2000..2005th ludic numbers. Stretch goal Show all triplets of ludic numbers < 250. A triplet is any three numbers     x , {\displaystyle x,}   x + 2 , {\displaystyle x+2,}   x + 6 {\displaystyle x+6}     where all three numbers are also ludic numbers.
#Fortran
Fortran
program ludic_numbers implicit none   integer, parameter :: nmax = 25000 logical :: ludic(nmax) = .true. integer :: i, j, n   do i = 2, nmax / 2 if (ludic(i)) then n = 0 do j = i+1, nmax if(ludic(j)) n = n + 1 if(n == i) then ludic(j) = .false. n = 0 end if end do end if end do   write(*, "(a)", advance = "no") "First 25 Ludic numbers: " n = 0 do i = 1, nmax if(ludic(i)) then write(*, "(i0, 1x)", advance = "no") i n = n + 1 end if if(n == 25) exit end do   write(*, "(/, a)", advance = "no") "Ludic numbers below 1000: " write(*, "(i0)") count(ludic(:999))   write(*, "(a)", advance = "no") "Ludic numbers 2000 to 2005: " n = 0 do i = 1, nmax if(ludic(i)) then n = n + 1 if(n >= 2000) then write(*, "(i0, 1x)", advance = "no") i if(n == 2005) exit end if end if end do   write(*, "(/, a)", advance = "no") "Ludic Triplets below 250: " do i = 1, 243 if(ludic(i) .and. ludic(i+2) .and. ludic(i+6)) then write(*, "(a, 2(i0, 1x), i0, a, 1x)", advance = "no") "[", i, i+2, i+6, "]" end if end do   end program