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/Long_year | Long year | Most years have 52 weeks, some have 53, according to ISO8601.
Task
Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
| #Factor | Factor | USING: calendar formatting io kernel math.ranges sequences ;
: long-year? ( n -- ? ) 12 28 <date> week-number 53 = ;
"Year Long?\n-----------" print 1990 2021 [a,b]
[ dup long-year? "yes" "no" ? "%d %s\n" printf ] each |
http://rosettacode.org/wiki/Long_year | Long year | Most years have 52 weeks, some have 53, according to ISO8601.
Task
Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
| #Forth | Forth | : dec31wd ( year -- weekday ) dup dup 4 / swap dup 100 / swap 400 / swap - + + 7 mod ;
: long? ( year -- flag ) dup dec31wd 4 = if drop 1 else 1 - dec31wd 3 = if 1 else 0 then then ;
: demo ( startyear endyear -- ) cr swap do i long? if i . then loop cr ; |
http://rosettacode.org/wiki/Long_primes | Long primes |
A long prime (as defined here) is a prime number whose reciprocal (in decimal) has
a period length of one less than the prime number.
Long primes are also known as:
base ten cyclic numbers
full reptend primes
golden primes
long period primes
maximal period primes
proper primes
Another definition: primes p such that the decimal expansion of 1/p has period p-1, which is the greatest period possible for any integer.
Example
7 is the first long prime, the reciprocal of seven
is 1/7, which
is equal to the repeating decimal fraction 0.142857142857···
The length of the repeating part of the decimal fraction
is six, (the underlined part) which is one less
than the (decimal) prime number 7.
Thus 7 is a long prime.
There are other (more) general definitions of a long prime which
include wording/verbiage for bases other than ten.
Task
Show all long primes up to 500 (preferably on one line).
Show the number of long primes up to 500
Show the number of long primes up to 1,000
Show the number of long primes up to 2,000
Show the number of long primes up to 4,000
Show the number of long primes up to 8,000
Show the number of long primes up to 16,000
Show the number of long primes up to 32,000
Show the number of long primes up to 64,000 (optional)
Show all output here.
Also see
Wikipedia: full reptend prime
MathWorld: full reptend prime
OEIS: A001913
| #Factor | Factor | USING: formatting fry io kernel math math.functions math.primes
math.primes.factors memoize prettyprint sequences ;
IN: rosetta-code.long-primes
: period-length ( p -- len )
[ 1 - divisors ] [ '[ 10 swap _ ^mod 1 = ] ] bi find nip ;
MEMO: long-prime? ( p -- ? ) [ period-length ] [ 1 - ] bi = ;
: .lp<=500 ( -- )
500 primes-upto [ long-prime? ] filter
"Long primes <= 500:" print [ pprint bl ] each nl ;
: .#lp<=n ( n -- )
dup primes-upto [ long-prime? t = ] count swap
"%-4d long primes <= %d\n" printf ;
: long-primes-demo ( -- )
.lp<=500 nl
{ 500 1,000 2,000 4,000 8,000 16,000 32,000 64,000 }
[ .#lp<=n ] each ;
MAIN: long-primes-demo |
http://rosettacode.org/wiki/Long_primes | Long primes |
A long prime (as defined here) is a prime number whose reciprocal (in decimal) has
a period length of one less than the prime number.
Long primes are also known as:
base ten cyclic numbers
full reptend primes
golden primes
long period primes
maximal period primes
proper primes
Another definition: primes p such that the decimal expansion of 1/p has period p-1, which is the greatest period possible for any integer.
Example
7 is the first long prime, the reciprocal of seven
is 1/7, which
is equal to the repeating decimal fraction 0.142857142857···
The length of the repeating part of the decimal fraction
is six, (the underlined part) which is one less
than the (decimal) prime number 7.
Thus 7 is a long prime.
There are other (more) general definitions of a long prime which
include wording/verbiage for bases other than ten.
Task
Show all long primes up to 500 (preferably on one line).
Show the number of long primes up to 500
Show the number of long primes up to 1,000
Show the number of long primes up to 2,000
Show the number of long primes up to 4,000
Show the number of long primes up to 8,000
Show the number of long primes up to 16,000
Show the number of long primes up to 32,000
Show the number of long primes up to 64,000 (optional)
Show all output here.
Also see
Wikipedia: full reptend prime
MathWorld: full reptend prime
OEIS: A001913
| #Forth | Forth | : prime? ( n -- ? ) here + c@ 0= ;
: notprime! ( n -- ) here + 1 swap c! ;
: sieve ( n -- )
here over erase
0 notprime!
1 notprime!
2
begin
2dup dup * >
while
dup prime? if
2dup dup * do
i notprime!
dup +loop
then
1+
repeat
2drop ;
: modpow { c b a -- a^b mod c }
c 1 = if 0 exit then
1
a c mod to a
begin
b 0>
while
b 1 and 1 = if
a * c mod
then
a a * c mod to a
b 2/ to b
repeat ;
: divide_out ( n1 n2 -- n )
begin
2dup mod 0=
while
tuck / swap
repeat drop ;
: long_prime? ( n -- ? )
dup prime? invert if drop false exit then
10 over mod 0= if drop false exit then
dup 1-
2 >r
begin
over r@ dup * >
while
r@ prime? if
dup r@ mod 0= if
over dup 1- r@ / 10 modpow 1 = if
2drop rdrop false exit
then
r@ divide_out
then
then
r> 1+ >r
repeat
rdrop
dup 1 = if 2drop true exit then
over 1- swap / 10 modpow 1 <> ;
: next_long_prime ( n -- n )
begin 2 + dup long_prime? until ;
500 constant limit1
512000 constant limit2
: main
limit2 1+ sieve
limit2 limit1 3
0 >r
." Long primes up to " over 1 .r ." :" cr
begin
2 pick over >
while
next_long_prime
dup limit1 < if dup . then
dup 2 pick > if
over limit1 = if cr then
." Number of long primes up to " over 6 .r ." : " r@ 5 .r cr
swap 2* swap
then
r> 1+ >r
repeat
2drop drop rdrop ;
main
bye |
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously | Loop over multiple arrays simultaneously | Task
Loop over multiple arrays (or lists or tuples or whatever they're called in
your language) and display the i th element of each.
Use your language's "for each" loop if it has one, otherwise iterate
through the collection in order with some other loop.
For this example, loop over the arrays:
(a,b,c)
(A,B,C)
(1,2,3)
to produce the output:
aA1
bB2
cC3
If possible, also describe what happens when the arrays are of different lengths.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #BaCon | BaCon |
DECLARE a1$[] = {"a", "b", "c"} TYPE STRING
DECLARE a2$[] = {"A", "B", "C"} TYPE STRING
DECLARE a3[] = {1, 2, 3} TYPE int
WHILE (a3[i] <= 3)
PRINT a1$[i], a2$[i], a3[i]
INCR i
WEND
|
http://rosettacode.org/wiki/Loops/Break | Loops/Break | Task
Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive).
If a number is 10, stop the loop after printing it, and do not generate any further numbers.
Otherwise, generate and print a second random number before restarting the loop.
If the number 10 is never generated as the first number in a loop, loop forever.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
| #C.2B.2B | C++ | #include <iostream>
#include <ctime>
#include <cstdlib>
int main(){
srand(time(NULL)); // randomize seed
while(true){
const int a = rand() % 20; // biased towards lower numbers if RANDMAX % 20 > 0
std::cout << a << std::endl;
if(a == 10)
break;
const int b = rand() % 20;
std::cout << b << std::endl;
}
return 0;
} |
http://rosettacode.org/wiki/Longest_common_subsequence | Longest common subsequence | Introduction
Define a subsequence to be any output string obtained by deleting zero or more symbols from an input string.
The Longest Common Subsequence (LCS) is a subsequence of maximum length common to two or more strings.
Let A ≡ A[0]… A[m - 1] and B ≡ B[0]… B[n - 1], m < n be strings drawn from an alphabet Σ of size s, containing every distinct symbol in A + B.
An ordered pair (i, j) will be referred to as a match if A[i] = B[j], where 0 < i ≤ m and 0 < j ≤ n.
Define a non-strict product-order (≤) over ordered pairs, such that (i1, j1) ≤ (i2, j2) ⇔ i1 ≤ i2 and j1 ≤ j2. We define (≥) similarly.
We say m1, m2 are comparable if either m1 ≤ m2 or m1 ≥ m2 holds. If i1 < i2 and j2 < j1 (or i2 < i1 and j1 < j2) then neither m1 ≤ m2 nor m1 ≥ m2 are possible; and we say m1, m2 are incomparable.
We also define the strict product-order (<) over ordered pairs, such that (i1, j1) < (i2, j2) ⇔ i1 < i2 and j1 < j2. We define (>) similarly.
Given a set of matches M, a chain C is a subset of M consisting of at least one element m; and where either m1 < m2 or m1 > m2 for every pair of distinct elements m1 and m2. An antichain D is any subset of M in which every pair of distinct elements m1 and m2 are incomparable.
The set M represents a relation over match pairs: M[i, j] ⇔ (i, j) ∈ M. A chain C can be visualized as a curve which strictly increases as it passes through each match pair in the m*n coordinate space.
Finding an LCS can be restated as the problem of finding a chain of maximum cardinality p over the set of matches M.
According to [Dilworth 1950], this cardinality p equals the minimum number of disjoint antichains into which M can be decomposed. Note that such a decomposition into the minimal number p of disjoint antichains may not be unique.
Contours
Forward Contours FC[k] of class k are defined inductively, as follows:
FC[0] consists of those elements m1 for which there exists no element m2 such that m2 < m1.
FC[k] consists of those elements m1 for which there exists no element m2 such that m2 < m1; and where neither m1 nor m2 are contained in FC[l] for any class l < k.
Reverse Contours RC[k] of class k are defined similarly.
Members of the Meet (∧), or Infimum of a Forward Contour are referred to as its Dominant Matches: those m1 for which there exists no m2 such that m2 < m1.
Members of the Join (∨), or Supremum of a Reverse Contour are referred to as its Dominant Matches: those m1 for which there exists no m2 such that m2 > m1.
Where multiple Dominant Matches exist within a Meet (or within a Join, respectively) the Dominant Matches will be incomparable to each other.
Background
Where the number of symbols appearing in matches is small relative to the length of the input strings, reuse of the symbols increases; and the number of matches will tend towards quadratic, O(m*n) growth. This occurs, for example, in the Bioinformatics application of nucleotide and protein sequencing.
The divide-and-conquer approach of [Hirschberg 1975] limits the space required to O(n). However, this approach requires O(m*n) time even in the best case.
This quadratic time dependency may become prohibitive, given very long input strings. Thus, heuristics are often favored over optimal Dynamic Programming solutions.
In the application of comparing file revisions, records from the input files form a large symbol space; and the number of symbols approaches the length of the LCS. In this case the number of matches reduces to linear, O(n) growth.
A binary search optimization due to [Hunt and Szymanski 1977] can be applied to the basic Dynamic Programming approach, resulting in an expected performance of O(n log m). Performance can degrade to O(m*n log m) time in the worst case, as the number of matches grows to O(m*n).
Note
[Rick 2000] describes a linear-space algorithm with a time bound of O(n*s + p*min(m, n - p)).
Legend
A, B are input strings of lengths m, n respectively
p is the length of the LCS
M is the set of match pairs (i, j) such that A[i] = B[j]
r is the magnitude of M
s is the magnitude of the alphabet Σ of distinct symbols in A + B
References
[Dilworth 1950] "A decomposition theorem for partially ordered sets"
by Robert P. Dilworth, published January 1950,
Annals of Mathematics [Volume 51, Number 1, pp. 161-166]
[Goeman and Clausen 2002] "A New Practical Linear Space Algorithm for the Longest Common
Subsequence Problem" by Heiko Goeman and Michael Clausen,
published 2002, Kybernetika [Volume 38, Issue 1, pp. 45-66]
[Hirschberg 1975] "A linear space algorithm for computing maximal common subsequences"
by Daniel S. Hirschberg, published June 1975
Communications of the ACM [Volume 18, Number 6, pp. 341-343]
[Hunt and McIlroy 1976] "An Algorithm for Differential File Comparison"
by James W. Hunt and M. Douglas McIlroy, June 1976
Computing Science Technical Report, Bell Laboratories 41
[Hunt and Szymanski 1977] "A Fast Algorithm for Computing Longest Common Subsequences"
by James W. Hunt and Thomas G. Szymanski, published May 1977
Communications of the ACM [Volume 20, Number 5, pp. 350-353]
[Rick 2000] "Simple and fast linear space computation of longest common subsequences"
by Claus Rick, received 17 March 2000, Information Processing Letters,
Elsevier Science [Volume 75, pp. 275–281]
Examples
The sequences "1234" and "1224533324" have an LCS of "1234":
1234
1224533324
For a string example, consider the sequences "thisisatest" and "testing123testing". An LCS would be "tsitest":
thisisatest
testing123testing
In this puzzle, your code only needs to deal with strings. Write a function which returns an LCS of two strings (case-sensitive). You don't need to show multiple LCS's.
For more information on this problem please see Wikipedia.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #CoffeeScript | CoffeeScript |
lcs = (s1, s2) ->
len1 = s1.length
len2 = s2.length
# Create a virtual matrix that is (len1 + 1) by (len2 + 1),
# where m[i][j] is the longest common string using only
# the first i chars of s1 and first j chars of s2. The
# matrix is virtual, because we only keep the last two rows
# in memory.
prior_row = ('' for i in [0..len2])
for i in [0...len1]
row = ['']
for j in [0...len2]
if s1[i] == s2[j]
row.push prior_row[j] + s1[i]
else
subs1 = row[j]
subs2 = prior_row[j+1]
if subs1.length > subs2.length
row.push subs1
else
row.push subs2
prior_row = row
row[len2]
s1 = "thisisatest"
s2 = "testing123testing"
console.log lcs(s1, s2) |
http://rosettacode.org/wiki/Look-and-say_sequence | Look-and-say sequence | The Look and say sequence is a recursively defined sequence of numbers studied most notably by John Conway.
The look-and-say sequence is also known as the Morris Number Sequence, after cryptographer Robert Morris, and the puzzle What is the next number in the sequence 1, 11, 21, 1211, 111221? is sometimes referred to as the Cuckoo's Egg, from a description of Morris in Clifford Stoll's book The Cuckoo's Egg.
Sequence Definition
Take a decimal number
Look at the number, visually grouping consecutive runs of the same digit.
Say the number, from left to right, group by group; as how many of that digit there are - followed by the digit grouped.
This becomes the next number of the sequence.
An example:
Starting with the number 1, you have one 1 which produces 11
Starting with 11, you have two 1's. I.E.: 21
Starting with 21, you have one 2, then one 1. I.E.: (12)(11) which becomes 1211
Starting with 1211, you have one 1, one 2, then two 1's. I.E.: (11)(12)(21) which becomes 111221
Task
Write a program to generate successive members of the look-and-say sequence.
Related tasks
Fours is the number of letters in the ...
Number names
Self-describing numbers
Self-referential sequence
Spelling of ordinal numbers
See also
Look-and-Say Numbers (feat John Conway), A Numberphile Video.
This task is related to, and an application of, the Run-length encoding task.
Sequence A005150 on The On-Line Encyclopedia of Integer Sequences.
| #BCPL | BCPL | get "libhdr"
manifest $(
amount = 15
bufsize = 128
$)
let move(dest,src) be
$( until !src = 0 do
$( !dest := !src
dest := dest + 1
src := src + 1
$)
!dest := 0
$)
let count(v) = valof
$( let i=1
while v!i = !v do i := i + 1
resultis i
$)
let looksay(in,out) be
$( until !in = 0 do
$( let n = count(in)
out!0 := n
out!1 := !in
out := out + 2
in := in + n
$)
!out := 0
$)
let show(v) be
$( until !v = 0 do
$( writen(!v)
v := v + 1
$)
wrch('*N')
$)
let start() be
$( let buf1 = vec bufsize and buf2 = vec bufsize
buf1!0 := 1
buf1!1 := 0
for n = 1 to amount do
$( show(buf1)
looksay(buf1,buf2)
move(buf1,buf2)
$)
$) |
http://rosettacode.org/wiki/Longest_string_challenge | Longest string challenge | Background
This "longest string challenge" is inspired by a problem that used to be given to students learning Icon. Students were expected to try to solve the problem in Icon and another language with which the student was already familiar. The basic problem is quite simple; the challenge and fun part came through the introduction of restrictions. Experience has shown that the original restrictions required some adjustment to bring out the intent of the challenge and make it suitable for Rosetta Code.
Basic problem statement
Write a program that reads lines from standard input and, upon end of file, writes the longest line to standard output.
If there are ties for the longest line, the program writes out all the lines that tie.
If there is no input, the program should produce no output.
Task
Implement a solution to the basic problem that adheres to the spirit of the restrictions (see below).
Describe how you circumvented or got around these 'restrictions' and met the 'spirit' of the challenge. Your supporting description may need to describe any challenges to interpreting the restrictions and how you made this interpretation. You should state any assumptions, warnings, or other relevant points. The central idea here is to make the task a bit more interesting by thinking outside of the box and perhaps by showing off the capabilities of your language in a creative way. Because there is potential for considerable variation between solutions, the description is key to helping others see what you've done.
This task is likely to encourage a variety of different types of solutions. They should be substantially different approaches.
Given the input:
a
bb
ccc
ddd
ee
f
ggg
the output should be (possibly rearranged):
ccc
ddd
ggg
Original list of restrictions
No comparison operators may be used.
No arithmetic operations, such as addition and subtraction, may be used.
The only datatypes you may use are integer and string. In particular, you may not use lists.
Do not re-read the input file. Avoid using files as a replacement for lists (this restriction became apparent in the discussion).
Intent of restrictions
Because of the variety of languages on Rosetta Code and the wide variety of concepts used in them, there needs to be a bit of clarification and guidance here to get to the spirit of the challenge and the intent of the restrictions.
The basic problem can be solved very conventionally, but that's boring and pedestrian. The original intent here wasn't to unduly frustrate people with interpreting the restrictions, it was to get people to think outside of their particular box and have a bit of fun doing it.
The guiding principle here should be to be creative in demonstrating some of the capabilities of the programming language being used. If you need to bend the restrictions a bit, explain why and try to follow the intent. If you think you've implemented a 'cheat', call out the fragment yourself and ask readers if they can spot why. If you absolutely can't get around one of the restrictions, explain why in your description.
Now having said that, the restrictions require some elaboration.
In general, the restrictions are meant to avoid the explicit use of these features.
"No comparison operators may be used" - At some level there must be some test that allows the solution to get at the length and determine if one string is longer. Comparison operators, in particular any less/greater comparison should be avoided. Representing the length of any string as a number should also be avoided. Various approaches allow for detecting the end of a string. Some of these involve implicitly using equal/not-equal; however, explicitly using equal/not-equal should be acceptable.
"No arithmetic operations" - Again, at some level something may have to advance through the string. Often there are ways a language can do this implicitly advance a cursor or pointer without explicitly using a +, - , ++, --, add, subtract, etc.
The datatype restrictions are amongst the most difficult to reinterpret. In the language of the original challenge strings are atomic datatypes and structured datatypes like lists are quite distinct and have many different operations that apply to them. This becomes a bit fuzzier with languages with a different programming paradigm. The intent would be to avoid using an easy structure to accumulate the longest strings and spit them out. There will be some natural reinterpretation here.
To make this a bit more concrete, here are a couple of specific examples:
In C, a string is an array of chars, so using a couple of arrays as strings is in the spirit while using a second array in a non-string like fashion would violate the intent.
In APL or J, arrays are the core of the language so ruling them out is unfair. Meeting the spirit will come down to how they are used.
Please keep in mind these are just examples and you may hit new territory finding a solution. There will be other cases like these. Explain your reasoning. You may want to open a discussion on the talk page as well.
The added "No rereading" restriction is for practical reasons, re-reading stdin should be broken. I haven't outright banned the use of other files but I've discouraged them as it is basically another form of a list. Somewhere there may be a language that just sings when doing file manipulation and where that makes sense; however, for most there should be a way to accomplish without resorting to an externality.
At the end of the day for the implementer this should be a bit of fun. As an implementer you represent the expertise in your language, the reader may have no knowledge of your language. For the reader it should give them insight into how people think outside the box in other languages. Comments, especially for non-obvious (to the reader) bits will be extremely helpful. While the implementations may be a bit artificial in the context of this task, the general techniques may be useful elsewhere.
| #Pascal | Pascal | program LongestStringChallenge_1(input, output);
var
Line: string;
Lines: array of string;
position, len: integer;
begin
if not eoln(input) then
begin
len := 1;
position := 0;
readln (line);
setlength(lines, len);
lines[position] := line;
while not eoln(input) do
begin
readln (line);
if length(line) = length(lines[0]) then
begin
inc(position);
inc(len);
setlength(lines, len);
lines[position] := line;
end;
if length(line) > length(lines[0]) then
begin
position := 0;
len := 1;
setlength(lines, 1);
lines[0] := line;
end;
end;
for position := low(lines) to high(lines) do
writeln (lines[position]);
end;
end. |
http://rosettacode.org/wiki/Longest_increasing_subsequence | Longest increasing subsequence | Calculate and show here a longest increasing subsequence of the list:
{
3
,
2
,
6
,
4
,
5
,
1
}
{\displaystyle \{3,2,6,4,5,1\}}
And of the list:
{
0
,
8
,
4
,
12
,
2
,
10
,
6
,
14
,
1
,
9
,
5
,
13
,
3
,
11
,
7
,
15
}
{\displaystyle \{0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15\}}
Note that a list may have more than one subsequence that is of the maximum length.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
Ref
Dynamic Programming #1: Longest Increasing Subsequence on YouTube
An efficient solution can be based on Patience sorting.
| #Kotlin | Kotlin | // version 1.1.0
fun longestIncreasingSubsequence(x: IntArray): IntArray =
when (x.size) {
0 -> IntArray(0)
1 -> x
else -> {
val n = x.size
val p = IntArray(n)
val m = IntArray(n + 1)
var len = 0
for (i in 0 until n) {
var lo = 1
var hi = len
while (lo <= hi) {
val mid = Math.ceil((lo + hi) / 2.0).toInt()
if (x[m[mid]] < x[i]) lo = mid + 1
else hi = mid - 1
}
val newLen = lo
p[i] = m[newLen - 1]
m[newLen] = i
if (newLen > len) len = newLen
}
val s = IntArray(len)
var k = m[len]
for (i in len - 1 downTo 0) {
s[i] = x[k]
k = p[k]
}
s
}
}
fun main(args: Array<String>) {
val lists = listOf(
intArrayOf(3, 2, 6, 4, 5, 1),
intArrayOf(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15)
)
lists.forEach { println(longestIncreasingSubsequence(it).asList()) }
} |
http://rosettacode.org/wiki/Loops/Continue | Loops/Continue | Task
Show the following output using one loop.
1, 2, 3, 4, 5
6, 7, 8, 9, 10
Try to achieve the result by forcing the next iteration within the loop
upon a specific condition, if your language allows it.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Dyalect | Dyalect | for i in 1..10 {
print(i, terminator: "")
if i % 5 == 0 {
print()
continue
}
print(", ", terminator: "")
} |
http://rosettacode.org/wiki/Loops/Continue | Loops/Continue | Task
Show the following output using one loop.
1, 2, 3, 4, 5
6, 7, 8, 9, 10
Try to achieve the result by forcing the next iteration within the loop
upon a specific condition, if your language allows it.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Ela | Ela | open monad io
loop n =
if n > 10 then do
return ()
else do
putStr (show n)
putStr f
loop (n + 1)
where f | n % 5 == 0 = "\r\n"
| else = ", "
_ = loop 1 ::: IO |
http://rosettacode.org/wiki/Longest_common_substring | Longest common substring | Task
Write a function that returns the longest common substring of two strings.
Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing".
Note that substrings are consecutive characters within a string. This distinguishes them from subsequences, which is any sequence of characters within a string, even if there are extraneous characters in between them.
Hence, the longest common subsequence between "thisisatest" and "testing123testing" is "tsitest", whereas the longest common substring is just "test".
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
References
Generalize Suffix Tree
Ukkonen’s Suffix Tree Construction
| #J | J | lcstr=:4 :0
C=. ({.~ 1+$) x=/y
M=. >./ (* * * >. * + (_1&|.)@:|:^:2)^:_ C
N=. >./ M
y {~ (M i. N)-i.-N
) |
http://rosettacode.org/wiki/Longest_common_substring | Longest common substring | Task
Write a function that returns the longest common substring of two strings.
Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing".
Note that substrings are consecutive characters within a string. This distinguishes them from subsequences, which is any sequence of characters within a string, even if there are extraneous characters in between them.
Hence, the longest common subsequence between "thisisatest" and "testing123testing" is "tsitest", whereas the longest common substring is just "test".
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
References
Generalize Suffix Tree
Ukkonen’s Suffix Tree Construction
| #Java | Java | public class LongestCommonSubstring {
public static void main(String[] args) {
System.out.println(lcs("testing123testing", "thisisatest"));
System.out.println(lcs("test", "thisisatest"));
System.out.println(lcs("testing", "sting"));
System.out.println(lcs("testing", "thisisasting"));
}
static String lcs(String a, String b) {
if (a.length() > b.length())
return lcs(b, a);
String res = "";
for (int ai = 0; ai < a.length(); ai++) {
for (int len = a.length() - ai; len > 0; len--) {
for (int bi = 0; bi <= b.length() - len; bi++) {
if (a.regionMatches(ai, b, bi, len) && len > res.length()) {
res = a.substring(ai, ai + len);
}
}
}
}
return res;
}
} |
http://rosettacode.org/wiki/Loops/Nested | Loops/Nested | Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over
[
1
,
…
,
20
]
{\displaystyle [1,\ldots ,20]}
.
The loops iterate rows and columns of the array printing the elements until the value
20
{\displaystyle 20}
is met.
Specifically, this task also shows how to break out of nested loops.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Smalltalk | Smalltalk | |i|
i := 1.
[:exit |
Transcript showCR:i.
i == 5 ifTrue:[ exit value:'stopped' ].
i := i + 1.
] loopWithExit |
http://rosettacode.org/wiki/Loops/Nested | Loops/Nested | Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over
[
1
,
…
,
20
]
{\displaystyle [1,\ldots ,20]}
.
The loops iterate rows and columns of the array printing the elements until the value
20
{\displaystyle 20}
is met.
Specifically, this task also shows how to break out of nested loops.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #SPL | SPL | 'fill array
mx,my = 30
> y, 1..my
> x, 1..mx
a[x,y] = #.rnd(20)+1
<
<
'scan array
> y, 1..my
> x, 1..mx
#.output("x=",x,", y=",y, ", a=",a[x,y])
<< a[x,y] = 20
<
<< x!>mx
< |
http://rosettacode.org/wiki/Loops/Foreach | Loops/Foreach | Loop through and print each element in a collection in order.
Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #XPL0 | XPL0 | include c:\cxpl\codes;
int List, I;
[List:= ["Red", "Green", "Blue", "Black", "White"];
for I:= 0, 5-1 do
[Text(0, List(I)); CrLf(0)];
] |
http://rosettacode.org/wiki/Loops/Foreach | Loops/Foreach | Loop through and print each element in a collection in order.
Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #XSLT | XSLT | <fo:block font-weight="bold">Adults:</fo:block>
<xsl:for-each select="person[@age >= 21]">
<fo:block><xsl:value-of select="position()"/>. <xsl:value-of select="@name"/></fo:block>
</xsl:for-each> |
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers | Luhn test of credit card numbers | The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits.
Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test:
Reverse the order of the digits in the number.
Take the first, third, ... and every other odd digit in the reversed digits and sum them to form the partial sum s1
Taking the second, fourth ... and every other even digit in the reversed digits:
Multiply each digit by two and sum the digits if the answer is greater than nine to form partial sums for the even digits
Sum the partial sums of the even digits to form s2
If s1 + s2 ends in zero then the original number is in the form of a valid credit card number as verified by the Luhn test.
For example, if the trial number is 49927398716:
Reverse the digits:
61789372994
Sum the odd digits:
6 + 7 + 9 + 7 + 9 + 4 = 42 = s1
The even digits:
1, 8, 3, 2, 9
Two times each even digit:
2, 16, 6, 4, 18
Sum the digits of each multiplication:
2, 7, 6, 4, 9
Sum the last:
2 + 7 + 6 + 4 + 9 = 28 = s2
s1 + s2 = 70 which ends in zero which means that 49927398716 passes the Luhn test
Task
Write a function/method/procedure/subroutine that will validate a number with the Luhn test, and
use it to validate the following numbers:
49927398716
49927398717
1234567812345678
1234567812345670
Related tasks
SEDOL
ISIN
| #Perl | Perl | sub luhn_test
{
my @rev = reverse split //,$_[0];
my ($sum1,$sum2,$i) = (0,0,0);
for(my $i=0;$i<@rev;$i+=2)
{
$sum1 += $rev[$i];
last if $i == $#rev;
$sum2 += 2*$rev[$i+1]%10 + int(2*$rev[$i+1]/10);
}
return ($sum1+$sum2) % 10 == 0;
}
print luhn_test('49927398716');
print luhn_test('49927398717');
print luhn_test('1234567812345678');
print luhn_test('1234567812345670'); |
http://rosettacode.org/wiki/Loops/Infinite | Loops/Infinite | Task
Print out SPAM followed by a newline in an infinite loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #PureBasic | PureBasic | Repeat
PrintN("SPAM")
ForEver |
http://rosettacode.org/wiki/Loops/Infinite | Loops/Infinite | Task
Print out SPAM followed by a newline in an infinite loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Python | Python | while 1:
print "SPAM" |
http://rosettacode.org/wiki/Loops/Infinite | Loops/Infinite | Task
Print out SPAM followed by a newline in an infinite loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Quackery | Quackery | [ say "SPAM" cr again ] |
http://rosettacode.org/wiki/Loops/While | Loops/While | Task
Start an integer value at 1024.
Loop while it is greater than zero.
Print the value (with a newline) and divide it by two each time through the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreachbas
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Phix | Phix | integer i = 1024
while i!=0 do
?i
i = floor(i/2) -- (see note)
end while
|
http://rosettacode.org/wiki/Loops/While | Loops/While | Task
Start an integer value at 1024.
Loop while it is greater than zero.
Print the value (with a newline) and divide it by two each time through the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreachbas
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #PHL | PHL | var i = 1024;
while (i > 0) {
printf("%i\n", i);
i = i/2;
} |
http://rosettacode.org/wiki/Loops/Downward_for | Loops/Downward for | Task
Write a for loop which writes a countdown from 10 to 0.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #R | R | for(i in 10:0) {print(i)} |
http://rosettacode.org/wiki/Loops/Downward_for | Loops/Downward for | Task
Write a for loop which writes a countdown from 10 to 0.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Racket | Racket |
#lang racket
(for ([i (in-range 10 -1 -1)])
(displayln i))
|
http://rosettacode.org/wiki/Loops/Do-while | Loops/Do-while | Start with a value at 0. Loop while value mod 6 is not equal to 0.
Each time through the loop, add 1 to the value then print it.
The loop must execute at least once.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
Reference
Do while loop Wikipedia.
| #MIPS_Assembly | MIPS Assembly |
.text
main: li $s0, 0 # start at 0.
li $s1, 6
loop: addi $s0, $s0, 1 # add 1 to $s0
div $s0, $s1 # divide $s0 by $s1. Result is in the multiplication/division registers
mfhi $s3 # copy the remainder from the higher multiplication register to $s3
move $a0, $s0 # variable must be in $a0 to print
li $v0, 1 # 1 must be in $v0 to tell the assembler to print an integer
syscall # print the integer in $a0
bnez $s3, loop # if $s3 is not 0, jump to loop
li $v0, 10
syscall # syscall to end the program
|
http://rosettacode.org/wiki/Loops/For | Loops/For | “For” loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code.
Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers.
Task
Show how two loops may be nested within each other, with the number of iterations performed by the inner for loop being controlled by the outer for loop.
Specifically print out the following pattern by using one for loop nested in another:
*
**
***
****
*****
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
Reference
For loop Wikipedia.
| #Fortran | Fortran | C WARNING: This program is not valid ANSI FORTRAN 77 code. It uses
C one nonstandard character on the line labelled 5001. Many F77
C compilers should be okay with it, but it is *not* standard.
PROGRAM FORLOOP
INTEGER I, J
DO 20 I = 1, 5
DO 10 J = 1, I
C Print the asterisk.
WRITE (*,5001) '*'
10 CONTINUE
C Print a newline.
WRITE (*,5000) ''
20 CONTINUE
STOP
5000 FORMAT (A)
C Standard FORTRAN 77 is completely incapable of completing a
C WRITE statement without printing a newline. If you wanted to
C write this program in valid F77, you would have to come up with
C a creative way of printing varying numbers of asterisks in a
C single write statement.
C
C The dollar sign at the end of the format is a nonstandard
C character. It tells the compiler not to print a newline. If you
C are actually using FORTRAN 77, you should figure out what your
C particular compiler accepts. If you are actually using Fortran
C 90 or later, you should replace this line with the commented
C line that follows it.
5001 FORMAT (A, $)
C5001 FORMAT (A, ADVANCE='NO')
END |
http://rosettacode.org/wiki/Loops/For_with_a_specified_step | Loops/For with a specified step |
Task
Demonstrate a for-loop where the step-value is greater than one.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Logo | Logo | for [i 2 8 2] [type :i type "|, |] print [who do we appreciate?] |
http://rosettacode.org/wiki/Loops/For_with_a_specified_step | Loops/For with a specified step |
Task
Demonstrate a for-loop where the step-value is greater than one.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Lua | Lua |
for i=2,9,2 do
print(i)
end
|
http://rosettacode.org/wiki/Long_multiplication | Long multiplication | Task
Explicitly implement long multiplication.
This is one possible approach to arbitrary-precision integer algebra.
For output, display the result of 264 * 264.
Optionally, verify your result against builtin arbitrary precision support.
The decimal representation of 264 is:
18,446,744,073,709,551,616
The output of 264 * 264 is 2128, and is:
340,282,366,920,938,463,463,374,607,431,768,211,456
| #ALGOL_W | ALGOL W | begin
% long multiplication of large integers %
% large integers are represented by arrays of integers whose absolute %
% values are in 0 .. ELEMENT_MAX - 1 %
% negative large integers should have negative values in all non-zero %
% elements %
% the least significant digits of the large integer are in element 1 %
integer ELEMENT_DIGITS; % number of digits in an element of a large %
% integer %
integer ELEMENT_MAX; % max absolute value of an element of a large %
% integer - must be 10^( ELEMENT_DIGITS + 1 ) %
integer ELEMENT_COUNT; % number of elements in each large integer %
% implements long multiplication, c is set to a * b %
% c can be the same array as a or b %
% n is the number of elements in the large integers a, b and c %
procedure longMultiply( integer array a, b, c ( * )
; integer value n
) ;
begin
% multiplies the large integer in b by the integer a, the result %
% is added to c, starting from offset %
% overflow is ignored %
procedure multiplyElement( integer value a
; integer array b, c ( * )
; integer value offset, n
) ;
begin
integer carry, cPos;
carry := 0;
cPos := offset;
for bPos := 1 until highestNonZeroElementPosition( b, ( n + 1 ) - offset ) do begin
integer cElement;
cElement := c( cPos ) + ( a * b( bPos ) ) + carry;
if abs cElement < ELEMENT_MAX then carry := 0
else begin
% have digits to carry %
carry := cElement div ELEMENT_MAX;
cElement := ( abs cElement ) rem ELEMENT_MAX;
if carry < 0 then cElement := - cElement
end if_no_carry_ ;
c( cPos ) := cElement;
cPos := cPos + 1
end for_aPos ;
if cPos <= n then c( cPos ) := carry
end multiplyElement ;
integer array mResult ( 1 :: n );
% the result will be computed in mResult, allowing a or b to be c %
for rPos := 1 until n do mResult( rPos ) := 0;
% multiply and add each element to the result %
for aPos := 1 until highestNonZeroElementPosition( a, n ) do begin
if a( aPos ) not = 0 then multiplyElement( a( aPos ), b, mResult, aPos, n )
end for_aPos ;
% return the result in c %
for rPos := 1 until n do c( rPos ) := mResult( rPos )
end longMultiply ;
% writes the decimal value of a large integer a with n elements %
procedure writeonLargeInteger( integer array a ( * )
; integer value n
) ;
begin
integer aMax;
aMax := highestNonZeroElementPosition( a, n );
if aMax < 1 then writeon( "0" )
else begin
% the large integer is non-zero %
writeon( i_w := 1, s_w := 0, a( aMax ) ); % highest element %
% handle the remaining elements - show leading zeros %
for aPos := aMax - 1 step -1 until 1 do begin
integer v;
integer array digits ( 1 :: ELEMENT_DIGITS );
v := abs a( aPos );
for dPos := ELEMENT_DIGITS step -1 until 1 do begin
digits( dPos ) := v rem 10;
v := v div 10
end for_dPos;
for dPos := 1 until ELEMENT_DIGITS do writeon( i_w := 1, s_w := 0, digits( dPos ) )
end for_aPos
end if_aMax_lt_1_
end writeonLargeInteger ;
% returns the position of the highest non-zero element of the large %
% integer a with n elements %
integer procedure highestNonZeroElementPosition( integer array a ( * )
; integer value n
) ;
begin
integer aMax;
aMax := n;
while aMax > 0 and a( aMax ) = 0 do aMax := aMax - 1;
aMax
end highestNonZeroElementPosition ;
% allow each element to contain 4 decimal digits, so element by element %
% multiplication won't overflow 32-bits %
ELEMENT_DIGITS := 4;
ELEMENT_MAX := 10000;
ELEMENT_COUNT := 12; % allows up to 48 digits - enough for the task %
begin
integer array twoTo64, twoTo128 ( 1 :: ELEMENT_COUNT );
integer pwr;
% construct 2^64 in twoTo64 %
for tPos := 2 until ELEMENT_COUNT do twoTo64( tPos ) := 0;
twoTo64( 1 ) := 2;
pwr := 1;
while pwr < 64 do begin
longMultiply( twoTo64, twoTo64, twoTo64, ELEMENT_COUNT );
pwr := pwr * 2
end while_pwr_lt_64 ;
% construct 2^128 %
longMultiply( twoTo64, twoTo64, twoTo128, ELEMENT_COUNT );
write( "2^128: " );
writeonLargeInteger( twoTo128, ELEMENT_COUNT )
end
end. |
http://rosettacode.org/wiki/Literals/String | Literals/String | Task
Show literal specification of characters and strings.
If supported, show how the following work:
verbatim strings (quotes where escape sequences are quoted literally)
here-strings
Also, discuss which quotes expand variables.
Related tasks
Special characters
Here document
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Arturo | Arturo | str: "Hello world"
print [str "->" type str]
fullLineStr: « This is a full-line string
print [fullLineStr "->" type fullLineStr]
multiline: {
This
is a multi-line
string
}
print [multiline "->" type multiline]
verbatim: {:
This is
a verbatim
multi-line
string
:}
print [verbatim "->" type verbatim] |
http://rosettacode.org/wiki/Literals/String | Literals/String | Task
Show literal specification of characters and strings.
If supported, show how the following work:
verbatim strings (quotes where escape sequences are quoted literally)
here-strings
Also, discuss which quotes expand variables.
Related tasks
Special characters
Here document
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #AutoHotkey | AutoHotkey | "c" ; character
"text" ; string
hereString = ; with interpolation of %variables%
(
"<>"
the time is %A_Now%
\!
)
hereString2 = ; with same line comments allowed, without interpolation of variables
(Comments %
literal %A_Now% ; no interpolation here
) |
http://rosettacode.org/wiki/Long_literals,_with_continuations | Long literals, with continuations | This task is about writing a computer program that has long literals (character
literals that may require specifying the words/tokens on more than one (source)
line, either with continuations or some other method, such as abutments or
concatenations (or some other mechanisms).
The literal is to be in the form of a "list", a literal that contains many
words (tokens) separated by a blank (space), in this case (so as to have a
common list), the (English) names of the chemical elements of the periodic table.
The list is to be in (ascending) order of the (chemical) element's atomic number:
hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium aluminum silicon ...
... up to the last known (named) chemical element (at this time).
Do not include any of the "unnamed" chemical element names such as:
ununennium unquadnilium triunhexium penthextrium penthexpentium septhexunium octenntrium ennennbium
To make computer programming languages comparable, the statement widths should be
restricted to less than 81 bytes (characters), or less
if a computer programming language has more restrictive limitations or standards.
Also mention what column the programming statements can start in if not
in column one.
The list may have leading/embedded/trailing blanks during the
declaration (the actual program statements), this is allow the list to be
more readable. The "final" list shouldn't have any leading/trailing or superfluous
blanks (when stored in the program's "memory").
This list should be written with the idea in mind that the
program will be updated, most likely someone other than the
original author, as there will be newer (discovered) elements of the periodic
table being added (possibly in the near future). These future updates
should be one of the primary concerns in writing these programs and it should be "easy"
for someone else to add chemical elements to the list (within the computer
program).
Attention should be paid so as to not exceed the clause length of
continued or specified statements, if there is such a restriction. If the
limit is greater than (say) 4,000 bytes or so, it needn't be mentioned here.
Task
Write a computer program (by whatever name) to contain a list of the known elements.
The program should eventually contain a long literal of words (the elements).
The literal should show how one could create a long list of blank-delineated words.
The "final" (stored) list should only have a single blank between elements.
Try to use the most idiomatic approach(es) in creating the final list.
Use continuation if possible, and/or show alternatives (possibly using concatenation).
Use a program comment to explain what the continuation character is if it isn't obvious.
The program should contain a variable that has the date of the last update/revision.
The program, when run, should display with verbiage:
The last update/revision date (and should be unambiguous).
The number of chemical elements in the list.
The name of the highest (last) element name.
Show all output here, on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #J | J | NB. create a multi-line literal
elements =: CRLF -.~ noun define
hydrogen helium lithium beryllium
boron carbon nitrogen oxygen
fluorine neon sodium magnesium
aluminum silicon phosphorous sulfur
chlorine argon potassium calcium
scandium titanium vanadium chromium
manganese iron cobalt nickel
copper zinc gallium germanium
arsenic selenium bromine krypton
rubidium strontium yttrium zirconium
niobium molybdenum technetium ruthenium
rhodium palladium silver cadmium
indium tin antimony tellurium
iodine xenon cesium barium
lanthanum cerium praseodymium neodymium
promethium samarium europium gadolinium
terbium dysprosium holmium erbium
thulium ytterbium lutetium hafnium
tantalum tungsten rhenium osmium
iridium platinum gold mercury
thallium lead bismuth polonium
astatine radon francium radium
actinium thorium protactinium uranium
neptunium plutonium americium curium
berkelium californium einsteinium fermium
mendelevium nobelium lawrencium rutherfordium
dubnium seaborgium bohrium hassium
meitnerium darmstadtium roentgenium copernicium
nihonium flerovium moscovium livermorium
tennessine oganesson
)
NB. same under words
space_separated_elements =: ]&.:;: elements
tally=: # ;: elements
last_element=: _1 {:: ;: elements
revision=: '2020-03-23'
'Last revision: ', revision
'Number of elements: ' , ": tally
'Last element: ', last_element
'first and last 30 characters:'
30 ;&({.&space_separated_elements) _30
Last revision: 2020-03-23
Number of elements: 118
Last element: oganesson
first and last 30 characters:
┌──────────────────────────────┬──────────────────────────────┐
│hydrogen helium lithium beryll│vermorium tennessine oganesson│
└──────────────────────────────┴──────────────────────────────┘ |
http://rosettacode.org/wiki/Long_literals,_with_continuations | Long literals, with continuations | This task is about writing a computer program that has long literals (character
literals that may require specifying the words/tokens on more than one (source)
line, either with continuations or some other method, such as abutments or
concatenations (or some other mechanisms).
The literal is to be in the form of a "list", a literal that contains many
words (tokens) separated by a blank (space), in this case (so as to have a
common list), the (English) names of the chemical elements of the periodic table.
The list is to be in (ascending) order of the (chemical) element's atomic number:
hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium aluminum silicon ...
... up to the last known (named) chemical element (at this time).
Do not include any of the "unnamed" chemical element names such as:
ununennium unquadnilium triunhexium penthextrium penthexpentium septhexunium octenntrium ennennbium
To make computer programming languages comparable, the statement widths should be
restricted to less than 81 bytes (characters), or less
if a computer programming language has more restrictive limitations or standards.
Also mention what column the programming statements can start in if not
in column one.
The list may have leading/embedded/trailing blanks during the
declaration (the actual program statements), this is allow the list to be
more readable. The "final" list shouldn't have any leading/trailing or superfluous
blanks (when stored in the program's "memory").
This list should be written with the idea in mind that the
program will be updated, most likely someone other than the
original author, as there will be newer (discovered) elements of the periodic
table being added (possibly in the near future). These future updates
should be one of the primary concerns in writing these programs and it should be "easy"
for someone else to add chemical elements to the list (within the computer
program).
Attention should be paid so as to not exceed the clause length of
continued or specified statements, if there is such a restriction. If the
limit is greater than (say) 4,000 bytes or so, it needn't be mentioned here.
Task
Write a computer program (by whatever name) to contain a list of the known elements.
The program should eventually contain a long literal of words (the elements).
The literal should show how one could create a long list of blank-delineated words.
The "final" (stored) list should only have a single blank between elements.
Try to use the most idiomatic approach(es) in creating the final list.
Use continuation if possible, and/or show alternatives (possibly using concatenation).
Use a program comment to explain what the continuation character is if it isn't obvious.
The program should contain a variable that has the date of the last update/revision.
The program, when run, should display with verbiage:
The last update/revision date (and should be unambiguous).
The number of chemical elements in the list.
The name of the highest (last) element name.
Show all output here, on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #jq | jq | # FOR FUTURE EDITORS:
# To add chemical elements, modify the CHEMICAL_ELEMENTS function,
# ensuring that the date is updated properly and that there is at least one
# space between the element names after concatenation of the strings.
# Do not include any of the "unnamed" chemical element names such as ununennium.
def CHEMICAL_ELEMENTS:
{date: "Wed Jun 23 00:00:00 EDT 2021",
elements: (
"hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon "
+ "sodium magnesium aluminum silicon phosphorus sulfur chlorine argon potassium "
+ "calcium scandium titanium vanadium chromium manganese iron cobalt nickel copper "
+ "zinc gallium germanium arsenic selenium bromine krypton rubidium strontium "
+ "yttrium zirconium niobium molybdenum technetium ruthenium rhodium palladium "
+ "silver cadmium indium tin antimony tellurium iodine xenon cesium barium "
+ "lanthanum cerium praseodymium neodymium promethium samarium europium gadolinium "
+ "terbium dysprosium holmium erbium thulium ytterbium lutetium hafnium tantalum "
+ "tungsten rhenium osmium iridium platinum gold mercury thallium lead bismuth "
+ "polonium astatine radon francium radium actinium thorium protactinium uranium "
+ "neptunium plutonium americium curium berkelium californium einsteinium fermium "
+ "mendelevium nobelium lawrencium rutherfordium dubnium seaborgium bohrium hassium "
+ "meitnerium darmstadtium roentgenium copernicium nihonium flerovium moscovium "
+ "livermorium tennessine oganesson"
) }
;
def chemical_elements_array:
CHEMICAL_ELEMENTS.elements
# remove leading and trailing whitespace
| sub("^ *";"") | sub(" *$";"")
# return a list after splitting using whitespace between words as a separator
| [splits("[ \t]+")] ;
def report:
chemical_elements_array as $a
| "List last revised: \(CHEMICAL_ELEMENTS.date)",
"Length of element list: \($a|length)",
"Last element in list: \($a[-1])";
report |
http://rosettacode.org/wiki/Long_literals,_with_continuations | Long literals, with continuations | This task is about writing a computer program that has long literals (character
literals that may require specifying the words/tokens on more than one (source)
line, either with continuations or some other method, such as abutments or
concatenations (or some other mechanisms).
The literal is to be in the form of a "list", a literal that contains many
words (tokens) separated by a blank (space), in this case (so as to have a
common list), the (English) names of the chemical elements of the periodic table.
The list is to be in (ascending) order of the (chemical) element's atomic number:
hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium aluminum silicon ...
... up to the last known (named) chemical element (at this time).
Do not include any of the "unnamed" chemical element names such as:
ununennium unquadnilium triunhexium penthextrium penthexpentium septhexunium octenntrium ennennbium
To make computer programming languages comparable, the statement widths should be
restricted to less than 81 bytes (characters), or less
if a computer programming language has more restrictive limitations or standards.
Also mention what column the programming statements can start in if not
in column one.
The list may have leading/embedded/trailing blanks during the
declaration (the actual program statements), this is allow the list to be
more readable. The "final" list shouldn't have any leading/trailing or superfluous
blanks (when stored in the program's "memory").
This list should be written with the idea in mind that the
program will be updated, most likely someone other than the
original author, as there will be newer (discovered) elements of the periodic
table being added (possibly in the near future). These future updates
should be one of the primary concerns in writing these programs and it should be "easy"
for someone else to add chemical elements to the list (within the computer
program).
Attention should be paid so as to not exceed the clause length of
continued or specified statements, if there is such a restriction. If the
limit is greater than (say) 4,000 bytes or so, it needn't be mentioned here.
Task
Write a computer program (by whatever name) to contain a list of the known elements.
The program should eventually contain a long literal of words (the elements).
The literal should show how one could create a long list of blank-delineated words.
The "final" (stored) list should only have a single blank between elements.
Try to use the most idiomatic approach(es) in creating the final list.
Use continuation if possible, and/or show alternatives (possibly using concatenation).
Use a program comment to explain what the continuation character is if it isn't obvious.
The program should contain a variable that has the date of the last update/revision.
The program, when run, should display with verbiage:
The last update/revision date (and should be unambiguous).
The number of chemical elements in the list.
The name of the highest (last) element name.
Show all output here, on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Julia | Julia | using Dates
# FOR FUTURE EDITORS:
#
# Add to this list by adding more lines of text to this listing, placing the
# new words of text before the last """ below, with all entries separated by
# spaces.
#
const CHEMICAL_ELEMENTS = """
hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon
sodium magnesium aluminum silicon phosphorus sulfur chlorine argon potassium
calcium scandium titanium vanadium chromium manganese iron cobalt nickel copper
zinc gallium germanium arsenic selenium bromine krypton rubidium strontium
yttrium zirconium niobium molybdenum technetium ruthenium rhodium palladium
silver cadmium indium tin antimony tellurium iodine xenon cesium barium
lanthanum cerium praseodymium neodymium promethium samarium europium gadolinium
terbium dysprosium holmium erbium thulium ytterbium lutetium hafnium tantalum
tungsten rhenium osmium iridium platinum gold mercury thallium lead bismuth
polonium astatine radon francium radium actinium thorium protactinium uranium
neptunium plutonium americium curium berkelium californium einsteinium fermium
mendelevium nobelium lawrencium rutherfordium dubnium seaborgium bohrium hassium
meitnerium darmstadtium roentgenium copernicium nihonium flerovium moscovium
livermorium tennessine oganesson
"""
#
# END OF ABOVE LISTING--DO NOT ADD ELEMENTS BELOW THIS LINE
#
const EXCLUDED = split(strip(
"ununennium unquadnilium triunhexium penthextrium penthexpentium " *
" septhexunium octenntrium ennennbium"), r"\s+")
function process_chemical_element_list(s = CHEMICAL_ELEMENTS)
# remove leading and trailing whitespace
s = strip(s)
# return a list after splitting using whitespace between words as a separator
return [element for element in split(s, r"\s+") if !(element in EXCLUDED)]
end
function report()
filedate = Dates.unix2datetime(mtime(@__FILE__))
element_list = process_chemical_element_list()
element_count = length(element_list)
last_element_in_list = element_list[end]
println("File last revised (formatted as dateTtime): ", filedate, " GMT")
println("Length of element list: ", element_count)
println("last element in list: ", last_element_in_list)
end
report()
|
http://rosettacode.org/wiki/Long_literals,_with_continuations | Long literals, with continuations | This task is about writing a computer program that has long literals (character
literals that may require specifying the words/tokens on more than one (source)
line, either with continuations or some other method, such as abutments or
concatenations (or some other mechanisms).
The literal is to be in the form of a "list", a literal that contains many
words (tokens) separated by a blank (space), in this case (so as to have a
common list), the (English) names of the chemical elements of the periodic table.
The list is to be in (ascending) order of the (chemical) element's atomic number:
hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium aluminum silicon ...
... up to the last known (named) chemical element (at this time).
Do not include any of the "unnamed" chemical element names such as:
ununennium unquadnilium triunhexium penthextrium penthexpentium septhexunium octenntrium ennennbium
To make computer programming languages comparable, the statement widths should be
restricted to less than 81 bytes (characters), or less
if a computer programming language has more restrictive limitations or standards.
Also mention what column the programming statements can start in if not
in column one.
The list may have leading/embedded/trailing blanks during the
declaration (the actual program statements), this is allow the list to be
more readable. The "final" list shouldn't have any leading/trailing or superfluous
blanks (when stored in the program's "memory").
This list should be written with the idea in mind that the
program will be updated, most likely someone other than the
original author, as there will be newer (discovered) elements of the periodic
table being added (possibly in the near future). These future updates
should be one of the primary concerns in writing these programs and it should be "easy"
for someone else to add chemical elements to the list (within the computer
program).
Attention should be paid so as to not exceed the clause length of
continued or specified statements, if there is such a restriction. If the
limit is greater than (say) 4,000 bytes or so, it needn't be mentioned here.
Task
Write a computer program (by whatever name) to contain a list of the known elements.
The program should eventually contain a long literal of words (the elements).
The literal should show how one could create a long list of blank-delineated words.
The "final" (stored) list should only have a single blank between elements.
Try to use the most idiomatic approach(es) in creating the final list.
Use continuation if possible, and/or show alternatives (possibly using concatenation).
Use a program comment to explain what the continuation character is if it isn't obvious.
The program should contain a variable that has the date of the last update/revision.
The program, when run, should display with verbiage:
The last update/revision date (and should be unambiguous).
The number of chemical elements in the list.
The name of the highest (last) element name.
Show all output here, on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Kotlin | Kotlin | import java.time.Instant
const val elementsChunk = """
hydrogen helium lithium beryllium
boron carbon nitrogen oxygen
fluorine neon sodium magnesium
aluminum silicon phosphorous sulfur
chlorine argon potassium calcium
scandium titanium vanadium chromium
manganese iron cobalt nickel
copper zinc gallium germanium
arsenic selenium bromine krypton
rubidium strontium yttrium zirconium
niobium molybdenum technetium ruthenium
rhodium palladium silver cadmium
indium tin antimony tellurium
iodine xenon cesium barium
lanthanum cerium praseodymium neodymium
promethium samarium europium gadolinium
terbium dysprosium holmium erbium
thulium ytterbium lutetium hafnium
tantalum tungsten rhenium osmium
iridium platinum gold mercury
thallium lead bismuth polonium
astatine radon francium radium
actinium thorium protactinium uranium
neptunium plutonium americium curium
berkelium californium einsteinium fermium
mendelevium nobelium lawrencium rutherfordium
dubnium seaborgium bohrium hassium
meitnerium darmstadtium roentgenium copernicium
nihonium flerovium moscovium livermorium
tennessine oganesson
"""
const val unamedElementsChunk = """
ununennium unquadnilium triunhexium penthextrium
penthexpentium septhexunium octenntrium ennennbium
"""
fun main() {
fun String.splitToList() = trim().split("\\s+".toRegex());
val elementsList =
elementsChunk.splitToList()
.filterNot(unamedElementsChunk.splitToList().toSet()::contains)
println("Last revision Date: ${Instant.now()}")
println("Number of elements: ${elementsList.size}")
println("Last element : ${elementsList.last()}")
println("The elements are : ${elementsList.joinToString(" ", limit = 5)}")
} |
http://rosettacode.org/wiki/List_rooted_trees | List rooted trees | You came back from grocery shopping. After putting away all the goods, you are left with a pile of plastic bags, which you want to save for later use, so you take one bag and stuff all the others into it, and throw it under the sink. In doing so, you realize that there are various ways of nesting the bags, with all bags viewed as identical.
If we use a matching pair of parentheses to represent a bag, the ways are:
For 1 bag, there's one way:
() <- a bag
for 2 bags, there's one way:
(()) <- one bag in another
for 3 bags, there are two:
((())) <- 3 bags nested Russian doll style
(()()) <- 2 bags side by side, inside the third
for 4 bags, four:
(()()())
((())())
((()()))
(((())))
Note that because all bags are identical, the two 4-bag strings ((())()) and (()(())) represent the same configuration.
It's easy to see that each configuration for n bags represents a n-node rooted tree, where a bag is a tree node, and a bag with its content forms a subtree. The outermost bag is the tree root. Number of configurations for given n is given by OEIS A81.
Task
Write a program that, when given n, enumerates all ways of nesting n bags. You can use the parentheses notation above, or any tree representation that's unambiguous and preferably intuitive.
This task asks for enumeration of trees only; for counting solutions without enumeration, that OEIS page lists various formulas, but that's not encouraged by this task, especially if implementing it would significantly increase code size.
As an example output, run 5 bags. There should be 9 ways.
| #Haskell | Haskell | -- break n down into sum of smaller integers
parts :: Int -> [[(Int, Int)]]
parts n = f n 1
where
f n x
| n == 0 = [[]]
| x > n = []
| otherwise =
f n (x + 1) ++
concatMap
(\c -> map ((c, x) :) (f (n - c * x) (x + 1)))
[1 .. n `div` x]
-- choose n strings out of a list and join them
pick :: Int -> [String] -> [String]
pick _ [] = []
pick 0 _ = [""]
pick n aa@(a:as) = map (a ++) (pick (n - 1) aa) ++ pick n as
-- pick parts to build a series of subtrees that add up to n-1,
-- then wrap them up
trees :: Int -> [String]
trees n =
map (\x -> "(" ++ x ++ ")") $
concatMap (foldr (prod . build) [""]) (parts (n - 1))
where
build (c, x) = pick c $ trees x
prod aa bb =
[ a ++ b
| a <- aa
, b <- bb ]
main :: IO ()
main = mapM_ putStrLn $ trees 5 |
http://rosettacode.org/wiki/Literals/Integer | Literals/Integer | Some programming languages have ways of expressing integer literals in bases other than the normal base ten.
Task
Show how integer literals can be expressed in as many bases as your language allows.
Note: this should not involve the calling of any functions/methods, but should be interpreted by the compiler or interpreter as an integer written to a given base.
Also show any other ways of expressing literals, e.g. for different types of integers.
Related task
Literals/Floating point
| #Arturo | Arturo | num: 18966
print [num "->" type num] |
http://rosettacode.org/wiki/Literals/Integer | Literals/Integer | Some programming languages have ways of expressing integer literals in bases other than the normal base ten.
Task
Show how integer literals can be expressed in as many bases as your language allows.
Note: this should not involve the calling of any functions/methods, but should be interpreted by the compiler or interpreter as an integer written to a given base.
Also show any other ways of expressing literals, e.g. for different types of integers.
Related task
Literals/Floating point
| #AutoHotkey | AutoHotkey | If (727 == 0x2d7)
MsgBox true |
http://rosettacode.org/wiki/Logical_operations | Logical operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a function that takes two logical (boolean) values, and outputs the result of "and" and "or" on both arguments as well as "not" on the first arguments.
If the programming language doesn't provide a separate type for logical values, use the type most commonly used for that purpose.
If the language supports additional logical operations on booleans such as XOR, list them as well.
| #Aikido | Aikido |
function logic(a,b) {
println("a AND b: " + (a && b))
println("a OR b: " + (a || b))
println("NOT a: " + (!a))
}
|
http://rosettacode.org/wiki/Logical_operations | Logical operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a function that takes two logical (boolean) values, and outputs the result of "and" and "or" on both arguments as well as "not" on the first arguments.
If the programming language doesn't provide a separate type for logical values, use the type most commonly used for that purpose.
If the language supports additional logical operations on booleans such as XOR, list them as well.
| #Aime | Aime | void
out(integer a, integer b)
{
o_integer(a && b);
o_byte('\n');
o_integer(a || b);
o_byte('\n');
o_integer(!a);
o_byte('\n');
} |
http://rosettacode.org/wiki/Loops/N_plus_one_half | Loops/N plus one half | Quite often one needs loops which, in the last iteration, execute only part of the loop body.
Goal
Demonstrate the best way to do this.
Task
Write a loop which writes the comma-separated list
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
using separate output statements for the number
and the comma from within the body of the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #UNIX_Shell | UNIX Shell | for(( Z=1; Z<=10; Z++ )); do
echo -e "$Z\c"
if (( Z != 10 )); then
echo -e ", \c"
fi
done |
http://rosettacode.org/wiki/Loops/N_plus_one_half | Loops/N plus one half | Quite often one needs loops which, in the last iteration, execute only part of the loop body.
Goal
Demonstrate the best way to do this.
Task
Write a loop which writes the comma-separated list
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
using separate output statements for the number
and the comma from within the body of the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #UnixPipes | UnixPipes | yes \ | cat -n | head -n 10 | paste -d\ - <(yes , | head -n 9) | xargs echo |
http://rosettacode.org/wiki/Literals/Floating_point | Literals/Floating point | Programming languages have different ways of expressing floating-point literals.
Task
Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features.
You may want to include a regular expression or BNF/ABNF/EBNF defining allowable formats for your language.
Related tasks
Literals/Integer
Extreme floating point values
| #Eiffel | Eiffel |
1.
1.23
1e-5
.5
1.23E4
|
http://rosettacode.org/wiki/Literals/Floating_point | Literals/Floating point | Programming languages have different ways of expressing floating-point literals.
Task
Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features.
You may want to include a regular expression or BNF/ABNF/EBNF defining allowable formats for your language.
Related tasks
Literals/Integer
Extreme floating point values
| #Elena | Elena | real r := 1;
r := 23.2r;
r := 1.2e+11r; |
http://rosettacode.org/wiki/Literals/Floating_point | Literals/Floating point | Programming languages have different ways of expressing floating-point literals.
Task
Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features.
You may want to include a regular expression or BNF/ABNF/EBNF defining allowable formats for your language.
Related tasks
Literals/Integer
Extreme floating point values
| #Elixir | Elixir | iex(180)> 0.123
0.123
iex(181)> -123.4
-123.4
iex(182)> 1.23e4
1.23e4
iex(183)> 1.2e-3
0.0012
iex(184)> 1.23E4
1.23e4
iex(185)> 10_000.0
1.0e4
iex(186)> .5
** (SyntaxError) iex:186: syntax error before: '.'
iex(186)> 2. + 3
** (CompileError) iex:186: invalid call 2.+(3)
iex(187)> 1e4
** (SyntaxError) iex:187: syntax error before: e4 |
http://rosettacode.org/wiki/Long_year | Long year | Most years have 52 weeks, some have 53, according to ISO8601.
Task
Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
| #Fortran | Fortran |
program longyear
use iso_fortran_env, only: output_unit, input_unit
implicit none
integer :: start, ende, i, counter
integer, parameter :: line_break=10
write(output_unit,*) "Enter beginning of interval"
read(input_unit,*) start
write(output_unit,*) "Enter end of interval"
read(input_unit,*) ende
if (start>=ende) error stop "Last year must be after first year!"
counter = 0
do i = start, ende
if (is_long_year(i)) then
write(output_unit,'(I0,x)', advance="no") i
counter = counter + 1
if (modulo(counter,line_break) == 0) write(output_unit,*)
end if
end do
contains
pure function p(year)
integer, intent(in) :: year
integer :: p
p = modulo(year + year/4 - year/100 + year/400, 7)
end function p
pure function is_long_year(year)
integer, intent(in) :: year
logical :: is_long_year
is_long_year = p(year) == 4 .or. p(year-1) == 3
end function is_long_year
end program longyear
|
http://rosettacode.org/wiki/Long_year | Long year | Most years have 52 weeks, some have 53, according to ISO8601.
Task
Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
| #Go | Go | package main
import (
"fmt"
"time"
)
func main() {
centuries := []string{"20th", "21st", "22nd"}
starts := []int{1900, 2000, 2100}
for i := 0; i < len(centuries); i++ {
var longYears []int
fmt.Printf("\nLong years in the %s century:\n", centuries[i])
for j := starts[i]; j < starts[i] + 100; j++ {
t := time.Date(j, time.December, 28, 0, 0, 0, 0, time.UTC)
if _, week := t.ISOWeek(); week == 53 {
longYears = append(longYears, j)
}
}
fmt.Println(longYears)
}
} |
http://rosettacode.org/wiki/Long_primes | Long primes |
A long prime (as defined here) is a prime number whose reciprocal (in decimal) has
a period length of one less than the prime number.
Long primes are also known as:
base ten cyclic numbers
full reptend primes
golden primes
long period primes
maximal period primes
proper primes
Another definition: primes p such that the decimal expansion of 1/p has period p-1, which is the greatest period possible for any integer.
Example
7 is the first long prime, the reciprocal of seven
is 1/7, which
is equal to the repeating decimal fraction 0.142857142857···
The length of the repeating part of the decimal fraction
is six, (the underlined part) which is one less
than the (decimal) prime number 7.
Thus 7 is a long prime.
There are other (more) general definitions of a long prime which
include wording/verbiage for bases other than ten.
Task
Show all long primes up to 500 (preferably on one line).
Show the number of long primes up to 500
Show the number of long primes up to 1,000
Show the number of long primes up to 2,000
Show the number of long primes up to 4,000
Show the number of long primes up to 8,000
Show the number of long primes up to 16,000
Show the number of long primes up to 32,000
Show the number of long primes up to 64,000 (optional)
Show all output here.
Also see
Wikipedia: full reptend prime
MathWorld: full reptend prime
OEIS: A001913
| #FreeBASIC | FreeBASIC | ' version 01-02-2019
' compile with: fbc -s console
Dim Shared As UByte prime()
Sub find_primes(n As UInteger)
ReDim prime(n)
Dim As UInteger i, k
' need only to consider odd primes, 2 has no repetion
For i = 3 To n Step 2
If prime(i) = 0 Then
For k = i * i To n Step i + i
prime(k) = 1
Next
End If
Next
End Sub
Function find_period(p As UInteger) As UInteger
' finds period for every positive number
Dim As UInteger period, r = 1
Do
r = (r * 10) Mod p
period += 1
If r <= 1 Then Return period
Loop
End Function
' ------=< MAIN >=------
#Define max 64000
Dim As UInteger p = 3, n1 = 3, n2 = 500, i, n50, count
find_primes(max)
Print "Long primes upto 500 are ";
For i = n1 To n2 Step 2
If prime(i) = 0 Then
If i -1 = find_period(i) Then
If n50 <= 50 Then
Print Str(i); " ";
End If
count += 1
End If
End If
Next
Print : Print
Do
Print "There are "; Str(count); " long primes upto "; Str(n2)
n1 = n2 +1
n2 += n2
If n1 > max Then Exit Do
For i = n1 To n2 Step 2
If prime(i) = 0 Then
If i -1 = find_period(i) Then
count += 1
End If
End If
Next
Loop
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End |
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously | Loop over multiple arrays simultaneously | Task
Loop over multiple arrays (or lists or tuples or whatever they're called in
your language) and display the i th element of each.
Use your language's "for each" loop if it has one, otherwise iterate
through the collection in order with some other loop.
For this example, loop over the arrays:
(a,b,c)
(A,B,C)
(1,2,3)
to produce the output:
aA1
bB2
cC3
If possible, also describe what happens when the arrays are of different lengths.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #BASIC256 | BASIC256 | dim arr1$(3) : arr1$ = {"a", "b", "c"}
dim arr2$(3) : arr2$ = {"A", "B", "C"}
dim arr3(3) : arr3 = {1, 2, 3}
for i = 0 to 2
print arr1$[i]; arr2$[i]; arr3[i]
next i
end |
http://rosettacode.org/wiki/Loops/Break | Loops/Break | Task
Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive).
If a number is 10, stop the loop after printing it, and do not generate any further numbers.
Otherwise, generate and print a second random number before restarting the loop.
If the number 10 is never generated as the first number in a loop, loop forever.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
| #Chapel | Chapel | use Random;
var r = new RandomStream();
while true {
var a = floor(r.getNext() * 20):int;
writeln(a);
if a == 10 then break;
var b = floor(r.getNext() * 20):int;
writeln(b);
}
delete r; |
http://rosettacode.org/wiki/Loops/Break | Loops/Break | Task
Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive).
If a number is 10, stop the loop after printing it, and do not generate any further numbers.
Otherwise, generate and print a second random number before restarting the loop.
If the number 10 is never generated as the first number in a loop, loop forever.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
| #Chef | Chef | (loop [[a b & more] (repeatedly #(rand-int 20))]
(println a)
(when-not (= 10 a)
(println b)
(recur more))) |
http://rosettacode.org/wiki/Longest_common_subsequence | Longest common subsequence | Introduction
Define a subsequence to be any output string obtained by deleting zero or more symbols from an input string.
The Longest Common Subsequence (LCS) is a subsequence of maximum length common to two or more strings.
Let A ≡ A[0]… A[m - 1] and B ≡ B[0]… B[n - 1], m < n be strings drawn from an alphabet Σ of size s, containing every distinct symbol in A + B.
An ordered pair (i, j) will be referred to as a match if A[i] = B[j], where 0 < i ≤ m and 0 < j ≤ n.
Define a non-strict product-order (≤) over ordered pairs, such that (i1, j1) ≤ (i2, j2) ⇔ i1 ≤ i2 and j1 ≤ j2. We define (≥) similarly.
We say m1, m2 are comparable if either m1 ≤ m2 or m1 ≥ m2 holds. If i1 < i2 and j2 < j1 (or i2 < i1 and j1 < j2) then neither m1 ≤ m2 nor m1 ≥ m2 are possible; and we say m1, m2 are incomparable.
We also define the strict product-order (<) over ordered pairs, such that (i1, j1) < (i2, j2) ⇔ i1 < i2 and j1 < j2. We define (>) similarly.
Given a set of matches M, a chain C is a subset of M consisting of at least one element m; and where either m1 < m2 or m1 > m2 for every pair of distinct elements m1 and m2. An antichain D is any subset of M in which every pair of distinct elements m1 and m2 are incomparable.
The set M represents a relation over match pairs: M[i, j] ⇔ (i, j) ∈ M. A chain C can be visualized as a curve which strictly increases as it passes through each match pair in the m*n coordinate space.
Finding an LCS can be restated as the problem of finding a chain of maximum cardinality p over the set of matches M.
According to [Dilworth 1950], this cardinality p equals the minimum number of disjoint antichains into which M can be decomposed. Note that such a decomposition into the minimal number p of disjoint antichains may not be unique.
Contours
Forward Contours FC[k] of class k are defined inductively, as follows:
FC[0] consists of those elements m1 for which there exists no element m2 such that m2 < m1.
FC[k] consists of those elements m1 for which there exists no element m2 such that m2 < m1; and where neither m1 nor m2 are contained in FC[l] for any class l < k.
Reverse Contours RC[k] of class k are defined similarly.
Members of the Meet (∧), or Infimum of a Forward Contour are referred to as its Dominant Matches: those m1 for which there exists no m2 such that m2 < m1.
Members of the Join (∨), or Supremum of a Reverse Contour are referred to as its Dominant Matches: those m1 for which there exists no m2 such that m2 > m1.
Where multiple Dominant Matches exist within a Meet (or within a Join, respectively) the Dominant Matches will be incomparable to each other.
Background
Where the number of symbols appearing in matches is small relative to the length of the input strings, reuse of the symbols increases; and the number of matches will tend towards quadratic, O(m*n) growth. This occurs, for example, in the Bioinformatics application of nucleotide and protein sequencing.
The divide-and-conquer approach of [Hirschberg 1975] limits the space required to O(n). However, this approach requires O(m*n) time even in the best case.
This quadratic time dependency may become prohibitive, given very long input strings. Thus, heuristics are often favored over optimal Dynamic Programming solutions.
In the application of comparing file revisions, records from the input files form a large symbol space; and the number of symbols approaches the length of the LCS. In this case the number of matches reduces to linear, O(n) growth.
A binary search optimization due to [Hunt and Szymanski 1977] can be applied to the basic Dynamic Programming approach, resulting in an expected performance of O(n log m). Performance can degrade to O(m*n log m) time in the worst case, as the number of matches grows to O(m*n).
Note
[Rick 2000] describes a linear-space algorithm with a time bound of O(n*s + p*min(m, n - p)).
Legend
A, B are input strings of lengths m, n respectively
p is the length of the LCS
M is the set of match pairs (i, j) such that A[i] = B[j]
r is the magnitude of M
s is the magnitude of the alphabet Σ of distinct symbols in A + B
References
[Dilworth 1950] "A decomposition theorem for partially ordered sets"
by Robert P. Dilworth, published January 1950,
Annals of Mathematics [Volume 51, Number 1, pp. 161-166]
[Goeman and Clausen 2002] "A New Practical Linear Space Algorithm for the Longest Common
Subsequence Problem" by Heiko Goeman and Michael Clausen,
published 2002, Kybernetika [Volume 38, Issue 1, pp. 45-66]
[Hirschberg 1975] "A linear space algorithm for computing maximal common subsequences"
by Daniel S. Hirschberg, published June 1975
Communications of the ACM [Volume 18, Number 6, pp. 341-343]
[Hunt and McIlroy 1976] "An Algorithm for Differential File Comparison"
by James W. Hunt and M. Douglas McIlroy, June 1976
Computing Science Technical Report, Bell Laboratories 41
[Hunt and Szymanski 1977] "A Fast Algorithm for Computing Longest Common Subsequences"
by James W. Hunt and Thomas G. Szymanski, published May 1977
Communications of the ACM [Volume 20, Number 5, pp. 350-353]
[Rick 2000] "Simple and fast linear space computation of longest common subsequences"
by Claus Rick, received 17 March 2000, Information Processing Letters,
Elsevier Science [Volume 75, pp. 275–281]
Examples
The sequences "1234" and "1224533324" have an LCS of "1234":
1234
1224533324
For a string example, consider the sequences "thisisatest" and "testing123testing". An LCS would be "tsitest":
thisisatest
testing123testing
In this puzzle, your code only needs to deal with strings. Write a function which returns an LCS of two strings (case-sensitive). You don't need to show multiple LCS's.
For more information on this problem please see Wikipedia.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Common_Lisp | Common Lisp | (defun longest-common-subsequence (array1 array2)
(let* ((l1 (length array1))
(l2 (length array2))
(results (make-array (list l1 l2) :initial-element nil)))
(declare (dynamic-extent results))
(labels ((lcs (start1 start2)
;; if either sequence is empty, return (() 0)
(if (or (eql start1 l1) (eql start2 l2)) (list '() 0)
;; otherwise, return any memoized value
(let ((result (aref results start1 start2)))
(if (not (null result)) result
;; otherwise, compute and store a value
(setf (aref results start1 start2)
(if (eql (aref array1 start1) (aref array2 start2))
;; if they start with the same element,
;; move forward in both sequences
(destructuring-bind (seq len)
(lcs (1+ start1) (1+ start2))
(list (cons (aref array1 start1) seq) (1+ len)))
;; otherwise, move ahead in each separately,
;; and return the better result.
(let ((a (lcs (1+ start1) start2))
(b (lcs start1 (1+ start2))))
(if (> (second a) (second b))
a
b)))))))))
(destructuring-bind (seq len) (lcs 0 0)
(values (coerce seq (type-of array1)) len))))) |
http://rosettacode.org/wiki/Look-and-say_sequence | Look-and-say sequence | The Look and say sequence is a recursively defined sequence of numbers studied most notably by John Conway.
The look-and-say sequence is also known as the Morris Number Sequence, after cryptographer Robert Morris, and the puzzle What is the next number in the sequence 1, 11, 21, 1211, 111221? is sometimes referred to as the Cuckoo's Egg, from a description of Morris in Clifford Stoll's book The Cuckoo's Egg.
Sequence Definition
Take a decimal number
Look at the number, visually grouping consecutive runs of the same digit.
Say the number, from left to right, group by group; as how many of that digit there are - followed by the digit grouped.
This becomes the next number of the sequence.
An example:
Starting with the number 1, you have one 1 which produces 11
Starting with 11, you have two 1's. I.E.: 21
Starting with 21, you have one 2, then one 1. I.E.: (12)(11) which becomes 1211
Starting with 1211, you have one 1, one 2, then two 1's. I.E.: (11)(12)(21) which becomes 111221
Task
Write a program to generate successive members of the look-and-say sequence.
Related tasks
Fours is the number of letters in the ...
Number names
Self-describing numbers
Self-referential sequence
Spelling of ordinal numbers
See also
Look-and-Say Numbers (feat John Conway), A Numberphile Video.
This task is related to, and an application of, the Run-length encoding task.
Sequence A005150 on The On-Line Encyclopedia of Integer Sequences.
| #BQN | BQN | LookSay ← ∾´((⊑∾˜ ≠+'0'˙)¨1↓((+`»≠⊢)⊸⊔))
>((⌈´≠¨)↑¨⊢) LookSay⍟(↕15)"1" |
http://rosettacode.org/wiki/Longest_string_challenge | Longest string challenge | Background
This "longest string challenge" is inspired by a problem that used to be given to students learning Icon. Students were expected to try to solve the problem in Icon and another language with which the student was already familiar. The basic problem is quite simple; the challenge and fun part came through the introduction of restrictions. Experience has shown that the original restrictions required some adjustment to bring out the intent of the challenge and make it suitable for Rosetta Code.
Basic problem statement
Write a program that reads lines from standard input and, upon end of file, writes the longest line to standard output.
If there are ties for the longest line, the program writes out all the lines that tie.
If there is no input, the program should produce no output.
Task
Implement a solution to the basic problem that adheres to the spirit of the restrictions (see below).
Describe how you circumvented or got around these 'restrictions' and met the 'spirit' of the challenge. Your supporting description may need to describe any challenges to interpreting the restrictions and how you made this interpretation. You should state any assumptions, warnings, or other relevant points. The central idea here is to make the task a bit more interesting by thinking outside of the box and perhaps by showing off the capabilities of your language in a creative way. Because there is potential for considerable variation between solutions, the description is key to helping others see what you've done.
This task is likely to encourage a variety of different types of solutions. They should be substantially different approaches.
Given the input:
a
bb
ccc
ddd
ee
f
ggg
the output should be (possibly rearranged):
ccc
ddd
ggg
Original list of restrictions
No comparison operators may be used.
No arithmetic operations, such as addition and subtraction, may be used.
The only datatypes you may use are integer and string. In particular, you may not use lists.
Do not re-read the input file. Avoid using files as a replacement for lists (this restriction became apparent in the discussion).
Intent of restrictions
Because of the variety of languages on Rosetta Code and the wide variety of concepts used in them, there needs to be a bit of clarification and guidance here to get to the spirit of the challenge and the intent of the restrictions.
The basic problem can be solved very conventionally, but that's boring and pedestrian. The original intent here wasn't to unduly frustrate people with interpreting the restrictions, it was to get people to think outside of their particular box and have a bit of fun doing it.
The guiding principle here should be to be creative in demonstrating some of the capabilities of the programming language being used. If you need to bend the restrictions a bit, explain why and try to follow the intent. If you think you've implemented a 'cheat', call out the fragment yourself and ask readers if they can spot why. If you absolutely can't get around one of the restrictions, explain why in your description.
Now having said that, the restrictions require some elaboration.
In general, the restrictions are meant to avoid the explicit use of these features.
"No comparison operators may be used" - At some level there must be some test that allows the solution to get at the length and determine if one string is longer. Comparison operators, in particular any less/greater comparison should be avoided. Representing the length of any string as a number should also be avoided. Various approaches allow for detecting the end of a string. Some of these involve implicitly using equal/not-equal; however, explicitly using equal/not-equal should be acceptable.
"No arithmetic operations" - Again, at some level something may have to advance through the string. Often there are ways a language can do this implicitly advance a cursor or pointer without explicitly using a +, - , ++, --, add, subtract, etc.
The datatype restrictions are amongst the most difficult to reinterpret. In the language of the original challenge strings are atomic datatypes and structured datatypes like lists are quite distinct and have many different operations that apply to them. This becomes a bit fuzzier with languages with a different programming paradigm. The intent would be to avoid using an easy structure to accumulate the longest strings and spit them out. There will be some natural reinterpretation here.
To make this a bit more concrete, here are a couple of specific examples:
In C, a string is an array of chars, so using a couple of arrays as strings is in the spirit while using a second array in a non-string like fashion would violate the intent.
In APL or J, arrays are the core of the language so ruling them out is unfair. Meeting the spirit will come down to how they are used.
Please keep in mind these are just examples and you may hit new territory finding a solution. There will be other cases like these. Explain your reasoning. You may want to open a discussion on the talk page as well.
The added "No rereading" restriction is for practical reasons, re-reading stdin should be broken. I haven't outright banned the use of other files but I've discouraged them as it is basically another form of a list. Somewhere there may be a language that just sings when doing file manipulation and where that makes sense; however, for most there should be a way to accomplish without resorting to an externality.
At the end of the day for the implementer this should be a bit of fun. As an implementer you represent the expertise in your language, the reader may have no knowledge of your language. For the reader it should give them insight into how people think outside the box in other languages. Comments, especially for non-obvious (to the reader) bits will be extremely helpful. While the implementations may be a bit artificial in the context of this task, the general techniques may be useful elsewhere.
| #Perl | Perl | #!/usr/bin/perl -n
END{ print $all }
substr($_, length($l)) and $all = $l = $_
or substr($l, length) or $all .= $_; |
http://rosettacode.org/wiki/Longest_string_challenge | Longest string challenge | Background
This "longest string challenge" is inspired by a problem that used to be given to students learning Icon. Students were expected to try to solve the problem in Icon and another language with which the student was already familiar. The basic problem is quite simple; the challenge and fun part came through the introduction of restrictions. Experience has shown that the original restrictions required some adjustment to bring out the intent of the challenge and make it suitable for Rosetta Code.
Basic problem statement
Write a program that reads lines from standard input and, upon end of file, writes the longest line to standard output.
If there are ties for the longest line, the program writes out all the lines that tie.
If there is no input, the program should produce no output.
Task
Implement a solution to the basic problem that adheres to the spirit of the restrictions (see below).
Describe how you circumvented or got around these 'restrictions' and met the 'spirit' of the challenge. Your supporting description may need to describe any challenges to interpreting the restrictions and how you made this interpretation. You should state any assumptions, warnings, or other relevant points. The central idea here is to make the task a bit more interesting by thinking outside of the box and perhaps by showing off the capabilities of your language in a creative way. Because there is potential for considerable variation between solutions, the description is key to helping others see what you've done.
This task is likely to encourage a variety of different types of solutions. They should be substantially different approaches.
Given the input:
a
bb
ccc
ddd
ee
f
ggg
the output should be (possibly rearranged):
ccc
ddd
ggg
Original list of restrictions
No comparison operators may be used.
No arithmetic operations, such as addition and subtraction, may be used.
The only datatypes you may use are integer and string. In particular, you may not use lists.
Do not re-read the input file. Avoid using files as a replacement for lists (this restriction became apparent in the discussion).
Intent of restrictions
Because of the variety of languages on Rosetta Code and the wide variety of concepts used in them, there needs to be a bit of clarification and guidance here to get to the spirit of the challenge and the intent of the restrictions.
The basic problem can be solved very conventionally, but that's boring and pedestrian. The original intent here wasn't to unduly frustrate people with interpreting the restrictions, it was to get people to think outside of their particular box and have a bit of fun doing it.
The guiding principle here should be to be creative in demonstrating some of the capabilities of the programming language being used. If you need to bend the restrictions a bit, explain why and try to follow the intent. If you think you've implemented a 'cheat', call out the fragment yourself and ask readers if they can spot why. If you absolutely can't get around one of the restrictions, explain why in your description.
Now having said that, the restrictions require some elaboration.
In general, the restrictions are meant to avoid the explicit use of these features.
"No comparison operators may be used" - At some level there must be some test that allows the solution to get at the length and determine if one string is longer. Comparison operators, in particular any less/greater comparison should be avoided. Representing the length of any string as a number should also be avoided. Various approaches allow for detecting the end of a string. Some of these involve implicitly using equal/not-equal; however, explicitly using equal/not-equal should be acceptable.
"No arithmetic operations" - Again, at some level something may have to advance through the string. Often there are ways a language can do this implicitly advance a cursor or pointer without explicitly using a +, - , ++, --, add, subtract, etc.
The datatype restrictions are amongst the most difficult to reinterpret. In the language of the original challenge strings are atomic datatypes and structured datatypes like lists are quite distinct and have many different operations that apply to them. This becomes a bit fuzzier with languages with a different programming paradigm. The intent would be to avoid using an easy structure to accumulate the longest strings and spit them out. There will be some natural reinterpretation here.
To make this a bit more concrete, here are a couple of specific examples:
In C, a string is an array of chars, so using a couple of arrays as strings is in the spirit while using a second array in a non-string like fashion would violate the intent.
In APL or J, arrays are the core of the language so ruling them out is unfair. Meeting the spirit will come down to how they are used.
Please keep in mind these are just examples and you may hit new territory finding a solution. There will be other cases like these. Explain your reasoning. You may want to open a discussion on the talk page as well.
The added "No rereading" restriction is for practical reasons, re-reading stdin should be broken. I haven't outright banned the use of other files but I've discouraged them as it is basically another form of a list. Somewhere there may be a language that just sings when doing file manipulation and where that makes sense; however, for most there should be a way to accomplish without resorting to an externality.
At the end of the day for the implementer this should be a bit of fun. As an implementer you represent the expertise in your language, the reader may have no knowledge of your language. For the reader it should give them insight into how people think outside the box in other languages. Comments, especially for non-obvious (to the reader) bits will be extremely helpful. While the implementations may be a bit artificial in the context of this task, the general techniques may be useful elsewhere.
| #Phix | Phix | with javascript_semantics
--integer fn = open(command_line()[2],"r") -- (reading the source file)
sequence fn = unix_dict()[1..40]&-1
function allx(string line)
line[1..-1] = 'x'
return line
end function
function longest(string mask)
-- object line = gets(fn)
object line = fn[1]; fn = fn[2..$];
if atom(line) then return mask end if
string newmask = allx(line)
if not match(mask,newmask) then return longest(mask) end if
mask = longest(newmask)
if match(mask,newmask) then
-- puts(1,line)
printf(1,"%s\n",line)
end if
return mask
end function
{} = longest("x")
--close(fn)
|
http://rosettacode.org/wiki/Longest_increasing_subsequence | Longest increasing subsequence | Calculate and show here a longest increasing subsequence of the list:
{
3
,
2
,
6
,
4
,
5
,
1
}
{\displaystyle \{3,2,6,4,5,1\}}
And of the list:
{
0
,
8
,
4
,
12
,
2
,
10
,
6
,
14
,
1
,
9
,
5
,
13
,
3
,
11
,
7
,
15
}
{\displaystyle \{0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15\}}
Note that a list may have more than one subsequence that is of the maximum length.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
Ref
Dynamic Programming #1: Longest Increasing Subsequence on YouTube
An efficient solution can be based on Patience sorting.
| #Lua | Lua | function buildLIS(seq)
local piles = { { {table.remove(seq, 1), nil} } }
while #seq>0 do
local x=table.remove(seq, 1)
for j=1,#piles do
if piles[j][#piles[j]][1]>x then
table.insert(piles[j], {x, (piles[j-1] and #piles[j-1])})
break
elseif j==#piles then
table.insert(piles, {{x, #piles[j]}})
end
end
end
local t={}
table.insert(t, piles[#piles][1][1])
local p=piles[#piles][1][2]
for i=#piles-1,1,-1 do
table.insert(t, piles[i][p][1])
p=piles[i][p][2]
end
table.sort(t)
print(unpack(t))
end
buildLIS({3,2,6,4,5,1})
buildLIS({0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15})
|
http://rosettacode.org/wiki/Loops/Continue | Loops/Continue | Task
Show the following output using one loop.
1, 2, 3, 4, 5
6, 7, 8, 9, 10
Try to achieve the result by forcing the next iteration within the loop
upon a specific condition, if your language allows it.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Elixir | Elixir | defmodule Loops do
def continue do
Enum.each(1..10, fn i ->
IO.write i
IO.write if rem(i,5)==0, do: "\n", else: ", "
end)
end
end
Loops.continue |
http://rosettacode.org/wiki/Loops/Continue | Loops/Continue | Task
Show the following output using one loop.
1, 2, 3, 4, 5
6, 7, 8, 9, 10
Try to achieve the result by forcing the next iteration within the loop
upon a specific condition, if your language allows it.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Erlang | Erlang | %% Implemented by Arjun Sunel
-module(continue).
-export([main/0, for_loop/1]).
main() ->
for_loop(1).
for_loop(N) when N /= 5 , N <10 ->
io:format("~p, ",[N] ),
for_loop(N+1);
for_loop(N) when N >=10->
if N=:=10 ->
io:format("~p\n",[N] )
end;
for_loop(N) ->
if N=:=5 ->
io:format("~p\n",[N] ),
for_loop(N+1)
end.
|
http://rosettacode.org/wiki/Longest_common_substring | Longest common substring | Task
Write a function that returns the longest common substring of two strings.
Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing".
Note that substrings are consecutive characters within a string. This distinguishes them from subsequences, which is any sequence of characters within a string, even if there are extraneous characters in between them.
Hence, the longest common subsequence between "thisisatest" and "testing123testing" is "tsitest", whereas the longest common substring is just "test".
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
References
Generalize Suffix Tree
Ukkonen’s Suffix Tree Construction
| #JavaScript | JavaScript | (() => {
'use strict';
// longestCommon :: String -> String -> String
const longestCommon = (s1, s2) => maximumBy(
comparing(length),
intersect(...apList(
[s => map(
concat,
concatMap(tails, compose(tail, inits)(s))
)],
[s1, s2]
))
);
// main :: IO ()
const main = () =>
console.log(
longestCommon(
"testing123testing",
"thisisatest"
)
);
// GENERIC FUNCTIONS ----------------------------
// Each member of a list of functions applied to each
// of a list of arguments, deriving a list of new values.
// apList (<*>) :: [(a -> b)] -> [a] -> [b]
const apList = (fs, xs) => //
fs.reduce((a, f) => a.concat(
xs.reduce((a, x) => a.concat([f(x)]), [])
), []);
// comparing :: (a -> b) -> (a -> a -> Ordering)
const comparing = f =>
(x, y) => {
const
a = f(x),
b = f(y);
return a < b ? -1 : (a > b ? 1 : 0);
};
// compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
const compose = (f, g) => x => f(g(x));
// concat :: [[a]] -> [a]
// concat :: [String] -> String
const concat = xs =>
0 < xs.length ? (() => {
const unit = 'string' !== typeof xs[0] ? (
[]
) : '';
return unit.concat.apply(unit, xs);
})() : [];
// concatMap :: (a -> [b]) -> [a] -> [b]
const concatMap = (f, xs) =>
xs.reduce((a, x) => a.concat(f(x)), []);
// inits([1, 2, 3]) -> [[], [1], [1, 2], [1, 2, 3]
// inits('abc') -> ["", "a", "ab", "abc"]
// inits :: [a] -> [[a]]
// inits :: String -> [String]
const inits = xs => [
[]
]
.concat(('string' === typeof xs ? xs.split('') : xs)
.map((_, i, lst) => lst.slice(0, i + 1)));
// intersect :: (Eq a) => [a] -> [a] -> [a]
const intersect = (xs, ys) =>
xs.filter(x => -1 !== ys.indexOf(x));
// Returns Infinity over objects without finite length.
// This enables zip and zipWith to choose the shorter
// argument when one is non-finite, like cycle, repeat etc
// length :: [a] -> Int
const length = xs =>
(Array.isArray(xs) || 'string' === typeof xs) ? (
xs.length
) : Infinity;
// map :: (a -> b) -> [a] -> [b]
const map = (f, xs) => xs.map(f);
// maximumBy :: (a -> a -> Ordering) -> [a] -> a
const maximumBy = (f, xs) =>
0 < xs.length ? (
xs.slice(1)
.reduce((a, x) => 0 < f(x, a) ? x : a, xs[0])
) : undefined;
// tail :: [a] -> [a]
const tail = xs => 0 < xs.length ? xs.slice(1) : [];
// tails :: [a] -> [[a]]
const tails = xs => {
const
es = ('string' === typeof xs) ? (
xs.split('')
) : xs;
return es.map((_, i) => es.slice(i))
.concat([
[]
]);
};
// MAIN ---
return main();
})(); |
http://rosettacode.org/wiki/Loops/Nested | Loops/Nested | Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over
[
1
,
…
,
20
]
{\displaystyle [1,\ldots ,20]}
.
The loops iterate rows and columns of the array printing the elements until the value
20
{\displaystyle 20}
is met.
Specifically, this task also shows how to break out of nested loops.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Stata | Stata | matrix a=J(20,20,0)
forv i=1/20 {
forv j=1/20 {
matrix a[`i',`j']=runiformint(1,20)
}
} |
http://rosettacode.org/wiki/Loops/Nested | Loops/Nested | Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over
[
1
,
…
,
20
]
{\displaystyle [1,\ldots ,20]}
.
The loops iterate rows and columns of the array printing the elements until the value
20
{\displaystyle 20}
is met.
Specifically, this task also shows how to break out of nested loops.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Swift | Swift | let array = [[2, 12, 10, 4], [18, 11, 20, 2]]
loop: for row in array {
for element in row {
println(" \(element)")
if element == 20 { break loop }
}
}
print("done") |
http://rosettacode.org/wiki/Loops/Foreach | Loops/Foreach | Loop through and print each element in a collection in order.
Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #zig | zig | const warn = @import("std").debug.warn;
pub fn main() void {
const items = [_]i16{ 0, 1, 1, 2, 3, 5, 8 };
for (items) |i| {
warn("{}\n", .{i});
}
}
|
http://rosettacode.org/wiki/Loops/Foreach | Loops/Foreach | Loop through and print each element in a collection in order.
Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #zkl | zkl | foreach c in (T("Red","Green","Blue","Black","White"))
{ print(c," "); } |
http://rosettacode.org/wiki/Loops/Foreach | Loops/Foreach | Loop through and print each element in a collection in order.
Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Zig_2 | Zig | const std = @import("std");
pub fn main() !void {
const stdout_wr = std.io.getStdOut().writer();
// 1. Index element index sizes are comptime-known
const a1: []const u8 = &[_]u8{ 'a', 'b', 'c' };
// also works with slices
//const a2: [] u8 = &a1;
for (a1) |el_a|
try stdout_wr.print("{c}\n", .{el_a});
// 2. Index element index sizes are not comptime-known
// Convention is to provide a `next()` method.
// TODO
} |
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
| #Phix | Phix | with javascript_semantics
function Luhn(string st)
integer s=0, d
for i=1 to length(st) do
d = st[-i]-'0'
s += iff(mod(i,2)?d,d*2-(d>4)*9)
end for
return remainder(s,10)=0
end function
procedure test(string s)
printf(1,"%20s : %t\n",{s,Luhn(s)})
end procedure
papply({"49927398716","49927398717","1234567812345678","1234567812345670"},test)
|
http://rosettacode.org/wiki/Loops/Infinite | Loops/Infinite | Task
Print out SPAM followed by a newline in an infinite loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #R | R | repeat print("SPAM") |
http://rosettacode.org/wiki/Loops/Infinite | Loops/Infinite | Task
Print out SPAM followed by a newline in an infinite loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Racket | Racket |
#lang racket
;; Using recursion
(define (loop)
(displayln "SPAM")
(loop))
(loop)
;; Using a for loop
(for ([i (in-naturals)])
(displayln "SPAM"))
|
http://rosettacode.org/wiki/Loops/While | Loops/While | Task
Start an integer value at 1024.
Loop while it is greater than zero.
Print the value (with a newline) and divide it by two each time through the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreachbas
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #PHP | PHP | $i = 1024;
while ($i > 0) {
echo "$i\n";
$i >>= 1;
} |
http://rosettacode.org/wiki/Loops/While | Loops/While | Task
Start an integer value at 1024.
Loop while it is greater than zero.
Print the value (with a newline) and divide it by two each time through the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreachbas
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Picat | Picat | go =>
N = 1024,
while (N > 0)
println(N),
N := N // 2
end. |
http://rosettacode.org/wiki/Loops/Downward_for | Loops/Downward for | Task
Write a for loop which writes a countdown from 10 to 0.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Raku | Raku | for 10 ... 0 {
.say;
} |
http://rosettacode.org/wiki/Loops/Downward_for | Loops/Downward for | Task
Write a for loop which writes a countdown from 10 to 0.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #REBOL | REBOL | for i 10 0 -1 [print i] |
http://rosettacode.org/wiki/Loops/Do-while | Loops/Do-while | Start with a value at 0. Loop while value mod 6 is not equal to 0.
Each time through the loop, add 1 to the value then print it.
The loop must execute at least once.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
Reference
Do while loop Wikipedia.
| #.D0.9C.D0.9A-61.2F52 | МК-61/52 | 0 П4 КИП4 ИП4 6 / {x} x=0 02 С/П |
http://rosettacode.org/wiki/Loops/Do-while | Loops/Do-while | Start with a value at 0. Loop while value mod 6 is not equal to 0.
Each time through the loop, add 1 to the value then print it.
The loop must execute at least once.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
Reference
Do while loop Wikipedia.
| #Modula-2 | Modula-2 | MODULE DoWhile;
IMPORT InOut;
VAR
i: INTEGER;
BEGIN
i := 0;
REPEAT
INC(i);
InOut.WriteInt(i, 1);
InOut.WriteLn;
UNTIL i MOD 6 = 0;
END DoWhile. |
http://rosettacode.org/wiki/Loops/For | Loops/For | “For” loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code.
Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers.
Task
Show how two loops may be nested within each other, with the number of iterations performed by the inner for loop being controlled by the outer for loop.
Specifically print out the following pattern by using one for loop nested in another:
*
**
***
****
*****
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
Reference
For loop Wikipedia.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
For i As Integer = 1 To 5
For j As Integer = 1 To i
Print "*";
Next
Print
Next
Sleep |
http://rosettacode.org/wiki/Loops/For_with_a_specified_step | Loops/For with a specified step |
Task
Demonstrate a for-loop where the step-value is greater than one.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #M2000_Interpreter | M2000 Interpreter |
Module LoopFor {
Locale 1036
Document doc$
\\ define i as a single
def single i
for i=1 to 21 step 5/3
Print i
doc$=format$(" {0}", i)
next i
doc$={
}
\\ make i as a single
for i=21 to 1 step 5/3
Print i
doc$=format$(" {0}", i)
next i
clipboard doc$
report doc$
}
LoopFor
|
http://rosettacode.org/wiki/Long_multiplication | Long multiplication | Task
Explicitly implement long multiplication.
This is one possible approach to arbitrary-precision integer algebra.
For output, display the result of 264 * 264.
Optionally, verify your result against builtin arbitrary precision support.
The decimal representation of 264 is:
18,446,744,073,709,551,616
The output of 264 * 264 is 2128, and is:
340,282,366,920,938,463,463,374,607,431,768,211,456
| #Arturo | Arturo | print 2^64 * 2 |
http://rosettacode.org/wiki/Literals/String | Literals/String | Task
Show literal specification of characters and strings.
If supported, show how the following work:
verbatim strings (quotes where escape sequences are quoted literally)
here-strings
Also, discuss which quotes expand variables.
Related tasks
Special characters
Here document
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #AWK | AWK | c = "x"
str= "hello"
s1 = "abcd" # simple string
s2 = "ab\"cd" # string containing a double quote, escaped with backslash
print s1
print s2 |
http://rosettacode.org/wiki/Literals/String | Literals/String | Task
Show literal specification of characters and strings.
If supported, show how the following work:
verbatim strings (quotes where escape sequences are quoted literally)
here-strings
Also, discuss which quotes expand variables.
Related tasks
Special characters
Here document
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Axe | Axe | 'A' |
http://rosettacode.org/wiki/Long_literals,_with_continuations | Long literals, with continuations | This task is about writing a computer program that has long literals (character
literals that may require specifying the words/tokens on more than one (source)
line, either with continuations or some other method, such as abutments or
concatenations (or some other mechanisms).
The literal is to be in the form of a "list", a literal that contains many
words (tokens) separated by a blank (space), in this case (so as to have a
common list), the (English) names of the chemical elements of the periodic table.
The list is to be in (ascending) order of the (chemical) element's atomic number:
hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium aluminum silicon ...
... up to the last known (named) chemical element (at this time).
Do not include any of the "unnamed" chemical element names such as:
ununennium unquadnilium triunhexium penthextrium penthexpentium septhexunium octenntrium ennennbium
To make computer programming languages comparable, the statement widths should be
restricted to less than 81 bytes (characters), or less
if a computer programming language has more restrictive limitations or standards.
Also mention what column the programming statements can start in if not
in column one.
The list may have leading/embedded/trailing blanks during the
declaration (the actual program statements), this is allow the list to be
more readable. The "final" list shouldn't have any leading/trailing or superfluous
blanks (when stored in the program's "memory").
This list should be written with the idea in mind that the
program will be updated, most likely someone other than the
original author, as there will be newer (discovered) elements of the periodic
table being added (possibly in the near future). These future updates
should be one of the primary concerns in writing these programs and it should be "easy"
for someone else to add chemical elements to the list (within the computer
program).
Attention should be paid so as to not exceed the clause length of
continued or specified statements, if there is such a restriction. If the
limit is greater than (say) 4,000 bytes or so, it needn't be mentioned here.
Task
Write a computer program (by whatever name) to contain a list of the known elements.
The program should eventually contain a long literal of words (the elements).
The literal should show how one could create a long list of blank-delineated words.
The "final" (stored) list should only have a single blank between elements.
Try to use the most idiomatic approach(es) in creating the final list.
Use continuation if possible, and/or show alternatives (possibly using concatenation).
Use a program comment to explain what the continuation character is if it isn't obvious.
The program should contain a variable that has the date of the last update/revision.
The program, when run, should display with verbiage:
The last update/revision date (and should be unambiguous).
The number of chemical elements in the list.
The name of the highest (last) element name.
Show all output here, on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Lua | Lua | revised = "February 2, 2021"
-- the long literal string is delimited by double square brackets: [[...]]
-- each word must be separated by at least one whitespace character
-- additional whitespace may optionally be used to improve readability
-- (starting column does not matter, clause length is more than adequate)
longliteral = [[
hydrogen helium lithium beryllium
boron carbon nitrogen oxygen
fluorine neon sodium magnesium
aluminum silicon phosphorous sulfur
chlorine argon potassium calcium
scandium titanium vanadium chromium
manganese iron cobalt nickel
copper zinc gallium germanium
arsenic selenium bromine krypton
rubidium strontium yttrium zirconium
niobium molybdenum technetium ruthenium
rhodium palladium silver cadmium
indium tin antimony tellurium
iodine xenon cesium barium
lanthanum cerium praseodymium neodymium
promethium samarium europium gadolinium
terbium dysprosium holmium erbium
thulium ytterbium lutetium hafnium
tantalum tungsten rhenium osmium
iridium platinum gold mercury
thallium lead bismuth polonium
astatine radon francium radium
actinium thorium protactinium uranium
neptunium plutonium americium curium
berkelium californium einsteinium fermium
mendelevium nobelium lawrencium rutherfordium
dubnium seaborgium bohrium hassium
meitnerium darmstadtium roentgenium copernicium
nihonium flerovium moscovium livermorium
tennessine oganesson
]]
-- the task requires the "final list" as single-space-between string version
-- (a more idiomatic overall approach would be to directly split into a table)
finallist = longliteral:gsub("%s+"," ")
elements = {}
-- longliteral could be used here DIRECTLY instead of using finallist:
for name in finallist:gmatch("%w+") do elements[#elements+1]=name end
print("revised date: " .. revised)
print("# elements : " .. #elements)
print("last element: " .. elements[#elements])
-- then, if still required, produce a single-space-between string version:
--finallist = table.concat(elements," ") |
http://rosettacode.org/wiki/Long_literals,_with_continuations | Long literals, with continuations | This task is about writing a computer program that has long literals (character
literals that may require specifying the words/tokens on more than one (source)
line, either with continuations or some other method, such as abutments or
concatenations (or some other mechanisms).
The literal is to be in the form of a "list", a literal that contains many
words (tokens) separated by a blank (space), in this case (so as to have a
common list), the (English) names of the chemical elements of the periodic table.
The list is to be in (ascending) order of the (chemical) element's atomic number:
hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium aluminum silicon ...
... up to the last known (named) chemical element (at this time).
Do not include any of the "unnamed" chemical element names such as:
ununennium unquadnilium triunhexium penthextrium penthexpentium septhexunium octenntrium ennennbium
To make computer programming languages comparable, the statement widths should be
restricted to less than 81 bytes (characters), or less
if a computer programming language has more restrictive limitations or standards.
Also mention what column the programming statements can start in if not
in column one.
The list may have leading/embedded/trailing blanks during the
declaration (the actual program statements), this is allow the list to be
more readable. The "final" list shouldn't have any leading/trailing or superfluous
blanks (when stored in the program's "memory").
This list should be written with the idea in mind that the
program will be updated, most likely someone other than the
original author, as there will be newer (discovered) elements of the periodic
table being added (possibly in the near future). These future updates
should be one of the primary concerns in writing these programs and it should be "easy"
for someone else to add chemical elements to the list (within the computer
program).
Attention should be paid so as to not exceed the clause length of
continued or specified statements, if there is such a restriction. If the
limit is greater than (say) 4,000 bytes or so, it needn't be mentioned here.
Task
Write a computer program (by whatever name) to contain a list of the known elements.
The program should eventually contain a long literal of words (the elements).
The literal should show how one could create a long list of blank-delineated words.
The "final" (stored) list should only have a single blank between elements.
Try to use the most idiomatic approach(es) in creating the final list.
Use continuation if possible, and/or show alternatives (possibly using concatenation).
Use a program comment to explain what the continuation character is if it isn't obvious.
The program should contain a variable that has the date of the last update/revision.
The program, when run, should display with verbiage:
The last update/revision date (and should be unambiguous).
The number of chemical elements in the list.
The name of the highest (last) element name.
Show all output here, on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Nim | Nim | import strutils
const RevDate = "2021-02-05"
# We use the concatenation operator "&" to assemble the strings.
# This is done at compile time and so the result is a long literal.
const ElementString =
"hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine " &
"neon sodium magnesium aluminum silicon phosphorous sulfur chlorine argon " &
"potassium calcium scandium titanium vanadium chromium manganese iron " &
"cobalt nickel copper zinc gallium germanium arsenic selenium bromine " &
"krypton rubidium strontium yttrium zirconium niobium molybdenum " &
"technetium ruthenium rhodium palladium silver cadmium indium tin " &
"antimony tellurium iodine xenon cesium barium lanthanum cerium " &
"praseodymium neodymium promethium samarium europium gadolinium terbium " &
"dysprosium holmium erbium thulium ytterbium lutetium hafnium tantalum " &
"tungsten rhenium osmium iridium platinum gold mercury thallium lead " &
"bismuth polonium astatine radon francium radium actinium thorium " &
"protactinium uranium neptunium plutonium americium curium berkelium " &
"californium einsteinium fermium mendelevium nobelium lawrencium " &
"rutherfordium dubnium seaborgium bohrium hassium meitnerium darmstadtium " &
"roentgenium copernicium nihonium flerovium moscovium livermorium " &
"tennessine oganesson"
when isMainModule:
const ElementList = ElementString.split()
echo "Last revision date: ", RevDate
echo "Number of elements: ", ElementList.len
echo "Last element in list: ", ElementList[^1] |
http://rosettacode.org/wiki/Long_literals,_with_continuations | Long literals, with continuations | This task is about writing a computer program that has long literals (character
literals that may require specifying the words/tokens on more than one (source)
line, either with continuations or some other method, such as abutments or
concatenations (or some other mechanisms).
The literal is to be in the form of a "list", a literal that contains many
words (tokens) separated by a blank (space), in this case (so as to have a
common list), the (English) names of the chemical elements of the periodic table.
The list is to be in (ascending) order of the (chemical) element's atomic number:
hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium aluminum silicon ...
... up to the last known (named) chemical element (at this time).
Do not include any of the "unnamed" chemical element names such as:
ununennium unquadnilium triunhexium penthextrium penthexpentium septhexunium octenntrium ennennbium
To make computer programming languages comparable, the statement widths should be
restricted to less than 81 bytes (characters), or less
if a computer programming language has more restrictive limitations or standards.
Also mention what column the programming statements can start in if not
in column one.
The list may have leading/embedded/trailing blanks during the
declaration (the actual program statements), this is allow the list to be
more readable. The "final" list shouldn't have any leading/trailing or superfluous
blanks (when stored in the program's "memory").
This list should be written with the idea in mind that the
program will be updated, most likely someone other than the
original author, as there will be newer (discovered) elements of the periodic
table being added (possibly in the near future). These future updates
should be one of the primary concerns in writing these programs and it should be "easy"
for someone else to add chemical elements to the list (within the computer
program).
Attention should be paid so as to not exceed the clause length of
continued or specified statements, if there is such a restriction. If the
limit is greater than (say) 4,000 bytes or so, it needn't be mentioned here.
Task
Write a computer program (by whatever name) to contain a list of the known elements.
The program should eventually contain a long literal of words (the elements).
The literal should show how one could create a long list of blank-delineated words.
The "final" (stored) list should only have a single blank between elements.
Try to use the most idiomatic approach(es) in creating the final list.
Use continuation if possible, and/or show alternatives (possibly using concatenation).
Use a program comment to explain what the continuation character is if it isn't obvious.
The program should contain a variable that has the date of the last update/revision.
The program, when run, should display with verbiage:
The last update/revision date (and should be unambiguous).
The number of chemical elements in the list.
The name of the highest (last) element name.
Show all output here, on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Pascal | Pascal | #!/usr/bin/perl
use strict; # https://rosettacode.org/wiki/Long_literals,_with_continuations
use warnings;
my $longliteral = join ' ', split ' ', <<END;
hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine
neon sodium magnesium aluminum silicon phosphorous sulfur chlorine argon
potassium calcium scandium titanium vanadium chromium manganese iron cobalt
nickel copper zinc gallium germanium arsenic selenium bromine krypton rubidium
strontium yttrium zirconium niobium molybdenum technetium ruthenium rhodium
palladium silver cadmium indium tin antimony tellurium iodine xenon cesium
barium lanthanum cerium praseodymium neodymium promethium samarium europium
gadolinium terbium dysprosium holmium erbium thulium ytterbium lutetium hafnium
tantalum tungsten rhenium osmium iridium platinum gold mercury thallium lead
bismuth polonium astatine radon francium radium actinium thorium protactinium
uranium neptunium plutonium americium curium berkelium californium einsteinium
fermium mendelevium nobelium lawrencium rutherfordium dubnium seaborgium
bohrium hassium meitnerium darmstadtium roentgenium copernicium nihonium
flerovium moscovium livermorium tennessine oganesson
END
my $version = 'Tue Feb 2 22:30:48 UTC 2021';
my $count = my @elements = split ' ', $longliteral;
my $last = $elements[-1];
print <<END;
version: $version
element count: $count
last element: $last
END |
http://rosettacode.org/wiki/List_rooted_trees | List rooted trees | You came back from grocery shopping. After putting away all the goods, you are left with a pile of plastic bags, which you want to save for later use, so you take one bag and stuff all the others into it, and throw it under the sink. In doing so, you realize that there are various ways of nesting the bags, with all bags viewed as identical.
If we use a matching pair of parentheses to represent a bag, the ways are:
For 1 bag, there's one way:
() <- a bag
for 2 bags, there's one way:
(()) <- one bag in another
for 3 bags, there are two:
((())) <- 3 bags nested Russian doll style
(()()) <- 2 bags side by side, inside the third
for 4 bags, four:
(()()())
((())())
((()()))
(((())))
Note that because all bags are identical, the two 4-bag strings ((())()) and (()(())) represent the same configuration.
It's easy to see that each configuration for n bags represents a n-node rooted tree, where a bag is a tree node, and a bag with its content forms a subtree. The outermost bag is the tree root. Number of configurations for given n is given by OEIS A81.
Task
Write a program that, when given n, enumerates all ways of nesting n bags. You can use the parentheses notation above, or any tree representation that's unambiguous and preferably intuitive.
This task asks for enumeration of trees only; for counting solutions without enumeration, that OEIS page lists various formulas, but that's not encouraged by this task, especially if implementing it would significantly increase code size.
As an example output, run 5 bags. There should be 9 ways.
| #J | J | root=: 1 1 $ _
incr=: ,/@(,"1 0/ i.@{:@$)
boxed=: $:&0 :(<@\:~@([ $:^:(0 < #@]) I.@:=))"1 1 0 |
http://rosettacode.org/wiki/List_rooted_trees | List rooted trees | You came back from grocery shopping. After putting away all the goods, you are left with a pile of plastic bags, which you want to save for later use, so you take one bag and stuff all the others into it, and throw it under the sink. In doing so, you realize that there are various ways of nesting the bags, with all bags viewed as identical.
If we use a matching pair of parentheses to represent a bag, the ways are:
For 1 bag, there's one way:
() <- a bag
for 2 bags, there's one way:
(()) <- one bag in another
for 3 bags, there are two:
((())) <- 3 bags nested Russian doll style
(()()) <- 2 bags side by side, inside the third
for 4 bags, four:
(()()())
((())())
((()()))
(((())))
Note that because all bags are identical, the two 4-bag strings ((())()) and (()(())) represent the same configuration.
It's easy to see that each configuration for n bags represents a n-node rooted tree, where a bag is a tree node, and a bag with its content forms a subtree. The outermost bag is the tree root. Number of configurations for given n is given by OEIS A81.
Task
Write a program that, when given n, enumerates all ways of nesting n bags. You can use the parentheses notation above, or any tree representation that's unambiguous and preferably intuitive.
This task asks for enumeration of trees only; for counting solutions without enumeration, that OEIS page lists various formulas, but that's not encouraged by this task, especially if implementing it would significantly increase code size.
As an example output, run 5 bags. There should be 9 ways.
| #Java | Java | import java.util.ArrayList;
import java.util.List;
public class ListRootedTrees {
private static final List<Long> TREE_LIST = new ArrayList<>();
private static final List<Integer> OFFSET = new ArrayList<>();
static {
for (int i = 0; i < 32; i++) {
if (i == 1) {
OFFSET.add(1);
} else {
OFFSET.add(0);
}
}
}
private static void append(long t) {
TREE_LIST.add(1 | (t << 1));
}
private static void show(long t, int l) {
while (l-- > 0) {
if (t % 2 == 1) {
System.out.print('(');
} else {
System.out.print(')');
}
t = t >> 1;
}
}
private static void listTrees(int n) {
for (int i = OFFSET.get(n); i < OFFSET.get(n + 1); i++) {
show(TREE_LIST.get(i), n * 2);
System.out.println();
}
}
private static void assemble(int n, long t, int sl, int pos, int rem) {
if (rem == 0) {
append(t);
return;
}
var pp = pos;
var ss = sl;
if (sl > rem) {
ss = rem;
pp = OFFSET.get(ss);
} else if (pp >= OFFSET.get(ss + 1)) {
ss--;
if (ss == 0) {
return;
}
pp = OFFSET.get(ss);
}
assemble(n, t << (2 * ss) | TREE_LIST.get(pp), ss, pp, rem - ss);
assemble(n, t, ss, pp + 1, rem);
}
private static void makeTrees(int n) {
if (OFFSET.get(n + 1) != 0) {
return;
}
if (n > 0) {
makeTrees(n - 1);
}
assemble(n, 0, n - 1, OFFSET.get(n - 1), n - 1);
OFFSET.set(n + 1, TREE_LIST.size());
}
private static void test(int n) {
if (n < 1 || n > 12) {
throw new IllegalArgumentException("Argument must be between 1 and 12");
}
append(0);
makeTrees(n);
System.out.printf("Number of %d-trees: %d\n", n, OFFSET.get(n + 1) - OFFSET.get(n));
listTrees(n);
}
public static void main(String[] args) {
test(5);
}
} |
http://rosettacode.org/wiki/Literals/Integer | Literals/Integer | Some programming languages have ways of expressing integer literals in bases other than the normal base ten.
Task
Show how integer literals can be expressed in as many bases as your language allows.
Note: this should not involve the calling of any functions/methods, but should be interpreted by the compiler or interpreter as an integer written to a given base.
Also show any other ways of expressing literals, e.g. for different types of integers.
Related task
Literals/Floating point
| #Avail | Avail | Print: "0b11001101 = " ++ “0b11001101”;
Print: "0o755 = " ++ “0o755”;
Print: "0xDEADBEEF = " ++ “0xDEADBEEF”; |
http://rosettacode.org/wiki/Literals/Integer | Literals/Integer | Some programming languages have ways of expressing integer literals in bases other than the normal base ten.
Task
Show how integer literals can be expressed in as many bases as your language allows.
Note: this should not involve the calling of any functions/methods, but should be interpreted by the compiler or interpreter as an integer written to a given base.
Also show any other ways of expressing literals, e.g. for different types of integers.
Related task
Literals/Floating point
| #AWK | AWK | BEGIN {
if ( (0x2d7 == 727) &&
(01327 == 727) ) {
print "true with GNU awk"
}
} |
http://rosettacode.org/wiki/Logical_operations | Logical operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a function that takes two logical (boolean) values, and outputs the result of "and" and "or" on both arguments as well as "not" on the first arguments.
If the programming language doesn't provide a separate type for logical values, use the type most commonly used for that purpose.
If the language supports additional logical operations on booleans such as XOR, list them as well.
| #ALGOL_68 | ALGOL 68 | PROC print_logic = (BOOL a, b)VOID:
(
# for a 6-7 bit/byte compiler #
printf(($"a and b is "gl$, a AND b);
printf(($"a or b is "gl$, a OR b);
printf(($"not a is "gl$, NOT a);
printf(($"a equivalent to b is "gl$, a EQ b);
printf(($"a not equivalent to b is "gl$, a NE b);
# Alternatively ASCII #
printf(($"a and b is "gl$, a & b);
printf(($"a and b is "gl$, a /\ b); <!-- http://web.archive.org/web/20021207211127/http://www.bobbemer.com/BRACES.HTM -->
printf(($"a or b is "gl$, a \/ b);
printf(($"a equivalent to b "gl$, a = b);
printf(($"a not equivalent to b "gl$, a /= b);
¢ for a European 8 bit/byte charcter set eg. ALCOR or GOST ¢
printf(($"a and b is "gl$, a ∧ b);
printf(($"a or b is "gl$, a ∨ b);
printf(($"not a is "gl$, ¬ a)
printf(($"a not equivalent to b is "gl$, a ≠ b)
) |
http://rosettacode.org/wiki/Loops/N_plus_one_half | Loops/N plus one half | Quite often one needs loops which, in the last iteration, execute only part of the loop body.
Goal
Demonstrate the best way to do this.
Task
Write a loop which writes the comma-separated list
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
using separate output statements for the number
and the comma from within the body of the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Ursa | Ursa | decl int i
for (set i 1) (< i 11) (inc i)
out i console
if (= i 10)
break
end if
out ", " console
end for
out endl console |
http://rosettacode.org/wiki/Loops/N_plus_one_half | Loops/N plus one half | Quite often one needs loops which, in the last iteration, execute only part of the loop body.
Goal
Demonstrate the best way to do this.
Task
Write a loop which writes the comma-separated list
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
using separate output statements for the number
and the comma from within the body of the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #V | V | [loop
[ [10 =] [puts]
[true] [dup put ',' put succ loop]
] when]. |
http://rosettacode.org/wiki/Literals/Floating_point | Literals/Floating point | Programming languages have different ways of expressing floating-point literals.
Task
Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features.
You may want to include a regular expression or BNF/ABNF/EBNF defining allowable formats for your language.
Related tasks
Literals/Integer
Extreme floating point values
| #Erlang | Erlang |
printf(1,"Exponential:\t%e, %e, %e, %e\n",{-10.1246,10.2356,16.123456789,64.12})
printf(1,"Floating Point\t%03.3f, %04.3f, %+3.3f, %3.3f\n",{-10.1246,10.2356,16.123456789,64.12})
printf(1,"Floating Point or Exponential: %g, %g, %g, %g\n",{10,16.123456789,64,123456789.123})
|
http://rosettacode.org/wiki/Literals/Floating_point | Literals/Floating point | Programming languages have different ways of expressing floating-point literals.
Task
Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features.
You may want to include a regular expression or BNF/ABNF/EBNF defining allowable formats for your language.
Related tasks
Literals/Integer
Extreme floating point values
| #Euphoria | Euphoria |
printf(1,"Exponential:\t%e, %e, %e, %e\n",{-10.1246,10.2356,16.123456789,64.12})
printf(1,"Floating Point\t%03.3f, %04.3f, %+3.3f, %3.3f\n",{-10.1246,10.2356,16.123456789,64.12})
printf(1,"Floating Point or Exponential: %g, %g, %g, %g\n",{10,16.123456789,64,123456789.123})
|
http://rosettacode.org/wiki/Long_year | Long year | Most years have 52 weeks, some have 53, according to ISO8601.
Task
Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
| #Haskell | Haskell | import Data.Time.Calendar (fromGregorian)
import Data.Time.Calendar.WeekDate (toWeekDate)
longYear :: Integer -> Bool
longYear y =
let (_, w, _) = toWeekDate $ fromGregorian y 12 28
in 52 < w
main :: IO ()
main = mapM_ print $ filter longYear [2000 .. 2100] |
http://rosettacode.org/wiki/Long_year | Long year | Most years have 52 weeks, some have 53, according to ISO8601.
Task
Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
| #J | J | p =: 1 4 _100 400&(7 | [: <. +/ @: %~)"1 0
ily =: (4=p) +. 3=p@:<:
ply =: (#~ ily)@:([ + 1+i.@:-~) |
http://rosettacode.org/wiki/Long_primes | Long primes |
A long prime (as defined here) is a prime number whose reciprocal (in decimal) has
a period length of one less than the prime number.
Long primes are also known as:
base ten cyclic numbers
full reptend primes
golden primes
long period primes
maximal period primes
proper primes
Another definition: primes p such that the decimal expansion of 1/p has period p-1, which is the greatest period possible for any integer.
Example
7 is the first long prime, the reciprocal of seven
is 1/7, which
is equal to the repeating decimal fraction 0.142857142857···
The length of the repeating part of the decimal fraction
is six, (the underlined part) which is one less
than the (decimal) prime number 7.
Thus 7 is a long prime.
There are other (more) general definitions of a long prime which
include wording/verbiage for bases other than ten.
Task
Show all long primes up to 500 (preferably on one line).
Show the number of long primes up to 500
Show the number of long primes up to 1,000
Show the number of long primes up to 2,000
Show the number of long primes up to 4,000
Show the number of long primes up to 8,000
Show the number of long primes up to 16,000
Show the number of long primes up to 32,000
Show the number of long primes up to 64,000 (optional)
Show all output here.
Also see
Wikipedia: full reptend prime
MathWorld: full reptend prime
OEIS: A001913
| #Go | Go | package main
import "fmt"
func sieve(limit int) []int {
var primes []int
c := make([]bool, limit + 1) // composite = true
// no need to process even numbers
p := 3
p2 := p * p
for p2 <= limit {
for i := p2; i <= limit; i += 2 * p {
c[i] = true
}
for ok := true; ok; ok = c[p] {
p += 2
}
p2 = p * p
}
for i := 3; i <= limit; i += 2 {
if !c[i] {
primes = append(primes, i)
}
}
return primes
}
// finds the period of the reciprocal of n
func findPeriod(n int) int {
r := 1
for i := 1; i <= n + 1; i++ {
r = (10 * r) % n
}
rr := r
period := 0
for ok := true; ok; ok = r != rr {
r = (10 * r) % n
period++
}
return period
}
func main() {
primes := sieve(64000)
var longPrimes []int
for _, prime := range primes {
if findPeriod(prime) == prime - 1 {
longPrimes = append(longPrimes, prime)
}
}
numbers := []int{500, 1000, 2000, 4000, 8000, 16000, 32000, 64000}
index := 0
count := 0
totals := make([]int, len(numbers))
for _, longPrime := range longPrimes {
if longPrime > numbers[index] {
totals[index] = count
index++
}
count++
}
totals[len(numbers)-1] = count
fmt.Println("The long primes up to", numbers[0], "are: ")
fmt.Println(longPrimes[:totals[0]])
fmt.Println("\nThe number of long primes up to: ")
for i, total := range totals {
fmt.Printf(" %5d is %d\n", numbers[i], total)
}
} |
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously | Loop over multiple arrays simultaneously | Task
Loop over multiple arrays (or lists or tuples or whatever they're called in
your language) and display the i th element of each.
Use your language's "for each" loop if it has one, otherwise iterate
through the collection in order with some other loop.
For this example, loop over the arrays:
(a,b,c)
(A,B,C)
(1,2,3)
to produce the output:
aA1
bB2
cC3
If possible, also describe what happens when the arrays are of different lengths.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #BBC_BASIC | BBC BASIC | DIM array1$(2), array2$(2), array3%(2)
array1$() = "a", "b", "c"
array2$() = "A", "B", "C"
array3%() = 1, 2, 3
FOR index% = 0 TO 2
PRINT array1$(index%) ; array2$(index%) ; array3%(index%)
NEXT |
http://rosettacode.org/wiki/Loops/Break | Loops/Break | Task
Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive).
If a number is 10, stop the loop after printing it, and do not generate any further numbers.
Otherwise, generate and print a second random number before restarting the loop.
If the number 10 is never generated as the first number in a loop, loop forever.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
| #Clojure | Clojure | (loop [[a b & more] (repeatedly #(rand-int 20))]
(println a)
(when-not (= 10 a)
(println b)
(recur more))) |
http://rosettacode.org/wiki/Longest_common_subsequence | Longest common subsequence | Introduction
Define a subsequence to be any output string obtained by deleting zero or more symbols from an input string.
The Longest Common Subsequence (LCS) is a subsequence of maximum length common to two or more strings.
Let A ≡ A[0]… A[m - 1] and B ≡ B[0]… B[n - 1], m < n be strings drawn from an alphabet Σ of size s, containing every distinct symbol in A + B.
An ordered pair (i, j) will be referred to as a match if A[i] = B[j], where 0 < i ≤ m and 0 < j ≤ n.
Define a non-strict product-order (≤) over ordered pairs, such that (i1, j1) ≤ (i2, j2) ⇔ i1 ≤ i2 and j1 ≤ j2. We define (≥) similarly.
We say m1, m2 are comparable if either m1 ≤ m2 or m1 ≥ m2 holds. If i1 < i2 and j2 < j1 (or i2 < i1 and j1 < j2) then neither m1 ≤ m2 nor m1 ≥ m2 are possible; and we say m1, m2 are incomparable.
We also define the strict product-order (<) over ordered pairs, such that (i1, j1) < (i2, j2) ⇔ i1 < i2 and j1 < j2. We define (>) similarly.
Given a set of matches M, a chain C is a subset of M consisting of at least one element m; and where either m1 < m2 or m1 > m2 for every pair of distinct elements m1 and m2. An antichain D is any subset of M in which every pair of distinct elements m1 and m2 are incomparable.
The set M represents a relation over match pairs: M[i, j] ⇔ (i, j) ∈ M. A chain C can be visualized as a curve which strictly increases as it passes through each match pair in the m*n coordinate space.
Finding an LCS can be restated as the problem of finding a chain of maximum cardinality p over the set of matches M.
According to [Dilworth 1950], this cardinality p equals the minimum number of disjoint antichains into which M can be decomposed. Note that such a decomposition into the minimal number p of disjoint antichains may not be unique.
Contours
Forward Contours FC[k] of class k are defined inductively, as follows:
FC[0] consists of those elements m1 for which there exists no element m2 such that m2 < m1.
FC[k] consists of those elements m1 for which there exists no element m2 such that m2 < m1; and where neither m1 nor m2 are contained in FC[l] for any class l < k.
Reverse Contours RC[k] of class k are defined similarly.
Members of the Meet (∧), or Infimum of a Forward Contour are referred to as its Dominant Matches: those m1 for which there exists no m2 such that m2 < m1.
Members of the Join (∨), or Supremum of a Reverse Contour are referred to as its Dominant Matches: those m1 for which there exists no m2 such that m2 > m1.
Where multiple Dominant Matches exist within a Meet (or within a Join, respectively) the Dominant Matches will be incomparable to each other.
Background
Where the number of symbols appearing in matches is small relative to the length of the input strings, reuse of the symbols increases; and the number of matches will tend towards quadratic, O(m*n) growth. This occurs, for example, in the Bioinformatics application of nucleotide and protein sequencing.
The divide-and-conquer approach of [Hirschberg 1975] limits the space required to O(n). However, this approach requires O(m*n) time even in the best case.
This quadratic time dependency may become prohibitive, given very long input strings. Thus, heuristics are often favored over optimal Dynamic Programming solutions.
In the application of comparing file revisions, records from the input files form a large symbol space; and the number of symbols approaches the length of the LCS. In this case the number of matches reduces to linear, O(n) growth.
A binary search optimization due to [Hunt and Szymanski 1977] can be applied to the basic Dynamic Programming approach, resulting in an expected performance of O(n log m). Performance can degrade to O(m*n log m) time in the worst case, as the number of matches grows to O(m*n).
Note
[Rick 2000] describes a linear-space algorithm with a time bound of O(n*s + p*min(m, n - p)).
Legend
A, B are input strings of lengths m, n respectively
p is the length of the LCS
M is the set of match pairs (i, j) such that A[i] = B[j]
r is the magnitude of M
s is the magnitude of the alphabet Σ of distinct symbols in A + B
References
[Dilworth 1950] "A decomposition theorem for partially ordered sets"
by Robert P. Dilworth, published January 1950,
Annals of Mathematics [Volume 51, Number 1, pp. 161-166]
[Goeman and Clausen 2002] "A New Practical Linear Space Algorithm for the Longest Common
Subsequence Problem" by Heiko Goeman and Michael Clausen,
published 2002, Kybernetika [Volume 38, Issue 1, pp. 45-66]
[Hirschberg 1975] "A linear space algorithm for computing maximal common subsequences"
by Daniel S. Hirschberg, published June 1975
Communications of the ACM [Volume 18, Number 6, pp. 341-343]
[Hunt and McIlroy 1976] "An Algorithm for Differential File Comparison"
by James W. Hunt and M. Douglas McIlroy, June 1976
Computing Science Technical Report, Bell Laboratories 41
[Hunt and Szymanski 1977] "A Fast Algorithm for Computing Longest Common Subsequences"
by James W. Hunt and Thomas G. Szymanski, published May 1977
Communications of the ACM [Volume 20, Number 5, pp. 350-353]
[Rick 2000] "Simple and fast linear space computation of longest common subsequences"
by Claus Rick, received 17 March 2000, Information Processing Letters,
Elsevier Science [Volume 75, pp. 275–281]
Examples
The sequences "1234" and "1224533324" have an LCS of "1234":
1234
1224533324
For a string example, consider the sequences "thisisatest" and "testing123testing". An LCS would be "tsitest":
thisisatest
testing123testing
In this puzzle, your code only needs to deal with strings. Write a function which returns an LCS of two strings (case-sensitive). You don't need to show multiple LCS's.
For more information on this problem please see Wikipedia.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #D | D | import std.stdio, std.array;
T[] lcs(T)(in T[] a, in T[] b) pure nothrow @safe {
if (a.empty || b.empty) return null;
if (a[0] == b[0])
return a[0] ~ lcs(a[1 .. $], b[1 .. $]);
const longest = (T[] x, T[] y) => x.length > y.length ? x : y;
return longest(lcs(a, b[1 .. $]), lcs(a[1 .. $], b));
}
void main() {
lcs("thisisatest", "testing123testing").writeln;
} |
http://rosettacode.org/wiki/Look-and-say_sequence | Look-and-say sequence | The Look and say sequence is a recursively defined sequence of numbers studied most notably by John Conway.
The look-and-say sequence is also known as the Morris Number Sequence, after cryptographer Robert Morris, and the puzzle What is the next number in the sequence 1, 11, 21, 1211, 111221? is sometimes referred to as the Cuckoo's Egg, from a description of Morris in Clifford Stoll's book The Cuckoo's Egg.
Sequence Definition
Take a decimal number
Look at the number, visually grouping consecutive runs of the same digit.
Say the number, from left to right, group by group; as how many of that digit there are - followed by the digit grouped.
This becomes the next number of the sequence.
An example:
Starting with the number 1, you have one 1 which produces 11
Starting with 11, you have two 1's. I.E.: 21
Starting with 21, you have one 2, then one 1. I.E.: (12)(11) which becomes 1211
Starting with 1211, you have one 1, one 2, then two 1's. I.E.: (11)(12)(21) which becomes 111221
Task
Write a program to generate successive members of the look-and-say sequence.
Related tasks
Fours is the number of letters in the ...
Number names
Self-describing numbers
Self-referential sequence
Spelling of ordinal numbers
See also
Look-and-Say Numbers (feat John Conway), A Numberphile Video.
This task is related to, and an application of, the Run-length encoding task.
Sequence A005150 on The On-Line Encyclopedia of Integer Sequences.
| #Bracmat | Bracmat | ( 1:?number
& 0:?lines
& whl
' ( 1+!lines:~>10:?lines
& :?say { This will accumulate all that has to be said after one iteration. }
& 0:?begin
& ( @( !number { Pattern matching. The '@' indicates we're looking in a string rather than a tree structure. }
: ?
( [!begin
%@?digit
?
[?end
( (|(%@:~!digit) ?) { The %@ guarantees we're testing one character - not less (%) and not more (@). The ? takes the rest. }
& !say !end+-1*!begin !digit:?say
& !end:?begin { When backtracking, 'begin' advances to the begin of the next sequence, or to the end of the string. }
)
& ~ { fail! This forces backtracking. Backtracking stops when all begin positions have been tried. }
)
)
| out$(str$!say:?number) { After backtracking, output string and set number to string for next iteration. }
)
)
); |
http://rosettacode.org/wiki/Longest_string_challenge | Longest string challenge | Background
This "longest string challenge" is inspired by a problem that used to be given to students learning Icon. Students were expected to try to solve the problem in Icon and another language with which the student was already familiar. The basic problem is quite simple; the challenge and fun part came through the introduction of restrictions. Experience has shown that the original restrictions required some adjustment to bring out the intent of the challenge and make it suitable for Rosetta Code.
Basic problem statement
Write a program that reads lines from standard input and, upon end of file, writes the longest line to standard output.
If there are ties for the longest line, the program writes out all the lines that tie.
If there is no input, the program should produce no output.
Task
Implement a solution to the basic problem that adheres to the spirit of the restrictions (see below).
Describe how you circumvented or got around these 'restrictions' and met the 'spirit' of the challenge. Your supporting description may need to describe any challenges to interpreting the restrictions and how you made this interpretation. You should state any assumptions, warnings, or other relevant points. The central idea here is to make the task a bit more interesting by thinking outside of the box and perhaps by showing off the capabilities of your language in a creative way. Because there is potential for considerable variation between solutions, the description is key to helping others see what you've done.
This task is likely to encourage a variety of different types of solutions. They should be substantially different approaches.
Given the input:
a
bb
ccc
ddd
ee
f
ggg
the output should be (possibly rearranged):
ccc
ddd
ggg
Original list of restrictions
No comparison operators may be used.
No arithmetic operations, such as addition and subtraction, may be used.
The only datatypes you may use are integer and string. In particular, you may not use lists.
Do not re-read the input file. Avoid using files as a replacement for lists (this restriction became apparent in the discussion).
Intent of restrictions
Because of the variety of languages on Rosetta Code and the wide variety of concepts used in them, there needs to be a bit of clarification and guidance here to get to the spirit of the challenge and the intent of the restrictions.
The basic problem can be solved very conventionally, but that's boring and pedestrian. The original intent here wasn't to unduly frustrate people with interpreting the restrictions, it was to get people to think outside of their particular box and have a bit of fun doing it.
The guiding principle here should be to be creative in demonstrating some of the capabilities of the programming language being used. If you need to bend the restrictions a bit, explain why and try to follow the intent. If you think you've implemented a 'cheat', call out the fragment yourself and ask readers if they can spot why. If you absolutely can't get around one of the restrictions, explain why in your description.
Now having said that, the restrictions require some elaboration.
In general, the restrictions are meant to avoid the explicit use of these features.
"No comparison operators may be used" - At some level there must be some test that allows the solution to get at the length and determine if one string is longer. Comparison operators, in particular any less/greater comparison should be avoided. Representing the length of any string as a number should also be avoided. Various approaches allow for detecting the end of a string. Some of these involve implicitly using equal/not-equal; however, explicitly using equal/not-equal should be acceptable.
"No arithmetic operations" - Again, at some level something may have to advance through the string. Often there are ways a language can do this implicitly advance a cursor or pointer without explicitly using a +, - , ++, --, add, subtract, etc.
The datatype restrictions are amongst the most difficult to reinterpret. In the language of the original challenge strings are atomic datatypes and structured datatypes like lists are quite distinct and have many different operations that apply to them. This becomes a bit fuzzier with languages with a different programming paradigm. The intent would be to avoid using an easy structure to accumulate the longest strings and spit them out. There will be some natural reinterpretation here.
To make this a bit more concrete, here are a couple of specific examples:
In C, a string is an array of chars, so using a couple of arrays as strings is in the spirit while using a second array in a non-string like fashion would violate the intent.
In APL or J, arrays are the core of the language so ruling them out is unfair. Meeting the spirit will come down to how they are used.
Please keep in mind these are just examples and you may hit new territory finding a solution. There will be other cases like these. Explain your reasoning. You may want to open a discussion on the talk page as well.
The added "No rereading" restriction is for practical reasons, re-reading stdin should be broken. I haven't outright banned the use of other files but I've discouraged them as it is basically another form of a list. Somewhere there may be a language that just sings when doing file manipulation and where that makes sense; however, for most there should be a way to accomplish without resorting to an externality.
At the end of the day for the implementer this should be a bit of fun. As an implementer you represent the expertise in your language, the reader may have no knowledge of your language. For the reader it should give them insight into how people think outside the box in other languages. Comments, especially for non-obvious (to the reader) bits will be extremely helpful. While the implementations may be a bit artificial in the context of this task, the general techniques may be useful elsewhere.
| #PHP | PHP | <?php
echo 'Enter strings (empty string to finish) :', PHP_EOL;
$output = $previous = readline();
while ($current = readline()) {
$p = $previous;
$c = $current;
// Remove first character from strings until one of them is empty
while ($p and $c) {
$p = substr($p, 1);
$c = substr($c, 1);
}
// If $p and $c are empty : strings are of equal length
if (!$p and !$c) {
$output .= PHP_EOL . $current;
}
// If $c is not empty, $current is longer
if ($c) {
$output = $previous = $current;
}
}
echo 'Longest string(s) = ', PHP_EOL, $output, PHP_EOL; |
Subsets and Splits
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.