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/Generic_swap
|
Generic swap
|
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation.
That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.
Generic swap is a task which brings together a few separate issues in programming language semantics.
Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.
Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.
Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).
Do your best!
|
#Rust
|
Rust
|
fn generic_swap<'a, T>(var1: &'a mut T, var2: &'a mut T) {
std::mem::swap(var1, var2)
}
|
http://rosettacode.org/wiki/Generic_swap
|
Generic swap
|
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation.
That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.
Generic swap is a task which brings together a few separate issues in programming language semantics.
Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.
Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.
Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).
Do your best!
|
#Sather
|
Sather
|
class SWAP{T} is
swap(inout a, inout b:T) is
t ::= a;
a := b;
b := t;
end;
end;
|
http://rosettacode.org/wiki/Greatest_element_of_a_list
|
Greatest element of a list
|
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
|
#WDTE
|
WDTE
|
let s => import 'stream';
let a => import 'arrays';
let max list =>
a.stream list
-> s.extent 1 >
-> at 0
;
|
http://rosettacode.org/wiki/Greatest_element_of_a_list
|
Greatest element of a list
|
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
|
#Wortel
|
Wortel
|
@maxl [1 6 4 6 4 8 6 3] ; returns 8
|
http://rosettacode.org/wiki/Generator/Exponential
|
Generator/Exponential
|
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided.
Generators are often built on top of coroutines or objects so that the internal state of the object is handled “naturally”.
Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state.
Task
Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size).
Use it to create a generator of:
Squares.
Cubes.
Create a new generator that filters all cubes from the generator of squares.
Drop the first 20 values from this last generator of filtered results, and then show the next 10 values.
Note that this task requires the use of generators in the calculation of the result.
Also see
Generator
|
#C.2B.2B
|
C++
|
#include <iostream>
using namespace std;
template<class T>
class Generator
{
public:
virtual T operator()() = 0;
};
// Does nothing unspecialized
template<class T, T P>
class PowersGenerator: Generator<T> {};
// Specialize with other types, or provide a generic version of pow
template<int P>
class PowersGenerator<int, P>: Generator<int>
{
public:
int i;
PowersGenerator() { i = 1; }
virtual int operator()()
{
int o = 1;
for(int j = 0; j < P; ++j) o *= i;
++i;
return o;
}
};
// Only works with non-decreasing generators
template<class T, class G, class F>
class Filter: Generator<T>
{
public:
G gen;
F filter;
T lastG, lastF;
Filter() { lastG = gen(); lastF = filter(); }
virtual T operator()()
{
while(lastG >= lastF)
{
if(lastG == lastF)
lastG = gen();
lastF = filter();
}
T out = lastG;
lastG = gen();
return out;
}
};
int main()
{
Filter<int, PowersGenerator<int, 2>, PowersGenerator<int, 3>> gen;
for(int i = 0; i < 20; ++i)
gen();
for(int i = 20; i < 30; ++i)
cout << i << ": " << gen() << endl;
}
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#Ring
|
Ring
|
see gcd (24, 32)
func gcd gcd, b
while b
c = gcd
gcd = b
b = c % b
end
return gcd
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#Ruby
|
Ruby
|
40902.gcd(24140) # => 34
|
http://rosettacode.org/wiki/Generate_random_chess_position
|
Generate random chess position
|
Task
Generate a random chess position in FEN format.
The position does not have to be realistic or even balanced, but it must comply to the following rules:
there is one and only one king of each color (one black king and one white king);
the kings must not be placed on adjacent squares;
there can not be any pawn in the promotion square (no white pawn in the eighth rank, and no black pawn in the first rank);
including the kings, up to 32 pieces of either color can be placed.
There is no requirement for material balance between sides.
The picking of pieces does not have to comply to a regular chess set --- there can be five knights, twenty rooks, whatever ... as long as the total number of pieces do not exceed thirty-two.
it is white's turn.
It's assumed that both sides have lost castling rights and that there is no possibility for en passant (the FEN should thus end in w - - 0 1).
No requirement is made regarding the probability distribution of your method, but your program should be able to span a reasonably representative sample of all possible positions. For instance, programs that would always generate positions with say five pieces on the board, or with kings on a corner, would not be considered truly random.
|
#Action.21
|
Action!
|
DEFINE BOARDSIZE="64"
DEFINE EMPTY="'."
BYTE FUNC AbsDist(BYTE a,b)
IF a>b THEN RETURN (a-b) FI
RETURN (b-a)
BYTE FUNC GetPiece(BYTE ARRAY board BYTE x,y)
RETURN (board(x+y*8))
PROC PutPiece(BYTE ARRAY board BYTE x,y,piece)
board(x+y*8)=piece
RETURN
PROC PrintBoard(BYTE ARRAY board)
BYTE i,j,c
FOR j=0 TO 7
DO
FOR i=0 TO 7
DO
c=GetPiece(board,i,j)
Put(c)
OD
PutE()
OD
RETURN
PROC Append(CHAR ARRAY s CHAR c)
s(0)==+1
s(s(0))=c
RETURN
PROC ExportToFen(BYTE ARRAY board CHAR ARRAY fen)
CHAR ARRAY s=" w - - 0 1"
INT x,y
BYTE count,p
fen(0)=0
FOR y=0 TO 7
DO
x=0
WHILE x<8
DO
count=0
WHILE x<8 AND GetPiece(board,x,y)=EMPTY
DO
x==+1 count==+1
OD
IF count>0 THEN
Append(fen,'0+count)
ELSE
p=GetPiece(board,x,y)
Append(fen,p)
x==+1
FI
OD
IF y<7 THEN
Append(fen,'/)
FI
OD
FOR x=1 TO s(0)
DO
Append(fen,s(x))
OD
RETURN
PROC PutKings(BYTE ARRAY board)
BYTE x1,y1,x2,y2
DO
x1=Rand(8) y1=Rand(8)
x2=Rand(8) y2=Rand(8)
IF AbsDist(x1,x2)>1 AND AbsDist(y1,y2)>1 THEN
PutPiece(board,x1,y1,'K)
PutPiece(board,x2,y2,'k)
RETURN
FI
OD
RETURN
PROC PutPieces(BYTE ARRAY board CHAR ARRAY pieces)
BYTE i,x,y,p
FOR i=1 TO pieces(0)
DO
p=pieces(i)
DO
x=Rand(8)
IF p='P OR p='p THEN
y=Rand(6)+1
ELSE
y=Rand(8)
FI
UNTIL GetPiece(board,x,y)=EMPTY
OD
PutPiece(board,x,y,p)
OD
RETURN
PROC Generate(BYTE ARRAY board CHAR ARRAY pieces)
SetBlock(board,BOARDSIZE,EMPTY)
PutKings(board)
PutPieces(board,pieces)
RETURN
PROC Test(CHAR ARRAY pieces)
BYTE ARRAY board(BOARDSIZE)
CHAR ARRAY fen(256)
Generate(board,pieces)
PrintBoard(board)
ExportToFen(board,fen)
PrintE(fen) PutE()
RETURN
PROC Main()
Test("PPPPPPPPBBNNQRRppppppppbbnnqrr")
Test("PPBNQRppbnqr")
RETURN
|
http://rosettacode.org/wiki/Generate_random_chess_position
|
Generate random chess position
|
Task
Generate a random chess position in FEN format.
The position does not have to be realistic or even balanced, but it must comply to the following rules:
there is one and only one king of each color (one black king and one white king);
the kings must not be placed on adjacent squares;
there can not be any pawn in the promotion square (no white pawn in the eighth rank, and no black pawn in the first rank);
including the kings, up to 32 pieces of either color can be placed.
There is no requirement for material balance between sides.
The picking of pieces does not have to comply to a regular chess set --- there can be five knights, twenty rooks, whatever ... as long as the total number of pieces do not exceed thirty-two.
it is white's turn.
It's assumed that both sides have lost castling rights and that there is no possibility for en passant (the FEN should thus end in w - - 0 1).
No requirement is made regarding the probability distribution of your method, but your program should be able to span a reasonably representative sample of all possible positions. For instance, programs that would always generate positions with say five pieces on the board, or with kings on a corner, would not be considered truly random.
|
#C
|
C
|
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#define TRUE 1
#define FALSE 0
typedef int bool;
char grid[8][8];
void placeKings() {
int r1, r2, c1, c2;
for (;;) {
r1 = rand() % 8;
c1 = rand() % 8;
r2 = rand() % 8;
c2 = rand() % 8;
if (r1 != r2 && abs(r1 - r2) > 1 && abs(c1 - c2) > 1) {
grid[r1][c1] = 'K';
grid[r2][c2] = 'k';
return;
}
}
}
void placePieces(const char *pieces, bool isPawn) {
int n, r, c;
int numToPlace = rand() % strlen(pieces);
for (n = 0; n < numToPlace; ++n) {
do {
r = rand() % 8;
c = rand() % 8;
}
while (grid[r][c] != 0 || (isPawn && (r == 7 || r == 0)));
grid[r][c] = pieces[n];
}
}
void toFen() {
char fen[80], ch;
int r, c, countEmpty = 0, index = 0;
for (r = 0; r < 8; ++r) {
for (c = 0; c < 8; ++c) {
ch = grid[r][c];
printf("%2c ", ch == 0 ? '.' : ch);
if (ch == 0) {
countEmpty++;
}
else {
if (countEmpty > 0) {
fen[index++] = countEmpty + 48;
countEmpty = 0;
}
fen[index++] = ch;
}
}
if (countEmpty > 0) {
fen[index++] = countEmpty + 48;
countEmpty = 0;
}
fen[index++]= '/';
printf("\n");
}
strcpy(fen + index, " w - - 0 1");
printf("%s\n", fen);
}
char *createFen() {
placeKings();
placePieces("PPPPPPPP", TRUE);
placePieces("pppppppp", TRUE);
placePieces("RNBQBNR", FALSE);
placePieces("rnbqbnr", FALSE);
toFen();
}
int main() {
srand(time(NULL));
createFen();
return 0;
}
|
http://rosettacode.org/wiki/General_FizzBuzz
|
General FizzBuzz
|
Task
Write a generalized version of FizzBuzz that works for any list of factors, along with their words.
This is basically a "fizzbuzz" implementation where the user supplies the parameters.
The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be printed.
For simplicity's sake, assume the user will input an integer as the max number and 3 factors, each with a word associated with them.
For example, given:
>20 #This is the maximum number, supplied by the user
>3 Fizz #The user now enters the starting factor (3) and the word they want associated with it (Fizz)
>5 Buzz #The user now enters the next factor (5) and the word they want associated with it (Buzz)
>7 Baxx #The user now enters the next factor (7) and the word they want associated with it (Baxx)
In other words: For this example, print the numbers 1 through 20, replacing every multiple of 3 with "Fizz", every multiple of 5 with "Buzz", and every multiple of 7 with "Baxx".
In the case where a number is a multiple of at least two factors, print each of the words associated with those factors in the order of least to greatest factor.
For instance, the number 15 is a multiple of both 3 and 5; print "FizzBuzz".
If the max number was 105 instead of 20, you would print "FizzBuzzBaxx" because it's a multiple of 3, 5, and 7.
Output:
1
2
Fizz
4
Buzz
Fizz
Baxx
8
Fizz
Buzz
11
Fizz
13
Baxx
FizzBuzz
16
17
Fizz
19
Buzz
|
#11l
|
11l
|
F genfizzbuzz(factorwords, numbers)
V sfactorwords = sorted(factorwords, key' p -> p[0])
[String] lines
L(num) numbers
V words = sfactorwords.filter2((fact, wrd) -> (@num % fact) == 0).map2((fact, wrd) -> wrd).join(‘’)
lines.append(I words != ‘’ {words} E String(num))
R lines.join("\n")
print(genfizzbuzz([(5, ‘Buzz’), (3, ‘Fizz’), (7, ‘Baxx’)], 1..20))
|
http://rosettacode.org/wiki/Hailstone_sequence
|
Hailstone sequence
|
The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.
This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):
hailstone sequence, hailstone numbers
3x + 2 mapping, 3n + 1 problem
Collatz sequence
Hasse's algorithm
Kakutani's problem
Syracuse algorithm, Syracuse problem
Thwaites conjecture
Ulam's problem
The hailstone sequence is also known as hailstone numbers (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).
Task
Create a routine to generate the hailstone sequence for a number.
Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
(But don't show the actual sequence!)
See also
xkcd (humourous).
The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).
The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
|
#Scheme
|
Scheme
|
(define (collatz n)
(if (= n 1) '(1)
(cons n (collatz (if (even? n) (/ n 2) (+ 1 (* 3 n)))))))
(define (collatz-length n)
(let aux ((n n) (r 1)) (if (= n 1) r
(aux (if (even? n) (/ n 2) (+ 1 (* 3 n))) (+ r 1)))))
(define (collatz-max a b)
(let aux ((i a) (j 0) (k 0))
(if (> i b) (list j k)
(let ((h (collatz-length i)))
(if (> h k) (aux (+ i 1) i h) (aux (+ i 1) j k))))))
(collatz 27)
; (27 82 41 124 62 31 94 47 142 71 214 107 322 161 484 242 121 364 182
; 91 274 137 412 206 103 310 155 466 233 700 350 175 526 263 790 395
; 1186 593 1780 890 445 1336 668 334 167 502 251 754 377 1132 566 283
; 850 425 1276 638 319 958 479 1438 719 2158 1079 3238 1619 4858 2429
; 7288 3644 1822 911 2734 1367 4102 2051 6154 3077 9232 4616 2308 1154
; 577 1732 866 433 1300 650 325 976 488 244 122 61 184 92 46 23 70 35
; 106 53 160 80 40 20 10 5 16 8 4 2 1)
(collatz-length 27)
; 112
(collatz-max 1 100000)
; (77031 351)
|
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
|
Generate lower case ASCII alphabet
|
Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code.
During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code:
set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z}
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
|
#6502_Assembly
|
6502 Assembly
|
ASCLOW: PHA ; push contents of registers that we
TXA ; shall be using onto the stack
PHA
LDA #$61 ; ASCII "a"
LDX #$00
ALLOOP: STA $2000,X
INX
CLC
ADC #$01
CMP #$7B ; have we got beyond ASCII "z"?
BNE ALLOOP
LDA #$00 ; terminate the string with ASCII NUL
STA $2000,X
PLA ; retrieve register contents from
TAX ; the stack
PLA
RTS ; return
|
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
|
Generate lower case ASCII alphabet
|
Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code.
During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code:
set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z}
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
|
#68000_Assembly
|
68000 Assembly
|
Ascii_Low:
MOVEM.L D0/A0,-(SP) ;store D0 and A0 on stack
LEA $00100000,A0 ;could also have used MOVE.L since the address is static
MOVE.B #$61,D0 ;ascii "a"
loop_AsciiLow:
MOVE.B D0,(A0)+ ;store letter in address and increment pointer by 1
ADDQ.B #1,D0 ;add 1 to D0 to get the next letter
CMP.B #$7B,D0 ;Are we done yet? (7B is the first character after lowercase "z")
BNE loop_AsciiLow ;if not, loop again
MOVE.B #0,(A0) ;store the null terminator
MOVEM.L (SP)+,D0/A0 ;pop D0 and A0
rts
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#Nanoquery
|
Nanoquery
|
println "Hello world!"
|
http://rosettacode.org/wiki/Generic_swap
|
Generic swap
|
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation.
That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.
Generic swap is a task which brings together a few separate issues in programming language semantics.
Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.
Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.
Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).
Do your best!
|
#Scala
|
Scala
|
def swap[A,B](a: A, b: B): (B, A) = (b, a)
|
http://rosettacode.org/wiki/Greatest_element_of_a_list
|
Greatest element of a list
|
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
|
#Wren
|
Wren
|
var max = Fn.new { |a| a.reduce { |m, x| (x > m) ? x : m } }
var a = [42, 7, -5, 11.7, 58, 22.31, 59, -18]
System.print(max.call(a))
|
http://rosettacode.org/wiki/Greatest_element_of_a_list
|
Greatest element of a list
|
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
|
#XPL0
|
XPL0
|
include c:\cxpl\codes; \include 'code' declarations
def Tab=$09, LF=$0A, CR=$0D, EOF=$1A;
int CpuReg, Hand;
char CmdTail($80);
int I, Max, C;
[\Copy file name on command line, which is in the Program Segment Prefix (PSP)
\ ES=CpuReg(11), to the CmdTail array, which is in our Data Segment = CpuReg(12)
CpuReg:= GetReg; \point to copy of CPU registers
Blit(CpuReg(11), $81, CpuReg(12), CmdTail, $7F);
Hand:= FOpen(CmdTail, 0); \open file for input and get its handle
FSet(Hand, ^I); \assign handle to device 3
OpenI(3); \initialize file for input
Max:= 0; \scan file for longest line
repeat I:= 0;
repeat C:= ChIn(3);
case C of
CR, LF, EOF: []; \don't count these characters
Tab: [I:= I+8 & ~7] \(every 8th column)
other I:= I+1; \count all other characters
until C=LF or C=EOF;
if I > Max then Max:= I;
until C = EOF;
Text(0, "Longest line = "); IntOut(0, Max); CrLf(0);
]
|
http://rosettacode.org/wiki/Generator/Exponential
|
Generator/Exponential
|
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided.
Generators are often built on top of coroutines or objects so that the internal state of the object is handled “naturally”.
Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state.
Task
Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size).
Use it to create a generator of:
Squares.
Cubes.
Create a new generator that filters all cubes from the generator of squares.
Drop the first 20 values from this last generator of filtered results, and then show the next 10 values.
Note that this task requires the use of generators in the calculation of the result.
Also see
Generator
|
#Clojure
|
Clojure
|
(defn powers [m] (for [n (iterate inc 1)] (reduce * (repeat m n)))))
(def squares (powers 2))
(take 5 squares) ; => (1 4 9 16 25)
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#Run_BASIC
|
Run BASIC
|
print abs(gcd(-220,160))
function gcd(gcd,b)
while b
c = gcd
gcd = b
b = c mod b
wend
end function
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#Rust
|
Rust
|
extern crate num;
use num::integer::gcd;
|
http://rosettacode.org/wiki/Generate_Chess960_starting_position
|
Generate Chess960 starting position
|
Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints:
as in the standard chess game, all eight white pawns must be placed on the second rank.
White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints:
the bishops must be placed on opposite color squares (i.e. they must be an odd number of spaces apart or there must be an even number of spaces between them)
the King must be between two rooks (with any number of other pieces between them all)
Black pawns and pieces must be placed respectively on the seventh and eighth ranks, mirroring the white pawns and pieces, just as in the standard game. (That is, their positions are not independently randomized.)
With those constraints there are 960 possible starting positions, thus the name of the variant.
Task
The purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed with Chess symbols in Unicode: ♔♕♖♗♘ or with the letters King Queen Rook Bishop kNight.
|
#11l
|
11l
|
F random960()
V start = [‘R’, ‘K’, ‘R’]
L(piece) [‘Q’, ‘N’, ‘N’]
start.insert(random:(start.len + 1), piece)
V bishpos = random:(start.len + 1)
start.insert(bishpos, Char(‘B’))
start.insert(random:(bishpos + 1), Char(‘B’))
R start
print(random960())
|
http://rosettacode.org/wiki/Generate_random_chess_position
|
Generate random chess position
|
Task
Generate a random chess position in FEN format.
The position does not have to be realistic or even balanced, but it must comply to the following rules:
there is one and only one king of each color (one black king and one white king);
the kings must not be placed on adjacent squares;
there can not be any pawn in the promotion square (no white pawn in the eighth rank, and no black pawn in the first rank);
including the kings, up to 32 pieces of either color can be placed.
There is no requirement for material balance between sides.
The picking of pieces does not have to comply to a regular chess set --- there can be five knights, twenty rooks, whatever ... as long as the total number of pieces do not exceed thirty-two.
it is white's turn.
It's assumed that both sides have lost castling rights and that there is no possibility for en passant (the FEN should thus end in w - - 0 1).
No requirement is made regarding the probability distribution of your method, but your program should be able to span a reasonably representative sample of all possible positions. For instance, programs that would always generate positions with say five pieces on the board, or with kings on a corner, would not be considered truly random.
|
#C.2B.2B
|
C++
|
#include <ctime>
#include <iostream>
#include <string>
#include <algorithm>
class chessBoard {
public:
void generateRNDBoard( int brds ) {
int a, b, i; char c;
for( int cc = 0; cc < brds; cc++ ) {
memset( brd, 0, 64 );
std::string pieces = "PPPPPPPPNNBBRRQKppppppppnnbbrrqk";
random_shuffle( pieces.begin(), pieces.end() );
while( pieces.length() ) {
i = rand() % pieces.length(); c = pieces.at( i );
while( true ) {
a = rand() % 8; b = rand() % 8;
if( brd[a][b] == 0 ) {
if( c == 'P' && !b || c == 'p' && b == 7 ||
( ( c == 'K' || c == 'k' ) && search( c == 'k' ? 'K' : 'k', a, b ) ) ) continue;
break;
}
}
brd[a][b] = c;
pieces = pieces.substr( 0, i ) + pieces.substr( i + 1 );
}
print();
}
}
private:
bool search( char c, int a, int b ) {
for( int y = -1; y < 2; y++ ) {
for( int x = -1; x < 2; x++ ) {
if( !x && !y ) continue;
if( a + x > -1 && a + x < 8 && b + y >-1 && b + y < 8 ) {
if( brd[a + x][b + y] == c ) return true;
}
}
}
return false;
}
void print() {
int e = 0;
for( int y = 0; y < 8; y++ ) {
for( int x = 0; x < 8; x++ ) {
if( brd[x][y] == 0 ) e++;
else {
if( e > 0 ) { std::cout << e; e = 0; }
std::cout << brd[x][y];
}
}
if( e > 0 ) { std::cout << e; e = 0; }
if( y < 7 ) std::cout << "/";
}
std::cout << " w - - 0 1\n\n";
for( int y = 0; y < 8; y++ ) {
for( int x = 0; x < 8; x++ ) {
if( brd[x][y] == 0 ) std::cout << ".";
else std::cout << brd[x][y];
}
std::cout << "\n";
}
std::cout << "\n\n";
}
char brd[8][8];
};
int main( int argc, char* argv[] ) {
srand( ( unsigned )time( 0 ) );
chessBoard c;
c.generateRNDBoard( 2 );
return 0;
}
|
http://rosettacode.org/wiki/General_FizzBuzz
|
General FizzBuzz
|
Task
Write a generalized version of FizzBuzz that works for any list of factors, along with their words.
This is basically a "fizzbuzz" implementation where the user supplies the parameters.
The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be printed.
For simplicity's sake, assume the user will input an integer as the max number and 3 factors, each with a word associated with them.
For example, given:
>20 #This is the maximum number, supplied by the user
>3 Fizz #The user now enters the starting factor (3) and the word they want associated with it (Fizz)
>5 Buzz #The user now enters the next factor (5) and the word they want associated with it (Buzz)
>7 Baxx #The user now enters the next factor (7) and the word they want associated with it (Baxx)
In other words: For this example, print the numbers 1 through 20, replacing every multiple of 3 with "Fizz", every multiple of 5 with "Buzz", and every multiple of 7 with "Baxx".
In the case where a number is a multiple of at least two factors, print each of the words associated with those factors in the order of least to greatest factor.
For instance, the number 15 is a multiple of both 3 and 5; print "FizzBuzz".
If the max number was 105 instead of 20, you would print "FizzBuzzBaxx" because it's a multiple of 3, 5, and 7.
Output:
1
2
Fizz
4
Buzz
Fizz
Baxx
8
Fizz
Buzz
11
Fizz
13
Baxx
FizzBuzz
16
17
Fizz
19
Buzz
|
#Action.21
|
Action!
|
DEFINE MAX_NUMBERS="200"
DEFINE MAX_LEN="20"
DEFINE MAX_FACTORS="5"
DEFINE PTR="CARD"
PROC PrintResult(BYTE max,n BYTE ARRAY factors PTR ARRAY texts)
BYTE i,j,t
BYTE ARRAY values(MAX_FACTORS)
FOR j=0 TO n-1
DO
values(j)=1
OD
FOR i=1 TO max
DO
t=0
FOR j=0 TO n-1
DO
IF values(j)=0 THEN
t=1 Print(texts(j))
FI
values(j)==+1
IF values(j)=factors(j) THEN
values(j)=0
FI
OD
IF t=0 THEN PrintB(i) FI
Put(32)
OD
RETURN
BYTE FUNC Find(CHAR ARRAY s CHAR c BYTE POINTER err)
BYTE i
FOR i=1 TO s(0)
DO
IF s(i)=c THEN
err^=0 RETURN (i)
FI
OD
err^=1
RETURN (0)
PROC Main()
BYTE max,i,n,pos,err
BYTE ARRAY factors(MAX_FACTORS)
PTR ARRAY texts(MAX_FACTORS)
CHAR ARRAY
s(100),tmp(100),
t0(MAX_LEN),t1(MAX_LEN),t2(MAX_LEN),
t3(MAX_LEN),t4(MAX_LEN)
texts(0)=t0 texts(1)=t1 texts(2)=t2
texts(3)=t3 texts(4)=t4
DO
PrintF("Max number (1-%B): ",MAX_NUMBERS)
max=InputB()
UNTIL max>=1 AND max<=MAX_NUMBERS
OD
n=0
DO
PrintF("Number of rules (1-%B): ",MAX_FACTORS)
n=InputB()
UNTIL n>=1 AND n<=MAX_FACTORS
OD
FOR i=0 TO n-1
DO
DO
PrintF("Rule #%B (number space text):",i+1)
InputS(s)
pos=Find(s,' ,@err)
IF pos=1 OR pos=s(0) THEN
err=1
FI
IF err=0 THEN
SCopyS(tmp,s,1,pos-1)
factors(i)=ValB(tmp)
IF factors(i)<2 THEN
err=1
FI
SCopyS(texts(i),s,pos+1,s(0))
FI
UNTIL err=0
OD
OD
PutE()
PrintResult(max,n,factors,texts)
RETURN
|
http://rosettacode.org/wiki/General_FizzBuzz
|
General FizzBuzz
|
Task
Write a generalized version of FizzBuzz that works for any list of factors, along with their words.
This is basically a "fizzbuzz" implementation where the user supplies the parameters.
The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be printed.
For simplicity's sake, assume the user will input an integer as the max number and 3 factors, each with a word associated with them.
For example, given:
>20 #This is the maximum number, supplied by the user
>3 Fizz #The user now enters the starting factor (3) and the word they want associated with it (Fizz)
>5 Buzz #The user now enters the next factor (5) and the word they want associated with it (Buzz)
>7 Baxx #The user now enters the next factor (7) and the word they want associated with it (Baxx)
In other words: For this example, print the numbers 1 through 20, replacing every multiple of 3 with "Fizz", every multiple of 5 with "Buzz", and every multiple of 7 with "Baxx".
In the case where a number is a multiple of at least two factors, print each of the words associated with those factors in the order of least to greatest factor.
For instance, the number 15 is a multiple of both 3 and 5; print "FizzBuzz".
If the max number was 105 instead of 20, you would print "FizzBuzzBaxx" because it's a multiple of 3, 5, and 7.
Output:
1
2
Fizz
4
Buzz
Fizz
Baxx
8
Fizz
Buzz
11
Fizz
13
Baxx
FizzBuzz
16
17
Fizz
19
Buzz
|
#Ada
|
Ada
|
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Containers.Generic_Array_Sort;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Text_IO.Unbounded_IO; use Ada.Text_IO.Unbounded_IO;
procedure Main is
type map_element is record
Num : Positive;
Word : Unbounded_String;
end record;
type map_list is array (Positive range <>) of map_element;
function "<" (Left, Right : map_element) return Boolean is
begin
return Left.Num < Right.Num;
end "<";
procedure list_sort is new Ada.Containers.Generic_Array_Sort
(Index_Type => Positive, Element_Type => map_element,
Array_Type => map_list);
procedure general_fizz_buzz (max : Positive; words : in out map_list) is
found : Boolean;
begin
list_sort (words);
for i in 1 .. max loop
found := False;
for element of words loop
if i mod element.Num = 0 then
found := True;
Put (element.Word);
end if;
end loop;
if not found then
Put (Item => i, Width => 1);
end if;
New_Line;
end loop;
end general_fizz_buzz;
fizzy : map_list :=
((3, To_Unbounded_String ("FIZZ")), (7, To_Unbounded_String ("BAXX")),
(5, To_Unbounded_String ("BUZZ")));
begin
general_fizz_buzz (20, fizzy);
end Main;
|
http://rosettacode.org/wiki/Hailstone_sequence
|
Hailstone sequence
|
The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.
This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):
hailstone sequence, hailstone numbers
3x + 2 mapping, 3n + 1 problem
Collatz sequence
Hasse's algorithm
Kakutani's problem
Syracuse algorithm, Syracuse problem
Thwaites conjecture
Ulam's problem
The hailstone sequence is also known as hailstone numbers (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).
Task
Create a routine to generate the hailstone sequence for a number.
Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
(But don't show the actual sequence!)
See also
xkcd (humourous).
The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).
The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
|
#Scilab
|
Scilab
|
function x=hailstone(n)
// iterative definition
// usage: global verbose; verbose=%T; hailstone(27)
global verbose
x=0; loop=%T
while(loop)
x=x+1
if verbose then
printf('%i ',n)
end
if n==1 then
loop=%F
elseif modulo(n,2)==1 then
n=3*n+1
else
n=n/2
end
end
endfunction
global verbose;
verbose=1;
N=hailstone(27);
printf('\n\n%i\n',N);
global verbose;
verbose=0;
N=100000;
M=zeros(N,1);
for k=1:N
M(k)=hailstone(k);
end;
[maxLength,n]=max(M)
|
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
|
Generate lower case ASCII alphabet
|
Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code.
During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code:
set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z}
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
|
#8080_Assembly
|
8080 Assembly
|
org 100h
jmp test
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Store the lowercase alphabet as a CP/M string
;; ($-terminated), starting at HL.
;; Destroys: b, c
alph: lxi b,611ah ; set B='a' and C=26 (counter)
aloop: mov m,b ; store letter in memory
inr b ; next letter
inx h ; next memory position
dcr c ; one fewer letter left
jnz aloop ; go do the next letter if there is one
mvi m,'$' ; terminate the string
ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Test code
test: lxi h,buf ; select buffer
call alph ; generate alphabet
lxi d,buf ; print string in buffer
mvi c,9
call 5
rst 0
buf: ds 27 ; buffer to keep the alphabet in
|
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
|
Generate lower case ASCII alphabet
|
Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code.
During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code:
set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z}
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
|
#8086_Assembly
|
8086 Assembly
|
bits 16
cpu 8086
org 100h
section .text
jmp demo
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Store the lowercase alphabet starting at [ES:DI]
;;; Destroys AX, CX, DI
alph: mov cx,13 ; 2*13 words = 26 bytes
mov ax,'ab' ; Do two bytes at once
.loop: stosw ; Store AX at ES:DI and add 2 to DI
add ax,202h ; Add 2 to both bytes (CD, EF, ...)
loop .loop
mov al,'$' ; MS-DOS string terminator
stosb
ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
demo: mov di,buf ; Pointer to buffer
call alph ; Generate the alphabet
mov dx,buf ; Print the contents of the buffer
mov ah,9
int 21h
ret
section .bss
buf: resb 27 ; Buffer to store the alphabet in
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#Neat
|
Neat
|
void main() writeln "Hello world!";
|
http://rosettacode.org/wiki/Generic_swap
|
Generic swap
|
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation.
That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.
Generic swap is a task which brings together a few separate issues in programming language semantics.
Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.
Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.
Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).
Do your best!
|
#Scheme
|
Scheme
|
; swap elements of a vector
; vector-swap! is not part of r5rs, so we define it
(define (vector-swap! v i j)
(let ((a (vector-ref v i)) (b (vector-ref v j)))
(vector-set! v i b)
(vector-set! v j a)))
(let ((vec (vector 1 2 3 4 5)))
(vector-swap! vec 0 4)
vec)
; #(5 2 3 4 1)
; we can swap also in lists
(define (list-swap! v i j)
(let* ((x (list-tail v i))
(y (list-tail v j))
(a (car x))
(b (car y)))
(set-car! x b)
(set-car! y a)))
(let ((lis (list 1 2 3 4 5)))
(list-swap! lis 0 4)
lis)
; (5 2 3 4 1)
; using macros (will work on variables, not on vectors or lists)
(define-syntax swap!
(syntax-rules ()
((_ a b)
(let ((tmp a))
(set! a b)
(set! b tmp)))))
; try it
(let ((a 1) (b 2)) (swap! a b) (list a b))
; (2 1)
|
http://rosettacode.org/wiki/Greatest_element_of_a_list
|
Greatest element of a list
|
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
|
#XSLT
|
XSLT
|
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="text"/>
<xsl:template match="/">
<xsl:for-each select="/*/*">
<!-- without data-type="number", items are sorted alphabetically -->
<xsl:sort data-type="number" order="descending"/>
<xsl:if test="position() = 1">
<xsl:value-of select="."/>
</xsl:if>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
|
http://rosettacode.org/wiki/Generator/Exponential
|
Generator/Exponential
|
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided.
Generators are often built on top of coroutines or objects so that the internal state of the object is handled “naturally”.
Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state.
Task
Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size).
Use it to create a generator of:
Squares.
Cubes.
Create a new generator that filters all cubes from the generator of squares.
Drop the first 20 values from this last generator of filtered results, and then show the next 10 values.
Note that this task requires the use of generators in the calculation of the result.
Also see
Generator
|
#Common_Lisp
|
Common Lisp
|
(defun take (seq &optional (n 1))
(values-list (loop repeat n collect (funcall seq))))
(defun power-seq (n)
(let ((x 0))
(lambda () (expt (incf x) n))))
(defun filter-seq (s1 s2) ;; remove s2 from s1
(let ((x1 (take s1)) (x2 (take s2)))
(lambda ()
(tagbody g
(if (= x1 x2)
(progn (setf x1 (take s1) x2 (take s2)) (go g)))
(if (> x1 x2)
(progn (setf x2 (take s2)) (go g))))
(prog1 x1 (setf x1 (take s1))))))
(let ((2not3 (filter-seq (power-seq 2) (power-seq 3))))
(take 2not3 20) ;; drop 20
(princ (multiple-value-list (take 2not3 10))))
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#Sass.2FSCSS
|
Sass/SCSS
|
@function gcd($a,$b) {
@while $b > 0 {
$c: $a % $b;
$a: $b;
$b: $c;
}
@return $a;
}
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#Sather
|
Sather
|
class MATH is
gcd_iter(u, v:INT):INT is
loop while!( v.bool );
t ::= u; u := v; v := t % v;
end;
return u.abs;
end;
gcd(u, v:INT):INT is
if v.bool then return gcd(v, u%v); end;
return u.abs;
end;
private swap(inout a, inout b:INT) is
t ::= a;
a := b;
b := t;
end;
gcd_bin(u, v:INT):INT is
t:INT;
u := u.abs; v := v.abs;
if u < v then swap(inout u, inout v); end;
if v = 0 then return u; end;
k ::= 1;
loop while!( u.is_even and v.is_even );
u := u / 2; v := v / 2;
k := k * 2;
end;
if u.is_even then
t := -v;
else
t := u;
end;
loop while!( t.bool );
loop while!( t.is_even );
t := t / 2;
end;
if t > 0 then
u := t;
else
v := -t;
end;
t := u - v;
end;
return u * k;
end;
end;
|
http://rosettacode.org/wiki/Generate_Chess960_starting_position
|
Generate Chess960 starting position
|
Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints:
as in the standard chess game, all eight white pawns must be placed on the second rank.
White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints:
the bishops must be placed on opposite color squares (i.e. they must be an odd number of spaces apart or there must be an even number of spaces between them)
the King must be between two rooks (with any number of other pieces between them all)
Black pawns and pieces must be placed respectively on the seventh and eighth ranks, mirroring the white pawns and pieces, just as in the standard game. (That is, their positions are not independently randomized.)
With those constraints there are 960 possible starting positions, thus the name of the variant.
Task
The purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed with Chess symbols in Unicode: ♔♕♖♗♘ or with the letters King Queen Rook Bishop kNight.
|
#Action.21
|
Action!
|
DEFINE MAX_NUMBERS="200"
DEFINE MAX_LEN="20"
DEFINE MAX_FACTORS="5"
DEFINE PTR="CARD"
PROC PrintResult(BYTE max,n BYTE ARRAY factors PTR ARRAY texts)
BYTE i,j,t
BYTE ARRAY values(MAX_FACTORS)
FOR j=0 TO n-1
DO
values(j)=1
OD
FOR i=1 TO max
DO
t=0
FOR j=0 TO n-1
DO
IF values(j)=0 THEN
t=1 Print(texts(j))
FI
values(j)==+1
IF values(j)=factors(j) THEN
values(j)=0
FI
OD
IF t=0 THEN PrintB(i) FI
Put(32)
OD
RETURN
BYTE FUNC Find(CHAR ARRAY s CHAR c BYTE POINTER err)
BYTE i
FOR i=1 TO s(0)
DO
IF s(i)=c THEN
err^=0 RETURN (i)
FI
OD
err^=1
RETURN (0)
PROC Main()
BYTE max,i,n,pos,err
BYTE ARRAY factors(MAX_FACTORS)
PTR ARRAY texts(MAX_FACTORS)
CHAR ARRAY
s(100),tmp(100),
t0(MAX_LEN),t1(MAX_LEN),t2(MAX_LEN),
t3(MAX_LEN),t4(MAX_LEN)
texts(0)=t0 texts(1)=t1 texts(2)=t2
texts(3)=t3 texts(4)=t4
DO
PrintF("Max number (1-%B): ",MAX_NUMBERS)
max=InputB()
UNTIL max>=1 AND max<=MAX_NUMBERS
OD
n=0
DO
PrintF("Number of rules (1-%B): ",MAX_FACTORS)
n=InputB()
UNTIL n>=1 AND n<=MAX_FACTORS
OD
FOR i=0 TO n-1
DO
DO
PrintF("Rule #%B (number space text):",i+1)
InputS(s)
pos=Find(s,' ,@err)
IF pos=1 OR pos=s(0) THEN
err=1
FI
IF err=0 THEN
SCopyS(tmp,s,1,pos-1)
factors(i)=ValB(tmp)
IF factors(i)<2 THEN
err=1
FI
SCopyS(texts(i),s,pos+1,s(0))
FI
UNTIL err=0
OD
OD
PutE()
PrintResult(max,n,factors,texts)
RETURN
|
http://rosettacode.org/wiki/Generate_Chess960_starting_position
|
Generate Chess960 starting position
|
Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints:
as in the standard chess game, all eight white pawns must be placed on the second rank.
White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints:
the bishops must be placed on opposite color squares (i.e. they must be an odd number of spaces apart or there must be an even number of spaces between them)
the King must be between two rooks (with any number of other pieces between them all)
Black pawns and pieces must be placed respectively on the seventh and eighth ranks, mirroring the white pawns and pieces, just as in the standard game. (That is, their positions are not independently randomized.)
With those constraints there are 960 possible starting positions, thus the name of the variant.
Task
The purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed with Chess symbols in Unicode: ♔♕♖♗♘ or with the letters King Queen Rook Bishop kNight.
|
#AutoHotkey
|
AutoHotkey
|
Loop, 5
Out .= Chess960() "`n"
MsgBox, % RTrim(Out, "`n")
Chess960() {
P := {}
P[K := Rand(2, 7)] := Chr(0x2654) ; King
P[Rand(1, K - 1)] := Chr(0x2656) ; Rook 1
P[Rand(K + 1, 8)] := Chr(0x2656) ; Rook 2
Loop, 8
Remaining .= P[A_Index] ? "" : A_Index "`n"
Sort, Remaining, Random N
P[Bishop1 := SubStr(Remaining, 1, 1)] := Chr(0x2657) ; Bishop 1
Remaining := SubStr(Remaining, 3)
Loop, Parse, Remaining, `n
if (Mod(Bishop1 - A_LoopField, 2))
Odd .= A_LoopField "`n"
else
Even .= A_LoopField "`n"
X := StrSplit(Odd Even, "`n")
P[X.1] := Chr(0x2657) ; Bishop 2
P[X.2] := Chr(0x2655) ; Queen
P[X.3] := Chr(0x2658) ; Knight 1
P[X.4] := Chr(0x2658) ; Knight 2
for Key, Val in P
Out .= Val
return Out
}
Rand(Min, Max) {
Random, n, Min, Max
return n
}
|
http://rosettacode.org/wiki/Generate_random_chess_position
|
Generate random chess position
|
Task
Generate a random chess position in FEN format.
The position does not have to be realistic or even balanced, but it must comply to the following rules:
there is one and only one king of each color (one black king and one white king);
the kings must not be placed on adjacent squares;
there can not be any pawn in the promotion square (no white pawn in the eighth rank, and no black pawn in the first rank);
including the kings, up to 32 pieces of either color can be placed.
There is no requirement for material balance between sides.
The picking of pieces does not have to comply to a regular chess set --- there can be five knights, twenty rooks, whatever ... as long as the total number of pieces do not exceed thirty-two.
it is white's turn.
It's assumed that both sides have lost castling rights and that there is no possibility for en passant (the FEN should thus end in w - - 0 1).
No requirement is made regarding the probability distribution of your method, but your program should be able to span a reasonably representative sample of all possible positions. For instance, programs that would always generate positions with say five pieces on the board, or with kings on a corner, would not be considered truly random.
|
#Crystal
|
Crystal
|
def hasNK(board, a, b)
(-1..1).each do |g|
(-1..1).each do |f|
aa = a + f; bb = b + g
if (0..7).includes?(aa) && (0..7).includes?(bb)
p = board[aa + 8 * bb]
return true if p == "K" || p == "k"
end
end
end
return false
end
def generateBoard(board, pieces)
pieces.each_char do |p|
while true
a = rand(8); b = rand(8)
next if ( (b == 0 || b == 7) && (p == "P" || p == "p") ) ||
( (p == "k" || p == "K") && hasNK(board, a, b) )
break if board[a + b * 8] == '.'
end
board[a + b * 8] = p
end
end
pieces = "ppppppppkqrrbbnnPPPPPPPPKQRRBBNN"
11.times do
e = pieces.size - 1
while e > 0
p = rand(e); t = pieces[e]
#pieces[e] = pieces[p]; pieces[p] = t; e -= 1 # in Ruby
pieces = pieces.sub(e, pieces[p]) # in Crystal because
pieces = pieces.sub(p, t); e -= 1 # strings immutable
end
end
# No 'nil' for Crystal arrays; use '.' for blank value
board = Array.new(64, '.'); generateBoard(board, pieces)
puts
e = 0
8.times do |j| row_j = j * 8
8.times do |i|
board[row_j + i ] == '.' ? (e += 1) :
( (print(e); e = 0) if e > 0
print board[row_j + i] )
end
(print(e); e = 0) if e > 0
print("/") if j < 7
end
print(" w - - 0 1\n")
8.times do |j| row_j = j * 8
8.times { |i| board[row_j + i] == '.' ? print(".") : print(board[row_j + i]) }
puts
end
# Simpler for same output
8.times{ |row| puts board[row*8..row*8 + 7].join("") }
|
http://rosettacode.org/wiki/General_FizzBuzz
|
General FizzBuzz
|
Task
Write a generalized version of FizzBuzz that works for any list of factors, along with their words.
This is basically a "fizzbuzz" implementation where the user supplies the parameters.
The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be printed.
For simplicity's sake, assume the user will input an integer as the max number and 3 factors, each with a word associated with them.
For example, given:
>20 #This is the maximum number, supplied by the user
>3 Fizz #The user now enters the starting factor (3) and the word they want associated with it (Fizz)
>5 Buzz #The user now enters the next factor (5) and the word they want associated with it (Buzz)
>7 Baxx #The user now enters the next factor (7) and the word they want associated with it (Baxx)
In other words: For this example, print the numbers 1 through 20, replacing every multiple of 3 with "Fizz", every multiple of 5 with "Buzz", and every multiple of 7 with "Baxx".
In the case where a number is a multiple of at least two factors, print each of the words associated with those factors in the order of least to greatest factor.
For instance, the number 15 is a multiple of both 3 and 5; print "FizzBuzz".
If the max number was 105 instead of 20, you would print "FizzBuzzBaxx" because it's a multiple of 3, 5, and 7.
Output:
1
2
Fizz
4
Buzz
Fizz
Baxx
8
Fizz
Buzz
11
Fizz
13
Baxx
FizzBuzz
16
17
Fizz
19
Buzz
|
#ALGOL_68
|
ALGOL 68
|
BEGIN # generalised FizzBuzz #
# prompts for an integer, reads it and returns it #
PROC read integer = ( STRING prompt )INT:
BEGIN
print( ( prompt ) );
INT result;
read( ( result, newline ) );
result
END; # read integer #
# prompts for a string, reads it and returns it #
PROC read string = ( STRING prompt )STRING:
BEGIN
print( ( prompt ) );
STRING result;
read( ( result, newline ) );
result
END; # read string #
# mode to hold a factor and associated text #
MODE FBFACTOR = STRUCT( INT factor, STRING text );
#===============================================================#
# quicksort routine for the factors, from the Algol 68 uicksort #
# task sample #
#---------------------------------------------------------------#
#--- Swap function ---#
PROC swap = (REF[]FBFACTOR array, INT first, INT second) VOID:
( FBFACTOR temp = array[first];
array[first] := array[second];
array[second] := temp
);
#--- Quick sort 3 arg function ---#
PROC quick = (REF[]FBFACTOR array, INT first, INT last) VOID:
( INT smaller := first + 1, larger := last;
FBFACTOR pivot := array[first];
WHILE smaller <= larger DO
WHILE array[smaller] < pivot AND smaller < last DO smaller +:= 1 OD;
WHILE array[larger] > pivot AND larger > first DO larger -:= 1 OD;
IF smaller < larger THEN
swap(array, smaller, larger);
smaller +:= 1;
larger -:= 1
ELSE
smaller +:= 1
FI
OD;
swap(array, first, larger);
IF first < larger -1 THEN quick(array, first, larger-1) FI;
IF last > larger +1 THEN quick(array, larger+1, last) FI
);
# comparison operators #
OP < = ( FBFACTOR a, b )BOOL: factor OF a < factor OF b;
OP > = ( FBFACTOR a, b )BOOL: factor OF a > factor OF b;
#===============================================================#
# get the maximum number to consider #
INT max number = read integer( "Numbers reuired: " );
# number of factors reuired #
INT max factor = 3;
# get the factors and associated words #
[ max factor ]FBFACTOR factors;
FOR i TO max factor DO
factor OF factors[ i ] := read integer( "Factor " + whole( i, 0 ) + ": " );
text OF factors [ i ] := read string( "Text for " + whole( factor OF factors[ i ], 0 ) + ": " )
OD;
# sort the factors into order #
quick( factors, 1, UPB factors );
# play the game #
FOR n TO max number DO
STRING text := "";
FOR factor TO max factor DO
IF n MOD factor OF factors[ factor ] = 0 THEN text +:= text OF factors[ factor ] FI
OD;
IF text = "" THEN
# no words applicable to n, just show the digits #
text := whole( n, 0 )
FI;
print( ( text, newline ) )
OD
END
|
http://rosettacode.org/wiki/Hailstone_sequence
|
Hailstone sequence
|
The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.
This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):
hailstone sequence, hailstone numbers
3x + 2 mapping, 3n + 1 problem
Collatz sequence
Hasse's algorithm
Kakutani's problem
Syracuse algorithm, Syracuse problem
Thwaites conjecture
Ulam's problem
The hailstone sequence is also known as hailstone numbers (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).
Task
Create a routine to generate the hailstone sequence for a number.
Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
(But don't show the actual sequence!)
See also
xkcd (humourous).
The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).
The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
|
#Seed7
|
Seed7
|
$ include "seed7_05.s7i";
const func array integer: hailstone (in var integer: n) is func
result
var array integer: hSequence is 0 times 0;
begin
while n <> 1 do
hSequence &:= n;
if odd(n) then
n := 3 * n + 1;
else
n := n div 2;
end if;
end while;
hSequence &:= n;
end func;
const func integer: hailstoneSequenceLength (in var integer: n) is func
result
var integer: sequenceLength is 1;
begin
while n <> 1 do
incr(sequenceLength);
if odd(n) then
n := 3 * n + 1;
else
n := n div 2;
end if;
end while;
end func;
const proc: main is func
local
var integer: number is 0;
var integer: length is 0;
var integer: maxLength is 0;
var integer: numberOfMaxLength is 0;
var array integer: h27 is 0 times 0;
begin
for number range 1 to 99999 do
length := hailstoneSequenceLength(number);
if length > maxLength then
maxLength := length;
numberOfMaxLength := number;
end if;
end for;
h27 := hailstone(27);
writeln("hailstone(27):");
for number range 1 to 4 do
write(h27[number] <& ", ");
end for;
write("....");
for number range length(h27) -3 to length(h27) do
write(", " <& h27[number]);
end for;
writeln(" length=" <& length(h27));
writeln("Maximum length " <& maxLength <& " at number=" <& numberOfMaxLength);
end func;
|
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
|
Generate lower case ASCII alphabet
|
Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code.
During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code:
set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z}
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
|
#8th
|
8th
|
"" ( 'a n:+ s:+ ) 0 25 loop
. cr
|
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
|
Generate lower case ASCII alphabet
|
Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code.
During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code:
set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z}
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
|
#ABAP
|
ABAP
|
REPORT lower_case_ascii.
WRITE: / to_lower( sy-abcde ).
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#Neko
|
Neko
|
$print("Hello world!");
|
http://rosettacode.org/wiki/Generic_swap
|
Generic swap
|
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation.
That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.
Generic swap is a task which brings together a few separate issues in programming language semantics.
Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.
Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.
Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).
Do your best!
|
#Seed7
|
Seed7
|
const proc: generate_swap (in type: aType) is func
begin
const proc: swap (inout aType: left, inout aType: right) is func
local
var aType: temp is aType.value;
begin
temp := left;
left := right;
right := temp;
end func;
end func;
|
http://rosettacode.org/wiki/Greatest_element_of_a_list
|
Greatest element of a list
|
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
|
#Yabasic
|
Yabasic
|
l$ = "1,1234,62,234,12,34,6"
dim n$(1)
n = token(l$, n$(), ", ")
for i = 1 to n
t$ = n$(i)
if t$ > m$ then m$ = t$ end if // or: if t$ > m$ m$ = t$
if val(t$) > m then m = val(t$) end if // or: if val(t$) > m m = val(t$)
next
print "Alphabetic order: ", m$, ", numeric order: ", m
|
http://rosettacode.org/wiki/Greatest_element_of_a_list
|
Greatest element of a list
|
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
|
#Yacas
|
Yacas
|
Max({1, 3, 3, 7})
Max({Pi,Exp(1)+2/5,17*Cos(6)/5,Sqrt(91/10)})
Max({1,6,Infinity})
Max({})
|
http://rosettacode.org/wiki/Generator/Exponential
|
Generator/Exponential
|
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided.
Generators are often built on top of coroutines or objects so that the internal state of the object is handled “naturally”.
Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state.
Task
Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size).
Use it to create a generator of:
Squares.
Cubes.
Create a new generator that filters all cubes from the generator of squares.
Drop the first 20 values from this last generator of filtered results, and then show the next 10 values.
Note that this task requires the use of generators in the calculation of the result.
Also see
Generator
|
#D
|
D
|
void main() {
import std.stdio, std.bigint, std.range, std.algorithm;
auto squares = 0.sequence!"n".map!(i => i.BigInt ^^ 2);
auto cubes = 0.sequence!"n".map!(i => i.BigInt ^^ 3);
squares.setDifference(cubes).drop(20).take(10).writeln;
}
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#S-BASIC
|
S-BASIC
|
rem - return p mod q
function mod(p, q = integer) = integer
end = p - q * (p / q)
rem - return greatest common divisor of x and y
function gcd(x, y = integer) = integer
var r, temp = integer
if x < y then
begin
temp = x
x = y
y = temp
end
r = mod(x, y)
while r <> 0 do
begin
x = y
y = r
r = mod(x, y)
end
end = y
rem - exercise the function
print "The GCD of 21 and 35 is"; gcd(21,35)
print "The GCD of 23 and 35 is"; gcd(23,35)
print "The GCD of 1071 and 1029 is"; gcd(1071, 1029)
print "The GCD of 3528 and 3780 is"; gcd(3528,3780)
end
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#Scala
|
Scala
|
def gcd(a: Int, b: Int): Int = if (b == 0) a.abs else gcd(b, a % b)
|
http://rosettacode.org/wiki/Generate_Chess960_starting_position
|
Generate Chess960 starting position
|
Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints:
as in the standard chess game, all eight white pawns must be placed on the second rank.
White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints:
the bishops must be placed on opposite color squares (i.e. they must be an odd number of spaces apart or there must be an even number of spaces between them)
the King must be between two rooks (with any number of other pieces between them all)
Black pawns and pieces must be placed respectively on the seventh and eighth ranks, mirroring the white pawns and pieces, just as in the standard game. (That is, their positions are not independently randomized.)
With those constraints there are 960 possible starting positions, thus the name of the variant.
Task
The purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed with Chess symbols in Unicode: ♔♕♖♗♘ or with the letters King Queen Rook Bishop kNight.
|
#BASIC
|
BASIC
|
for i = 1 to 10
inicio$ = "RKR"
pieza$ = "QNN"
for n = 1 to length(pieza$)
posic = int(rand*(length(inicio$) + 1)) + 1
inicio$ = left(inicio$, posic-1) + mid(pieza$, n, 1) + right(inicio$, length(inicio$) - posic + 1)
next n
posic = int(rand*(length(inicio$) + 1)) + 1
inicio$ = left(inicio$, posic-1) + "B" + right(inicio$, length(inicio$) - posic + 1)
posic += 1 + 2 * int(int(rand*(length(inicio$) - posic)) / 2)
inicio$ = left(inicio$, posic-1) + "B" + right(inicio$, length(inicio$) - posic + 1)
print inicio$
next i
end
|
http://rosettacode.org/wiki/Generate_Chess960_starting_position
|
Generate Chess960 starting position
|
Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints:
as in the standard chess game, all eight white pawns must be placed on the second rank.
White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints:
the bishops must be placed on opposite color squares (i.e. they must be an odd number of spaces apart or there must be an even number of spaces between them)
the King must be between two rooks (with any number of other pieces between them all)
Black pawns and pieces must be placed respectively on the seventh and eighth ranks, mirroring the white pawns and pieces, just as in the standard game. (That is, their positions are not independently randomized.)
With those constraints there are 960 possible starting positions, thus the name of the variant.
Task
The purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed with Chess symbols in Unicode: ♔♕♖♗♘ or with the letters King Queen Rook Bishop kNight.
|
#Befunge
|
Befunge
|
#.#.#.#.065*0#v_1-\>>?1v
v,":".:%*8"x"$<^!:\*2<+<
>48*,:4%2*1#v+#02#\3#g<<
v"B"*2%4:/4p<vg0:+1<\-1<
>\0p4/:6%0:0g>68*`#^_\:|
v"RKRNN"p11/6$p0\ "Q" \<
>"NRNKRRNNKRNRKNRRNKNR"v
v"NRNKRNRKNRNRKRNRNNKR"<
>"RKRNN"11g:!#v_\$\$\$\v
v _v#!`*86:g0:<^!:-1$\$<
>$\>,1+ :7`#@_^> v960v <
|
http://rosettacode.org/wiki/Generate_random_chess_position
|
Generate random chess position
|
Task
Generate a random chess position in FEN format.
The position does not have to be realistic or even balanced, but it must comply to the following rules:
there is one and only one king of each color (one black king and one white king);
the kings must not be placed on adjacent squares;
there can not be any pawn in the promotion square (no white pawn in the eighth rank, and no black pawn in the first rank);
including the kings, up to 32 pieces of either color can be placed.
There is no requirement for material balance between sides.
The picking of pieces does not have to comply to a regular chess set --- there can be five knights, twenty rooks, whatever ... as long as the total number of pieces do not exceed thirty-two.
it is white's turn.
It's assumed that both sides have lost castling rights and that there is no possibility for en passant (the FEN should thus end in w - - 0 1).
No requirement is made regarding the probability distribution of your method, but your program should be able to span a reasonably representative sample of all possible positions. For instance, programs that would always generate positions with say five pieces on the board, or with kings on a corner, would not be considered truly random.
|
#Factor
|
Factor
|
USING: combinators.short-circuit grouping io kernel math
math.parser math.ranges math.vectors prettyprint random
sequences sets splitting.monotonic strings ;
IN: rosetta-code.random-chess-position
<PRIVATE
CONSTANT: pieces "RNBQBNRPPPPPPPPrnbqbnrpppppppp"
CONSTANT: empty CHAR: .
: <empty-board> ( -- seq ) 64 [ empty ] "" replicate-as ;
: empty-index ( seq -- n ) empty swap indices random ;
: place ( seq elt n -- seq' ) rot [ set-nth ] keep ;
! return a list of indices that are adjacent to n
: adj ( n -- seq )
[ 1 - ] [ 1 + ] bi [a,b] { 8 8 8 } [ v- ] 2keep dupd v+
append append ;
: rand-non-adjacent ( m -- n ) 64 <iota> swap adj diff random ;
: place-kings ( seq -- seq' )
CHAR: K over empty-index [ place ] keep [ CHAR: k ] dip
rand-non-adjacent place ;
: non-pawn ( seq elt -- seq' ) over empty-index place ;
! prevent placing of pawns in ranks 1 and 8
: pawn ( seq elt -- seq' )
over empty swap indices
[ { [ 7 > ] [ 56 < ] } 1&& ] filter random place ;
: place-piece ( seq -- seq' )
pieces random dup "Pp" member? [ pawn ] [ non-pawn ] if ;
PRIVATE>
: position ( -- seq )
<empty-board> place-kings 30 random [ place-piece ] times ;
: position. ( seq -- )
[ 1string ] { } map-as 8 group simple-table. ;
: position>fen ( seq -- seq' )
8 group [
[ = ] monotonic-split
[ dup first empty = [ length number>string ] when ]
map concat
] map "/" join "/ w - - 0 1" append ;
: random-chess-position-demo ( -- )
position [ position. ] [ position>fen print ] bi ;
MAIN: random-chess-position-demo
|
http://rosettacode.org/wiki/Generate_random_chess_position
|
Generate random chess position
|
Task
Generate a random chess position in FEN format.
The position does not have to be realistic or even balanced, but it must comply to the following rules:
there is one and only one king of each color (one black king and one white king);
the kings must not be placed on adjacent squares;
there can not be any pawn in the promotion square (no white pawn in the eighth rank, and no black pawn in the first rank);
including the kings, up to 32 pieces of either color can be placed.
There is no requirement for material balance between sides.
The picking of pieces does not have to comply to a regular chess set --- there can be five knights, twenty rooks, whatever ... as long as the total number of pieces do not exceed thirty-two.
it is white's turn.
It's assumed that both sides have lost castling rights and that there is no possibility for en passant (the FEN should thus end in w - - 0 1).
No requirement is made regarding the probability distribution of your method, but your program should be able to span a reasonably representative sample of all possible positions. For instance, programs that would always generate positions with say five pieces on the board, or with kings on a corner, would not be considered truly random.
|
#FreeBASIC
|
FreeBASIC
|
Dim Shared As Byte grid(8, 8), r, c
Sub placeKings()
Dim As Byte r1, r2, c1, c2
Do
r1 = Int(Rnd*8)
c1 = Int(Rnd*8)
r2 = Int(Rnd*8)
c2 = Int(Rnd*8)
If (r1 <> r2 And Abs(r1 - r2) > 1 And Abs(c1 - c2) > 1) Then
grid(r1, c1) = Asc("K")
grid(r2, c2) = Asc("k")
Return
End If
Loop
End Sub
Sub placePieces(pieces As String, isPawn As Byte)
Dim numToPlace As Byte = Int(Rnd*(Len(pieces)))
For n As Byte = 0 To numToPlace-1
Do
r = Int(Rnd*8)
c = Int(Rnd*8)
Loop Until(Not(grid(r, c) Or (isPawn And (r = 7 Or r = 0))))
grid(r, c) = Asc(Mid(pieces, n, 1))
Next n
End Sub
Sub toFen()
Dim As Byte ch, countEmpty = 0
Dim As String fen
For r = 0 To 8-1
For c = 0 To 8-1
ch = grid(r, c)
If ch <> 0 Then
Print " " & Chr(ch);
Else
Print " .";
End If
If ch = 0 Then
countEmpty += 1
Else
If countEmpty > 0 Then
fen += Chr(countEmpty + 48)
countEmpty = 0
End If
fen += Chr(ch)
End If
Next c
If countEmpty > 0 Then
fen += Chr(countEmpty + 48)
countEmpty = 0
End If
fen += "/"
Print
Next r
fen += " w - - 0 1"
Print fen
End Sub
Randomize Timer
placeKings()
placePieces("PPPPPPPP", True)
placePieces("pppppppp", True)
placePieces("RNBQBNR", False)
placePieces("rnbqbnr", False)
toFen()
Sleep
|
http://rosettacode.org/wiki/General_FizzBuzz
|
General FizzBuzz
|
Task
Write a generalized version of FizzBuzz that works for any list of factors, along with their words.
This is basically a "fizzbuzz" implementation where the user supplies the parameters.
The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be printed.
For simplicity's sake, assume the user will input an integer as the max number and 3 factors, each with a word associated with them.
For example, given:
>20 #This is the maximum number, supplied by the user
>3 Fizz #The user now enters the starting factor (3) and the word they want associated with it (Fizz)
>5 Buzz #The user now enters the next factor (5) and the word they want associated with it (Buzz)
>7 Baxx #The user now enters the next factor (7) and the word they want associated with it (Baxx)
In other words: For this example, print the numbers 1 through 20, replacing every multiple of 3 with "Fizz", every multiple of 5 with "Buzz", and every multiple of 7 with "Baxx".
In the case where a number is a multiple of at least two factors, print each of the words associated with those factors in the order of least to greatest factor.
For instance, the number 15 is a multiple of both 3 and 5; print "FizzBuzz".
If the max number was 105 instead of 20, you would print "FizzBuzzBaxx" because it's a multiple of 3, 5, and 7.
Output:
1
2
Fizz
4
Buzz
Fizz
Baxx
8
Fizz
Buzz
11
Fizz
13
Baxx
FizzBuzz
16
17
Fizz
19
Buzz
|
#AppleScript
|
AppleScript
|
--------------------- GENERAL FIZZBUZZ -------------------
-- fizzEtc :: [(Int, String)] -> [Symbol]
on fizzEtc(rules)
-- A non-finite sequence of fizzEtc symbols,
-- as defined by the given list of rules.
script numberOrNoise
on |λ|(n)
script ruleMatch
on |λ|(a, mk)
set {m, k} to mk
if 0 = (n mod m) then
if integer is class of a then
k
else
a & k
end if
else
a
end if
end |λ|
end script
foldl(ruleMatch, n, rules)
end |λ|
end script
fmapGen(numberOrNoise, enumFrom(1))
end fizzEtc
--------------------------- TEST -------------------------
on run
unlines(take(20, ¬
fizzEtc({{3, "Fizz"}, {5, "Buzz"}, {7, "Baxx"}})))
end run
------------------------- GENERIC ------------------------
-- enumFrom :: Enum a => a -> [a]
on enumFrom(x)
script
property v : missing value
on |λ|()
if missing value is not v then
set v to 1 + v
else
set v to x
end if
return v
end |λ|
end script
end enumFrom
-- fmapGen <$> :: (a -> b) -> Gen [a] -> Gen [b]
on fmapGen(f, gen)
script
property g : mReturn(f)
on |λ|()
set v to gen's |λ|()
if v is missing value then
v
else
g's |λ|(v)
end if
end |λ|
end script
end fmapGen
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
-- 2nd class handler function lifted into 1st class script wrapper.
if script is class of f then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- take :: Int -> [a] -> [a]
-- take :: Int -> String -> String
on take(n, xs)
set ys to {}
repeat with i from 1 to n
set v to |λ|() of xs
if missing value is v then
return ys
else
set end of ys to v
end if
end repeat
return ys
end take
-- unlines :: [String] -> String
on unlines(xs)
-- A single string formed by the intercalation
-- of a list of strings with the newline character.
set {dlm, my text item delimiters} to ¬
{my text item delimiters, linefeed}
set s to xs as text
set my text item delimiters to dlm
s
end unlines
|
http://rosettacode.org/wiki/Hailstone_sequence
|
Hailstone sequence
|
The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.
This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):
hailstone sequence, hailstone numbers
3x + 2 mapping, 3n + 1 problem
Collatz sequence
Hasse's algorithm
Kakutani's problem
Syracuse algorithm, Syracuse problem
Thwaites conjecture
Ulam's problem
The hailstone sequence is also known as hailstone numbers (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).
Task
Create a routine to generate the hailstone sequence for a number.
Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
(But don't show the actual sequence!)
See also
xkcd (humourous).
The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).
The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
|
#Sidef
|
Sidef
|
func hailstone (n) {
var sequence = [n]
while (n > 1) {
sequence << (
n.is_even ? n.div!(2)
: n.mul!(3).add!(1)
)
}
return(sequence)
}
# The hailstone sequence for the number 27
var arr = hailstone(var nr = 27)
say "#{nr}: #{arr.first(4)} ... #{arr.last(4)} (#{arr.len})"
# The longest hailstone sequence for a number less than 100,000
var h = [0, 0]
for i (1 .. 99_999) {
(var l = hailstone(i).len) > h[1] && (
h = [i, l]
)
}
printf("%d: (%d)\n", h...)
|
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
|
Generate lower case ASCII alphabet
|
Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code.
During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code:
set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z}
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
|
#Action.21
|
Action!
|
byte X
Proc Main()
For X=97 To 122
Do
Put(x)
Od
Return
|
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
|
Generate lower case ASCII alphabet
|
Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code.
During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code:
set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z}
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
|
#Ada
|
Ada
|
type Lower_Case is new Character range 'a' .. 'z';
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#Nemerle
|
Nemerle
|
class Hello
{
static Main () : void
{
System.Console.WriteLine ("Hello world!");
}
}
|
http://rosettacode.org/wiki/Generic_swap
|
Generic swap
|
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation.
That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.
Generic swap is a task which brings together a few separate issues in programming language semantics.
Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.
Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.
Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).
Do your best!
|
#SenseTalk
|
SenseTalk
|
set [x,y] to [13,"Hello"] -- assign values to two variables
put x,y
put
set [x,y] to [y,x] -- swap the variable values
put x,y
|
http://rosettacode.org/wiki/Generic_swap
|
Generic swap
|
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation.
That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.
Generic swap is a task which brings together a few separate issues in programming language semantics.
Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.
Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.
Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).
Do your best!
|
#Sidef
|
Sidef
|
func swap(Ref a, Ref b) {
var tmp = *a;
*a = *b;
*b = tmp;
}
|
http://rosettacode.org/wiki/Greatest_element_of_a_list
|
Greatest element of a list
|
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
|
#Yorick
|
Yorick
|
> foo = [4, 3, 2, 7, 8, 9]
> max(foo)
9
|
http://rosettacode.org/wiki/Greatest_element_of_a_list
|
Greatest element of a list
|
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
|
#zkl
|
zkl
|
(1).max(1,2,3) //-->3
(66).max(1,2,3.14) //-->66
|
http://rosettacode.org/wiki/Generator/Exponential
|
Generator/Exponential
|
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided.
Generators are often built on top of coroutines or objects so that the internal state of the object is handled “naturally”.
Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state.
Task
Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size).
Use it to create a generator of:
Squares.
Cubes.
Create a new generator that filters all cubes from the generator of squares.
Drop the first 20 values from this last generator of filtered results, and then show the next 10 values.
Note that this task requires the use of generators in the calculation of the result.
Also see
Generator
|
#E
|
E
|
def genPowers(exponent) {
var i := -1
return def powerGenerator() {
return (i += 1) ** exponent
}
}
def filtered(source, filter) {
var fval := filter()
return def filterGenerator() {
while (true) {
def sval := source()
while (sval > fval) {
fval := filter()
}
if (sval < fval) {
return sval
}
}
}
}
def drop(n, gen) {
for _ in 1..n { gen() }
}
def squares := genPowers(2)
def cubes := genPowers(3)
def squaresNotCubes := filtered(squares, cubes)
drop(20, squaresNotCubes)
for _ in 1..10 {
print(`${squaresNotCubes()} `)
}
println()
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#Scheme
|
Scheme
|
(define (gcd a b)
(if (= b 0)
a
(gcd b (modulo a b))))
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#Sed
|
Sed
|
#! /bin/sed -nf
# gcd.sed Copyright (c) 2010 by Paweł Zuzelski <[email protected]>
# dc.sed Copyright (c) 1995 - 1997 by Greg Ubben <[email protected]>
# usage:
#
# echo N M | ./gcd.sed
#
# Computes the greatest common divisor of N and M integers using euclidean
# algorithm.
s/^/|P|K0|I10|O10|?~/
s/$/ [lalb%sclbsalcsblb0<F]sF sasblFxlap/
:next
s/|?./|?/
s/|?#[ -}]*/|?/
/|?!*[lLsS;:<>=]\{0,1\}$/N
/|?!*[-+*/%^<>=]/b binop
/^|.*|?[dpPfQXZvxkiosStT;:]/b binop
/|?[_0-9A-F.]/b number
/|?\[/b string
/|?l/b load
/|?L/b Load
/|?[sS]/b save
/|?c/ s/[^|]*//
/|?d/ s/[^~]*~/&&/
/|?f/ s//&[pSbz0<aLb]dSaxsaLa/
/|?x/ s/\([^~]*~\)\(.*|?x\)~*/\2\1/
/|?[KIO]/ s/.*|\([KIO]\)\([^|]*\).*|?\1/\2~&/
/|?T/ s/\.*0*~/~/
# a slow, non-stackable array implementation in dc, just for completeness
# A fast, stackable, associative array implementation could be done in sed
# (format: {key}value{key}value...), but would be longer, like load & save.
/|?;/ s/|?;\([^{}]\)/|?~[s}s{L{s}q]S}[S}l\1L}1-d0>}s\1L\1l{xS\1]dS{xL}/
/|?:/ s/|?:\([^{}]\)/|?~[s}L{s}L{s}L}s\1q]S}S}S{[L}1-d0>}S}l\1s\1L\1l{xS\1]dS{x/
/|?[ ~ cdfxKIOT]/b next
/|?\n/b next
/|?[pP]/b print
/|?k/ s/^\([0-9]\{1,3\}\)\([.~].*|K\)[^|]*/\2\1/
/|?i/ s/^\(-\{0,1\}[0-9]*\.\{0,1\}[0-9]\{1,\}\)\(~.*|I\)[^|]*/\2\1/
/|?o/ s/^\(-\{0,1\}[1-9][0-9]*\.\{0,1\}[0-9]*\)\(~.*|O\)[^|]*/\2\1/
/|?[kio]/b pop
/|?t/b trunc
/|??/b input
/|?Q/b break
/|?q/b quit
h
/|?[XZz]/b count
/|?v/b sqrt
s/.*|?\([^Y]\).*/\1 is unimplemented/
s/\n/\\n/g
l
g
b next
:print
/^-\{0,1\}[0-9]*\.\{0,1\}[0-9]\{1,\}~.*|?p/!b Print
/|O10|/b Print
# Print a number in a non-decimal output base. Uses registers a,b,c,d.
# Handles fractional output bases (O<-1 or O>=1), unlike other dc's.
# Converts the fraction correctly on negative output bases, unlike
# UNIX dc. Also scales the fraction more accurately than UNIX dc.
#
s,|?p,&KSa0kd[[-]Psa0la-]Sad0>a[0P]sad0=a[A*2+]saOtd0>a1-ZSd[[[[ ]P]sclb1\
!=cSbLdlbtZ[[[-]P0lb-sb]sclb0>c1+]sclb0!<c[0P1+dld>c]scdld>cscSdLbP]q]Sb\
[t[1P1-d0<c]scd0<c]ScO_1>bO1!<cO[16]<bOX0<b[[q]sc[dSbdA>c[A]sbdA=c[B]sbd\
B=c[C]sbdC=c[D]sbdD=c[E]sbdE=c[F]sb]xscLbP]~Sd[dtdZOZ+k1O/Tdsb[.5]*[.1]O\
X^*dZkdXK-1+ktsc0kdSb-[Lbdlb*lc+tdSbO*-lb0!=aldx]dsaxLbsb]sad1!>a[[.]POX\
+sb1[SbO*dtdldx-LbO*dZlb!<a]dsax]sadXd0<asbsasaLasbLbscLcsdLdsdLdLak[]pP,
b next
:Print
/|?p/s/[^~]*/&\
~&/
s/\(.*|P\)\([^|]*\)/\
\2\1/
s/\([^~]*\)\n\([^~]*\)\(.*|P\)/\1\3\2/
h
s/~.*//
/./{ s/.//; p; }
# Just s/.//p would work if we knew we were running under the -n option.
# Using l vs p would kind of do \ continuations, but would break strings.
g
:pop
s/[^~]*~//
b next
:load
s/\(.*|?.\)\(.\)/\20~\1/
s/^\(.\)0\(.*|r\1\([^~|]*\)~\)/\1\3\2/
s/.//
b next
:Load
s/\(.*|?.\)\(.\)/\2\1/
s/^\(.\)\(.*|r\1\)\([^~|]*~\)/|\3\2/
/^|/!i\
register empty
s/.//
b next
:save
s/\(.*|?.\)\(.\)/\2\1/
/^\(.\).*|r\1/ !s/\(.\).*|/&r\1|/
/|?S/ s/\(.\).*|r\1/&~/
s/\(.\)\([^~]*~\)\(.*|r\1\)[^~|]*~\{0,1\}/\3\2/
b next
:quit
t quit
s/|?[^~]*~[^~]*~/|?q/
t next
# Really should be using the -n option to avoid printing a final newline.
s/.*|P\([^|]*\).*/\1/
q
:break
s/[0-9]*/&;987654321009;/
:break1
s/^\([^;]*\)\([1-9]\)\(0*\)\([^1]*\2\(.\)[^;]*\3\(9*\).*|?.\)[^~]*~/\1\5\6\4/
t break1
b pop
:input
N
s/|??\(.*\)\(\n.*\)/|?\2~\1/
b next
:count
/|?Z/ s/~.*//
/^-\{0,1\}[0-9]*\.\{0,1\}[0-9]\{1,\}$/ s/[-.0]*\([^.]*\)\.*/\1/
/|?X/ s/-*[0-9A-F]*\.*\([0-9A-F]*\).*/\1/
s/|.*//
/~/ s/[^~]//g
s/./a/g
:count1
s/a\{10\}/b/g
s/b*a*/&a9876543210;/
s/a.\{9\}\(.\).*;/\1/
y/b/a/
/a/b count1
G
/|?z/ s/\n/&~/
s/\n[^~]*//
b next
:trunc
# for efficiency, doesn't pad with 0s, so 10k 2 5/ returns just .40
# The X* here and in a couple other places works around a SunOS 4.x sed bug.
s/\([^.~]*\.*\)\(.*|K\([^|]*\)\)/\3;9876543210009909:\1,\2/
:trunc1
s/^\([^;]*\)\([1-9]\)\(0*\)\([^1]*\2\(.\)[^:]*X*\3\(9*\)[^,]*\),\([0-9]\)/\1\5\6\4\7,/
t trunc1
s/[^:]*:\([^,]*\)[^~]*/\1/
b normal
:number
s/\(.*|?\)\(_\{0,1\}[0-9A-F]*\.\{0,1\}[0-9A-F]*\)/\2~\1~/
s/^_/-/
/^[^A-F~]*~.*|I10|/b normal
/^[-0.]*~/b normal
s:\([^.~]*\)\.*\([^~]*\):[Ilb^lbk/,\1\2~0A1B2C3D4E5F1=11223344556677889900;.\2:
:digit
s/^\([^,]*\),\(-*\)\([0-F]\)\([^;]*\(.\)\3[^1;]*\(1*\)\)/I*+\1\2\6\5~,\2\4/
t digit
s:...\([^/]*.\)\([^,]*\)[^.]*\(.*|?.\):\2\3KSb[99]k\1]SaSaXSbLalb0<aLakLbktLbk:
b next
:string
/|?[^]]*$/N
s/\(|?[^]]*\)\[\([^]]*\)]/\1|{\2|}/
/|?\[/b string
s/\(.*|?\)|{\(.*\)|}/\2~\1[/
s/|{/[/g
s/|}/]/g
b next
:binop
/^[^~|]*~[^|]/ !i\
stack empty
//!b next
/^-\{0,1\}[0-9]*\.\{0,1\}[0-9]\{1,\}~/ !s/[^~]*\(.*|?!*[^!=<>]\)/0\1/
/^[^~]*~-\{0,1\}[0-9]*\.\{0,1\}[0-9]\{1,\}~/ !s/~[^~]*\(.*|?!*[^!=<>]\)/~0\1/
h
/|?\*/b mul
/|?\//b div
/|?%/b rem
/|?^/b exp
/|?[+-]/ s/^\(-*\)\([^~]*~\)\(-*\)\([^~]*~\).*|?\(-\{0,1\}\).*/\2\4s\3o\1\3\5/
s/\([^.~]*\)\([^~]*~[^.~]*\)\(.*\)/<\1,\2,\3|=-~.0,123456789<></
/^<\([^,]*,[^~]*\)\.*0*~\1\.*0*~/ s/</=/
:cmp1
s/^\(<[^,]*\)\([0-9]\),\([^,]*\)\([0-9]\),/\1,\2\3,\4/
t cmp1
/^<\([^~]*\)\([^~]\)[^~]*~\1\(.\).*|=.*\3.*\2/ s/</>/
/|?/{
s/^\([<>]\)\(-[^~]*~-.*\1\)\(.\)/\3\2/
s/^\(.\)\(.*|?!*\)\1/\2!\1/
s/|?![^!]\(.\)/&l\1x/
s/[^~]*~[^~]*~\(.*|?\)!*.\(.*\)|=.*/\1\2/
b next
}
s/\(-*\)\1|=.*/;9876543210;9876543210/
/o-/ s/;9876543210/;0123456789/
s/^>\([^~]*~\)\([^~]*~\)s\(-*\)\(-*o\3\(-*\)\)/>\2\1s\5\4/
s/,\([0-9]*\)\.*\([^,]*\),\([0-9]*\)\.*\([0-9]*\)/\1,\2\3.,\4;0/
:right1
s/,\([0-9]\)\([^,]*\),;*\([0-9]\)\([0-9]*\);*0*/\1,\2\3,\4;0/
t right1
s/.\([^,]*\),~\(.*\);0~s\(-*\)o-*/\1~\30\2~/
:addsub1
s/\(.\{0,1\}\)\(~[^,]*\)\([0-9]\)\(\.*\),\([^;]*\)\(;\([^;]*\(\3[^;]*\)\).*X*\1\(.*\)\)/\2,\4\5\9\8\7\6/
s/,\([^~]*~\).\{10\}\(.\)[^;]\{0,9\}\([^;]\{0,1\}\)[^;]*/,\2\1\3/
# could be done in one s/// if we could have >9 back-refs...
/^~.*~;/!b addsub1
:endbin
s/.\([^,]*\),\([0-9.]*\).*/\1\2/
G
s/\n[^~]*~[^~]*//
:normal
s/^\(-*\)0*\([0-9.]*[0-9]\)[^~]*/\1\2/
s/^[^1-9~]*~/0~/
b next
:mul
s/\(-*\)\([0-9]*\)\.*\([0-9]*\)~\(-*\)\([0-9]*\)\.*\([0-9]*\).*|K\([^|]*\).*/\1\4\2\5.!\3\6,|\2<\3~\5>\6:\7;9876543210009909/
:mul1
s/![0-9]\([^<]*\)<\([0-9]\{0,1\}\)\([^>]*\)>\([0-9]\{0,1\}\)/0!\1\2<\3\4>/
/![0-9]/ s/\(:[^;]*\)\([1-9]\)\(0*\)\([^0]*\2\(.\).*X*\3\(9*\)\)/\1\5\6\4/
/<~[^>]*>:0*;/!t mul1
s/\(-*\)\1\([^>]*\).*/;\2^>:9876543210aaaaaaaaa/
:mul2
s/\([0-9]~*\)^/^\1/
s/<\([0-9]*\)\(.*[~^]\)\([0-9]*\)>/\1<\2>\3/
:mul3
s/>\([0-9]\)\(.*\1.\{9\}\(a*\)\)/\1>\2;9\38\37\36\35\34\33\32\31\30/
s/\(;[^<]*\)\([0-9]\)<\([^;]*\).*\2[0-9]*\(.*\)/\4\1<\2\3/
s/a[0-9]/a/g
s/a\{10\}/b/g
s/b\{10\}/c/g
/|0*[1-9][^>]*>0*[1-9]/b mul3
s/;/a9876543210;/
s/a.\{9\}\(.\)[^;]*\([^,]*\)[0-9]\([.!]*\),/\2,\1\3/
y/cb/ba/
/|<^/!b mul2
b endbin
:div
# CDDET
/^[-.0]*[1-9]/ !i\
divide by 0
//!b pop
s/\(-*\)\([0-9]*\)\.*\([^~]*~-*\)\([0-9]*\)\.*\([^~]*\)/\2.\3\1;0\4.\5;0/
:div1
s/^\.0\([^.]*\)\.;*\([0-9]\)\([0-9]*\);*0*/.\1\2.\3;0/
s/^\([^.]*\)\([0-9]\)\.\([^;]*;\)0*\([0-9]*\)\([0-9]\)\./\1.\2\30\4.\5/
t div1
s/~\(-*\)\1\(-*\);0*\([^;]*[0-9]\)[^~]*/~123456789743222111~\2\3/
s/\(.\(.\)[^~]*\)[^9]*\2.\{8\}\(.\)[^~]*/\3~\1/
s,|?.,&SaSadSaKdlaZ+LaX-1+[sb1]Sbd1>bkLatsbLa[dSa2lbla*-*dLa!=a]dSaxsakLasbLb*t,
b next
:rem
s,|?%,&Sadla/LaKSa[999]k*Lak-,
b next
:exp
# This decimal method is just a little faster than the binary method done
# totally in dc: 1LaKLb [kdSb*LbK]Sb [[.5]*d0ktdSa<bkd*KLad1<a]Sa d1<a kk*
/^[^~]*\./i\
fraction in exponent ignored
s,[^-0-9].*,;9d**dd*8*d*d7dd**d*6d**d5d*d*4*d3d*2lbd**1lb*0,
:exp1
s/\([0-9]\);\(.*\1\([d*]*\)[^l]*\([^*]*\)\(\**\)\)/;dd*d**d*\4\3\5\2/
t exp1
G
s,-*.\{9\}\([^9]*\)[^0]*0.\(.*|?.\),\2~saSaKdsaLb0kLbkK*+k1\1LaktsbkLax,
s,|?.,&SadSbdXSaZla-SbKLaLadSb[0Lb-d1lb-*d+K+0kkSb[1Lb/]q]Sa0>a[dk]sadK<a[Lb],
b next
:sqrt
# first square root using sed: 8k2v at 1:30am Dec 17, 1996
/^-/i\
square root of negative number
/^[-0]/b next
s/~.*//
/^\./ s/0\([0-9]\)/\1/g
/^\./ !s/[0-9][0-9]/7/g
G
s/\n/~/
s,|?.,&K1+k KSbSb[dk]SadXdK<asadlb/lb+[.5]*[sbdlb/lb+[.5]*dlb>a]dsaxsasaLbsaLatLbk K1-kt,
b next
# END OF GSU dc.sed
|
http://rosettacode.org/wiki/Generate_Chess960_starting_position
|
Generate Chess960 starting position
|
Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints:
as in the standard chess game, all eight white pawns must be placed on the second rank.
White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints:
the bishops must be placed on opposite color squares (i.e. they must be an odd number of spaces apart or there must be an even number of spaces between them)
the King must be between two rooks (with any number of other pieces between them all)
Black pawns and pieces must be placed respectively on the seventh and eighth ranks, mirroring the white pawns and pieces, just as in the standard game. (That is, their positions are not independently randomized.)
With those constraints there are 960 possible starting positions, thus the name of the variant.
Task
The purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed with Chess symbols in Unicode: ♔♕♖♗♘ or with the letters King Queen Rook Bishop kNight.
|
#C
|
C
|
#include<stdlib.h>
#include<locale.h>
#include<wchar.h>
#include<stdio.h>
#include<time.h>
char rank[9];
int pos[8];
void swap(int i,int j){
int temp = pos[i];
pos[i] = pos[j];
pos[j] = temp;
}
void generateFirstRank(){
int kPos,qPos,bPos1,bPos2,rPos1,rPos2,nPos1,nPos2,i;
for(i=0;i<8;i++){
rank[i] = 'e';
pos[i] = i;
}
do{
kPos = rand()%8;
rPos1 = rand()%8;
rPos2 = rand()%8;
}while((rPos1-kPos<=0 && rPos2-kPos<=0)||(rPos1-kPos>=0 && rPos2-kPos>=0)||(rPos1==rPos2 || kPos==rPos1 || kPos==rPos2));
rank[pos[rPos1]] = 'R';
rank[pos[kPos]] = 'K';
rank[pos[rPos2]] = 'R';
swap(rPos1,7);
swap(rPos2,6);
swap(kPos,5);
do{
bPos1 = rand()%5;
bPos2 = rand()%5;
}while(((pos[bPos1]-pos[bPos2])%2==0)||(bPos1==bPos2));
rank[pos[bPos1]] = 'B';
rank[pos[bPos2]] = 'B';
swap(bPos1,4);
swap(bPos2,3);
do{
qPos = rand()%3;
nPos1 = rand()%3;
}while(qPos==nPos1);
rank[pos[qPos]] = 'Q';
rank[pos[nPos1]] = 'N';
for(i=0;i<8;i++)
if(rank[i]=='e'){
rank[i] = 'N';
break;
}
}
void printRank(){
int i;
#ifdef _WIN32
printf("%s\n",rank);
#else
{
setlocale(LC_ALL,"");
printf("\n");
for(i=0;i<8;i++){
if(rank[i]=='K')
printf("%lc",(wint_t)9812);
else if(rank[i]=='Q')
printf("%lc",(wint_t)9813);
else if(rank[i]=='R')
printf("%lc",(wint_t)9814);
else if(rank[i]=='B')
printf("%lc",(wint_t)9815);
if(rank[i]=='N')
printf("%lc",(wint_t)9816);
}
}
#endif
}
int main()
{
int i;
srand((unsigned)time(NULL));
for(i=0;i<9;i++){
generateFirstRank();
printRank();
}
return 0;
}
|
http://rosettacode.org/wiki/Gapful_numbers
|
Gapful numbers
|
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the
first and last digit are known as gapful numbers.
Evenly divisible means divisible with no remainder.
All one─ and two─digit numbers have this property and are trivially excluded. Only
numbers ≥ 100 will be considered for this Rosetta Code task.
Example
187 is a gapful number because it is evenly divisible by the
number 17 which is formed by the first and last decimal digits
of 187.
About 7.46% of positive integers are gapful.
Task
Generate and show all sets of numbers (below) on one line (horizontally) with a title, here on this page
Show the first 30 gapful numbers
Show the first 15 gapful numbers ≥ 1,000,000
Show the first 10 gapful numbers ≥ 1,000,000,000
Related tasks
Harshad or Niven series.
palindromic gapful numbers.
largest number divisible by its digits.
Also see
The OEIS entry: A108343 gapful numbers.
numbersaplenty gapful numbers
|
#11l
|
11l
|
L(start, n) [(100, 30), (1'000'000, 15), (1'000'000'000, 10)]
print("\nFirst "n‘ gapful numbers from ’start)
[Int] l
L(x) start..
I x % (Int(String(x)[0]) * 10 + (x % 10)) == 0
l.append(x)
I l.len == n
L.break
print(l)
|
http://rosettacode.org/wiki/Generate_random_chess_position
|
Generate random chess position
|
Task
Generate a random chess position in FEN format.
The position does not have to be realistic or even balanced, but it must comply to the following rules:
there is one and only one king of each color (one black king and one white king);
the kings must not be placed on adjacent squares;
there can not be any pawn in the promotion square (no white pawn in the eighth rank, and no black pawn in the first rank);
including the kings, up to 32 pieces of either color can be placed.
There is no requirement for material balance between sides.
The picking of pieces does not have to comply to a regular chess set --- there can be five knights, twenty rooks, whatever ... as long as the total number of pieces do not exceed thirty-two.
it is white's turn.
It's assumed that both sides have lost castling rights and that there is no possibility for en passant (the FEN should thus end in w - - 0 1).
No requirement is made regarding the probability distribution of your method, but your program should be able to span a reasonably representative sample of all possible positions. For instance, programs that would always generate positions with say five pieces on the board, or with kings on a corner, would not be considered truly random.
|
#Go
|
Go
|
package main
import (
"fmt"
"math/rand"
"strconv"
"strings"
"time"
)
var grid [8][8]byte
func abs(i int) int {
if i >= 0 {
return i
} else {
return -i
}
}
func createFen() string {
placeKings()
placePieces("PPPPPPPP", true)
placePieces("pppppppp", true)
placePieces("RNBQBNR", false)
placePieces("rnbqbnr", false)
return toFen()
}
func placeKings() {
for {
r1 := rand.Intn(8)
c1 := rand.Intn(8)
r2 := rand.Intn(8)
c2 := rand.Intn(8)
if r1 != r2 && abs(r1-r2) > 1 && abs(c1-c2) > 1 {
grid[r1][c1] = 'K'
grid[r2][c2] = 'k'
return
}
}
}
func placePieces(pieces string, isPawn bool) {
numToPlace := rand.Intn(len(pieces))
for n := 0; n < numToPlace; n++ {
var r, c int
for {
r = rand.Intn(8)
c = rand.Intn(8)
if grid[r][c] == '\000' && !(isPawn && (r == 7 || r == 0)) {
break
}
}
grid[r][c] = pieces[n]
}
}
func toFen() string {
var fen strings.Builder
countEmpty := 0
for r := 0; r < 8; r++ {
for c := 0; c < 8; c++ {
ch := grid[r][c]
if ch == '\000' {
ch = '.'
}
fmt.Printf("%2c ", ch)
if ch == '.' {
countEmpty++
} else {
if countEmpty > 0 {
fen.WriteString(strconv.Itoa(countEmpty))
countEmpty = 0
}
fen.WriteByte(ch)
}
}
if countEmpty > 0 {
fen.WriteString(strconv.Itoa(countEmpty))
countEmpty = 0
}
fen.WriteString("/")
fmt.Println()
}
fen.WriteString(" w - - 0 1")
return fen.String()
}
func main() {
rand.Seed(time.Now().UnixNano())
fmt.Println(createFen())
}
|
http://rosettacode.org/wiki/General_FizzBuzz
|
General FizzBuzz
|
Task
Write a generalized version of FizzBuzz that works for any list of factors, along with their words.
This is basically a "fizzbuzz" implementation where the user supplies the parameters.
The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be printed.
For simplicity's sake, assume the user will input an integer as the max number and 3 factors, each with a word associated with them.
For example, given:
>20 #This is the maximum number, supplied by the user
>3 Fizz #The user now enters the starting factor (3) and the word they want associated with it (Fizz)
>5 Buzz #The user now enters the next factor (5) and the word they want associated with it (Buzz)
>7 Baxx #The user now enters the next factor (7) and the word they want associated with it (Baxx)
In other words: For this example, print the numbers 1 through 20, replacing every multiple of 3 with "Fizz", every multiple of 5 with "Buzz", and every multiple of 7 with "Baxx".
In the case where a number is a multiple of at least two factors, print each of the words associated with those factors in the order of least to greatest factor.
For instance, the number 15 is a multiple of both 3 and 5; print "FizzBuzz".
If the max number was 105 instead of 20, you would print "FizzBuzzBaxx" because it's a multiple of 3, 5, and 7.
Output:
1
2
Fizz
4
Buzz
Fizz
Baxx
8
Fizz
Buzz
11
Fizz
13
Baxx
FizzBuzz
16
17
Fizz
19
Buzz
|
#Arturo
|
Arturo
|
maxNum: to :integer strip input "Set maximum number: "
facts: map 1..3 'x -> split.words strip input ~"Enter factor |x|: "
loop 1..maxNum 'i [
printNum: true
loop facts 'fact ->
if zero? i % to :integer fact\0 [
prints fact\1
printNum: false
]
print (printNum)? -> i -> ""
]
|
http://rosettacode.org/wiki/Hailstone_sequence
|
Hailstone sequence
|
The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.
This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):
hailstone sequence, hailstone numbers
3x + 2 mapping, 3n + 1 problem
Collatz sequence
Hasse's algorithm
Kakutani's problem
Syracuse algorithm, Syracuse problem
Thwaites conjecture
Ulam's problem
The hailstone sequence is also known as hailstone numbers (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).
Task
Create a routine to generate the hailstone sequence for a number.
Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
(But don't show the actual sequence!)
See also
xkcd (humourous).
The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).
The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
|
#Smalltalk
|
Smalltalk
|
Object subclass: Sequences [
Sequences class >> hailstone: n [
|seq|
seq := OrderedCollection new.
seq add: n.
(n = 1) ifTrue: [ ^seq ].
(n even) ifTrue: [ seq addAll: (Sequences hailstone: (n / 2)) ]
ifFalse: [ seq addAll: (Sequences hailstone: ( (3*n) + 1 ) ) ].
^seq.
]
Sequences class >> hailstoneCount: n [
^ (Sequences hailstoneCount: n num: 1)
]
"this 'version' avoids storing the sequence, it just counts
its length - no memoization anyway"
Sequences class >> hailstoneCount: n num: m [
(n = 1) ifTrue: [ ^m ].
(n even) ifTrue: [ ^ Sequences hailstoneCount: (n / 2) num: (m + 1) ]
ifFalse: [ ^ Sequences hailstoneCount: ( (3*n) + 1) num: (m + 1) ].
]
].
|
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
|
Generate lower case ASCII alphabet
|
Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code.
During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code:
set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z}
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#ALGOL_68
|
ALGOL 68
|
# in ALGOL 68, a STRING is an array of characters with flexible bounds #
# so we can declare an array of 26 characters and assign a string #
# containing the lower-case letters to it #
[ 26 ]CHAR lc := "abcdefghijklmnopqrstuvwxyz"
|
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
|
Generate lower case ASCII alphabet
|
Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code.
During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code:
set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z}
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#ALGOL_W
|
ALGOL W
|
% set lc to the lower case alphabet %
string(26) lc;
for c := 0 until 25 do lc( c // 1 ) := code( decode( "a" ) + c );
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#NetRexx
|
NetRexx
|
say 'Hello world!'
|
http://rosettacode.org/wiki/Generic_swap
|
Generic swap
|
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation.
That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.
Generic swap is a task which brings together a few separate issues in programming language semantics.
Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.
Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.
Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).
Do your best!
|
#Slate
|
Slate
|
x@(Syntax LoadVariable traits) swapWith: y@(Syntax LoadVariable traits) &environment: env
"A macro that expands into simple code swapping the values of two variables
in the current scope."
[
env ifNil: [error: 'Cannot swap variables outside of a method'].
tmpVar ::= env addVariable.
{tmpVar store: x variable load.
x variable store: y variable load.
y variable store: tmpVar load} parenthesize
].
|
http://rosettacode.org/wiki/Generic_swap
|
Generic swap
|
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation.
That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.
Generic swap is a task which brings together a few separate issues in programming language semantics.
Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.
Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.
Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).
Do your best!
|
#Smalltalk
|
Smalltalk
|
OrderedCollection extend [
swap: a and: b [
|t|
t := self at: a.
self at: a put: (self at: b).
self at: b put: t
]
]
|
http://rosettacode.org/wiki/Greatest_element_of_a_list
|
Greatest element of a list
|
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
|
#Zoea
|
Zoea
|
program: max
case: 1
input: [7,3,5,9,2,6]
output: 9
case: 2
input: [1,5,3,2,7]
output: 7
|
http://rosettacode.org/wiki/Greatest_element_of_a_list
|
Greatest element of a list
|
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
|
#ZX_Spectrum_Basic
|
ZX Spectrum Basic
|
10 PRINT "Values"''
20 LET z=0
30 FOR x=1 TO INT (RND*10)+1
40 LET y=RND*10-5
50 PRINT y
60 LET z=(y AND y>z)+(z AND y<z)
70 NEXT x
80 PRINT '"Max. value = ";z
|
http://rosettacode.org/wiki/Generator/Exponential
|
Generator/Exponential
|
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided.
Generators are often built on top of coroutines or objects so that the internal state of the object is handled “naturally”.
Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state.
Task
Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size).
Use it to create a generator of:
Squares.
Cubes.
Create a new generator that filters all cubes from the generator of squares.
Drop the first 20 values from this last generator of filtered results, and then show the next 10 values.
Note that this task requires the use of generators in the calculation of the result.
Also see
Generator
|
#EchoLisp
|
EchoLisp
|
(lib 'tasks) ;; for make-generator
;; generator of generators
(define (gen-power power)
(make-generator
(lambda(n) (yield (expt n power)) (1+ n)) 1))
(define powers-2 (gen-power 2))
(define powers-3 (gen-power 3))
(take powers-3 10)
→ (1 8 27 64 125 216 343 512 729 1000)
;; generators substraction
;; input : two generators ga, gb - Sequences must be increasing
;; output : new generator = ga sequence minus gb sequence
(define (gen-substract ga gb)
(define (substract b (a))
(set! a (next ga))
(while (>= a b) ; avance b until > a
(when (= a b) (set! a (next ga)))
(set! b (next gb)))
(yield a)
b ) ;; b := next state
(make-generator substract (next gb)))
;; application
(define task (gen-substract (gen-power 2) (gen-power 3)))
(drop task 20)
(take task 10)
→ (529 576 625 676 784 841 900 961 1024 1089)
; inspect
task → #generator:state: 1331
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#Seed7
|
Seed7
|
const func integer: gcd (in var integer: a, in var integer: b) is func
result
var integer: gcd is 0;
local
var integer: help is 0;
begin
while a <> 0 do
help := b rem a;
b := a;
a := help;
end while;
gcd := b;
end func;
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#SequenceL
|
SequenceL
|
gcd(a, b) :=
a when b = 0
else
gcd(b, a mod b);
|
http://rosettacode.org/wiki/Generate_Chess960_starting_position
|
Generate Chess960 starting position
|
Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints:
as in the standard chess game, all eight white pawns must be placed on the second rank.
White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints:
the bishops must be placed on opposite color squares (i.e. they must be an odd number of spaces apart or there must be an even number of spaces between them)
the King must be between two rooks (with any number of other pieces between them all)
Black pawns and pieces must be placed respectively on the seventh and eighth ranks, mirroring the white pawns and pieces, just as in the standard game. (That is, their positions are not independently randomized.)
With those constraints there are 960 possible starting positions, thus the name of the variant.
Task
The purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed with Chess symbols in Unicode: ♔♕♖♗♘ or with the letters King Queen Rook Bishop kNight.
|
#C.2B.2B
|
C++
|
#include <iostream>
#include <string>
#include <time.h>
using namespace std;
namespace
{
void placeRandomly(char* p, char c)
{
int loc = rand() % 8;
if (!p[loc])
p[loc] = c;
else
placeRandomly(p, c); // try again
}
int placeFirst(char* p, char c, int loc = 0)
{
while (p[loc]) ++loc;
p[loc] = c;
return loc;
}
string startPos()
{
char p[8]; memset( p, 0, 8 );
// bishops on opposite color
p[2 * (rand() % 4)] = 'B';
p[2 * (rand() % 4) + 1] = 'B';
// queen knight knight, anywhere
for (char c : "QNN")
placeRandomly(p, c);
// rook king rook, in that order
placeFirst(p, 'R', placeFirst(p, 'K', placeFirst(p, 'R')));
return string(p, 8);
}
} // leave local
namespace chess960
{
void generate( int c )
{
for( int x = 0; x < c; x++ )
cout << startPos() << "\n";
}
}
int main( int argc, char* argv[] )
{
srand( time( NULL ) );
chess960::generate( 10 );
cout << "\n\n";
return system( "pause" );
}
|
http://rosettacode.org/wiki/Gapful_numbers
|
Gapful numbers
|
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the
first and last digit are known as gapful numbers.
Evenly divisible means divisible with no remainder.
All one─ and two─digit numbers have this property and are trivially excluded. Only
numbers ≥ 100 will be considered for this Rosetta Code task.
Example
187 is a gapful number because it is evenly divisible by the
number 17 which is formed by the first and last decimal digits
of 187.
About 7.46% of positive integers are gapful.
Task
Generate and show all sets of numbers (below) on one line (horizontally) with a title, here on this page
Show the first 30 gapful numbers
Show the first 15 gapful numbers ≥ 1,000,000
Show the first 10 gapful numbers ≥ 1,000,000,000
Related tasks
Harshad or Niven series.
palindromic gapful numbers.
largest number divisible by its digits.
Also see
The OEIS entry: A108343 gapful numbers.
numbersaplenty gapful numbers
|
#Ada
|
Ada
|
with Ada.Text_IO; use Ada.Text_IO;
procedure Gapful_Numbers is
function Divisor (N : in Positive) return Positive is
NN : Positive := N;
begin
while NN >= 10 loop
NN := NN / 10;
end loop;
return 10 * NN + (N mod 10);
end Divisor;
function Is_Gapful (N : in Positive) return Boolean is
begin
return N mod Divisor (N) = 0;
end Is_Gapful;
procedure Find_Gapful (Count : in Positive; From : in Positive) is
Found : Natural := 0;
begin
for Candidate in From .. Positive'Last loop
if Is_Gapful (Candidate) then
Put (Candidate'Image);
Found := Found + 1;
exit when Found = Count;
end if;
end loop;
New_Line;
end Find_Gapful;
begin
Put_Line ("First 30 gapful numbers over 100:");
Find_Gapful (From => 100, Count => 30);
New_Line;
Put_Line ("First 15 gapful numbers over 1_000_000:");
Find_Gapful (From => 1_000_000, Count => 15);
New_Line;
Put_Line ("First 10 gapful numbers over 1_000_000_000:");
Find_Gapful (From => 1_000_000_000, Count => 10);
New_Line;
end Gapful_Numbers;
|
http://rosettacode.org/wiki/Generate_random_chess_position
|
Generate random chess position
|
Task
Generate a random chess position in FEN format.
The position does not have to be realistic or even balanced, but it must comply to the following rules:
there is one and only one king of each color (one black king and one white king);
the kings must not be placed on adjacent squares;
there can not be any pawn in the promotion square (no white pawn in the eighth rank, and no black pawn in the first rank);
including the kings, up to 32 pieces of either color can be placed.
There is no requirement for material balance between sides.
The picking of pieces does not have to comply to a regular chess set --- there can be five knights, twenty rooks, whatever ... as long as the total number of pieces do not exceed thirty-two.
it is white's turn.
It's assumed that both sides have lost castling rights and that there is no possibility for en passant (the FEN should thus end in w - - 0 1).
No requirement is made regarding the probability distribution of your method, but your program should be able to span a reasonably representative sample of all possible positions. For instance, programs that would always generate positions with say five pieces on the board, or with kings on a corner, would not be considered truly random.
|
#Haskell
|
Haskell
|
{-# LANGUAGE LambdaCase, TupleSections #-}
module RandomChess
( placeKings
, placePawns
, placeRemaining
, emptyBoard
, toFen
, ChessBoard
, Square (..)
, BoardState (..)
, getBoard
)
where
import Control.Monad.State (State, get, gets, put)
import Data.List (find, sortBy)
import System.Random (Random, RandomGen, StdGen, random, randomR)
type Pos = (Char, Int)
type ChessBoard = [(Square, Pos)]
data PieceRank = King | Queen | Rook | Bishop | Knight | Pawn
deriving (Enum, Bounded, Show, Eq, Ord)
data PieceColor = Black | White
deriving (Enum, Bounded, Show, Eq, Ord)
data Square = ChessPiece PieceRank PieceColor | EmptySquare
deriving (Eq, Ord)
type PieceCount = [(Square, Int)]
data BoardState = BoardState { board :: ChessBoard , generator :: StdGen }
instance Show Square where
show (ChessPiece King Black) = "♚"
show (ChessPiece Queen Black) = "♛"
show (ChessPiece Rook Black) = "♜"
show (ChessPiece Bishop Black) = "♝"
show (ChessPiece Knight Black) = "♞"
show (ChessPiece Pawn Black) = "♟"
show (ChessPiece King White) = "♔"
show (ChessPiece Queen White) = "♕"
show (ChessPiece Rook White) = "♖"
show (ChessPiece Bishop White) = "♗"
show (ChessPiece Knight White) = "♘"
show (ChessPiece Pawn White) = "♙"
show EmptySquare = " "
instance Random PieceRank where
randomR (a, b) g = case randomR (fromEnum a, fromEnum b) g of
(x, g'') -> (toEnum x, g'')
random = randomR (minBound, maxBound)
instance Random PieceColor where
randomR (a, b) g = case randomR (fromEnum a, fromEnum b) g of
(x, g'') -> (toEnum x, g'')
random = randomR (minBound, maxBound)
fullBoard :: PieceCount
fullBoard =
[ (ChessPiece King Black , 1)
, (ChessPiece Queen Black , 1)
, (ChessPiece Rook Black , 2)
, (ChessPiece Bishop Black, 2)
, (ChessPiece Knight Black, 2)
, (ChessPiece Pawn Black , 8)
, (ChessPiece King White , 1)
, (ChessPiece Queen White , 1)
, (ChessPiece Rook White , 2)
, (ChessPiece Bishop White, 2)
, (ChessPiece Knight White, 2)
, (ChessPiece Pawn White , 8)
, (EmptySquare , 32)
]
emptyBoard :: ChessBoard
emptyBoard = fmap (EmptySquare,) . (,) <$> ['a'..'h'] <*> [1..8]
replaceSquareByPos :: (Square, Pos) -> ChessBoard -> ChessBoard
replaceSquareByPos e@(_, p) = fmap (\x -> if p == snd x then e else x)
isPosOccupied :: Pos -> ChessBoard -> Bool
isPosOccupied p = occupied . find (\x -> p == snd x)
where
occupied (Just (EmptySquare, _)) = False
occupied _ = True
isAdjacent :: Pos -> Pos -> Bool
isAdjacent (x1, y1) (x2, y2) =
let upOrDown = (pred y1 == y2 || succ y1 == y2)
leftOrRight = (pred x1 == x2 || succ x1 == x2)
in (x2 == x1 && upOrDown)
|| (pred x1 == x2 && upOrDown)
|| (succ x1 == x2 && upOrDown)
|| (leftOrRight && y1 == y2)
fen :: Square -> String
fen (ChessPiece King Black) = "k"
fen (ChessPiece Queen Black) = "q"
fen (ChessPiece Rook Black) = "r"
fen (ChessPiece Bishop Black) = "b"
fen (ChessPiece Knight Black) = "n"
fen (ChessPiece Pawn Black) = "p"
fen (ChessPiece King White) = "K"
fen (ChessPiece Queen White) = "Q"
fen (ChessPiece Rook White) = "R"
fen (ChessPiece Bishop White) = "B"
fen (ChessPiece Knight White) = "N"
fen (ChessPiece Pawn White) = "P"
boardSort :: (Square, Pos) -> (Square, Pos) -> Ordering
boardSort (_, (x1, y1)) (_, (x2, y2)) | y1 < y2 = GT
| y1 > y2 = LT
| y1 == y2 = compare x1 x2
toFen :: ChessBoard -> String
toFen [] = " w - - 0 1" <> []
toFen b = scanRow (fst <$> take 8 b) 0
where
scanRow [] 0 = nextRow
scanRow [] n = show n <> nextRow
scanRow (EmptySquare:xs) n = scanRow xs (succ n)
scanRow (x:xs) 0 = nextPiece x xs
scanRow (x:xs) n = show n <> nextPiece x xs
nextRow = "/" <> toFen (drop 8 b)
nextPiece x xs = fen x <> scanRow xs 0
-- State functions
withStateGen :: (StdGen -> (a, StdGen)) -> State BoardState a
withStateGen f = do
currentState <- get
let gen1 = generator currentState
let (x, gen2) = f gen1
put (currentState {generator = gen2})
pure x
randomPos :: State BoardState Pos
randomPos = do
boardState <- gets board
chr <- withStateGen (randomR ('a', 'h'))
num <- withStateGen (randomR (1, 8))
let pos = (chr, num)
if isPosOccupied pos boardState then
randomPos
else
pure pos
randomPiece :: State BoardState Square
randomPiece = ChessPiece <$> withStateGen random <*> withStateGen random
placeKings :: State BoardState ()
placeKings = do
currentState <- get
p1 <- randomPos
p2 <- randomPos
if p1 `isAdjacent` p2 || p1 == p2
then placeKings
else do
let updatedBoard = replaceSquareByPos (ChessPiece King White, p1) $
replaceSquareByPos (ChessPiece King Black, p2) (board currentState)
put currentState { board = updatedBoard }
placePawns :: State BoardState ()
placePawns = withStateGen (randomR (1, 16)) >>= go
where
go :: Int -> State BoardState ()
go 0 = pure ()
go n = do
currentState <- get
pos <- randomPos
color <- withStateGen random
let pawn = ChessPiece Pawn color
let currentBoard = board currentState
if promoted color == snd pos || isPosOccupied pos currentBoard ||
enpassant color == snd pos || firstPos color == snd pos
then go n
else do
put currentState { board = replaceSquareByPos (pawn, pos) currentBoard }
go $ pred n
promoted White = 8
promoted Black = 1
enpassant White = 5
enpassant Black = 4
firstPos White = 1
firstPos Black = 8
placeRemaining :: State BoardState ()
placeRemaining =
withStateGen (randomR (5, sum $ fmap snd remaining)) >>= go remaining
where
remaining = filter (\case
(ChessPiece King _, _) -> False
(ChessPiece Pawn _, _) -> False
(EmptySquare, _) -> False
_ -> True)
fullBoard
go :: PieceCount -> Int -> State BoardState ()
go _ 0 = pure ()
go remaining n = do
currentState <- get
let currentBoard = board currentState
position <- randomPos
piece <- randomPiece
if not (isPermitted piece) || isPosOccupied position currentBoard
then go remaining n
else do
let updatedBoard = replaceSquareByPos (piece, position) currentBoard
put currentState { board = updatedBoard }
go (consume piece remaining) (pred n)
where
isPermitted p =
case find ((==p) . fst) remaining of
Just (_, count) -> count > 0
Nothing -> False
consume p'' = fmap (\(p, c) -> if p == p'' then (p, pred c) else (p, c))
getBoard :: State BoardState ChessBoard
getBoard = gets (sortBy boardSort . board)
|
http://rosettacode.org/wiki/Gauss-Jordan_matrix_inversion
|
Gauss-Jordan matrix inversion
|
Task
Invert matrix A using Gauss-Jordan method.
A being an n × n matrix.
|
#11l
|
11l
|
V Eps = 1e-10
F transformToRref(&mat)
V lead = 0
L(r) 0 .< mat.len
I lead >= mat[0].len
R
V i = r
L mat[i][lead] == 0
i++
I i == mat.len
i = r
lead++
I lead == mat[0].len
R
swap(&mat[i], &mat[r])
V d = mat[r][lead]
I abs(d) > Eps
L(&item) mat[r]
item /= d
L(i) 0 .< mat.len
I i != r
V m = mat[i][lead]
L(c) 0 .< mat[0].len
mat[i][c] -= mat[r][c] * m
lead++
F inverse(mat)
V augmat = [[0.0] * (2 * mat.len)] * mat.len
L(i) 0 .< mat.len
L(j) 0 .< mat.len
augmat[i][j] = mat[i][j]
augmat[i][mat.len + i] = 1
transformToRref(&augmat)
V result = [[0.0] * mat.len] * mat.len
L(i) 0 .< mat.len
L(j) 0 .< mat.len
I augmat[i][j] != Float(i == j)
X ValueError(‘matrix is singular’)
result[i][j] = augmat[i][mat.len + j]
R result
F print_mat(mat)
L(row) mat
V line = ‘’
L(val) row
I !line.empty
line ‘’= ‘ ’
line ‘’= ‘#3.5’.format(val)
print(line)
F runTest(mat)
print(‘Matrix:’)
print_mat(mat)
print()
print(‘Inverse:’)
print_mat(inverse(mat))
print()
print()
V m1 = [[Float(1), 2, 3],
[Float(4), 1, 6],
[Float(7), 8, 9]]
V m2 = [[Float( 2), -1, 0],
[Float(-1), 2, -1],
[Float( 0), -1, 2]]
V m3 = [[Float(-1), -2, 3, 2],
[Float(-4), -1, 6, 2],
[Float( 7), -8, 9, 1],
[Float( 1), -2, 1, 3]]
runTest(m1)
runTest(m2)
runTest(m3)
|
http://rosettacode.org/wiki/General_FizzBuzz
|
General FizzBuzz
|
Task
Write a generalized version of FizzBuzz that works for any list of factors, along with their words.
This is basically a "fizzbuzz" implementation where the user supplies the parameters.
The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be printed.
For simplicity's sake, assume the user will input an integer as the max number and 3 factors, each with a word associated with them.
For example, given:
>20 #This is the maximum number, supplied by the user
>3 Fizz #The user now enters the starting factor (3) and the word they want associated with it (Fizz)
>5 Buzz #The user now enters the next factor (5) and the word they want associated with it (Buzz)
>7 Baxx #The user now enters the next factor (7) and the word they want associated with it (Baxx)
In other words: For this example, print the numbers 1 through 20, replacing every multiple of 3 with "Fizz", every multiple of 5 with "Buzz", and every multiple of 7 with "Baxx".
In the case where a number is a multiple of at least two factors, print each of the words associated with those factors in the order of least to greatest factor.
For instance, the number 15 is a multiple of both 3 and 5; print "FizzBuzz".
If the max number was 105 instead of 20, you would print "FizzBuzzBaxx" because it's a multiple of 3, 5, and 7.
Output:
1
2
Fizz
4
Buzz
Fizz
Baxx
8
Fizz
Buzz
11
Fizz
13
Baxx
FizzBuzz
16
17
Fizz
19
Buzz
|
#AutoHotkey
|
AutoHotkey
|
; Test parameters
max := 20, fizz := 3, buzz := 5, baxx := 7
Loop % max {
output := ""
if (Mod(A_Index, fizz) = 0)
output .= "Fizz"
if (Mod(A_Index, buzz) = 0)
output .= "Buzz"
if (Mod(A_Index, baxx) = 0)
output .= "Baxx"
if (output = "")
FileAppend %A_Index%`n, *
else
FileAppend %output%`n, *
}
|
http://rosettacode.org/wiki/Hailstone_sequence
|
Hailstone sequence
|
The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.
This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):
hailstone sequence, hailstone numbers
3x + 2 mapping, 3n + 1 problem
Collatz sequence
Hasse's algorithm
Kakutani's problem
Syracuse algorithm, Syracuse problem
Thwaites conjecture
Ulam's problem
The hailstone sequence is also known as hailstone numbers (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).
Task
Create a routine to generate the hailstone sequence for a number.
Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
(But don't show the actual sequence!)
See also
xkcd (humourous).
The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).
The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
|
#SNUSP
|
SNUSP
|
/@+@@@+++# 27
| halve odd /===count<<\ /recurse\ #/?\ zero
$>@/===!/===-?\==>?!/-<+++\ \!/=!\@\>?!\@/<@\.!\-/
/+<-\!>\?-<+>/++++<\?>+++/*6+4 | | \=/ \=itoa=@@@+@+++++#
\=>?/<=!=\ | | ! /+ !/+ !/+ !/+ \ mod10
|//!==/========\ | /<+> -\!?-\!?-\!?-\!?-\!
/=>?\<=/\<+>!\->+>+<<?/>>=print@/\ln \?!\-?!\-?!\-?!\-?!\-?/\ div10
\+<-/!< ----------.++++++++++/ # +/! +/! +/! +/! +/
|
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
|
Generate lower case ASCII alphabet
|
Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code.
During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code:
set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z}
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
|
#APL
|
APL
|
⎕UCS 96+⍳26
|
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
|
Generate lower case ASCII alphabet
|
Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code.
During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code:
set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z}
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#AppleScript
|
AppleScript
|
-------------------- ALPHABETIC SERIES -------------------
on run
unlines(map(concat, ¬
({enumFromTo("a", "z"), ¬
enumFromTo("🐟", "🐐"), ¬
enumFromTo("z", "a"), ¬
enumFromTo("α", "ω")})))
end run
-------------------- GENERIC FUNCTIONS -------------------
-- concat :: [[a]] -> [a]
-- concat :: [String] -> String
on concat(xs)
set lng to length of xs
if 0 < lng and string is class of (item 1 of xs) then
set acc to ""
else
set acc to {}
end if
repeat with i from 1 to lng
set acc to acc & item i of xs
end repeat
acc
end concat
-- enumFromTo :: Enum a => a -> a -> [a]
on enumFromTo(m, n)
if class of m is integer then
enumFromToInt(m, n)
else
enumFromToChar(m, n)
end if
end enumFromTo
-- enumFromToChar :: Char -> Char -> [Char]
on enumFromToChar(m, n)
set {intM, intN} to {id of m, id of n}
set xs to {}
repeat with i from intM to intN by signum(intN - intM)
set end of xs to character id i
end repeat
return xs
end enumFromToChar
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
-- 2nd class handler function lifted into 1st class script wrapper.
if script is class of f then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
-- The list obtained by applying f
-- to each element of xs.
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- signum :: Num -> Num
on signum(x)
if x < 0 then
-1
else if x = 0 then
0
else
1
end if
end signum
-- unlines :: [String] -> String
on unlines(xs)
-- A single string formed by the intercalation
-- of a list of strings with the newline character.
set {dlm, my text item delimiters} to ¬
{my text item delimiters, linefeed}
set s to xs as text
set my text item delimiters to dlm
s
end unlines
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#Never
|
Never
|
func main() -> int {
prints("Hello world!\n");
0
}
|
http://rosettacode.org/wiki/Generic_swap
|
Generic swap
|
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation.
That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.
Generic swap is a task which brings together a few separate issues in programming language semantics.
Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.
Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.
Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).
Do your best!
|
#SNOBOL4
|
SNOBOL4
|
* SWAP(.V1, .V2) - Exchange the contents of two variables.
* The variables must be prefixed with the name operator
* when the function is called.
DEFINE('SWAP(X,Y)TEMP') :(SWAP_END)
SWAP TEMP = $X
$X = $Y
$Y = TEMP :(RETURN)
SWAP_END
|
http://rosettacode.org/wiki/Generic_swap
|
Generic swap
|
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation.
That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.
Generic swap is a task which brings together a few separate issues in programming language semantics.
Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.
Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.
Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).
Do your best!
|
#Standard_ML
|
Standard ML
|
fun swap (x, y) = (y, x)
|
http://rosettacode.org/wiki/Generator/Exponential
|
Generator/Exponential
|
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided.
Generators are often built on top of coroutines or objects so that the internal state of the object is handled “naturally”.
Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state.
Task
Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size).
Use it to create a generator of:
Squares.
Cubes.
Create a new generator that filters all cubes from the generator of squares.
Drop the first 20 values from this last generator of filtered results, and then show the next 10 values.
Note that this task requires the use of generators in the calculation of the result.
Also see
Generator
|
#Elixir
|
Elixir
|
defmodule Generator do
def filter( source_pid, remove_pid ) do
first_remove = next( remove_pid )
spawn( fn -> filter_loop(source_pid, remove_pid, first_remove) end )
end
def next( pid ) do
send(pid, {:next, self})
receive do
x -> x
end
end
def power( m ), do: spawn( fn -> power_loop(m, 0) end )
def task do
squares_pid = power( 2 )
cubes_pid = power( 3 )
filter_pid = filter( squares_pid, cubes_pid )
for _x <- 1..20, do: next(filter_pid)
for _x <- 1..10, do: next(filter_pid)
end
defp filter_loop( pid1, pid2, n2 ) do
receive do
{:next, pid} ->
{n, new_n2} = filter_loop_next( next(pid1), n2, pid1, pid2 )
send( pid, n )
filter_loop( pid1, pid2, new_n2 )
end
end
defp filter_loop_next( n1, n2, pid1, pid2 ) when n1 > n2, do:
filter_loop_next( n1, next(pid2), pid1, pid2 )
defp filter_loop_next( n, n, pid1, pid2 ), do:
filter_loop_next( next(pid1), next(pid2), pid1, pid2 )
defp filter_loop_next( n1, n2, _pid1, _pid2 ), do: {n1, n2}
defp power_loop( m, n ) do
receive do
{:next, pid} -> send( pid, round(:math.pow(n, m) ) )
end
power_loop( m, n + 1 )
end
end
IO.inspect Generator.task
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#SETL
|
SETL
|
a := 33; b := 77;
print(" the gcd of",a," and ",b," is ",gcd(a,b));
c := 49865; d := 69811;
print(" the gcd of",c," and ",d," is ",gcd(c,d));
proc gcd (u, v);
return if v = 0 then abs u else gcd (v, u mod v) end;
end;
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#Sidef
|
Sidef
|
var arr = [100, 1_000, 10_000, 20];
say Math.gcd(arr...);
|
http://rosettacode.org/wiki/Generate_Chess960_starting_position
|
Generate Chess960 starting position
|
Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints:
as in the standard chess game, all eight white pawns must be placed on the second rank.
White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints:
the bishops must be placed on opposite color squares (i.e. they must be an odd number of spaces apart or there must be an even number of spaces between them)
the King must be between two rooks (with any number of other pieces between them all)
Black pawns and pieces must be placed respectively on the seventh and eighth ranks, mirroring the white pawns and pieces, just as in the standard game. (That is, their positions are not independently randomized.)
With those constraints there are 960 possible starting positions, thus the name of the variant.
Task
The purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed with Chess symbols in Unicode: ♔♕♖♗♘ or with the letters King Queen Rook Bishop kNight.
|
#Clojure
|
Clojure
|
(ns c960.core
(:gen-class)
(:require [clojure.string :as s]))
;; legal starting rank - unicode chars for rook, knight, bishop, queen, king, bishop, knight, rook
(def starting-rank [\♖ \♘ \♗ \♕ \♔ \♗ \♘ \♖])
(defn bishops-legal?
"True if Bishops are odd number of indicies apart"
[rank]
(odd? (apply - (cons 0 (sort > (keep-indexed #(when (= \♗ %2) %1) rank))))))
(defn king-legal?
"True if the king is between two rooks"
[rank]
(let [king-&-rooks (filter #{\♔ \♖} rank)]
(and
(= 3 (count king-&-rooks))
(= \u2654 (second king-&-rooks)))))
(defn c960
"Return a legal rank for c960 chess"
([] (c960 1))
([n]
(->> #(shuffle starting-rank)
repeatedly
(filter #(and (king-legal? %) (bishops-legal? %)))
(take n)
(map #(s/join ", " %)))))
(c960)
;; => "♗, ♖, ♔, ♕, ♘, ♘, ♖, ♗"
(c960)
;; => "♖, ♕, ♘, ♔, ♗, ♗, ♘, ♖"
(c960 4)
;; => ("♘, ♖, ♔, ♘, ♗, ♗, ♖, ♕" "♗, ♖, ♔, ♘, ♘, ♕, ♖, ♗" "♘, ♕, ♗, ♖, ♔, ♗, ♘, ♖" "♖, ♔, ♘, ♘, ♕, ♖, ♗, ♗")
|
http://rosettacode.org/wiki/Gapful_numbers
|
Gapful numbers
|
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the
first and last digit are known as gapful numbers.
Evenly divisible means divisible with no remainder.
All one─ and two─digit numbers have this property and are trivially excluded. Only
numbers ≥ 100 will be considered for this Rosetta Code task.
Example
187 is a gapful number because it is evenly divisible by the
number 17 which is formed by the first and last decimal digits
of 187.
About 7.46% of positive integers are gapful.
Task
Generate and show all sets of numbers (below) on one line (horizontally) with a title, here on this page
Show the first 30 gapful numbers
Show the first 15 gapful numbers ≥ 1,000,000
Show the first 10 gapful numbers ≥ 1,000,000,000
Related tasks
Harshad or Niven series.
palindromic gapful numbers.
largest number divisible by its digits.
Also see
The OEIS entry: A108343 gapful numbers.
numbersaplenty gapful numbers
|
#ALGOL_68
|
ALGOL 68
|
BEGIN # find some gapful numbers - numbers divisible by f*10 + b #
# where f is the first digit and b is the final digit #
# unary GAPFUL operator - returns TRUE if n is gapful #
# FALSE otherwise #
OP GAPFUL = ( INT n )BOOL:
BEGIN
INT abs n = ABS n;
INT back = abs n MOD 10; # final digit #
INT front := abs n OVER 10;
WHILE front > 9 DO front OVERAB 10 OD;
abs n MOD ( ( front * 10 ) + back ) = 0
END; # GAPFUL #
# dyadic GAPFUL operator - returns an array of n gapful #
# numbers starting from first #
PRIO GAPFUL = 9;
OP GAPFUL = ( INT n, INT first )[]INT:
BEGIN
[ 1 : n ]INT result;
INT g pos := 0;
FOR i FROM first WHILE g pos < n DO
IF GAPFUL i THEN result[ g pos +:= 1 ] := i FI
OD;
result
END; # GAPFUL #
# prints a sequence of gapful numbers #
PROC print gapful = ( []INT seq, INT start )VOID:
BEGIN
print( ( "First ", whole( ( UPB seq + 1 ) - LWB seq, 0 )
, " gapful numbers starting from ", whole( start, 0 )
, ":", newline
)
);
FOR i FROM LWB seq TO UPB seq DO print( ( " ", whole( seq[ i ], 0 ) ) ) OD;
print( ( newline ) )
END; # print gapful #
print gapful( 30 GAPFUL 100, 100 );
print gapful( 15 GAPFUL 1 000 000, 1 000 000 );
print gapful( 10 GAPFUL 1 000 000 000, 1 000 000 000 )
END
|
http://rosettacode.org/wiki/Generate_random_chess_position
|
Generate random chess position
|
Task
Generate a random chess position in FEN format.
The position does not have to be realistic or even balanced, but it must comply to the following rules:
there is one and only one king of each color (one black king and one white king);
the kings must not be placed on adjacent squares;
there can not be any pawn in the promotion square (no white pawn in the eighth rank, and no black pawn in the first rank);
including the kings, up to 32 pieces of either color can be placed.
There is no requirement for material balance between sides.
The picking of pieces does not have to comply to a regular chess set --- there can be five knights, twenty rooks, whatever ... as long as the total number of pieces do not exceed thirty-two.
it is white's turn.
It's assumed that both sides have lost castling rights and that there is no possibility for en passant (the FEN should thus end in w - - 0 1).
No requirement is made regarding the probability distribution of your method, but your program should be able to span a reasonably representative sample of all possible positions. For instance, programs that would always generate positions with say five pieces on the board, or with kings on a corner, would not be considered truly random.
|
#J
|
J
|
getlayout=:3 :0
whilst. NB. first two positions are non-adjacent kings
(0{pos) e. (1{pos)+(,-)1 7 8 9
do.
pos=: y?64
end.
)
randboard=:3 :0
n=: ?30 NB. number of non-king pieces on board
layout=: getlayout 2+n NB. where they go
white=: 0 1,?n#2 NB. which ones are white?
pawns=: 0 0,?n#2 NB. where are the pawns?
pawns=: pawns * 1- white*layout e.56+i.8
pawns=: pawns * 1-(1-white)*layout e.i.8
ptyp=: 'pkqbjnPKQBJN'{~(6*white)+1 1,(1-2}.pawns)*2+?n#4
8 8$ptyp layout}64#'.'
)
NB. fen compress a line
fen1=:3 :0
for_n.8-i.8 do.
y=. y rplc (#&'.';":) n
end.
)
NB. translate 8x8 board to fen notation
NB. (just the task specific crippled fen)
b2fen=:3 :0
(}.;|.<@(('/',fen1)"1) y),' w - - 0 1'
)
randfen=:b2fen@randboard
|
http://rosettacode.org/wiki/Gauss-Jordan_matrix_inversion
|
Gauss-Jordan matrix inversion
|
Task
Invert matrix A using Gauss-Jordan method.
A being an n × n matrix.
|
#360_Assembly
|
360 Assembly
|
* Gauss-Jordan matrix inversion 17/01/2021
GAUSSJOR CSECT
USING GAUSSJOR,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
SAVE (14,12) save previous context
ST R13,4(R15) link backward
ST R15,8(R13) link forward
LR R13,R15 set addressability
LA R6,1 i=1
DO WHILE=(C,R6,LE,N) do i=1 to n
LA R7,1 j=1
DO WHILE=(C,R7,LE,N) do j=1 to n
LR R1,R6 i
BCTR R1,0 -1
MH R1,HN *n
LR R0,R7 j
BCTR R0,0 -1
AR R1,R0 (i-1)*n+j-1
SLA R1,2 *4
LE F0,AA(R1) aa(i,j)
LR R1,R6 i
BCTR R1,0 -1
MH R1,HN2 *n*2
LR R0,R7 j
BCTR R0,0 -1
AR R1,R0 (i-1)*n*2+j-1
SLA R1,2 *4
STE F0,TMP(R1) tmp(i,j)=aa(i,j)
LA R7,1(R7) j++
ENDDO , enddo j
LA R7,1 j=1
A R7,N j=n+1
DO WHILE=(C,R7,LE,N2) do j=n+1 to 2*n
LR R1,R6 i
BCTR R1,0 -1
MH R1,HN2 *n*2
LR R0,R7 j
BCTR R0,0 -1
AR R1,R0 (i-1)*n*2+j-1
SLA R1,2 *4
LE F0,=E'0' 0
STE F0,TMP(R1) tmp(i,j)=0
LA R7,1(R7) j++
ENDDO , enddo j
LR R2,R6 i
A R2,N i+n
LR R1,R6 i
BCTR R1,0 -1
MH R1,HN2 *n*2
BCTR R2,0 -1
AR R1,R2 (i+n-1)*n*2+i-1
SLA R1,2 *4
LE F0,=E'1' 1
STE F0,TMP(R1) tmp(i,i+n)=1
LA R6,1(R6) i++
ENDDO , enddo i
LA R6,1 i=1
DO WHILE=(C,R6,LE,N) do r=1 to n
LR R1,R6 r
BCTR R1,0 -1
MH R1,HN2 *n*2
LR R0,R6 r
BCTR R0,0 -1
AR R1,R0 (r-1)*n*2+r-1
SLA R1,2 *4
LE F0,TMP(R1) tmp(r,r)
STE F0,T t=tmp(r,r)
LA R7,1 c=1
DO WHILE=(C,R7,LE,N2) do c=1 to n*2
LR R1,R6 r
BCTR R1,0
MH R1,HN2
LR R0,R7 c
BCTR R0,0
AR R1,R0
SLA R1,2
LE F0,TMP(R1)
LTER F0,F0
BZ *+8
DE F0,T tmp(r,c)/t
LR R1,R6 r
BCTR R1,0
MH R1,HN2
LR R0,R7 c
BCTR R0,0
AR R1,R0
SLA R1,2
STE F0,TMP(R1) tmp(r,c)=tmp(r,c)/t
LA R7,1(R7) c++
ENDDO , enddo c
LA R8,1 i=1
DO WHILE=(C,R8,LE,N) do i=1 to n
IF CR,R8,NE,R6 THEN if i^=r then
LR R1,R8 i
BCTR R1,0
MH R1,HN2
LR R0,R6 r
BCTR R0,0
AR R1,R0
SLA R1,2
LE F0,TMP(R1) tmp(i,r)
STE F0,T t=tmp(i,r)
LA R7,1 c=1
DO WHILE=(C,R7,LE,N2) do c=1 to n*2
LR R2,R8 i
BCTR R2,0
MH R2,HN2
LR R0,R7 c
BCTR R0,0
AR R2,R0
SLA R2,2
LE F0,TMP(R2) f0=tmp(i,c)
LR R1,R6 r
BCTR R1,0
MH R1,HN2
LR R0,R7 c
BCTR R0,0
AR R1,R0
SLA R1,2
LE F2,TMP(R1) f2=tmp(r,c)
LE F4,T t
MER F4,F2 f4=t*tmp(r,c)
SER F0,F4 f0=tmp(i,c)-t*tmp(r,c)
STE F0,TMP(R2) tmp(i,c)=f0
LA R7,1(R7) c++
ENDDO , enddo c
ENDIF , endif
LA R8,1(R8) i++
ENDDO , enddo i
LA R6,1(R6) r++
ENDDO , enddo r
LA R6,1 i=1
DO WHILE=(C,R6,LE,N) do i=1 to n
L R7,N n
LA R7,1(R7) j=n+1
DO WHILE=(C,R7,LE,N2) do j=n+1 to 2*n
LR R2,R7 j
S R2,N -n
LR R1,R6 i
BCTR R1,0
MH R1,HN2 *2*n
LR R0,R7 j
BCTR R0,0
AR R1,R0
SLA R1,2
LE F0,TMP(R1) tmp(i,j)
LR R1,R6 i
BCTR R1,0
MH R1,HN *n
BCTR R2,0
AR R1,R2
SLA R1,2
STE F0,BB(R1) bb(i,j-n)=tmp(i,j)
LA R7,1(R7) j++
ENDDO , enddo j
LA R6,1(R6) i++
ENDDO , enddo i
LA R6,1 i=1
DO WHILE=(C,R6,LE,N) do i=1 to n
LA R3,PG @pg
LA R7,1 j=1
DO WHILE=(C,R7,LE,N) do j=1 to n
LR R1,R6 i
BCTR R1,0
MH R1,HN *n
LR R0,R7 j
BCTR R0,0
AR R1,R0
SLA R1,2
LE F0,BB(R1) bb(i,j)
LA R0,5 number of decimals
BAL R14,FORMATF FormatF(bb(i,j))
MVC 0(13,R3),0(R1) edit
LA R3,13(R3) @pg+=13
LA R7,1(R7) j++
ENDDO , enddo j
XPRNT PG,L'PG print buffer
LA R6,1(R6) i++
ENDDO , enddo i
L R13,4(0,R13) restore previous savearea pointer
RETURN (14,12),RC=0 restore registers from calling save
COPY plig\$_FORMATF.MLC format a float
NN EQU 5
N DC A(NN)
N2 DC A(NN*2)
AA DC E'3.0',E'1.0',E'5.0',E'9.0',E'7.0'
DC E'8.0',E'2.0',E'8.0',E'0.0',E'1.0'
DC E'1.0',E'7.0',E'2.0',E'0.0',E'3.0'
DC E'0.0',E'1.0',E'7.0',E'0.0',E'9.0'
DC E'3.0',E'5.0',E'6.0',E'1.0',E'1.0'
BB DS (NN*NN)E
TMP DS (NN*NN*2)E
T DS E
HN DC AL2(NN)
HN2 DC AL2(NN*2)
PG DC CL80' ' buffer
REGEQU
END GAUSSJOR
|
http://rosettacode.org/wiki/General_FizzBuzz
|
General FizzBuzz
|
Task
Write a generalized version of FizzBuzz that works for any list of factors, along with their words.
This is basically a "fizzbuzz" implementation where the user supplies the parameters.
The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be printed.
For simplicity's sake, assume the user will input an integer as the max number and 3 factors, each with a word associated with them.
For example, given:
>20 #This is the maximum number, supplied by the user
>3 Fizz #The user now enters the starting factor (3) and the word they want associated with it (Fizz)
>5 Buzz #The user now enters the next factor (5) and the word they want associated with it (Buzz)
>7 Baxx #The user now enters the next factor (7) and the word they want associated with it (Baxx)
In other words: For this example, print the numbers 1 through 20, replacing every multiple of 3 with "Fizz", every multiple of 5 with "Buzz", and every multiple of 7 with "Baxx".
In the case where a number is a multiple of at least two factors, print each of the words associated with those factors in the order of least to greatest factor.
For instance, the number 15 is a multiple of both 3 and 5; print "FizzBuzz".
If the max number was 105 instead of 20, you would print "FizzBuzzBaxx" because it's a multiple of 3, 5, and 7.
Output:
1
2
Fizz
4
Buzz
Fizz
Baxx
8
Fizz
Buzz
11
Fizz
13
Baxx
FizzBuzz
16
17
Fizz
19
Buzz
|
#AWK
|
AWK
|
105
3 Fizz
5 Buzz
7 Baxx
|
http://rosettacode.org/wiki/General_FizzBuzz
|
General FizzBuzz
|
Task
Write a generalized version of FizzBuzz that works for any list of factors, along with their words.
This is basically a "fizzbuzz" implementation where the user supplies the parameters.
The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be printed.
For simplicity's sake, assume the user will input an integer as the max number and 3 factors, each with a word associated with them.
For example, given:
>20 #This is the maximum number, supplied by the user
>3 Fizz #The user now enters the starting factor (3) and the word they want associated with it (Fizz)
>5 Buzz #The user now enters the next factor (5) and the word they want associated with it (Buzz)
>7 Baxx #The user now enters the next factor (7) and the word they want associated with it (Baxx)
In other words: For this example, print the numbers 1 through 20, replacing every multiple of 3 with "Fizz", every multiple of 5 with "Buzz", and every multiple of 7 with "Baxx".
In the case where a number is a multiple of at least two factors, print each of the words associated with those factors in the order of least to greatest factor.
For instance, the number 15 is a multiple of both 3 and 5; print "FizzBuzz".
If the max number was 105 instead of 20, you would print "FizzBuzzBaxx" because it's a multiple of 3, 5, and 7.
Output:
1
2
Fizz
4
Buzz
Fizz
Baxx
8
Fizz
Buzz
11
Fizz
13
Baxx
FizzBuzz
16
17
Fizz
19
Buzz
|
#Batch_File
|
Batch File
|
@echo off
rem input range
set /p "range=> "
rem input data (no error-checking)
set "data_ctr=0"
:input_loop
set "data="
set /p "data=> "
if "%data%" equ "" goto count
rem parsing data into 1-based pseudo-array
set /a "data_ctr+=1"
for /f "tokens=1-2 delims= " %%D in ("%data%") do (
set "facto%data_ctr%=%%D"
set "print%data_ctr%=%%E"
)
goto input_loop
rem perform fizzbuzz now
:count
setlocal enabledelayedexpansion
for /l %%C in (1,1,%range%) do (
set "out="
for /l %%X in (1,1,%data_ctr%) do (
set /a "mod=%%C %% facto%%X"
if !mod! equ 0 set "out=!out!!print%%X!"
)
if not defined out (echo %%C) else (echo !out!)
)
pause
exit /b 0
|
http://rosettacode.org/wiki/Hailstone_sequence
|
Hailstone sequence
|
The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.
This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):
hailstone sequence, hailstone numbers
3x + 2 mapping, 3n + 1 problem
Collatz sequence
Hasse's algorithm
Kakutani's problem
Syracuse algorithm, Syracuse problem
Thwaites conjecture
Ulam's problem
The hailstone sequence is also known as hailstone numbers (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).
Task
Create a routine to generate the hailstone sequence for a number.
Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
(But don't show the actual sequence!)
See also
xkcd (humourous).
The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).
The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
|
#Swift
|
Swift
|
func hailstone(var n:Int) -> [Int] {
var arr = [n]
while n != 1 {
if n % 2 == 0 {
n /= 2
} else {
n = (3 * n) + 1
}
arr.append(n)
}
return arr
}
let n = hailstone(27)
println("hailstone(27): \(n[0...3]) ... \(n[n.count-4...n.count-1]) for a count of \(n.count).")
var longest = (n: 1, len: 1)
for i in 1...100_000 {
let new = hailstone(i)
if new.count > longest.len {
longest = (i, new.count)
}
}
println("Longest sequence for numbers under 100,000 is with \(longest.n). Which has \(longest.len) items.")
|
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
|
Generate lower case ASCII alphabet
|
Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code.
During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code:
set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z}
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#Applesoft_BASIC
|
Applesoft BASIC
|
L$="abcdefghijklmnopqrstuvwxyz"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.