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/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
|
#ARM_Assembly
|
ARM Assembly
|
ProgramStart:
mov sp,#0x03000000 ;Init Stack Pointer
mov r4,#0x04000000 ;DISPCNT -LCD Control
mov r2,#0x403 ;4= Layer 2 on / 3= ScreenMode 3
str r2,[r4] ;hardware specific routine, activates Game Boy's bitmap mode
mov r0,#0x61 ;ASCII "a"
mov r2,#ramarea
mov r1,#26
rep_inc_stosb: ;repeatedly store a byte into memory, incrementing the destination and the value stored
; each time.
strB r0,[r2]
add r0,r0,#1
add r2,r2,#1
subs r1,r1,#1
bne rep_inc_stosb
mov r0,#255
strB r0,[r2] ;store a 255 terminator into r1
mov r1,#ramarea
bl PrintString ;Prints a 255-terminated string using a pre-defined bitmap font. Code omitted for brevity
forever:
b forever ;halt the cpu
|
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
|
#newLISP
|
newLISP
|
(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!
|
#Stata
|
Stata
|
mata
a=1,2,3
b="ars longa vita brevis"
swap(a, b)
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!
|
#Swift
|
Swift
|
func swap<T>(inout a: T, inout b: T) {
(a, b) = (b, a)
}
|
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
|
#Emacs_Lisp
|
Emacs Lisp
|
;; lexical-binding: t
(require 'generator)
(iter-defun exp-gen (pow)
(let ((i -1))
(while
(setq i (1+ i))
(iter-yield (expt i pow)))))
(iter-defun flt-gen ()
(let* ((g (exp-gen 2))
(f (exp-gen 3))
(i (iter-next g))
(j (iter-next f)))
(while
(setq i (iter-next g))
(while (> i j)
(setq j (iter-next f)))
(unless (= i j)
(iter-yield i)))))
(let ((g (flt-gen))
(o 'nil))
(dotimes (i 29)
(setq o (iter-next g))
(when (>= i 20)
(print o))))
|
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.
|
#Simula
|
Simula
|
BEGIN
INTEGER PROCEDURE GCD(a, b); INTEGER a, b;
BEGIN
IF a = 0 THEN a := b
ELSE
WHILE 0 < b DO BEGIN INTEGER i;
i := MOD(a, b); a := b; b := i;
END;
GCD := a
END;
INTEGER a, b;
!outint(SYSOUT.IMAGE.MAIN.LENGTH, 0);!OUTIMAGE;!OUTIMAGE;
!SYSOUT.IMAGE :- BLANKS(132); ! this may or may not work;
FOR b := 1 STEP 5 UNTIL 37 DO BEGIN
FOR a := 0 STEP 2 UNTIL 21 DO BEGIN
OUTTEXT(" ("); OUTINT(a, 0);
OUTCHAR(','); OUTINT(b, 2);
OUTCHAR(')'); OUTINT(GCD(a, b), 3);
END;
OUTIMAGE
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.
|
#Slate
|
Slate
|
40902 gcd: 24140
|
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.
|
#Common_Lisp
|
Common Lisp
|
(defun chess960-from-sp-id
(&optional (sp-id (random 360 (make-random-state t))))
(labels
((combinations (lst r)
(cond
((numberp lst)
(combinations (loop for i from 0 while (< i lst) collect i) r))
((= r 1)
(mapcar #'list lst))
(t
(loop for i in lst append
(let ((left (loop for j in lst if (< i j) collect j)))
(mapcar (lambda (c) (cons i c))
(combinations left (1- r))))))))
(enumerate (ary)
(loop for item across ary for index from 0
collect (list index item))))
(let*
((first-bishop -1)
(knight-combo '())
(placements (list
;divisor function to get position piece symbol
(list 4 (lambda (n) (setq first-bishop n)
(1+ (* 2 n))) '♝)
(list 4 (lambda (n) ( - (* 2 n) (if (> n first-bishop) 1 0))) '♝)
(list 6 #'identity '♛)
(list 10 (lambda (n)
(setq knight-combo (nth n (combinations 5 2)))
(car knight-combo)) '♞)
(list 1 (lambda (n) (1- (cadr knight-combo))) '♞)
(list 1 (lambda (n) 0) '♜)
(list 1 (lambda (n) 0) '♚)
(list 1 (lambda (n) 0) '♜)))
(p sp-id)
(ary (make-array 8 :initial-element '-)))
(loop for (divisor func piece) in placements doing
(let* ((n (mod p divisor))
(square (funcall func n)))
(setq p (floor p divisor))
(setq index
(car (nth square (remove-if-not (lambda (p) (eq (cadr p) '-))
(enumerate ary)))))
(setf (aref ary index) piece)))
(list sp-id ary))))
;; demo
(format t "~a~%" (chess960-from-sp-id 518))
(format t "~a~%" (chess960-from-sp-id))
|
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
|
#AppleScript
|
AppleScript
|
on isGapful(n)
set units to n mod 10
set temp to n div 10
repeat until (temp < 10)
set temp to temp div 10
end repeat
return (n mod (temp * 10 + units) = 0)
end isGapful
-- Task code:
on getGapfuls(n, q)
set collector to {}
repeat until ((count collector) = q)
if (isGapful(n)) then set end of collector to n
set n to n + 1
end repeat
return collector
end getGapfuls
local output, astid
set output to {}
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to " "
set end of output to "First 30 gapful numbers ≥ 100:" & linefeed & getGapfuls(100, 30)
set end of output to "First 15 gapful numbers ≥ 1,000,000:" & linefeed & getGapfuls(1000000, 15)
set end of output to "First 10 gapful numbers ≥ 100,000,000:" & linefeed & getGapfuls(1.0E+9, 10)
set AppleScript's text item delimiters to linefeed & linefeed
set output to output as text
set AppleScript's text item delimiters to astid
return output
|
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.
|
#Java
|
Java
|
import static java.lang.Math.abs;
import java.util.Random;
public class Fen {
static Random rand = new Random();
public static void main(String[] args) {
System.out.println(createFen());
}
static String createFen() {
char[][] grid = new char[8][8];
placeKings(grid);
placePieces(grid, "PPPPPPPP", true);
placePieces(grid, "pppppppp", true);
placePieces(grid, "RNBQBNR", false);
placePieces(grid, "rnbqbnr", false);
return toFen(grid);
}
static void placeKings(char[][] grid) {
int r1, c1, r2, c2;
while (true) {
r1 = rand.nextInt(8);
c1 = rand.nextInt(8);
r2 = rand.nextInt(8);
c2 = rand.nextInt(8);
if (r1 != r2 && abs(r1 - r2) > 1 && abs(c1 - c2) > 1)
break;
}
grid[r1][c1] = 'K';
grid[r2][c2] = 'k';
}
static void placePieces(char[][] grid, String pieces, boolean isPawn) {
int numToPlace = rand.nextInt(pieces.length());
for (int n = 0; n < numToPlace; n++) {
int r, c;
do {
r = rand.nextInt(8);
c = rand.nextInt(8);
} while (grid[r][c] != 0 || (isPawn && (r == 7 || r == 0)));
grid[r][c] = pieces.charAt(n);
}
}
static String toFen(char[][] grid) {
StringBuilder fen = new StringBuilder();
int countEmpty = 0;
for (int r = 0; r < 8; r++) {
for (int c = 0; c < 8; c++) {
char ch = grid[r][c];
System.out.printf("%2c ", ch == 0 ? '.' : ch);
if (ch == 0) {
countEmpty++;
} else {
if (countEmpty > 0) {
fen.append(countEmpty);
countEmpty = 0;
}
fen.append(ch);
}
}
if (countEmpty > 0) {
fen.append(countEmpty);
countEmpty = 0;
}
fen.append("/");
System.out.println();
}
return fen.append(" w - - 0 1").toString();
}
}
|
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.
|
#ALGOL_60
|
ALGOL 60
|
begin
comment Gauss-Jordan matrix inversion - 22/01/2021;
integer n;
n:=4;
begin
procedure rref(m); real array m;
begin
integer r, c, i;
real d, w;
for r := 1 step 1 until n do begin
d := m[r,r];
if d notequal 0 then
for c := 1 step 1 until n*2 do
m[r,c] := m[r,c] / d
else
outstring(1,"inversion impossible!\n");
for i := 1 step 1 until n do
if i notequal r then begin
w := m[i,r];
for c := 1 step 1 until n*2 do
m[i,c] := m[i,c] - w * m[r,c]
end
end
end rref;
procedure inverse(mat,inv); real array mat, inv;
begin
integer i, j;
real array aug[1:n,1:n*2];
for i := 1 step 1 until n do begin
for j := 1 step 1 until n do
aug[i,j] := mat[i,j];
for j := 1+n step 1 until n*2 do
aug[i,j] := 0;
aug[i,i+n] := 1
end;
rref(aug);
for i := 1 step 1 until n do
for j := n+1 step 1 until 2*n do
inv[i,j-n] := aug[i,j]
end inverse;
procedure show(c, m); string c; real array m;
begin
integer i, j;
outstring(1,"matrix "); outstring(1,c); outstring(1,"\n");
for i := 1 step 1 until n do begin
for j := 1 step 1 until n do
outreal(1,m[i,j]);
outstring(1,"\n")
end
end show;
integer i;
real array a[1:n,1:n], b[1:n,1:n], c[1:n,1:n];
i:=1; a[i,1]:= 2; a[i,2]:= 1; a[i,3]:= 1; a[i,4]:= 4;
i:=2; a[i,1]:= 0; a[i,2]:=-1; a[i,3]:= 0; a[i,4]:=-1;
i:=3; a[i,1]:= 1; a[i,2]:= 0; a[i,3]:=-2; a[i,4]:= 4;
i:=4; a[i,1]:= 4; a[i,2]:= 1; a[i,3]:= 2; a[i,4]:= 2;
show("a",a);
inverse(a,b);
show("b",b);
inverse(b,c);
show("c",c)
end
end
|
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
|
#BBC_BASIC
|
BBC BASIC
|
REM >genfizzb
INPUT "Maximum number: " max%
INPUT "Number of factors: " n%
DIM factors%(n% - 1)
DIM words$(n% - 1)
FOR i% = 0 TO n% - 1
INPUT "> " factor$
factors%(i%) = VAL(LEFT$(factor$, INSTR(factor$, " ") - 1))
words$(i%) = MID$(factor$, INSTR(factor$, " ") + 1)
NEXT
FOR i% = 1 TO max%
matched% = FALSE
FOR j% = 0 TO n% - 1
IF i% MOD factors%(j%) = 0 THEN
PRINT words$(j%);
matched% = TRUE
ENDIF
NEXT
IF matched% THEN PRINT ELSE PRINT;i%
NEXT
|
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
|
#BQN
|
BQN
|
GenFizzBuzz ← {factors‿words ← <˘⍉>𝕨 ⋄ (∾´∾⟜words/˜·(¬∨´)⊸∾0=factors|⊢)¨1+↕𝕩}
|
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).
|
#Tcl
|
Tcl
|
proc hailstone n {
while 1 {
lappend seq $n
if {$n == 1} {return $seq}
set n [expr {$n & 1 ? $n*3+1 : $n/2}]
}
}
set h27 [hailstone 27]
puts "h27 len=[llength $h27]"
puts "head4 = [lrange $h27 0 3]"
puts "tail4 = [lrange $h27 end-3 end]"
set maxlen [set max 0]
for {set i 1} {$i<100000} {incr i} {
set l [llength [hailstone $i]]
if {$l>$maxlen} {set maxlen $l;set max $i}
}
puts "max is $max, with length $maxlen"
|
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
|
#Arturo
|
Arturo
|
print to [:char] 97..122
|
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
|
#ATS
|
ATS
|
(* ****** ****** *)
//
// How to compile:
//
// patscc -DATS_MEMALLOC_LIBC -o lowercase lowercase.dats
//
(* ****** ****** *)
//
#include
"share/atspre_staload.hats"
//
(* ****** ****** *)
implement
main0 () =
{
//
val N = 26
//
val A =
arrayref_tabulate_cloref<char>
(
i2sz(N), lam(i) => int2char0(char2int0('a') + sz2i(i))
) (* end of [val] *)
//
} (* end of [main0] *)
|
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
|
#Nickle
|
Nickle
|
printf("Hello world!\n")
|
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!
|
#Tcl
|
Tcl
|
proc swap {aName bName} {
upvar 1 $aName a $bName b
lassign [list $a $b] b a
}
|
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
|
#Erlang
|
Erlang
|
-module( generator ).
-export( [filter/2, next/1, power/1, task/0] ).
filter( Source_pid, Remove_pid ) ->
First_remove = next( Remove_pid ),
erlang:spawn( fun() -> filter_loop(Source_pid, Remove_pid, First_remove) end ).
next( Pid ) ->
Pid ! {next, erlang:self()},
receive X -> X end.
power( M ) -> erlang:spawn( fun() -> power_loop(M, 0) end ).
task() ->
Squares_pid = power( 2 ),
Cubes_pid = power( 3 ),
Filter_pid = filter( Squares_pid, Cubes_pid ),
[next(Filter_pid) || _X <- lists:seq(1, 20)],
[next(Filter_pid) || _X <- lists:seq(1, 10)].
filter_loop( Pid1, Pid2, N2 ) ->
receive
{next, Pid} ->
{N, New_N2} = filter_loop_next( next(Pid1), N2, Pid1, Pid2 ),
Pid ! N
end,
filter_loop( Pid1, Pid2, New_N2 ).
filter_loop_next( N1, N2, Pid1, Pid2 ) when N1 > N2 -> filter_loop_next( N1, next(Pid2), Pid1, Pid2 );
filter_loop_next( N, N, Pid1, Pid2 ) -> filter_loop_next( next(Pid1), next(Pid2), Pid1, Pid2 );
filter_loop_next( N1, N2, _Pid1, _Pid2 ) -> {N1, N2}.
power_loop( M, N ) ->
receive {next, Pid} -> Pid ! erlang:round(math:pow(N, M) ) end,
power_loop( M, N + 1 ).
|
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.
|
#Smalltalk
|
Smalltalk
|
(40902 gcd: 24140) displayNl
|
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.
|
#SNOBOL4
|
SNOBOL4
|
define('gcd(i,j)') :(gcd_end)
gcd ?eq(i,0) :s(freturn)
?eq(j,0) :s(freturn)
loop gcd = remdr(i,j)
gcd = ?eq(gcd,0) j :s(return)
i = j
j = gcd :(loop)
gcd_end
output = gcd(1071,1029)
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.
|
#D
|
D
|
void main() {
import std.stdio, std.range, std.algorithm, std.string, permutations2;
const pieces = "KQRrBbNN";
alias I = indexOf;
auto starts = pieces.dup.permutations.filter!(p =>
I(p, 'B') % 2 != I(p, 'b') % 2 && // Bishop constraint.
// King constraint.
((I(p, 'r') < I(p, 'K') && I(p, 'K') < I(p, 'R')) ||
(I(p, 'R') < I(p, 'K') && I(p, 'K') < I(p, 'r'))))
.map!toUpper.array.sort().uniq;
writeln(starts.walkLength, "\n", starts.front);
}
|
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
|
#Arturo
|
Arturo
|
gapful?: function [n][
s: to :string n
divisor: to :integer (first s) ++ last s
0 = n % divisor
]
specs: [100 30, 1000000 15, 1000000000 10, 7123 25]
loop specs [start,count][
print "----------------------------------------------------------------"
print ["first" count "gapful numbers starting from" start]
print "----------------------------------------------------------------"
i: start
took: 0
while [took < count][
if gapful? i [
prints i
prints " "
took: took + 1
]
i: i + 1
]
print "\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.
|
#JavaScript
|
JavaScript
|
Array.prototype.shuffle = function() {
for (let i = this.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * (i + 1));
[this[i], this[j]] = [this[j], this[i]];
}
}
function randomFEN() {
let board = [];
for (let x = 0; x < 8; x++) board.push('. . . . . . . .'.split(' '));
function getRandPos() {
return [Math.floor(Math.random() * 8), Math.floor(Math.random() * 8)];
}
function isOccupied(pos) {
return board[pos[0]][pos[1]] != '.';
}
function isAdjacent(pos1, pos2) {
if (pos1[0] == pos2[0] || pos1[0] == pos2[0]-1 || pos1[0] == pos2[0]+1)
if (pos1[1] == pos2[1] || pos1[1] == pos2[1]-1 || pos1[1] == pos2[1]+1)
return true;
return false;
}
// place kings
let wk, bk;
do { wk = getRandPos(); bk = getRandPos(); }
while (isAdjacent(wk, bk));
board[wk[0]][wk[1]] = 'K';
board[bk[0]][bk[1]] = 'k';
// get peaces
let peaces = [];
let names = 'PRNBQ';
function pick() {
for (x = 1; x < Math.floor(Math.random() * 32); x++)
peaces.push(names[Math.floor(Math.random() * names.length)]);
}
pick();
names = names.toLowerCase();
pick();
peaces.shuffle();
// place peaces
while (peaces.length > 0) {
let p = peaces.shift(), pos;
// paws: cannot be placed in bottom or top row
if (p == 'p' || p == 'P')
do { pos = getRandPos() }
while (isOccupied(pos) || pos[0] == 0 || pos[0] == 7);
// everything else
else do { pos = getRandPos(); } while (isOccupied(pos));
board[pos[0]][pos[1]] = p;
}
// write FEN
let fen = [];
for (x = 0; x < board.length; x++) {
let str ='', buf = 0;
for (let y = 0; y < board[x].length; y++)
if (board[x][y] == '.') buf++;
else {
if (buf > 0) { str += buf; buf = 0; }
str += board[x][y];
}
if (buf > 0) str += buf;
fen.push(str);
}
fen = fen.join('/') + ' w - - 0 1';
console.table(board); // for demonstrating purpose
return fen;
}
// example
console.log(randomFEN());
|
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.
|
#ALGOL_68
|
ALGOL 68
|
BEGIN # Gauss-Jordan matrix inversion #
PROC rref = ( REF[,]REAL m )VOID:
BEGIN
INT n = 1 UPB m;
FOR r TO n DO
REAL d = m[ r, r ];
IF d /= 0 THEN
FOR c TO n * 2 DO m[ r, c ] := m[ r, c ] / d OD
ELSE
print( ( "inversion impossible!", newline ) )
FI;
FOR i TO n DO
IF i /= r THEN
REAL w = m[ i, r ];
FOR c TO n * 2 DO m[ i, c ] := m[ i, c ] - w * m[ r, c ] OD
FI
OD
OD
END # rref # ;
PROC inverse = ( REF[,]REAL mat )[,]REAL:
BEGIN
INT n = 1 UPB mat;
[ 1 : n, 1 : n ]REAL inv;
[ 1 : n, 1 : n * 2 ]REAL aug;
FOR i TO n DO
FOR j TO n DO aug[ i, j ] := mat[ i, j ] OD;
FOR j FROM 1 + n TO n * 2 DO aug[ i, j ] := 0 OD;
aug[ i, i + n ] := 1
OD;
rref( aug );
FOR i TO n DO
FOR j FROM n + 1 TO 2 * n DO inv[ i, j - n ] := aug[ i, j ] OD
OD;
inv
END # inverse # ;
PROC show = ( STRING c, [,]REAL m )VOID:
BEGIN
INT n = 1 UPB m;
print( ( "matrix ", c, newline ) );
FOR i TO n DO
FOR j TO n DO print( ( " ", fixed( m[ i, j ], -8, 3 ) ) ) OD;
print( ( newline ) )
OD
END # show #;
INT n = 4;
[ 1 : n, 1 : n ]REAL a, b, c;
a := [,]REAL( ( 2, 1, 1, 4 )
, ( 0, -1, 0, -1 )
, ( 1, 0, -2, 4 )
, ( 4, 1, 2, 2 )
);
show( "a", a );
b := inverse( a );
show( "b", b );
c := inverse( b );
show( "c", c )
END
|
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
|
#C
|
C
|
#include <stdio.h>
#include <stdlib.h>
struct replace_info {
int n;
char *text;
};
int compare(const void *a, const void *b)
{
struct replace_info *x = (struct replace_info *) a;
struct replace_info *y = (struct replace_info *) b;
return x->n - y->n;
}
void generic_fizz_buzz(int max, struct replace_info *info, int info_length)
{
int i, it;
int found_word;
for (i = 1; i < max; ++i) {
found_word = 0;
/* Assume sorted order of values in the info array */
for (it = 0; it < info_length; ++it) {
if (0 == i % info[it].n) {
printf("%s", info[it].text);
found_word = 1;
}
}
if (0 == found_word)
printf("%d", i);
printf("\n");
}
}
int main(void)
{
struct replace_info info[3] = {
{5, "Buzz"},
{7, "Baxx"},
{3, "Fizz"}
};
/* Sort information array */
qsort(info, 3, sizeof(struct replace_info), compare);
/* Print output for generic FizzBuzz */
generic_fizz_buzz(20, info, 3);
return 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).
|
#TI-83_BASIC
|
TI-83 BASIC
|
prompt N
N→M: 0→X: 1→L
While L=1
X+1→X
Disp M
If M=1
Then: 0→L
Else
If remainder(M,2)=1
Then: 3*M+1→M
Else: M/2→M
End
End
End
{N,X}
|
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
|
#AutoHotkey
|
AutoHotkey
|
a :={}
Loop, 26
a.Insert(Chr(A_Index + 96))
|
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
|
#Nim
|
Nim
|
echo("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!
|
#ThinBASIC
|
ThinBASIC
|
Swap Var1, Var2
|
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
|
#F.23
|
F#
|
let m n = Seq.unfold(fun i -> Some(bigint.Pow(i, n), i + 1I)) 0I
let squares = m 2
let cubes = m 3
let (--) orig veto = Seq.where(fun n -> n <> (Seq.find(fun m -> m >= n) veto)) orig
let ``squares without cubes`` = squares -- cubes
Seq.take 10 (Seq.skip 20 (``squares without cubes``))
|> Seq.toList |> printfn "%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.
|
#Sparkling
|
Sparkling
|
function factors(n) {
var f = {};
for var i = 2; n > 1; i++ {
while n % i == 0 {
n /= i;
f[i] = f[i] != nil ? f[i] + 1 : 1;
}
}
return f;
}
function GCD(n, k) {
let f1 = factors(n);
let f2 = factors(k);
let fs = map(f1, function(factor, multiplicity) {
let m = f2[factor];
return m == nil ? 0 : min(m, multiplicity);
});
let rfs = {};
foreach(fs, function(k, v) {
rfs[sizeof rfs] = pow(k, v);
});
return reduce(rfs, 1, function(x, y) { return x * y; });
}
function LCM(n, k) {
return n * k / GCD(n, k);
}
|
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.
|
#SQL
|
SQL
|
DROP TABLE tbl;
CREATE TABLE tbl
(
u NUMBER,
v NUMBER
);
INSERT INTO tbl ( u, v ) VALUES ( 20, 50 );
INSERT INTO tbl ( u, v ) VALUES ( 21, 50 );
INSERT INTO tbl ( u, v ) VALUES ( 21, 51 );
INSERT INTO tbl ( u, v ) VALUES ( 22, 50 );
INSERT INTO tbl ( u, v ) VALUES ( 22, 55 );
commit;
WITH
FUNCTION gcd ( ui IN NUMBER, vi IN NUMBER )
RETURN NUMBER
IS
u NUMBER := ui;
v NUMBER := vi;
t NUMBER;
BEGIN
while v > 0
loop
t := u;
u := v;
v:= MOD(t, v );
END loop;
RETURN abs(u);
END gcd;
SELECT u, v, gcd ( u, v )
FROM tbl
/
|
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.
|
#EchoLisp
|
EchoLisp
|
(define-values (K Q R B N) (iota 5))
(define *pos* (list R N B Q K B N R)) ;; standard starter
;; check opposite color bishops, and King between rooks
(define (legal-pos p)
(and
(> (list-index K p) (list-index R p))
(> (list-index K (reverse p)) (list-index R (reverse p)))
(even? (+ (list-index B p) (list-index B (reverse p))))))
;; random shuffle current position until a legal one is found
(define (c960)
(set! *pos* (shuffle *pos*))
(if (legal-pos *pos*)
(map unicode-piece *pos*) (c960)))
|
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
|
#AutoHotkey
|
AutoHotkey
|
Gapful_numbers(Min, Qty){
counter:= 0, output := ""
while (counter < Qty){
n := A_Index+Min-1
d := SubStr(n, 1, 1) * 10 + SubStr(n, 0)
if (n/d = Floor(n/d))
output .= ++counter ": " n "`t" n " / " d " = " Format("{:d}", n/d) "`n"
}
return output
}
|
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.
|
#Julia
|
Julia
|
module Chess
using Printf
struct King end
struct Pawn end
function placepieces!(grid, ::King)
axis = axes(grid, 1)
while true
r1, c1, r2, c2 = rand(axis, 4)
if r1 != r2 && abs(r1 - r2) > 1 && abs(c1 - c2) > 1
grid[r1, c1] = '♚'
grid[r2, c2] = '♔'
return grid
end
end
end
function placepieces!(grid, ch)
axis = axes(grid, 1)
while true
r, c = rand(axis, 2)
if grid[r, c] == ' '
grid[r, c] = ch
return grid
end
end
end
function placepieces!(grid, ch, ::Pawn)
axis = axes(grid, 1)
while true
r, c = rand(axis, 2)
if grid[r, c] == ' ' && r ∉ extrema(axis)
grid[r, c] = ch
return grid
end
end
end
function randposition!(grid)
placepieces!(grid, King())
foreach("♙♙♙♙♙♙♙♙♙♟♟♟♟♟♟♟♟") do ch
placepieces!(grid, ch, Pawn())
end
foreach("♖♘♗♕♗♘♖♜♞♝♛♝♞♜") do ch
placepieces!(grid, ch)
end
return grid
end
printgrid(grid) = println(join((join(grid[r, :], ' ') for r in 1:size(grid, 1)), '\n'))
end # module Chess
|
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.
|
#Kotlin
|
Kotlin
|
// version 1.2.0
import java.util.Random
import kotlin.math.abs
val rand = Random()
val grid = List(8) { CharArray(8) }
const val NUL = '\u0000'
fun createFen(): String {
placeKings()
placePieces("PPPPPPPP", true)
placePieces("pppppppp", true)
placePieces("RNBQBNR", false)
placePieces("rnbqbnr", false)
return toFen()
}
fun placeKings() {
while (true) {
val r1 = rand.nextInt(8)
val c1 = rand.nextInt(8)
val r2 = rand.nextInt(8)
val c2 = rand.nextInt(8)
if (r1 != r2 && abs(r1 - r2) > 1 && abs(c1 - c2) > 1) {
grid[r1][c1] = 'K'
grid[r2][c2] = 'k'
return
}
}
}
fun placePieces(pieces: String, isPawn: Boolean) {
val numToPlace = rand.nextInt(pieces.length)
for (n in 0 until numToPlace) {
var r: Int
var c: Int
do {
r = rand.nextInt(8)
c = rand.nextInt(8)
}
while (grid[r][c] != NUL || (isPawn && (r == 7 || r == 0)))
grid[r][c] = pieces[n]
}
}
fun toFen(): String {
val fen = StringBuilder()
var countEmpty = 0
for (r in 0..7) {
for (c in 0..7) {
val ch = grid[r][c]
print ("%2c ".format(if (ch == NUL) '.' else ch))
if (ch == NUL) {
countEmpty++
}
else {
if (countEmpty > 0) {
fen.append(countEmpty)
countEmpty = 0
}
fen.append(ch)
}
}
if (countEmpty > 0) {
fen.append(countEmpty)
countEmpty = 0
}
fen.append("/")
println()
}
return fen.append(" w - - 0 1").toString()
}
fun main(args: Array<String>) {
println(createFen())
}
|
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.
|
#C
|
C
|
/*----------------------------------------------------------------------
gjinv - Invert a matrix, Gauss-Jordan algorithm
A is destroyed. Returns 1 for a singular matrix.
___Name_____Type______In/Out____Description_____________________________
a[n*n] double* In An N by N matrix
n int In Order of matrix
b[n*n] double* Out Inverse of A
----------------------------------------------------------------------*/
#include <math.h>
int gjinv (double *a, int n, double *b)
{
int i, j, k, p;
double f, g, tol;
if (n < 1) return -1; /* Function Body */
f = 0.; /* Frobenius norm of a */
for (i = 0; i < n; ++i) {
for (j = 0; j < n; ++j) {
g = a[j+i*n];
f += g * g;
}
}
f = sqrt(f);
tol = f * 2.2204460492503131e-016;
for (i = 0; i < n; ++i) { /* Set b to identity matrix. */
for (j = 0; j < n; ++j) {
b[j+i*n] = (i == j) ? 1. : 0.;
}
}
for (k = 0; k < n; ++k) { /* Main loop */
f = fabs(a[k+k*n]); /* Find pivot. */
p = k;
for (i = k+1; i < n; ++i) {
g = fabs(a[k+i*n]);
if (g > f) {
f = g;
p = i;
}
}
if (f < tol) return 1; /* Matrix is singular. */
if (p != k) { /* Swap rows. */
for (j = k; j < n; ++j) {
f = a[j+k*n];
a[j+k*n] = a[j+p*n];
a[j+p*n] = f;
}
for (j = 0; j < n; ++j) {
f = b[j+k*n];
b[j+k*n] = b[j+p*n];
b[j+p*n] = f;
}
}
f = 1. / a[k+k*n]; /* Scale row so pivot is 1. */
for (j = k; j < n; ++j) a[j+k*n] *= f;
for (j = 0; j < n; ++j) b[j+k*n] *= f;
for (i = 0; i < n; ++i) { /* Subtract to get zeros. */
if (i == k) continue;
f = a[k+i*n];
for (j = k; j < n; ++j) a[j+i*n] -= a[j+k*n] * f;
for (j = 0; j < n; ++j) b[j+i*n] -= b[j+k*n] * f;
}
}
return 0;
} /* end of gjinv */
|
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
|
#C.23
|
C#
|
using System;
public class GeneralFizzBuzz
{
public static void Main()
{
int i;
int j;
int k;
int limit;
string iString;
string jString;
string kString;
Console.WriteLine("First integer:");
i = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("First string:");
iString = Console.ReadLine();
Console.WriteLine("Second integer:");
j = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Second string:");
jString = Console.ReadLine();
Console.WriteLine("Third integer:");
k = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Third string:");
kString = Console.ReadLine();
Console.WriteLine("Limit (inclusive):");
limit = Convert.ToInt32(Console.ReadLine());
for(int n = 1; n<= limit; n++)
{
bool flag = true;
if(n%i == 0)
{
Console.Write(iString);
flag = false;
}
if(n%j == 0)
{
Console.Write(jString);
flag = false;
}
if(n%k == 0)
{
Console.Write(kString);
flag = false;
}
if(flag)
Console.Write(n);
Console.WriteLine();
}
}
}
|
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).
|
#Transd
|
Transd
|
#lang transd
MainModule: {
hailstone: (λ n Int()
(with seq Vector<Int>([n])
(while (> n 1)
(= n (if (mod n 2) (+ (* 3 n) 1)
else (/ n 2)))
(append seq n)
)
(ret seq)
)
),
_start: (λ
(with h (hailstone 27) l 0 n 0 t 0
(lout "Length of (27): " (size h))
(lout "First 4 of (27): " Range(in: h 0 4))
(lout "Last 4 of (27): " Range(in: h -4 -0))
(for i in Range(100000) do
(= t (size (hailstone (to-Int i)))) (if (> t l) (= l t) (= n i))
)
(lout "For n < 100.000 the max. sequence length is " l " for " n)
)
)
}
|
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
|
#AutoIt
|
AutoIt
|
Func _a2z()
Local $a2z = ""
For $i = 97 To 122
$a2z &= Chr($i)
Next
Return $a2z
EndFunc
|
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
|
#Nit
|
Nit
|
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!
|
#TI-89_BASIC
|
TI-89 BASIC
|
Define swap(swapvar1, swapvar2) = Prgm
Local swaptmp
#swapvar1 → swaptmp
#swapvar2 → #swapvar1
swaptmp → #swapvar2
EndPrgm
1 → x
2 → y
swap("x", "y")
x
2
y
1
|
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!
|
#Tiny_BASIC
|
Tiny BASIC
|
LET a = 11
LET b = 22
PRINT a, " ", b
GOSUB 100
PRINT a, " ", b
END
100 REM swap(a, b)
LET t = a
LET a = b
LET b = t
RETURN
|
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
|
#Factor
|
Factor
|
USING: fry kernel lists lists.lazy math math.functions
prettyprint ;
IN: rosetta-code.generator-exponential
: mth-powers-generator ( m -- lazy-list )
[ 0 lfrom ] dip [ ^ ] curry lmap-lazy ;
: lmember? ( elt list -- ? )
over '[ unswons dup _ >= ] [ drop ] until nip = ;
: 2-not-3-generator ( -- lazy-list )
2 mth-powers-generator
[ 3 mth-powers-generator lmember? not ] <lazy-filter> ;
10 2-not-3-generator 20 [ cdr ] times ltake list>array .
|
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.
|
#Standard_ML
|
Standard ML
|
(* Euclid’s algorithm. *)
fun gcd (u, v) =
let
fun loop (u, v) =
if v = 0 then
u
else
loop (v, u mod v)
in
loop (abs u, abs v)
end
(* Using the Rosetta Code example for assertions in Standard ML. *)
fun assert cond =
if cond then () else raise Fail "assert"
val () = assert (gcd (0, 0) = 0)
val () = assert (gcd (0, 10) = 10)
val () = assert (gcd (~10, 0) = 10)
val () = assert (gcd (9, 6) = 3)
val () = assert (gcd (~6, ~9) = 3)
val () = assert (gcd (40902, 24140) = 34)
val () = assert (gcd (40902, ~24140) = 34)
val () = assert (gcd (~40902, 24140) = 34)
val () = assert (gcd (~40902, ~24140) = 34)
val () = assert (gcd (24140, 40902) = 34)
val () = assert (gcd (~24140, 40902) = 34)
val () = assert (gcd (24140, ~40902) = 34)
val () = assert (gcd (~24140, ~40902) = 34)
|
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.
|
#Stata
|
Stata
|
function gcd(a_,b_) {
a = abs(a_)
b = abs(b_)
while (b>0) {
a = mod(a,b)
swap(a,b)
}
return(a)
}
|
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.
|
#Elixir
|
Elixir
|
defmodule Chess960 do
@pieces ~w(♔ ♕ ♘ ♘ ♗ ♗ ♖ ♖) # ~w(K Q N N B B R R)
@regexes [~r/♗(..)*♗/, ~r/♖.*♔.*♖/] # [~r/B(..)*B/, ~r/R.*K.*R/]
def shuffle do
row = Enum.shuffle(@pieces) |> Enum.join
if Enum.all?(@regexes, &Regex.match?(&1, row)), do: row, else: shuffle
end
end
Enum.each(1..5, fn _ -> IO.puts Chess960.shuffle 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.
|
#Factor
|
Factor
|
USING: io kernel math random sequences ;
IN: rosetta-code.chess960
: empty ( seq -- n ) 32 swap indices random ; ! return a random empty index (i.e. equal to 32) of seq
: next ( seq -- n ) 32 swap index ; ! return the leftmost empty index of seq
: place ( seq elt n -- seq' ) rot [ set-nth ] keep ; ! set nth member of seq to elt, keeping seq on the stack
: white-bishop ( -- elt n ) CHAR: ♗ 4 random 2 * ;
: black-bishop ( -- elt n ) white-bishop 1 + ;
: queen ( seq -- seq elt n ) CHAR: ♕ over empty ;
: knight ( seq -- seq elt n ) CHAR: ♘ over empty ;
: rook ( seq -- seq elt n ) CHAR: ♖ over next ;
: king ( seq -- seq elt n ) CHAR: ♔ over next ;
: chess960 ( -- str )
" " clone
black-bishop place
white-bishop place
queen place
knight place
knight place
rook place
king place
rook place ;
: chess960-demo ( -- ) 5 [ chess960 print ] times ;
MAIN: chess960-demo
|
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
|
#AWK
|
AWK
|
# syntax: GAWK -f GAPFUL_NUMBERS.AWK
# converted from C++
BEGIN {
show_gapful(100,30)
show_gapful(1000000,15)
show_gapful(1000000000,10)
show_gapful(7123,25)
exit(0)
}
function is_gapful(n, m) {
m = n
while (m >= 10) {
m = int(m / 10)
}
return(n % ((n % 10) + 10 * (m % 10)) == 0)
}
function show_gapful(n, count,i) {
printf("first %d gapful numbers >= %d:",count,n)
for (i=0; i<count; n++) {
if (is_gapful(n)) {
printf(" %d",n)
i++
}
}
printf("\n")
}
|
http://rosettacode.org/wiki/Gaussian_elimination
|
Gaussian elimination
|
Task
Solve Ax=b using Gaussian elimination then backwards substitution.
A being an n by n matrix.
Also, x and b are n by 1 vectors.
To improve accuracy, please use partial pivoting and scaling.
See also
the Wikipedia entry: Gaussian elimination
|
#11l
|
11l
|
F swap_row(&a, &b, r1, r2)
I r1 != r2
swap(&a[r1], &a[r2])
swap(&b[r1], &b[r2])
F gauss_eliminate(&a, &b)
L(dia) 0 .< a.len
V (max_row, max) = (dia, a[dia][dia])
L(row) dia+1 .< a.len
V tmp = abs(a[row][dia])
I tmp > max
(max_row, max) = (row, tmp)
swap_row(&a, &b, dia, max_row)
L(row) dia+1 .< a.len
V tmp = a[row][dia] / a[dia][dia]
L(col) dia+1 .< a.len
a[row][col] -= tmp * a[dia][col]
a[row][dia] = 0
b[row] -= tmp * b[dia]
V r = [0.0] * a.len
L(row) (a.len-1 .. 0).step(-1)
V tmp = b[row]
L(j) (a.len-1 .< row).step(-1)
tmp -= r[j] * a[row][j]
r[row] = tmp / a[row][row]
R r
V a = [[1.00, 0.00, 0.00, 0.00, 0.00, 0.00],
[1.00, 0.63, 0.39, 0.25, 0.16, 0.10],
[1.00, 1.26, 1.58, 1.98, 2.49, 3.13],
[1.00, 1.88, 3.55, 6.70, 12.62, 23.80],
[1.00, 2.51, 6.32, 15.88, 39.90, 100.28],
[1.00, 3.14, 9.87, 31.01, 97.41, 306.02]]
V b = [-0.01, 0.61, 0.91, 0.99, 0.60, 0.02]
print(gauss_eliminate(&a, &b))
|
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.
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
g = ConstantArray["", {8, 8}];
While[Norm@First@Differences[r = RandomChoice[Tuples[Range[8], 2], 2]] <= Sqrt[2], Null];
g = ReplacePart[g, {r[[1]] -> "K", r[[2]] -> "k"}];
avail = Position[g, "", {2}];
n = RandomInteger[{2, 14}];
rls = Thread[RandomSample[avail, n] -> RandomChoice[Characters@"NBRQnbrq", n]];
g = ReplacePart[g, rls];
avail = RandomSample[DeleteCases[Position[g, "", {2}], {8, _}], RandomInteger[{2, 8}]];
g = ReplacePart[g, Thread[avail -> "P"]];
avail = RandomSample[DeleteCases[Position[g, "", {2}], {1, _}], RandomInteger[{2, 8}]];
g = ReplacePart[g, Thread[avail -> "p"]];
g //= Map[Split];
g = g /. (x : {"" ..}) :> ToString[Length[x]];
g //= Map[StringJoin@*Flatten];
g = StringRiffle[Reverse[g], "/"];
g = g <> " w - - 0 1";
g
|
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.
|
#Nim
|
Nim
|
import random
type
Piece {.pure.} = enum
None
WhiteBishop = ('B', "♗")
WhiteKing = ('K', "♔")
WhiteKnight = ('N', "♘")
WhitePawn = ('P', "♙")
WhiteQueen = ('Q', "♕")
WhiteRook = ('R', "♖")
BlackBishop = ('b', "♝")
BlackKing = ('k', "♚")
BlackKnight = ('n', "♞")
BlackPawn = ('p', "♟")
BlackQueen = ('q', "♛")
BlackRook = ('r', "♜")
Color {.pure.} = enum White, Black
Grid = array[8, array[8, Piece]]
const
# White pieces except king and pawns.
WhitePieces = [WhiteQueen, WhiteRook, WhiteRook, WhiteBishop,
WhiteBishop, WhiteKnight, WhiteKnight]
# Black pieces except king and pawns.
BlackPieces = [BlackQueen, BlackRook, BlackRook, BlackBishop,
BlackBishop, BlackKnight, BlackKnight]
proc placeKings(grid: var Grid) =
while true:
let r1 = rand(7)
let c1 = rand(7)
let r2 = rand(7)
let c2 = rand(7)
if r1 != r2 and abs(r1 - r2) > 1 and abs(c1 - c2) > 1:
grid[r1][c1] = WhiteKing
grid[r2][c2] = BlackKing
break
proc placePawns(grid: var Grid; color: Color) =
let piece = if color == White: WhitePawn else: BlackPawn
let numToPlace = rand(8)
for n in 0..<numToPlace:
var r, c: int
while true:
r = rand(7)
c = rand(7)
if grid[r][c] == None and r notin {0, 7}: break
grid[r][c] = piece
proc placePieces(grid: var Grid; color: Color) =
var pieces = if color == White: WhitePieces else: BlackPieces
pieces.shuffle()
let numToPlace = rand(7)
for n in 0..<numToPlace:
var r, c: int
while true:
r = rand(7)
c = rand(7)
if grid[r][c] == None: break
grid[r][c] = pieces[n]
proc toFen(grid: Grid): string =
var countEmpty = 0
for r in 0..7:
for c in 0..7:
let piece = grid[r][c]
if piece == None:
stdout.write " . "
inc countEmpty
else:
stdout.write ' ' & $piece & ' '
if countEmpty > 0:
result.add $countEmpty
countEmpty = 0
result.add chr(ord(piece))
if countEmpty > 0:
result.add $countEmpty
countEmpty = 0
result.add '/'
echo ""
result.add " w - - 0 1"
proc createFen(): string =
var grid: Grid
grid.placeKings()
grid.placePawns(White)
grid.placePawns(Black)
grid.placePieces(White)
grid.placePieces(Black)
result = grid.toFen()
randomize()
echo createFen()
|
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.
|
#C.23
|
C#
|
using System;
namespace Rosetta
{
internal class Vector
{
private double[] b;
internal readonly int rows;
internal Vector(int rows)
{
this.rows = rows;
b = new double[rows];
}
internal Vector(double[] initArray)
{
b = (double[])initArray.Clone();
rows = b.Length;
}
internal Vector Clone()
{
Vector v = new Vector(b);
return v;
}
internal double this[int row]
{
get { return b[row]; }
set { b[row] = value; }
}
internal void SwapRows(int r1, int r2)
{
if (r1 == r2) return;
double tmp = b[r1];
b[r1] = b[r2];
b[r2] = tmp;
}
internal double norm(double[] weights)
{
double sum = 0;
for (int i = 0; i < rows; i++)
{
double d = b[i] * weights[i];
sum += d*d;
}
return Math.Sqrt(sum);
}
internal void print()
{
for (int i = 0; i < rows; i++)
Console.WriteLine(b[i]);
Console.WriteLine();
}
public static Vector operator-(Vector lhs, Vector rhs)
{
Vector v = new Vector(lhs.rows);
for (int i = 0; i < lhs.rows; i++)
v[i] = lhs[i] - rhs[i];
return v;
}
}
class Matrix
{
private double[] b;
internal readonly int rows, cols;
internal Matrix(int rows, int cols)
{
this.rows = rows;
this.cols = cols;
b = new double[rows * cols];
}
internal Matrix(int size)
{
this.rows = size;
this.cols = size;
b = new double[rows * cols];
for (int i = 0; i < size; i++)
this[i, i] = 1;
}
internal Matrix(int rows, int cols, double[] initArray)
{
this.rows = rows;
this.cols = cols;
b = (double[])initArray.Clone();
if (b.Length != rows * cols) throw new Exception("bad init array");
}
internal double this[int row, int col]
{
get { return b[row * cols + col]; }
set { b[row * cols + col] = value; }
}
public static Vector operator*(Matrix lhs, Vector rhs)
{
if (lhs.cols != rhs.rows) throw new Exception("I can't multiply matrix by vector");
Vector v = new Vector(lhs.rows);
for (int i = 0; i < lhs.rows; i++)
{
double sum = 0;
for (int j = 0; j < rhs.rows; j++)
sum += lhs[i,j]*rhs[j];
v[i] = sum;
}
return v;
}
internal void SwapRows(int r1, int r2)
{
if (r1 == r2) return;
int firstR1 = r1 * cols;
int firstR2 = r2 * cols;
for (int i = 0; i < cols; i++)
{
double tmp = b[firstR1 + i];
b[firstR1 + i] = b[firstR2 + i];
b[firstR2 + i] = tmp;
}
}
//with partial pivot
internal bool InvPartial()
{
const double Eps = 1e-12;
if (rows != cols) throw new Exception("rows != cols for Inv");
Matrix M = new Matrix(rows); //unitary
for (int diag = 0; diag < rows; diag++)
{
int max_row = diag;
double max_val = Math.Abs(this[diag, diag]);
double d;
for (int row = diag + 1; row < rows; row++)
if ((d = Math.Abs(this[row, diag])) > max_val)
{
max_row = row;
max_val = d;
}
if (max_val <= Eps) return false;
SwapRows(diag, max_row);
M.SwapRows(diag, max_row);
double invd = 1 / this[diag, diag];
for (int col = diag; col < cols; col++)
{
this[diag, col] *= invd;
}
for (int col = 0; col < cols; col++)
{
M[diag, col] *= invd;
}
for (int row = 0; row < rows; row++)
{
d = this[row, diag];
if (row != diag)
{
for (int col = diag; col < this.cols; col++)
{
this[row, col] -= d * this[diag, col];
}
for (int col = 0; col < this.cols; col++)
{
M[row, col] -= d * M[diag, col];
}
}
}
}
b = M.b;
return true;
}
internal void print()
{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
Console.Write(this[i,j].ToString()+" ");
Console.WriteLine();
}
}
}
}
|
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
|
#C.2B.2B
|
C++
|
#include <algorithm>
#include <iostream>
#include <vector>
#include <string>
class pair {
public:
pair( int s, std::string z ) { p = std::make_pair( s, z ); }
bool operator < ( const pair& o ) const { return i() < o.i(); }
int i() const { return p.first; }
std::string s() const { return p.second; }
private:
std::pair<int, std::string> p;
};
void gFizzBuzz( int c, std::vector<pair>& v ) {
bool output;
for( int x = 1; x <= c; x++ ) {
output = false;
for( std::vector<pair>::iterator i = v.begin(); i != v.end(); i++ ) {
if( !( x % ( *i ).i() ) ) {
std::cout << ( *i ).s();
output = true;
}
}
if( !output ) std::cout << x;
std::cout << "\n";
}
}
int main( int argc, char* argv[] ) {
std::vector<pair> v;
v.push_back( pair( 7, "Baxx" ) );
v.push_back( pair( 3, "Fizz" ) );
v.push_back( pair( 5, "Buzz" ) );
std::sort( v.begin(), v.end() );
gFizzBuzz( 20, v );
return 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).
|
#TXR
|
TXR
|
@(do (defun hailstone (n)
(cons n
(gen (not (eq n 1))
(set n (if (evenp n)
(trunc n 2)
(+ (* 3 n) 1)))))))
@(next :list @(mapcar* (fun tostring) (hailstone 27)))
27
82
41
124
@(skip)
8
4
2
1
@(eof)
@(do (let ((max 0) maxi)
(each* ((i (range 1 99999))
(h (mapcar* (fun hailstone) i))
(len (mapcar* (fun length) h)))
(if (> len max)
(progn
(set max len)
(set maxi i))))
(format t "longest sequence is ~a for n = ~a\n" max maxi)))
|
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
|
#AWK
|
AWK
|
# syntax: GAWK -f GENERATE_LOWER_CASE_ASCII_ALPHABET.AWK
BEGIN {
for (i=0; i<=255; i++) {
c = sprintf("%c",i)
if (c ~ /[[:lower:]]/) {
lower_chars = lower_chars c
}
}
printf("%s %d: %s\n",ARGV[0],length(lower_chars),lower_chars)
exit(0)
}
|
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
|
#Nix
|
Nix
|
"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!
|
#Trith
|
Trith
|
swap
|
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!
|
#True_BASIC
|
True BASIC
|
SUB SWAP(a, b)
LET temp = a
LET a = b
LET b = temp
END SUB
LET a = 1
LET b = 2
PRINT a, b
CALL SWAP(a, b)
PRINT a, b
END
|
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
|
#Fantom
|
Fantom
|
class Main
{
// Create and return a function which generates mth powers when called
|->Int| make_generator (Int m)
{
current := 0
return |->Int|
{
current += 1
return (current-1).pow (m)
}
}
|->Int| squares_without_cubes ()
{
squares := make_generator (2)
cubes := make_generator (3)
c := cubes.call
return |->Int|
{
while (true)
{
s := squares.call
while (c < s) { c = cubes.call }
if (c != s) return s
}
return 0
}
}
Void main ()
{
swc := squares_without_cubes ()
20.times { swc.call } // drop 20 values
10.times // display the next 10
{
echo (swc.call)
}
}
}
|
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.
|
#Swift
|
Swift
|
// Iterative
func gcd(var a: Int, var b: Int) -> Int {
a = abs(a); b = abs(b)
if (b > a) { swap(&a, &b) }
while (b > 0) { (a, b) = (b, a % b) }
return a
}
// Recursive
func gcdr (var a: Int, var b: Int) -> Int {
a = abs(a); b = abs(b)
if (b > a) { swap(&a, &b) }
return gcd_rec(a,b)
}
private func gcd_rec(a: Int, b: Int) -> Int {
return b == 0 ? a : gcd_rec(b, a % b)
}
for (a,b) in [(1,1), (100, -10), (10, -100), (-36, -17), (27, 18), (30, -42)] {
println("Iterative: GCD of \(a) and \(b) is \(gcd(a, b))")
println("Recursive: GCD of \(a) and \(b) is \(gcdr(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.
|
#Tcl
|
Tcl
|
package require Tcl 8.5
namespace path {::tcl::mathop ::tcl::mathfunc}
proc gcd_iter {p q} {
while {$q != 0} {
lassign [list $q [% $p $q]] p q
}
abs $p
}
|
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.
|
#Forth
|
Forth
|
\ make starting position for Chess960, constructive
\ 0 1 2 3 4 5 6 7 8 9
create krn S" NNRKRNRNKRNRKNRNRKRNRNNKRRNKNRRNKRNRKNNRRKNRNRKRNN" mem,
create pieces 8 allot
: chess960 ( n -- )
pieces 8 erase
4 /mod swap 2* 1+ pieces + 'B swap c!
4 /mod swap 2* pieces + 'B swap c!
6 /mod swap pieces swap bounds begin dup c@ if swap 1+ swap then 2dup > while 1+ repeat drop 'Q swap c!
5 * krn + pieces 8 bounds do i c@ 0= if dup c@ i c! 1+ then loop drop
cr pieces 8 type ;
0 chess960 \ BBQNNRKR ok
518 chess960 \ RNBQKBNR ok
959 chess960 \ RKRNNQBB ok
960 choose chess960 \ random position
|
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.
|
#Fortran
|
Fortran
|
program chess960
implicit none
integer, pointer :: a,b,c,d,e,f,g,h
integer, target :: p(8)
a => p(1)
b => p(2)
c => p(3)
d => p(4)
e => p(5)
f => p(6)
g => p(7)
h => p(8)
king: do a=2,7 ! King on an internal square
r1: do b=1,a-1 ! R1 left of the King
r2: do c=a+1,8 ! R2 right of the King
b1: do d=1,7,2 ! B1 on an odd square
if (skip_pos(d,4)) cycle
b2: do e=2,8,2 ! B2 on an even square
if (skip_pos(e,5)) cycle
queen: do f=1,8 ! Queen anywhere else
if (skip_pos(f,6)) cycle
n1: do g=1,7 ! First knight
if (skip_pos(g,7)) cycle
n2: do h=g+1,8 ! Second knight (indistinguishable from first)
if (skip_pos(h,8)) cycle
if (sum(p) /= 36) stop 'Loop error' ! Sanity check
call write_position
end do n2
end do n1
end do queen
end do b2
end do b1
end do r2
end do r1
end do king
contains
logical function skip_pos(i, n)
integer, intent(in) :: i, n
skip_pos = any(p(1:n-1) == i)
end function skip_pos
subroutine write_position
integer :: i, j
character(len=15) :: position = ' '
character(len=1), parameter :: names(8) = ['K','R','R','B','B','Q','N','N']
do i=1,8
j = 2*p(i)-1
position(j:j) = names(i)
end do
write(*,'(a)') position
end subroutine write_position
end program chess960
|
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
|
#BASIC256
|
BASIC256
|
function is_gapful(n)
m = n
l = n mod 10
while (m >= 10)
m = int(m / 10)
end while
return (m * 10) + l
end function
subroutine muestra_gapful(n, gaps)
inc = 0
print "Primeros "; gaps; " números gapful >= "; n
while inc < gaps
if n mod is_gapful(n) = 0 then
print " " ; n ;
inc = inc + 1
end if
n = n + 1
end while
print chr(10)
end subroutine
call muestra_gapful(100, 30)
call muestra_gapful(1000000, 15)
call muestra_gapful(1000000000, 10)
call muestra_gapful(7123,25)
end
|
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
|
#C
|
C
|
#include<stdio.h>
void generateGaps(unsigned long long int start,int count){
int counter = 0;
unsigned long long int i = start;
char str[100];
printf("\nFirst %d Gapful numbers >= %llu :\n",count,start);
while(counter<count){
sprintf(str,"%llu",i);
if((i%(10*(str[0]-'0') + i%10))==0L){
printf("\n%3d : %llu",counter+1,i);
counter++;
}
i++;
}
}
int main()
{
unsigned long long int i = 100;
int count = 0;
char str[21];
generateGaps(100,30);
printf("\n");
generateGaps(1000000,15);
printf("\n");
generateGaps(1000000000,15);
printf("\n");
return 0;
}
|
http://rosettacode.org/wiki/Gaussian_elimination
|
Gaussian elimination
|
Task
Solve Ax=b using Gaussian elimination then backwards substitution.
A being an n by n matrix.
Also, x and b are n by 1 vectors.
To improve accuracy, please use partial pivoting and scaling.
See also
the Wikipedia entry: Gaussian elimination
|
#360_Assembly
|
360 Assembly
|
* Gaussian elimination 09/02/2019
GAUSSEL CSECT
USING GAUSSEL,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 R7,1 j=1
DO WHILE=(C,R7,LE,N) do j=1 to n
LA R9,1(R7) j+1
LR R6,R9 i=j+1
DO WHILE=(C,R6,LE,N) do i=j+1 to n
LR R1,R7 j
MH R1,=AL2(NN) *n
AR R1,R7 +j
BCTR R1,0 j*n+j-1
SLA R1,2 ~
LE F0,A-(NN*4)(R1) a(j,j)
LR R1,R6 i
MH R1,=AL2(NN) *n
AR R1,R7 j
BCTR R1,0 i*n+j-1
SLA R1,2 ~
LE F2,A-(NN*4)(R1) a(i,j)
DER F0,F2 a(j,j)/a(i,j)
STE F0,W w=a(j,j)/a(i,j)
LR R8,R9 k=j+1
DO WHILE=(C,R8,LE,N) do k=j+1 to n
LR R1,R7 j
MH R1,=AL2(NN) *n
AR R1,R8 +k
BCTR R1,0 j*n+k-1
SLA R1,2 ~
LE F0,A-(NN*4)(R1) a(j,k)
LR R1,R6 i
MH R1,=AL2(NN) *n
AR R1,R8 +k
BCTR R1,0 i*n+k-1
SLA R1,2 ~
LE F2,A-(NN*4)(R1) a(i,k)
LE F6,W w
MER F6,F2 *a(i,k)
SER F0,F6 a(j,k)-w*a(i,k)
STE F0,A-(NN*4)(R1) a(i,k)=a(j,k)-w*a(i,k)
LA R8,1(R8) k=k+1
ENDDO , end do k
LR R1,R7 j
SLA R1,2 ~
LE F0,B-4(R1) b(j)
LR R1,R6 i
SLA R1,2 ~
LE F2,B-4(R1) b(i)
LE F6,W w
MER F6,F2 *b(i)
SER F0,F6 b(j)-w*b(i)
STE F0,B-4(R1) b(i)=b(j)-w*b(i)
LA R6,1(R6) i=i+1
ENDDO , end do i
LA R7,1(R7) j=j+1
ENDDO , end do j
L R2,N n
SLA R2,2 ~
LE F0,B-4(R1) b(n)
L R1,N n
MH R1,=AL2(NN) *n
A R1,N n
BCTR R1,0 n*n+n-1
SLA R1,2 ~
LE F2,A-(NN*4)(R1) a(n,n)
DER F0,F2 b(n)/a(n,n)
STE F0,X-4(R2) x(n)=b(n)/a(n,n)
L R7,N n
BCTR R7,0 j=n-1
DO WHILE=(C,R7,GE,=F'1') do j=n-1 to 1 by -1
LE F0,=E'0' 0
STE F0,W w=0
LA R9,1(R7) j+1
LR R6,R9 i=j+1
DO WHILE=(C,R6,LE,N) do i=j+1 to n
LR R1,R7 j
MH R1,=AL2(NN) *n
AR R1,R6 i
BCTR R1,0 j*n+i-1
SLA R1,2 ~
LE F0,A-(NN*4)(R1) a(j,i)
LR R1,R6 i
SLA R1,2 ~
LE F2,X-4(R1) x(i)
MER F0,F2 a(j,i)*x(i)
LE F6,W w
AER F6,F0 +a(j,i)*x(i)
STE F6,W w=w+a(j,i)*x(i)
LA R6,1(R6) i=i+1
ENDDO , end do i
LR R2,R7 j
SLA R2,2 ~
LE F0,B-4(R2) b(j)
SE F0,W -w
LR R1,R7 j
MH R1,=AL2(NN) *n
AR R1,R7 j
BCTR R1,0 j*n+j-1
SLA R1,2 ~
LE F2,A-(NN*4)(R1) a(j,j)
DER F0,F2 (b(j)-w)/a(j,j)
STE F0,X-4(R2) x(j)=(b(j)-w)/a(j,j)
BCTR R7,0 j=j-1
ENDDO , end do j
XPRNT =CL8'SOLUTION',8 print
MVC PG,=CL91' ' clear buffer
LA R6,1 i=1
DO WHILE=(C,R6,LE,N) do i=1 to n
LR R1,R6 i
SLA R1,2 ~
LE F0,X-4(R1) x(i)
LA R0,5 number of decimals
BAL R14,FORMATF edit
MVC PG(13),0(R1) output
XPRNT PG,L'PG print
LA R6,1(R6) i=i+1
ENDDO , end do i
L R13,4(0,R13) restore previous savearea pointer
RETURN (14,12),RC=0 restore registers from calling sav
COPY plig\$_FORMATF.MLC format F13.n
NN EQU (X-B)/4 n
N DC A(NN) n
A DC E'1',E'0',E'0',E'0',E'0',E'0'
DC E'1',E'0.63',E'0.39',E'0.25',E'0.16',E'0.10'
DC E'1',E'1.26',E'1.58',E'1.98',E'2.49',E'3.13'
DC E'1',E'1.88',E'3.55',E'6.70',E'12.62',E'23.80'
DC E'1',E'2.51',E'6.32',E'15.88',E'39.90',E'100.28'
DC E'1',E'3.14',E'9.87',E'31.01',E'97.41',E'306.02'
B DC E'-0.01',E'0.61',E'0.91',E'0.99',E'0.60',E'0.02'
X DS (NN)E x(n)
W DS E w
PG DC CL91' ' buffer
REGEQU
END GAUSSEL
|
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.
|
#Perl
|
Perl
|
use strict;
use warnings;
use feature 'say';
use utf8;
use List::AllUtils <shuffle any natatime>;
sub pick1 { return @_[rand @_] }
sub gen_FEN {
my $n = 1 + int rand 31;
my @n = (shuffle(0 .. 63))[1 .. $n];
my @kings;
KINGS: {
for my $a (@n) {
for my $b (@n) {
next unless $a != $b && abs(int($a/8) - int($b/8)) > 1 || abs($a%8 - $b%8) > 1;
@kings = ($a, $b);
last KINGS;
}
die 'No good place for kings!';
}
}
my ($row, @pp);
my @pieces = <p P n N b B r R q Q>;
my @k = rand() < .5 ? <K k> : <k K>;
for my $sq (0 .. 63) {
if (any { $_ == $sq } @kings) {
push @pp, shift @k;
}
elsif (any { $_ == $sq } @n) {
$row = 7 - int $sq / 8;
push @pp,
$row == 0 ? pick1(grep { $_ ne 'P' } @pieces)
: $row == 7 ? pick1(grep { $_ ne 'P' } @pieces)
: pick1(@pieces);
}
else {
push @pp, 'ø';
}
}
my @qq;
my $iter = natatime 8, @pp;
while (my $row = join '', $iter->()) {
$row =~ s/((ø)\2*)/length($1)/eg;
push @qq, $row;
}
return join('/', @qq) . ' w - - 0 1';
}
say gen_FEN();
|
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.
|
#C.2B.2B
|
C++
|
#include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>
#include <vector>
template <typename scalar_type> class matrix {
public:
matrix(size_t rows, size_t columns)
: rows_(rows), columns_(columns), elements_(rows * columns) {}
matrix(size_t rows, size_t columns, scalar_type value)
: rows_(rows), columns_(columns), elements_(rows * columns, value) {}
matrix(size_t rows, size_t columns, std::initializer_list<scalar_type> values)
: rows_(rows), columns_(columns), elements_(rows * columns) {
assert(values.size() <= rows_ * columns_);
std::copy(values.begin(), values.end(), elements_.begin());
}
size_t rows() const { return rows_; }
size_t columns() const { return columns_; }
scalar_type& operator()(size_t row, size_t column) {
assert(row < rows_);
assert(column < columns_);
return elements_[row * columns_ + column];
}
const scalar_type& operator()(size_t row, size_t column) const {
assert(row < rows_);
assert(column < columns_);
return elements_[row * columns_ + column];
}
private:
size_t rows_;
size_t columns_;
std::vector<scalar_type> elements_;
};
template <typename scalar_type>
matrix<scalar_type> product(const matrix<scalar_type>& a,
const matrix<scalar_type>& b) {
assert(a.columns() == b.rows());
size_t arows = a.rows();
size_t bcolumns = b.columns();
size_t n = a.columns();
matrix<scalar_type> c(arows, bcolumns);
for (size_t i = 0; i < arows; ++i) {
for (size_t j = 0; j < n; ++j) {
for (size_t k = 0; k < bcolumns; ++k)
c(i, k) += a(i, j) * b(j, k);
}
}
return c;
}
template <typename scalar_type>
void swap_rows(matrix<scalar_type>& m, size_t i, size_t j) {
size_t columns = m.columns();
for (size_t column = 0; column < columns; ++column)
std::swap(m(i, column), m(j, column));
}
// Convert matrix to reduced row echelon form
template <typename scalar_type>
void rref(matrix<scalar_type>& m) {
size_t rows = m.rows();
size_t columns = m.columns();
for (size_t row = 0, lead = 0; row < rows && lead < columns; ++row, ++lead) {
size_t i = row;
while (m(i, lead) == 0) {
if (++i == rows) {
i = row;
if (++lead == columns)
return;
}
}
swap_rows(m, i, row);
if (m(row, lead) != 0) {
scalar_type f = m(row, lead);
for (size_t column = 0; column < columns; ++column)
m(row, column) /= f;
}
for (size_t j = 0; j < rows; ++j) {
if (j == row)
continue;
scalar_type f = m(j, lead);
for (size_t column = 0; column < columns; ++column)
m(j, column) -= f * m(row, column);
}
}
}
template <typename scalar_type>
matrix<scalar_type> inverse(const matrix<scalar_type>& m) {
assert(m.rows() == m.columns());
size_t rows = m.rows();
matrix<scalar_type> tmp(rows, 2 * rows, 0);
for (size_t row = 0; row < rows; ++row) {
for (size_t column = 0; column < rows; ++column)
tmp(row, column) = m(row, column);
tmp(row, row + rows) = 1;
}
rref(tmp);
matrix<scalar_type> inv(rows, rows);
for (size_t row = 0; row < rows; ++row) {
for (size_t column = 0; column < rows; ++column)
inv(row, column) = tmp(row, column + rows);
}
return inv;
}
template <typename scalar_type>
void print(std::ostream& out, const matrix<scalar_type>& m) {
size_t rows = m.rows(), columns = m.columns();
out << std::fixed << std::setprecision(4);
for (size_t row = 0; row < rows; ++row) {
for (size_t column = 0; column < columns; ++column) {
if (column > 0)
out << ' ';
out << std::setw(7) << m(row, column);
}
out << '\n';
}
}
int main() {
matrix<double> m(3, 3, {2, -1, 0, -1, 2, -1, 0, -1, 2});
std::cout << "Matrix:\n";
print(std::cout, m);
auto inv(inverse(m));
std::cout << "Inverse:\n";
print(std::cout, inv);
std::cout << "Product of matrix and inverse:\n";
print(std::cout, product(m, inv));
std::cout << "Inverse of inverse:\n";
print(std::cout, inverse(inv));
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
|
#Cach.C3.A9_ObjectScript
|
Caché ObjectScript
|
GENFIZBUZZ(MAX,WORDS,NUMBERS)
; loop until max, casting numeric to avoid errors
for i=1:1:+MAX {
set j = 1
set descr = ""
; assumes NUMBERS parameter is comma-delimited
while (j <= $length(NUMBERS,",")) {
if ((i # $piece(NUMBERS,",",j,j)) = 0) {
; build descriptor string, again assuming comma-delimited WORDS parameter
set descr = descr_$piece(WORDS,",",j,j)
}
set j = j + 1
} ; check list of numbers
; output values to screen
write " "_$case(descr,"":i,:descr)
} ; next value until MAX
quit
|
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
|
#Ceylon
|
Ceylon
|
shared void run() {
print("enter the max value");
assert(exists maxLine = process.readLine(),
exists max = parseInteger(maxLine));
print("enter your number/word pairs
enter a blank line to stop");
variable value divisorsToWords = map<Integer, String> {};
while(true) {
value line = process.readLine();
assert(exists line);
if(line.trimmed.empty) {
break;
}
value pair = line.trimmed.split().sequence();
if(exists first = pair.first,
exists integer = parseInteger(first),
exists word = pair[1]) {
divisorsToWords = divisorsToWords.patch(map {integer -> word});
}
}
value divisors = divisorsToWords.keys.sort(byIncreasing(Integer.magnitude));
for(i in 1..max) {
value builder = StringBuilder();
for(divisor in divisors) {
if(divisor.divides(i), exists word = divisorsToWords[divisor]) {
builder.append(word);
}
}
if(builder.empty) {
print(i);
} else {
print(builder.string);
}
}
}
|
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).
|
#uBasic.2F4tH
|
uBasic/4tH
|
' ------=< MAIN >=------
m = 0
Proc _hailstone_print(27)
Print
For x = 1 To 10000
n = Func(_hailstone(x))
If n > m Then
t = x
m = n
EndIf
Next
Print "The longest sequence is for "; t; ", it has a sequence length of "; m
End
_hailstone_print Param (1)
' print the number and sequence
Local (1)
b@ = 1
Print "sequence for number "; a@
Print Using "________"; a@; 'starting number
Do While a@ # 1
If (a@ % 2 ) = 1 Then
a@ = a@ * 3 + 1 ' n * 3 + 1
Else
a@ = a@ / 2 ' n / 2
EndIf
b@ = b@ + 1
Print Using "________"; a@;
If (b@ % 10) = 0 Then Print
Loop
Print : Print
Print "sequence length = "; b@
Print
For b@ = 0 To 79
Print "-";
Next
Print
Return
_hailstone Param (1)
' normal version
' only counts the sequence
Local (1)
b@ = 1
Do While a@ # 1
If (a@ % 2) = 1 Then
a@ = a@ * 3 + 1 ' n * 3 + 1
Else
a@ = a@ / 2 ' divide number by 2
EndIf
b@ = b@ + 1
Loop
Return (b@)
|
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
|
#BASIC
|
BASIC
|
DIM lower&(25)
FOR i%=0TO25
lower&(i%)=ASC"a"+i%
NEXT
END
|
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
|
#Batch_File
|
Batch File
|
@echo off
setlocal enabledelayedexpansion
:: This code appends the ASCII characters from 97-122 to %alphabet%, removing any room for error.
for /l %%i in (97,1,122) do (
cmd /c exit %%i
set "alphabet=!alphabet! !=exitcodeAscii!"
)
echo %alphabet%
pause>nul
|
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
|
#NLP.2B.2B
|
NLP++
|
@CODE
"output.txt" << "Hello world!";
@@CODE
|
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!
|
#TXR
|
TXR
|
(defmacro swp (left right)
(with-gensyms (tmp)
^(let ((,tmp ,left))
(set ,left ,right
,right ,tmp))))
|
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!
|
#uBasic.2F4tH
|
uBasic/4tH
|
a = 5 : b = 7
Print a,b
Push a,b : a = Pop() : b = Pop()
Print a,b
|
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
|
#Forth
|
Forth
|
\ genexp-rcode.fs Generator/Exponential for RosettaCode.org
\ Generator/filter implementation using return stack as continuations stack
: ENTER ( cont.addr -- ;borrowed from M.L.Gasanenko papers)
>R
;
: | ( f -- ;true->go ahead, false->return into generator )
IF EXIT THEN R> DROP
;
: GEN ( -- ;generate forever what is between 'GEN' and ';' )
BEGIN R@ ENTER AGAIN
;
: STOP ( f -- ;return to caller of word that contain 'GEN' )
IF R> DROP R> DROP R> DROP THEN
;
\ Problem at hand
: square ( n -- n^2 ) dup * ;
: cube ( n -- n^3 ) dup square * ;
\ Faster tests using info that tested numbers are monotonic growing
VARIABLE Sqroot \ last square root
VARIABLE Cbroot \ last cubic root
: square? ( u -- f ;test U for square number)
BEGIN
Sqroot @ square over <
WHILE
1 Sqroot +!
REPEAT
Sqroot @ square =
;
: cube? ( u -- f ;test U for cubic number)
BEGIN
Cbroot @ cube over <
WHILE
1 Cbroot +!
REPEAT
Cbroot @ cube =
;
VARIABLE Counter
: (go) ( u -- u' )
GEN 1+ Counter @ 30 >= STOP
dup square? | dup cube? 0= | Counter @ 20 >= 1 Counter +! | dup .
;
:noname 0 Counter ! 1 Sqroot ! 1 Cbroot ! 0 (go) drop ;
execute cr bye
|
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.
|
#TI-83_BASIC.2C_TI-89_BASIC
|
TI-83 BASIC, TI-89 BASIC
|
gcd(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.
|
#Tiny_BASIC
|
Tiny BASIC
|
10 PRINT "First number"
20 INPUT A
30 PRINT "Second number"
40 INPUT B
50 IF A<0 THEN LET A=-A
60 IF B<0 THEN LET B=-B
70 IF A>B THEN GOTO 130
80 LET B = B - A
90 IF A=0 THEN GOTO 110
100 GOTO 50
110 PRINT B
120 END
130 LET C=A
140 LET A=B
150 LET B=C
160 GOTO 70
|
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.
|
#Go
|
Go
|
package main
import (
"fmt"
"math/rand"
)
type symbols struct{ k, q, r, b, n rune }
var A = symbols{'K', 'Q', 'R', 'B', 'N'}
var W = symbols{'♔', '♕', '♖', '♗', '♘'}
var B = symbols{'♚', '♛', '♜', '♝', '♞'}
var krn = []string{
"nnrkr", "nrnkr", "nrknr", "nrkrn",
"rnnkr", "rnknr", "rnkrn",
"rknnr", "rknrn",
"rkrnn"}
func (sym symbols) chess960(id int) string {
var pos [8]rune
q, r := id/4, id%4
pos[r*2+1] = sym.b
q, r = q/4, q%4
pos[r*2] = sym.b
q, r = q/6, q%6
for i := 0; ; i++ {
if pos[i] != 0 {
continue
}
if r == 0 {
pos[i] = sym.q
break
}
r--
}
i := 0
for _, f := range krn[q] {
for pos[i] != 0 {
i++
}
switch f {
case 'k':
pos[i] = sym.k
case 'r':
pos[i] = sym.r
case 'n':
pos[i] = sym.n
}
}
return string(pos[:])
}
func main() {
fmt.Println(" ID Start position")
for _, id := range []int{0, 518, 959} {
fmt.Printf("%3d %s\n", id, A.chess960(id))
}
fmt.Println("\nRandom")
for i := 0; i < 5; i++ {
fmt.Println(W.chess960(rand.Intn(960)))
}
}
|
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
|
#C.2B.2B
|
C++
|
#include <iostream>
bool gapful(int n) {
int m = n;
while (m >= 10)
m /= 10;
return n % ((n % 10) + 10 * (m % 10)) == 0;
}
void show_gapful_numbers(int n, int count) {
std::cout << "First " << count << " gapful numbers >= " << n << ":\n";
for (int i = 0; i < count; ++n) {
if (gapful(n)) {
if (i != 0)
std::cout << ", ";
std::cout << n;
++i;
}
}
std::cout << '\n';
}
int main() {
show_gapful_numbers(100, 30);
show_gapful_numbers(1000000, 15);
show_gapful_numbers(1000000000, 10);
return 0;
}
|
http://rosettacode.org/wiki/Gaussian_elimination
|
Gaussian elimination
|
Task
Solve Ax=b using Gaussian elimination then backwards substitution.
A being an n by n matrix.
Also, x and b are n by 1 vectors.
To improve accuracy, please use partial pivoting and scaling.
See also
the Wikipedia entry: Gaussian elimination
|
#Ada
|
Ada
|
with Ada.Text_IO;
with Ada.Numerics.Generic_Real_Arrays;
procedure Gaussian_Eliminations is
type Real is new Float;
package Real_Arrays is
new Ada.Numerics.Generic_Real_Arrays (Real);
use Real_Arrays;
function Gaussian_Elimination (A : in Real_Matrix;
B : in Real_Vector) return Real_Vector
is
procedure Swap_Row (A : in out Real_Matrix;
B : in out Real_Vector;
R_1, R_2 : in Integer)
is
Temp : Real;
begin
if R_1 = R_2 then return; end if;
-- Swal matrix row
for Col in A'Range (1) loop
Temp := A (R_1, Col);
A (R_1, Col) := A (R_2, Col);
A (R_2, Col) := Temp;
end loop;
-- Swap vector row
Temp := B (R_1);
B (R_1) := B (R_2);
B (R_2) := Temp;
end Swap_Row;
AC : Real_Matrix := A;
BC : Real_Vector := B;
X : Real_Vector (A'Range (1)) := BC;
Max, Tmp : Real;
Max_Row : Integer;
begin
if
A'Length (1) /= A'Length (2) or
A'Length (1) /= B'Length
then
raise Constraint_Error with "Dimensions do not match";
end if;
if
A'First (1) /= A'First (2) or
A'First (1) /= B'First
then
raise Constraint_Error with "First index must be same";
end if;
for Dia in Ac'Range (1) loop
Max_Row := Dia;
Max := Ac (Dia, Dia);
for Row in Dia + 1 .. Ac'Last (1) loop
Tmp := abs (Ac (Row, Dia));
if Tmp > Max then
Max_Row := Row;
Max := Tmp;
end if;
end loop;
Swap_Row (Ac, Bc, Dia, Max_Row);
for Row in Dia + 1 .. Ac'Last (1) loop
Tmp := Ac (Row, Dia) / Ac (Dia, Dia);
for Col in Dia + 1 .. Ac'Last (1) loop
Ac (Row, Col) := Ac (Row, Col) - Tmp * Ac (Dia, Col);
end loop;
Ac (Row, Dia) := 0.0;
Bc (Row) := Bc (Row) - Tmp * Bc (Dia);
end loop;
end loop;
for Row in reverse Ac'Range (1) loop
Tmp := Bc (Row);
for J in reverse Row + 1 .. Ac'Last (1) loop
Tmp := Tmp - X (J) * Ac (Row, J);
end loop;
X (Row) := Tmp / Ac (Row, Row);
end loop;
return X;
end Gaussian_Elimination;
procedure Put (V : in Real_Vector) is
use Ada.Text_IO;
package Real_IO is
new Ada.Text_IO.Float_IO (Real);
begin
Put ("[ ");
for E of V loop
Real_IO.Put (E, Exp => 0, Aft => 6);
Put (" ");
end loop;
Put (" ]");
New_Line;
end Put;
A : constant Real_Matrix :=
((1.00, 0.00, 0.00, 0.00, 0.00, 0.00),
(1.00, 0.63, 0.39, 0.25, 0.16, 0.10),
(1.00, 1.26, 1.58, 1.98, 2.49, 3.13),
(1.00, 1.88, 3.55, 6.70, 12.62, 23.80),
(1.00, 2.51, 6.32, 15.88, 39.90, 100.28),
(1.00, 3.14, 9.87, 31.01, 97.41, 306.02));
B : constant Real_Vector :=
( -0.01, 0.61, 0.91, 0.99, 0.60, 0.02 );
X : constant Real_Vector := Gaussian_Elimination (A, B);
begin
Put (X);
end Gaussian_Eliminations;
|
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.
|
#Phix
|
Phix
|
with javascript_semantics
constant show_bad_boards = false
string board
function fen()
string res = ""
for i=1 to 64 by 8 do
integer empty = 0
for j=i to i+7 do
if board[j]='.' then
empty += 1
else
if empty then
res &= empty+'0'
empty = 0
end if
res &= board[j]
end if
end for
if empty then
res &= empty+'0'
end if
if i<57 then res &= '/' end if
end for
res &= " w - - 0 1"
return res
end function
function p15()
string res = "pppppppprrnnbbq"
-- promote 0..8 pawns
for i=1 to rand(9)-1 do
res[i] = res[rand(7)+8]
end for
res = shuffle(res)
return res
end function
function kings_adjacent(sequence p12)
integer {p1,p2} = sq_sub(p12,1),
row_diff = abs(floor(p1/8)-floor(p2/8)),
col_diff = abs(mod(p1,8)-mod(p2,8))
return row_diff<=1 and col_diff<=1
end function
integer lp
procedure show_board()
printf(1,"%d pieces\n%s",{lp,join_by(board,1,8,"")})
end procedure
while true do
string pieces = "Kk"& -- kings
upper(p15())[1..rand(16)-1]& -- white
lower(p15())[1..rand(16)-1] -- black
lp = length(pieces)
sequence p = tagset(64)
p = shuffle(p)
board = repeat('.',64)
for i=1 to lp do board[p[i]] = pieces[i] end for
if kings_adjacent(p[1..2]) then
if show_bad_boards then show_board() end if
puts(1,"kings adjacent - reshuffle\n\n")
else
-- check no pawn will be on a promotion square,
-- and (above spec) no pawn has gone backwards:
if find('p',lower(board[1..8]&board[57..64]))=0 then exit end if
if show_bad_boards then show_board() end if
puts(1,"pawn on rank 1/8 - reshuffle\n\n")
end if
end while
show_board()
printf(1,"\n%s\n",{fen()})
|
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.
|
#Factor
|
Factor
|
USING: kernel math.matrices math.matrices.elimination
prettyprint sequences ;
! Augment a matrix with its identity. E.g.
!
! 1 2 3 1 2 3 1 0 0
! 4 5 6 augment-identity -> 4 5 6 0 1 0
! 7 8 9 7 8 9 0 0 1
: augment-identity ( matrix -- new-matrix )
dup first length <identity-matrix>
[ flip ] bi@ append flip ;
! Note: the 'solution' word finds the reduced row echelon form
! of a matrix.
: gauss-jordan-invert ( matrix -- inverted )
dup square-matrix? [ "Matrix must be square." throw ] unless
augment-identity solution
! now remove the vestigial identity portion of the matrix
flip halves nip flip ;
{
{ -1 -2 3 2 }
{ -4 -1 6 2 }
{ 7 -8 9 1 }
{ 1 -2 1 3 }
} gauss-jordan-invert simple-table.
|
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
|
#Clojure
|
Clojure
|
(defn fix [pairs]
(map second pairs))
(defn getvalid [pairs n]
(filter (fn [p] (zero? (mod n (first p))))
(sort-by first pairs)))
(defn gfizzbuzz [pairs numbers]
(interpose "\n"
(map (fn [n] (let [f (getvalid pairs n)]
(if (empty? f)
n
(apply str
(fix f)))))
numbers)))
|
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).
|
#UNIX_Shell
|
UNIX Shell
|
#!/bin/bash
# seq is the array genereated by hailstone
# index is used for seq
declare -a seq
declare -i index
# Create a routine to generate the hailstone sequence for a number
hailstone () {
unset seq index
seq[$((index++))]=$((n=$1))
while [ $n -ne 1 ]; do
[ $((n % 2)) -eq 1 ] && ((n=n*3+1)) || ((n=n/2))
seq[$((index++))]=$n
done
}
# 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
i=27
hailstone $i
echo "$i: ${#seq[@]}"
echo "${seq[@]:0:4} ... ${seq[@]:(-4):4}"
# Show the number less than 100,000 which has the longest hailstone
# sequence together with that sequences length.
# (But don't show the actual sequence)!
max=0
maxlen=0
for ((i=1;i<100000;i++)); do
hailstone $i
if [ $((len=${#seq[@]})) -gt $maxlen ]; then
max=$i
maxlen=$len
fi
done
echo "${max} has a hailstone sequence length of ${maxlen}"
|
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
|
#Befunge
|
Befunge
|
0"z":>"a"`#v_ >:#,_$@
^:- 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
|
#BQN
|
BQN
|
'a'+↕26
|
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
|
#NS-HUBASIC
|
NS-HUBASIC
|
10 ? "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!
|
#UNIX_Shell
|
UNIX Shell
|
$ swap() { typeset -n var1=$1 var2=$2; set -- "$var1" "$var2"; var1=$2; var2=$1; }
$ a=1 b=2
$ echo $a $b
1 2
$ swap a b
$ echo $a $b
2 1
$ swap a b
$ echo $a $b
1 2
|
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
|
#FreeBASIC
|
FreeBASIC
|
Dim Shared As Long lastsquare, nextsquare, lastcube, midcube, nextcube
Function squares() As Long
lastsquare += nextsquare
nextsquare += 2
squares = lastsquare
End Function
Function cubes() As Long
lastcube += nextcube
nextcube += midcube
midcube += 6
cubes = lastcube
End Function
lastsquare = 1 : nextsquare = -1 : lastcube = -1 : midcube = 0 : nextcube = 1
Dim As Long cube, square
cube = cubes
For i As Byte = 1 To 30
Do
square = squares
Do While cube < square
cube = cubes
Loop
If square <> cube Then Exit Do
Loop
If i > 20 Then Print square;
Next i
Sleep
|
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.
|
#Transact-SQL
|
Transact-SQL
|
CREATE OR ALTER FUNCTION [dbo].[PGCD]
( @a BigInt
, @b BigInt
)
RETURNS BigInt
WITH RETURNS NULL ON NULL INPUT
-- Calculates the Greatest Common Denominator of two numbers (1 if they are coprime).
BEGIN
DECLARE @PGCD BigInt;
WITH Vars(A, B)
As ( SELECT Max(V.N) As A
, Min(V.N) As B
FROM ( VALUES ( Abs(@a) , Abs(@b)) ) Params(A, B)
-- First, get absolute value
Cross APPLY ( VALUES (Params.A) , (Params.B) ) V(N)
-- Then, order parameters without Greatest/Least functions
WHERE Params.A > 0
And Params.B > 0 -- If 0 passed in, NULL shall be the output
)
, Calc(A, B)
As ( SELECT A
, B
FROM Vars
UNION ALL
SELECT B As A
, A % B As B -- Self-ordering
FROM Calc
WHERE Calc.A > 0
And Calc.B > 0
)
SELECT @PGCD = Min(A)
FROM Calc
WHERE Calc.B = 0
;
RETURN @PGCD;
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.
|
#True_BASIC
|
True BASIC
|
REM Solución iterativa
FUNCTION gcdI(x, y)
DO WHILE y > 0
LET t = y
LET y = remainder(x, y)
LET x = t
LOOP
LET gcdI = x
END FUNCTION
LET a = 111111111111111
LET b = 11111
PRINT
PRINT "GCD(";a;", ";b;") = "; gcdI(a, b)
PRINT
PRINT "GCD(";a;", 111) = "; gcdI(a, 111)
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.
|
#Haskell
|
Haskell
|
import Data.List
import qualified Data.Set as Set
data Piece = K | Q | R | B | N deriving (Eq, Ord, Show)
isChess960 :: [Piece] -> Bool
isChess960 rank =
(odd . sum $ findIndices (== B) rank) && king > rookA && king < rookB
where
Just king = findIndex (== K) rank
[rookA, rookB] = findIndices (== R) rank
main :: IO ()
main = mapM_ (putStrLn . concatMap show) . Set.toList . Set.fromList
. filter isChess960 $ permutations [R,N,B,Q,K,B,N,R]
|
http://rosettacode.org/wiki/Function_prototype
|
Function prototype
|
Some languages provide the facility to declare functions and subroutines through the use of function prototyping.
Task
Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include:
An explanation of any placement restrictions for prototype declarations
A prototype declaration for a function that does not require arguments
A prototype declaration for a function that requires two arguments
A prototype declaration for a function that utilizes varargs
A prototype declaration for a function that utilizes optional arguments
A prototype declaration for a function that utilizes named parameters
Example of prototype declarations for subroutines or procedures (if these differ from functions)
An explanation and example of any special forms of prototyping not covered by the above
Languages that do not provide function prototyping facilities should be omitted from this task.
|
#Ada
|
Ada
|
function noargs return Integer;
function twoargs (a, b : Integer) return Integer;
-- varargs do not exist
function optionalargs (a, b : Integer := 0) return Integer;
-- all parameters are always named, only calling by name differs
procedure dostuff (a : Integer);
|
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
|
#C.23
|
C#
|
using System;
namespace GapfulNumbers
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("The first 30 gapful numbers are: ");
/* Starting at 100, find 30 gapful numbers */
FindGap(100, 30);
Console.WriteLine("The first 15 gapful numbers > 1,000,000 are: ");
FindGap(1000000, 15);
Console.WriteLine("The first 10 gapful numbers > 1,000,000,000 are: ");
FindGap(1000000000, 10);
Console.Read();
}
public static int firstNum(int n)
{
/*Divide by ten until the leading digit remains.*/
while (n >= 10)
{
n /= 10;
}
return (n);
}
public static int lastNum(int n)
{
/*Modulo gives you the last digit. */
return (n % 10);
}
static void FindGap(int n, int gaps)
{
int count = 0;
while (count < gaps)
{
/* We have to convert our first and last digits to strings to concatenate.*/
string concat = firstNum(n).ToString() + lastNum(n).ToString();
/* And then convert our concatenated string back to an integer. */
int i = Convert.ToInt32(concat);
/* Modulo with our new integer and output the result. */
if (n % i == 0)
{
Console.Write(n + " ");
count++;
n++;
}
else
{
n++;
continue;
}
}
}
}
}
|
http://rosettacode.org/wiki/Gaussian_elimination
|
Gaussian elimination
|
Task
Solve Ax=b using Gaussian elimination then backwards substitution.
A being an n by n matrix.
Also, x and b are n by 1 vectors.
To improve accuracy, please use partial pivoting and scaling.
See also
the Wikipedia entry: Gaussian elimination
|
#ALGOL_68
|
ALGOL 68
|
# -*- coding: utf-8 -*- #
COMMENT PROVIDES
MODE FIXED; INT fixed exception, unfixed exception;
PROC (STRING message) FIXED raise, raise value error
END COMMENT
# Note: ℵ indicates attribute is "private", and
should not be used outside of this prelude #
MODE FIXED = BOOL; # if an exception is detected, can it be fixed "on-site"? #
FIXED fixed exception = TRUE, unfixed exception = FALSE;
MODE #ℵ#SIMPLEOUTV = [0]UNION(CHAR, STRING, INT, REAL, BOOL, BITS);
MODE #ℵ#SIMPLEOUTM = [0]#ℵ#SIMPLEOUTV;
MODE #ℵ#SIMPLEOUTT = [0]#ℵ#SIMPLEOUTM;
MODE SIMPLEOUT = [0]#ℵ#SIMPLEOUTT;
PROC raise = (#ℵ#SIMPLEOUT message)FIXED: (
putf(stand error, ($"Exception:"$, $xg$, message, $l$));
stop
);
PROC raise value error = (#ℵ#SIMPLEOUT message)FIXED:
IF raise(message) NE fixed exception THEN exception value error; FALSE FI;
SKIP
|
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.
|
#PicoLisp
|
PicoLisp
|
(load "@lib/simul.l")
(seed (in "/dev/urandom" (rd 8)))
(de pieceN (P)
(case P
("p" 8)
("q" 1)
(T 2) ) )
(de pieceset ()
(let C 0
(make
(for P (conc (cons "p") (shuffle '("r" "n" "b" "q")))
(let (X (pieceN P) N (rand 0 (+ X C)))
(do N
(link P) )
(if (= P "p")
(and
(> X N)
(inc 'C (- X N)) )
(and
(> N X)
(dec 'C (- N X)) ) ) ) ) ) ) )
(de neib (A)
(let
(X (/ (dec A) 8)
Y (% (dec A) 8) )
(filter
'((N)
(and
(<= 1 N 64)
(<=
(abs (- (/ (dec N) 8) X))
1 )
(<=
(abs (- (% (dec N) 8) Y))
1 ) ) )
(mapcar
'((B) (+ B A))
(-9 -8 -7 -1 1 7 8 9) ) ) ) )
(setq *B (need 64 "."))
(setq *P (conc (pieceset) (mapcar uppc (pieceset)) (cons "K")))
(for P *P
(loop
(T
(=
"."
(car
(setq @@
(nth
*B
(apply
rand
(if (or (= "p" P) (= "P" P))
(9 56)
(1 64) ) ) ) ) ) )
(set @@ P) ) ) )
(loop
(T
(and
(=
"."
(car
(setq @@ (nth *B (setq @@@ (rand 1 64)))) ) )
(fully
'((N) (<> "K" (get *B N)))
(neib @@@) ) )
(set @@ "k") ) )
(setq *FEN
(make
(while *B
(let (C 0 Lst (cut 8 '*B))
(prinl Lst)
(link
(make
(for L Lst
(if (= L ".")
(inc 'C)
(and
(gt0 C)
(link (swap 'C 0)) )
(link L) ) )
(and
(gt0 C)
(link C) ) ) ) ) ) ) )
(println (pack (glue "/" *FEN) " w - - 0 1"))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.