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/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#ArnoldC
|
ArnoldC
|
LISTEN TO ME VERY CAREFULLY multiply
I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE a
I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE b
GIVE THESE PEOPLE AIR
HEY CHRISTMAS TREE product
YOU SET US UP @I LIED
GET TO THE CHOPPER product
HERE IS MY INVITATION a
YOU'RE FIRED b
ENOUGH TALK
I'LL BE BACK product
HASTA LA VISTA, BABY
|
http://rosettacode.org/wiki/Fusc_sequence
|
Fusc sequence
|
Definitions
The fusc integer sequence is defined as:
fusc(0) = 0
fusc(1) = 1
for n>1, the nth term is defined as:
if n is even; fusc(n) = fusc(n/2)
if n is odd; fusc(n) = fusc((n-1)/2) + fusc((n+1)/2)
Note that MathWorld's definition starts with unity, not zero. This task will be using the OEIS' version (above).
An observation
fusc(A) = fusc(B)
where A is some non-negative integer expressed in binary, and
where B is the binary value of A reversed.
Fusc numbers are also known as:
fusc function (named by Dijkstra, 1982)
Stern's Diatomic series (although it starts with unity, not zero)
Stern-Brocot sequence (although it starts with unity, not zero)
Task
show the first 61 fusc numbers (starting at zero) in a horizontal format.
show the fusc number (and its index) whose length is greater than any previous fusc number length.
(the length is the number of decimal digits when the fusc number is expressed in base ten.)
show all numbers with commas (if appropriate).
show all output here.
Related task
RosettaCode Stern-Brocot sequence
Also see
the MathWorld entry: Stern's Diatomic Series.
the OEIS entry: A2487.
|
#Mathematica_.2F_Wolfram_Language
|
Mathematica / Wolfram Language
|
ClearAll[Fusc]
Fusc[0] := 0
Fusc[1] := 1
Fusc[n_] := Fusc[n] = If[EvenQ[n], Fusc[n/2], Fusc[(n - 1)/2] + Fusc[(n + 1)/2]]
Fusc /@ Range[0, 60]
res = {{0, 1}};
i = 0;
PrintTemporary[Dynamic[{res, i}]];
While[Length[res] < 6,
f = Fusc[i];
If[IntegerLength[res[[-1, -1]]] < IntegerLength[f],
AppendTo[res, {i, f}]
];
i++;
];
res
|
http://rosettacode.org/wiki/Fusc_sequence
|
Fusc sequence
|
Definitions
The fusc integer sequence is defined as:
fusc(0) = 0
fusc(1) = 1
for n>1, the nth term is defined as:
if n is even; fusc(n) = fusc(n/2)
if n is odd; fusc(n) = fusc((n-1)/2) + fusc((n+1)/2)
Note that MathWorld's definition starts with unity, not zero. This task will be using the OEIS' version (above).
An observation
fusc(A) = fusc(B)
where A is some non-negative integer expressed in binary, and
where B is the binary value of A reversed.
Fusc numbers are also known as:
fusc function (named by Dijkstra, 1982)
Stern's Diatomic series (although it starts with unity, not zero)
Stern-Brocot sequence (although it starts with unity, not zero)
Task
show the first 61 fusc numbers (starting at zero) in a horizontal format.
show the fusc number (and its index) whose length is greater than any previous fusc number length.
(the length is the number of decimal digits when the fusc number is expressed in base ten.)
show all numbers with commas (if appropriate).
show all output here.
Related task
RosettaCode Stern-Brocot sequence
Also see
the MathWorld entry: Stern's Diatomic Series.
the OEIS entry: A2487.
|
#Nim
|
Nim
|
import strformat
func fusc(n: int): int =
if n == 0 or n == 1:
n
elif n mod 2 == 0:
fusc(n div 2)
else:
fusc((n - 1) div 2) + fusc((n + 1) div 2)
echo "The first 61 Fusc numbers:"
for i in 0..61:
write(stdout, fmt"{fusc(i)} ")
echo "\n\nThe Fusc numbers whose lengths are greater than those of previous Fusc numbers:"
echo fmt" n fusc(n)"
echo "--------- ---------"
var maxLength = 0
for i in 0..700_000:
var f = fusc(i)
var length = len($f)
if length > maxLength:
maxLength = length
echo fmt"{i:9} {f:9}"
|
http://rosettacode.org/wiki/Gamma_function
|
Gamma function
|
Task
Implement one algorithm (or more) to compute the Gamma (
Γ
{\displaystyle \Gamma }
) function (in the real field only).
If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function.
The Gamma function can be defined as:
Γ
(
x
)
=
∫
0
∞
t
x
−
1
e
−
t
d
t
{\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt}
This suggests a straightforward (but inefficient) way of computing the
Γ
{\displaystyle \Gamma }
through numerical integration.
Better suggested methods:
Lanczos approximation
Stirling's approximation
|
#Java
|
Java
|
public class GammaFunction {
public double st_gamma(double x){
return Math.sqrt(2*Math.PI/x)*Math.pow((x/Math.E), x);
}
public double la_gamma(double x){
double[] p = {0.99999999999980993, 676.5203681218851, -1259.1392167224028,
771.32342877765313, -176.61502916214059, 12.507343278686905,
-0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7};
int g = 7;
if(x < 0.5) return Math.PI / (Math.sin(Math.PI * x)*la_gamma(1-x));
x -= 1;
double a = p[0];
double t = x+g+0.5;
for(int i = 1; i < p.length; i++){
a += p[i]/(x+i);
}
return Math.sqrt(2*Math.PI)*Math.pow(t, x+0.5)*Math.exp(-t)*a;
}
public static void main(String[] args) {
GammaFunction test = new GammaFunction();
System.out.println("Gamma \t\tStirling \t\tLanczos");
for(double i = 1; i <= 20; i += 1){
System.out.println("" + i/10.0 + "\t\t" + test.st_gamma(i/10.0) + "\t" + test.la_gamma(i/10.0));
}
}
}
|
http://rosettacode.org/wiki/Galton_box_animation
|
Galton box animation
|
Example of a Galton Box at the end of animation.
A Galton device Sir Francis Galton's device is also known as a bean machine, a Galton Board, or a quincunx.
Description of operation
In a Galton box, there are a set of pins arranged in a triangular pattern. A number of balls are dropped so that they fall in line with the top pin, deflecting to the left or the right of the pin. The ball continues to fall to the left or right of lower pins before arriving at one of the collection points between and to the sides of the bottom row of pins.
Eventually the balls are collected into bins at the bottom (as shown in the image), the ball column heights in the bins approximate a bell curve. Overlaying Pascal's triangle onto the pins shows the number of different paths that can be taken to get to each bin.
Task
Generate an animated simulation of a Galton device.
Task requirements
The box should have at least 5 pins on the bottom row.
A solution can use graphics or ASCII animation.
Provide a sample of the output/display such as a screenshot.
There can be one or more balls in flight at the same time.
If multiple balls are in flight, ensure they don't interfere with each other.
A solution should allow users to specify the number of balls, or it should run until full or a preset limit.
Optionally, display the number of balls.
|
#zig
|
zig
|
const std = @import("std");
const rand = std.rand;
const time = std.os.time;
const PEG_LINES = 20;
fn boardSize(comptime peg_lines: u16) u16 {
var i: u16 = 0;
var size: u16 = 0;
inline while (i <= PEG_LINES) : (i += 1) {
size += i+1;
}
return size;
}
const BOARD_SIZE = boardSize(PEG_LINES);
fn stepBoard(board: *[BOARD_SIZE]u1, count: *[PEG_LINES+1]u8) void {
var prng = rand.DefaultPrng.init(time.timestamp());
var p: u8 = 0;
var sum: u16 = 0;
while (p <= PEG_LINES) : (p += 1) {
const pegs = PEG_LINES-p;
var i: u16 = 0;
while (i < pegs+1) : (i += 1) {
if (pegs != PEG_LINES and board[BOARD_SIZE-1-sum-i] == 1) {
if (prng.random.boolean()) {
board.*[BOARD_SIZE-1-sum-i+pegs+1] = 1;
} else {
board.*[BOARD_SIZE-1-sum-i+pegs+2] = 1;
}
} else if (pegs == PEG_LINES and board[BOARD_SIZE-1-sum-i] == 1) {
count.*[pegs-i] += 1;
}
board.*[BOARD_SIZE-1-sum-i] = 0;
}
sum += pegs+1;
}
}
fn printBoard(board: *[BOARD_SIZE]u1, count: *[PEG_LINES+1]u8) !void {
var stdout = try std.io.getStdOut();
try stdout.write("\x1B[2J\x1B[1;1H");
var pegs: u16 = 0;
var sum: u16 = 0;
while (pegs <= PEG_LINES) : (pegs += 1) {
var i: u16 = 0;
while (i < (PEG_LINES-pegs)) : (i += 1) try stdout.write(" ");
i = 0;
while (i < pegs+1) : (i += 1) {
const spot = if (board[i+sum] == 1) "o" else " ";
try stdout.write(spot);
if (i != pegs) try stdout.write("*");
}
sum += pegs+1;
try stdout.write("\n");
}
for (count) |n| {
const num_char = [2]u8{'0'+n, ' '};
try stdout.write(num_char);
}
try stdout.write("\n");
}
pub fn main() !void {
var board: [BOARD_SIZE]u1 = []u1{0} ** BOARD_SIZE;
var bottom_count: [PEG_LINES+1]u8 = []u8{0} ** (PEG_LINES+1);
var i: u16 = 0;
while (i < 35) : (i += 1) {
if (i < 10) board[0] = 1;
try printBoard(&board, &bottom_count);
stepBoard(&board, &bottom_count);
time.sleep(150000000);
}
}
|
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
|
#Python
|
Python
|
from itertools import islice, count
for start, n in [(100, 30), (1_000_000, 15), (1_000_000_000, 10)]:
print(f"\nFirst {n} gapful numbers from {start:_}")
print(list(islice(( x for x in count(start)
if (x % (int(str(x)[0]) * 10 + (x % 10)) == 0) )
, 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
|
#PHP
|
PHP
|
function swap_rows(&$a, &$b, $r1, $r2)
{
if ($r1 == $r2) return;
$tmp = $a[$r1];
$a[$r1] = $a[$r2];
$a[$r2] = $tmp;
$tmp = $b[$r1];
$b[$r1] = $b[$r2];
$b[$r2] = $tmp;
}
function gauss_eliminate($A, $b, $N)
{
for ($col = 0; $col < $N; $col++)
{
$j = $col;
$max = $A[$j][$j];
for ($i = $col + 1; $i < $N; $i++)
{
$tmp = abs($A[$i][$col]);
if ($tmp > $max)
{
$j = $i;
$max = $tmp;
}
}
swap_rows($A, $b, $col, $j);
for ($i = $col + 1; $i < $N; $i++)
{
$tmp = $A[$i][$col] / $A[$col][$col];
for ($j = $col + 1; $j < $N; $j++)
{
$A[$i][$j] -= $tmp * $A[$col][$j];
}
$A[$i][$col] = 0;
$b[$i] -= $tmp * $b[$col];
}
}
$x = array();
for ($col = $N - 1; $col >= 0; $col--)
{
$tmp = $b[$col];
for ($j = $N - 1; $j > $col; $j--)
{
$tmp -= $x[$j] * $A[$col][$j];
}
$x[$col] = $tmp / $A[$col][$col];
}
return $x;
}
function test_gauss()
{
$a = array(
array(1.00, 0.00, 0.00, 0.00, 0.00, 0.00),
array(1.00, 0.63, 0.39, 0.25, 0.16, 0.10),
array(1.00, 1.26, 1.58, 1.98, 2.49, 3.13),
array(1.00, 1.88, 3.55, 6.70, 12.62, 23.80),
array(1.00, 2.51, 6.32, 15.88, 39.90, 100.28),
array(1.00, 3.14, 9.87, 31.01, 97.41, 306.02)
);
$b = array( -0.01, 0.61, 0.91, 0.99, 0.60, 0.02 );
$x = gauss_eliminate($a, $b, 6);
ksort($x);
print_r($x);
}
test_gauss();
|
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
|
#Tcl
|
Tcl
|
proc fizzbuzz {n args} {
if {$args eq ""} {
set args {{3 Fizz} {5 Buzz}}
}
while {[incr i] <= $n} {
set out ""
foreach rule $args {
lassign $rule m echo
if {$i % $m == 0} {append out $echo}
}
if {$out eq ""} {set out $i}
puts $out
}
}
fizzbuzz 20 {3 Fizz} {5 Buzz} {7 Baxx}
|
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
|
#MATLAB_.2F_Octave
|
MATLAB / Octave
|
'a':'z'
|
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
|
#Maxima
|
Maxima
|
delete([], makelist(if(alphacharp(ascii(i))) then parse_string(ascii(i)) else [], i, 96, 122));
|
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
|
#Pict
|
Pict
|
(prNL "Hello World!");
|
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
|
#Scheme
|
Scheme
|
(define (power-seq n)
(let ((i 0))
(lambda ()
(set! i (+ 1 i))
(expt i n))))
(define (filter-seq m n)
(let* ((s1 (power-seq m)) (s2 (power-seq n))
(a 0) (b 0))
(lambda ()
(set! a (s1))
(let loop ()
(if (>= a b) (begin
(cond ((> a b) (set! b (s2)))
((= a b) (set! a (s1))))
(loop))))
a)))
(let loop ((seq (filter-seq 2 3)) (i 0))
(if (< i 30)
(begin
(if (> i 20)
(begin
(display (seq))
(newline))
(seq))
(loop seq (+ 1 i)))))
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#Fortress
|
Fortress
|
compose[\A, B, C\](f:A->B, g:B->C, i:Any): A->C = do
f(g(i))
end
composed(i:RR64): RR64 = compose(sin, cos, i)
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#FreeBASIC
|
FreeBASIC
|
function compose( f as function(as integer) as integer,_
g as function(as integer) as integer,_
n as integer ) as integer
return f(g(n))
end function
|
http://rosettacode.org/wiki/Fractal_tree
|
Fractal tree
|
Generate and draw a fractal tree.
Draw the trunk
At the end of the trunk, split by some angle and draw two branches
Repeat at the end of each branch until a sufficient level of branching is reached
Related tasks
Pythagoras Tree
|
#Liberty_BASIC
|
Liberty BASIC
|
NoMainWin
sw = 640 : sh = 480
WindowWidth = sw+8 : WindowHeight = sh+31
UpperLeftX = (DisplayWidth -sw)/2
UpperLeftY = (DisplayHeight-sh)/2
Open"Fractal Tree" For Graphics_nf_nsb As #g
#g "Down; Color darkgreen; TrapClose halt"
h$ = "#g"
'initial assignments
initAngle = Acs(-1)*1.5 'radian equivalent of 270 degrees
theta = 29 * (Acs(-1)/180) 'convert 29 degrees to radians
length = 110 'length in pixels
depth = 25 'max recursion depth
'draw the tree
Call tree h$, 320, 470, initAngle, theta, length, depth
#g "Flush; when leftButtonDown halt" 'L-click to exit
Wait
Sub halt handle$
Close #handle$
End
End Sub
Sub tree h$, x, y, initAngle, theta, length, depth
Scan
newX = Cos(initAngle) * length + x
newY = Sin(initAngle) * length + y
#h$ "Line ";x;" ";y;" ";newX;" ";newY
length = length * .78
depth = depth - 1
If depth > 0 Then
Call tree h$, newX, newY, initAngle-theta, theta, length, depth
Call tree h$, newX, newY, initAngle+theta, theta, length, depth
End If
End Sub
|
http://rosettacode.org/wiki/Fraction_reduction
|
Fraction reduction
|
There is a fine line between numerator and denominator. ─── anonymous
A method to "reduce" some reducible fractions is to cross out a digit from the
numerator and the denominator. An example is:
16 16
──── and then (simply) cross─out the sixes: ────
64 64
resulting in:
1
───
4
Naturally, this "method" of reduction must reduce to the proper value (shown as a fraction).
This "method" is also known as anomalous cancellation and also accidental cancellation.
(Of course, this "method" shouldn't be taught to impressionable or gullible minds.) 😇
Task
Find and show some fractions that can be reduced by the above "method".
show 2-digit fractions found (like the example shown above)
show 3-digit fractions
show 4-digit fractions
show 5-digit fractions (and higher) (optional)
show each (above) n-digit fractions separately from other different n-sized fractions, don't mix different "sizes" together
for each "size" fraction, only show a dozen examples (the 1st twelve found)
(it's recognized that not every programming solution will have the same generation algorithm)
for each "size" fraction:
show a count of how many reducible fractions were found. The example (above) is size 2
show a count of which digits were crossed out (one line for each different digit)
for each "size" fraction, show a count of how many were found. The example (above) is size 2
show each n-digit example (to be shown on one line):
show each n-digit fraction
show each reduced n-digit fraction
show what digit was crossed out for the numerator and the denominator
Task requirements/restrictions
only proper fractions and their reductions (the result) are to be used (no vulgar fractions)
only positive fractions are to be used (no negative signs anywhere)
only base ten integers are to be used for the numerator and denominator
no zeros (decimal digit) can be used within the numerator or the denominator
the numerator and denominator should be composed of the same number of digits
no digit can be repeated in the numerator
no digit can be repeated in the denominator
(naturally) there should be a shared decimal digit in the numerator and the denominator
fractions can be shown as 16/64 (for example)
Show all output here, on this page.
Somewhat related task
Farey sequence (It concerns fractions.)
References
Wikipedia entry: proper and improper fractions.
Wikipedia entry: anomalous cancellation and/or accidental cancellation.
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
ClearAll[AnomalousCancellationQ2]
AnomalousCancellationQ2[frac : {i_?Positive, j_?Positive}] :=
Module[{samedigits, idig, jdig, ff, p, q, r, tmp},
idig = IntegerDigits[i];
jdig = IntegerDigits[j];
samedigits = Intersection[idig, jdig];
ff = i/j;
If[samedigits != {},
r = {};
Do[
p = Flatten[Position[idig, s]];
q = Flatten[Position[jdig, s]];
p = FromDigits[Delete[idig, #]] & /@ p;
q = FromDigits[Delete[jdig, #]] & /@ q;
tmp = Select[Tuples[{p, q}], #[[1]]/#[[2]] == ff &];
If[Length[tmp] > 0,
r = Join[r, Join[#, {i, j, s}] & /@ tmp];
];
,
{s, samedigits}
];
r
,
{}
]
]
ijs = Select[Select[Range[1, 9999], IntegerDigits /* FreeQ[0]], IntegerDigits /* DuplicateFreeQ];
res = Reap[
Do[
Do[
num = ijs[[i]];
den = ijs[[j]];
out = AnomalousCancellationQ2[{num, den}];
If[Length[out] > 0,
Sow[out]
]
,
{i, 1, j - 1}
]
,
{j, Length[ijs]}
]
][[2, 1]];
tmp = Catenate[res];
sel = Sort@Select[tmp, IntegerLength[#[[3]]] == IntegerLength[#[[4]]] == 2 &];
Length[sel]
t = Take[sel, UpTo[12]];
Column[Row[{#3, "/", #4, " = ", #1, "/", #2, " by removing ", #5}] & @@@ t]
SortBy[Tally[sel[[All, -1]]], First]
sel = Sort@Select[tmp, IntegerLength[#[[3]]] == IntegerLength[#[[4]]] == 3 &];
Length[sel]
t = Take[sel, UpTo[12]];
Column[Row[{#3, "/", #4, " = ", #1, "/", #2, " by removing ", #5}] & @@@ t]
SortBy[Tally[sel[[All, -1]]], First]
sel = Sort@Select[tmp, IntegerLength[#[[3]]] == IntegerLength[#[[4]]] == 4 &];
Length[sel]
t = Take[sel, UpTo[12]];
Column[Row[{#3, "/", #4, " = ", #1, "/", #2, " by removing ", #5}] & @@@ t]
SortBy[Tally[sel[[All, -1]]], First]
|
http://rosettacode.org/wiki/Fractran
|
Fractran
|
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway.
A FRACTRAN program is an ordered list of positive fractions
P
=
(
f
1
,
f
2
,
…
,
f
m
)
{\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})}
, together with an initial positive integer input
n
{\displaystyle n}
.
The program is run by updating the integer
n
{\displaystyle n}
as follows:
for the first fraction,
f
i
{\displaystyle f_{i}}
, in the list for which
n
f
i
{\displaystyle nf_{i}}
is an integer, replace
n
{\displaystyle n}
with
n
f
i
{\displaystyle nf_{i}}
;
repeat this rule until no fraction in the list produces an integer when multiplied by
n
{\displaystyle n}
, then halt.
Conway gave a program for primes in FRACTRAN:
17
/
91
{\displaystyle 17/91}
,
78
/
85
{\displaystyle 78/85}
,
19
/
51
{\displaystyle 19/51}
,
23
/
38
{\displaystyle 23/38}
,
29
/
33
{\displaystyle 29/33}
,
77
/
29
{\displaystyle 77/29}
,
95
/
23
{\displaystyle 95/23}
,
77
/
19
{\displaystyle 77/19}
,
1
/
17
{\displaystyle 1/17}
,
11
/
13
{\displaystyle 11/13}
,
13
/
11
{\displaystyle 13/11}
,
15
/
14
{\displaystyle 15/14}
,
15
/
2
{\displaystyle 15/2}
,
55
/
1
{\displaystyle 55/1}
Starting with
n
=
2
{\displaystyle n=2}
, this FRACTRAN program will change
n
{\displaystyle n}
to
15
=
2
×
(
15
/
2
)
{\displaystyle 15=2\times (15/2)}
, then
825
=
15
×
(
55
/
1
)
{\displaystyle 825=15\times (55/1)}
, generating the following sequence of integers:
2
{\displaystyle 2}
,
15
{\displaystyle 15}
,
825
{\displaystyle 825}
,
725
{\displaystyle 725}
,
1925
{\displaystyle 1925}
,
2275
{\displaystyle 2275}
,
425
{\displaystyle 425}
,
390
{\displaystyle 390}
,
330
{\displaystyle 330}
,
290
{\displaystyle 290}
,
770
{\displaystyle 770}
,
…
{\displaystyle \ldots }
After 2, this sequence contains the following powers of 2:
2
2
=
4
{\displaystyle 2^{2}=4}
,
2
3
=
8
{\displaystyle 2^{3}=8}
,
2
5
=
32
{\displaystyle 2^{5}=32}
,
2
7
=
128
{\displaystyle 2^{7}=128}
,
2
11
=
2048
{\displaystyle 2^{11}=2048}
,
2
13
=
8192
{\displaystyle 2^{13}=8192}
,
2
17
=
131072
{\displaystyle 2^{17}=131072}
,
2
19
=
524288
{\displaystyle 2^{19}=524288}
,
…
{\displaystyle \ldots }
which are the prime powers of 2.
Task
Write a program that reads a list of fractions in a natural format from the keyboard or from a string,
to parse it into a sequence of fractions (i.e. two integers),
and runs the FRACTRAN starting from a provided integer, writing the result at each step.
It is also required that the number of steps is limited (by a parameter easy to find).
Extra credit
Use this program to derive the first 20 or so prime numbers.
See also
For more on how to program FRACTRAN as a universal programming language, see:
J. H. Conway (1987). Fractran: A Simple Universal Programming Language for Arithmetic. In: Open Problems in Communication and Computation, pages 4–26. Springer.
J. H. Conway (2010). "FRACTRAN: A simple universal programming language for arithmetic". In Jeffrey C. Lagarias. The Ultimate Challenge: the 3x+1 problem. American Mathematical Society. pp. 249–264. ISBN 978-0-8218-4940-8. Zbl 1216.68068.
Number Pathology: Fractran by Mark C. Chu-Carroll; October 27, 2006.
|
#FreeBASIC
|
FreeBASIC
|
' version 06-07-2015
' compile with: fbc -s console
' uses gmp
#Include Once "gmp.bi"
' in case the two #define's are missing from 'gmp.bi' define them now
#Ifndef mpq_numref
#Define mpq_numref(Q) (@(Q)->_mp_num)
#Define mpq_denref(Q) (@(Q)->_mp_den)
#EndIf
Dim As String prog(0 To ...) = {"17/91", "78/85", "19/51", "23/38", "29/33",_
"77/29", "95/23", "77/19", "1/17", "11/13", "13/11", "15/14", "15/2", "55/1"}
Dim As UInteger i, j, c, max = UBound(prog)
Dim As Integer scanbit
Dim As ZString Ptr gmp_str : gmp_str = Allocate(10000)
Dim As Mpq_ptr in_, out_
in_ = Allocate(Len(__mpq_struct)) : Mpq_init(in_)
out_ = Allocate(Len(__mpq_struct)) : Mpq_init(out_)
Dim As mpz_ptr num, den
num = Allocate(Len(__mpz_struct)) : Mpz_init(num)
den = Allocate(Len(__mpz_struct)) : Mpz_init(den)
Dim As mpq_ptr instruction(max)
For i = 0 To max
instruction(i) = Allocate(Len(__mpq_struct))
mpq_init(instruction(i))
mpq_set_str(instruction(i), prog(i), 10 )
Next
mpq_set_str(in_ ,"2",10)
i = 0 : j = 0
Print "2";
Do
mpq_mul(out_, instruction(i), in_)
i = i + 1
den = mpq_denref(out_)
If mpz_cmp_ui(den, 1) = 0 Then
Mpq_get_str(gmp_str, 10, out_)
Print ", ";*gmp_str;
mpq_swap(in_, out_)
i = 0
j = j + 1
End If
Loop Until j > 14
' this one only display if the integer is 2^p, p being prime
mpq_set_str(in_ ,"2",10)
i = 0 : j = 0 : c = 0
Print : Print : Print
Print "count iterations prime 2^prime"
Do
mpq_mul(out_, instruction(i), in_)
i = i + 1
j = j + 1
den = mpq_denref(out_)
If mpz_cmp_ui(den, 1) = 0 Then
num = mpq_numref(out_)
scanbit = mpz_scan1(num, 0)
' if scanbit = 0 then number is odd
If scanbit > 0 Then
' return from mpz_scan1(num, scanbit+1) is -1 for power of 2
If mpz_scan1(num, scanbit +1) = -1 Then
If c <= 20 Then Mpq_get_str(gmp_str, 10, out_) Else *gmp_str = ""
c = c + 1
Print Using "##### ################### ######## "; c; j; scanbit;
Print *gmp_str
If InKey <> "" Then Exit Do
End If
End If
mpq_swap(in_, out_)
i = 0
End If
Loop
' Loop Until scanbit > 300
' Loop Until InKey <> ""
' Loop Until scanbit > 300 Or InKey <> ""
' stopping conditions will slow down the hole loop
' loop will check for key if it's printing a result
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#Arturo
|
Arturo
|
multiply: $[x,y][x*y]
print multiply 3 7
multiply2: function [x,y][
return x*y
]
print multiply2 3 7
|
http://rosettacode.org/wiki/Fusc_sequence
|
Fusc sequence
|
Definitions
The fusc integer sequence is defined as:
fusc(0) = 0
fusc(1) = 1
for n>1, the nth term is defined as:
if n is even; fusc(n) = fusc(n/2)
if n is odd; fusc(n) = fusc((n-1)/2) + fusc((n+1)/2)
Note that MathWorld's definition starts with unity, not zero. This task will be using the OEIS' version (above).
An observation
fusc(A) = fusc(B)
where A is some non-negative integer expressed in binary, and
where B is the binary value of A reversed.
Fusc numbers are also known as:
fusc function (named by Dijkstra, 1982)
Stern's Diatomic series (although it starts with unity, not zero)
Stern-Brocot sequence (although it starts with unity, not zero)
Task
show the first 61 fusc numbers (starting at zero) in a horizontal format.
show the fusc number (and its index) whose length is greater than any previous fusc number length.
(the length is the number of decimal digits when the fusc number is expressed in base ten.)
show all numbers with commas (if appropriate).
show all output here.
Related task
RosettaCode Stern-Brocot sequence
Also see
the MathWorld entry: Stern's Diatomic Series.
the OEIS entry: A2487.
|
#Pascal
|
Pascal
|
program fusc;
uses
sysutils;
const
{$IFDEF FPC}
MaxIdx = 1253 * 1000 * 1000; //19573420; // must be even
{$ELSE}
// Dynamics arrays in Delphi cann't be to large
MaxIdx = 19573420;
{$ENDIF}
type
tFuscElem = LongWord;
tFusc = array of tFuscElem;
var
FuscField : tFusc;
function commatize(n:NativeUint):string;
var
l,i : NativeUint;
begin
str(n,result);
l := length(result);
//no commatize
if l < 4 then
exit;
//new length
i := l+ (l-1) DIV 3;
setlength(result,i);
//copy chars to the right place
While i <> l do
Begin
result[i]:= result[l];result[i-1]:= result[l-1];
result[i-2]:= result[l-2];result[i-3]:= ',';
dec(i,4);dec(l,3);
end;
end;
procedure OutFusc(StartIdx,EndIdx :NativeInt;const FF:tFusc);
Begin
IF StartIdx < Low(FF) then StartIdx :=Low(FF);
IF EndIdx > High(FF) then EndIdx := High(FF);
For StartIdx := StartIdx to EndIdx do
write(FF[StartIdx],' ');
writeln;
end;
procedure FuscCalc(var FF:tFusc);
var
pFFn,pFFi : ^tFuscElem;
i,n,sum : NativeUint;
Begin
FF[0]:= 0;
FF[1]:= 1;
n := 2;
i := 1;
pFFn := @FF[n];
pFFi := @FF[i];
sum := pFFi^;
while n <= MaxIdx-2 do
begin
//even
pFFn^ := sum;//FF[n] := FF[i];
//odd
inc(pFFi);//FF[i+1]
inc(pFFn);//FF[n+1]
sum := sum+pFFi^;
pFFn^:= sum; //FF[n+1] := FF[i]+FF[i+1];
sum := pFFi^;
inc(pFFn);
inc(n,2);
//inc(i);
end;
end;
procedure OutHeader(base:NativeInt);
begin
writeln('Fusc numbers with more digits in base ',base,' than all previous ones:');
writeln('Value':10,'Index':10,' IndexNum/IndexNumBefore');
writeln('======':10,' =======':14);
end;
procedure CheckFuscDigits(const FF:tFusc;Base:NativeUint);
var
pFF : ^tFuscElem;
Dig,
i,lastIdx: NativeInt;
Begin
OutHeader(base);
Dig := -1;
i := 0;
lastIdx := 0;
pFF := @FF[0];// aka FF[i]
repeat
//search in tight loop speeds up
repeat
inc(pFF);
inc(i);
until pFF^ >Dig;
if i>= MaxIdx then
BREAK;
//output
write(commatize(pFF^):10,commatize(i):14);//,DIG:10);
IF lastIdx> 0 then
write(i/lastIdx:12:7);
writeln;
lastIdx := i;
IF Dig >0 then
Dig := Dig*Base+Base-1
else
Dig := Base-1;
until false;
writeln;
end;
BEGIN
setlength(FuscField,MaxIdx);
FuscCalc(FuscField);
writeln('First 61 fusc numbers:');
OutFusc(0,60,FuscField);
CheckFuscDigits(FuscField,10);
CheckFuscDigits(FuscField,11); //11 ~phi^5 1.6180..^5 = 11,09
setlength(FuscField,0);
{$IFDEF WIN}readln;{$ENDIF}
END.
|
http://rosettacode.org/wiki/Gamma_function
|
Gamma function
|
Task
Implement one algorithm (or more) to compute the Gamma (
Γ
{\displaystyle \Gamma }
) function (in the real field only).
If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function.
The Gamma function can be defined as:
Γ
(
x
)
=
∫
0
∞
t
x
−
1
e
−
t
d
t
{\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt}
This suggests a straightforward (but inefficient) way of computing the
Γ
{\displaystyle \Gamma }
through numerical integration.
Better suggested methods:
Lanczos approximation
Stirling's approximation
|
#JavaScript
|
JavaScript
|
function gamma(x) {
var p = [0.99999999999980993, 676.5203681218851, -1259.1392167224028,
771.32342877765313, -176.61502916214059, 12.507343278686905,
-0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7
];
var g = 7;
if (x < 0.5) {
return Math.PI / (Math.sin(Math.PI * x) * gamma(1 - x));
}
x -= 1;
var a = p[0];
var t = x + g + 0.5;
for (var i = 1; i < p.length; i++) {
a += p[i] / (x + i);
}
return Math.sqrt(2 * Math.PI) * Math.pow(t, x + 0.5) * Math.exp(-t) * a;
}
|
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
|
#Raku
|
Raku
|
use Lingua::EN::Numbers;
for (1e2, 30, 1e6, 15, 1e9, 10, 7123, 25)».Int -> $start, $count {
put "\nFirst $count gapful numbers starting at {comma $start}:\n" ~
<Sir Lord Duke King>.pick ~ ": ", ~
($start..*).grep( { $_ %% .comb[0, *-1].join } )[^$count];
}
|
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
|
#PL.2FI
|
PL/I
|
Solve: procedure options (main); /* 11 January 2014 */
declare n fixed binary;
put ('Program to solve n simultaneous equations of the form Ax = b. Please type n:' );
get (n);
begin;
declare (A(n, n), b(n), x(n)) float(18);
declare (SA(n,n), Sb(n)) float (18);
declare i fixed binary;
put skip list ('Please type A:');
get (a);
put skip list ('Please type the right-hand sides, b:');
get (b);
SA = A; Sb = b;
put skip list ('The equations are:');
do i = 1 to n;
put skip edit (A(i,*), b(i)) (f(5), x(1));
end;
call Gauss_elimination (A, b);
call Backward_substitution (A, b, x);
put skip list ('Solutions:'); put skip data (x);
/* Check solutions: */
put skip list ('Residuals:');
do i = 1 to n;
put skip list (sum(SA(i,*) * x(*)) - Sb(i));
end;
end;
Gauss_elimination: procedure (A, b) options (reorder); /* Triangularise */
declare (A(*,*), b(*)) float(18);
declare n fixed binary initial (hbound(A, 1));
declare (i, j, k) fixed binary;
declare t float(18);
do j = 1 to n;
do i = j+1 to n; /* For each of the rows beneath the current (pivot) row. */
t = A(j,j) / A(i,j);
do k = j+1 to n; /* Subtract a multiple of row i from row j. */
A(i,k) = A(j,k) - t*A(i,k);
end;
b(i) = b(j) - t*b(i); /* ... and the right-hand side. */
end;
end;
end Gauss_elimination;
Backward_substitution: procedure (A, b, x) options (reorder);
declare (A(*,*), b(*), x(*)) float(18);
declare t float(18);
declare n fixed binary initial (hbound(A, 1));
declare (i, j) fixed binary;
x(n) = b(n) / a(n,n);
do j = n-1 to 1 by -1;
t = 0;
do i = j+1 to n;
t = t + a(j,i)*x(i);
end;
x(j) = (b(j) - t) / a(j,j);
end;
end Backward_substitution;
end Solve;
|
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
|
#Ursa
|
Ursa
|
#
# general fizzbuzz
#
decl int<> factors
decl string<> words
decl int max
# get the max number
out ">" console
set max (in int console)
# get the factors
decl string input
set input " "
while (not (= input ""))
out ">" console
set input (in string console)
if (not (= input ""))
append (int (split input " ")<0>) factors
append (split input " ")<1> words
end if
end while
# output all the numbers
decl int i
for (set i 1) (< i (+ max 1)) (inc i)
decl boolean foundfactor
set foundfactor false
for (decl int j) (< j (size factors)) (inc j)
if (= (mod i factors<j>) 0)
set foundfactor true
out words<j> console
end if
end for
set j 0
if (not foundfactor)
out i console
end if
out endl console
end for
|
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
|
#VBA
|
VBA
|
Option Explicit
Private Type Choice
Number As Integer
Name As String
End Type
Private MaxNumber As Integer
Sub Main()
Dim U(1 To 3) As Choice, i As Integer, j As Integer, t$
MaxNumber = Application.InputBox("Enter the max number : ", "Integer please", Type:=1)
For i = 1 To 3
U(i) = UserChoice
Next
For i = 1 To MaxNumber
t = vbNullString
For j = 1 To 3
If i Mod U(j).Number = 0 Then t = t & U(j).Name
Next
Debug.Print IIf(t = vbNullString, i, t)
Next i
End Sub
Private Function UserChoice() As Choice
Dim ok As Boolean
Do While Not ok
UserChoice.Number = Application.InputBox("Enter the factors to be calculated : ", "Integer please", Type:=1)
UserChoice.Name = InputBox("Enter the corresponding word : ")
If StrPtr(UserChoice.Name) <> 0 And UserChoice.Number < MaxNumber Then ok = True
Loop
End Function
|
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
|
#Mercury
|
Mercury
|
:- module gen_lowercase_ascii.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module char, int, list.
main(!IO) :-
list.map(char.det_from_int, 0'a .. 0'z, Alphabet),
io.print_line(Alphabet, !IO).
:- end_module gen_lowercase_ascii.
|
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
|
#MiniScript
|
MiniScript
|
letters = []
for i in range(code("a"), code("z"))
letters.push char(i)
end for
print letters
|
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
|
#Pikachu
|
Pikachu
|
pikachu pika pikachu pika pika pi pi pika pikachu pika pikachu pi pikachu pi pikachu pi pika pi pikachu pikachu pi pi pika pika pikachu pika pikachu pikachu pi pika pi pika pika pi pikachu pikachu pi pikachu pi pika pikachu pi pikachu pika pikachu pi pikachu pikachu pi pikachu pika pika pikachu pi pikachu pi pi pikachu pikachu pika pikachu pi pika pi pi pika pika pikachu pikachu pi pi pikachu pi pikachu
pikachu pikachu pi pikachu
pikachu pika pika pikachu pika pikachu pikachu pika pika pikachu pikachu pi pi pikachu pika pikachu pika pika pi pika pikachu pikachu pi pika pika pikachu pi pika pi pika pi pikachu pi pikachu pika pika pi pi pika pi pika pika pikachu pikachu pika pikachu pikachu pika pi pikachu pika pi pikachu pi pika pika pi pikachu pika pi pika pikachu pi pi pikachu pika pika pi pika pi pikachu
pikachu pikachu pi pikachu
pikachu pika pi pika pika pikachu pika pikachu pi pikachu pi pi pika pi pikachu pika pi pi pika pikachu pi pikachu pi pi pikachu pikachu pika pikachu pikachu pika pi pikachu pi pika pikachu pi pikachu pika pika pikachu pika pi pi pikachu pikachu pika pika pikachu pi pika pikachu pikachu pi pika pikachu pikachu pika pi pi pikachu pikachu pi pikachu pi pikachu pi pikachu pi pika pikachu pi pikachu pika pikachu pi pika pi pikachu
pi pika
pikachu pikachu pi pikachu
pika pi
pikachu pikachu pi pikachu
pikachu pi pikachu pi pi pikachu pi pikachu pika pikachu pikachu pi pikachu pikachu pika pi pi pika pikachu pika pikachu pi pi pikachu pika pi pi pikachu pika pika pi pika pika pikachu pika pikachu pi pi pika pikachu pika pi pikachu pikachu pi pikachu pika pikachu pikachu pika pi pi pikachu pikachu pi pika pikachu pi pikachu pika pikachu pikachu pika pi pikachu pikachu pika pikachu pi pikachu pika pika pi pikachu pi pika pi pikachu pikachu pi pikachu
pi pika
pikachu pikachu pi pikachu
pikachu pikachu pi pika pikachu pi pika pika pi pi pika pi pikachu pi pika pi pika pi pika pikachu pika pi pi pikachu pi pikachu pi pika pi pika pika pikachu pi pikachu
pikachu pikachu pi pikachu
pikachu pi pikachu pika pikachu pi pika pi pikachu pikachu pika pika pi pi pikachu pi pika pi pikachu pi pika pikachu pi pika pi pi pikachu pikachu pika pika pikachu pikachu pi pi pikachu pi pikachu pi pikachu pi pi pikachu pikachu pi pikachu pi pikachu pi pika pika pikachu pikachu pika pi pika pikachu pi pikachu pi pi pika pikachu pika pi pikachu pi pika pi pi pikachu pikachu pika pika pikachu pika pika pikachu pi pika pi pika pikachu pi pika pikachu pika pi pika pikachu
pikachu pikachu pika pikachu
pikachu pikachu pika pikachu
pi pi pikachu pi pikachu pika pika pi pikachu pika pika pi pi pika pika pikachu pi pi pikachu pi pika pi pika pikachu pi pikachu pi pikachu pikachu pi pi pika pika pi pika pika pi pika pikachu pikachu pi pikachu pika pi pi pika pi pi pikachu pikachu pika pi pi pika pika pi pika pikachu pi pikachu pi pi pika pi pika pika pikachu pika pi pika pikachu pi pikachu pikachu pi pi pika pi pika pika pikachu pikachu pi pikachu
pikachu pikachu pi pikachu
pikachu pi pikachu pikachu pika pikachu pikachu pika pika pikachu pikachu pika pikachu pi pika pikachu pika pika pi pikachu pi pi pika pi pi pikachu pika pika pikachu pikachu pika pikachu pikachu pi pika pi pi pikachu pikachu pika pi pi pikachu pikachu pika pikachu pika pi pikachu pi pika pi pika pikachu pika pi pikachu pi pikachu pikachu pi pika pikachu pi pikachu pikachu pi pika pi pikachu pikachu pi pikachu pika pika pi pi pikachu
pikachu pi pi pika pi pi pikachu pika pikachu pikachu pika pika pi pi pika pikachu pi pikachu pi pi pika pi pika pi pi pika pikachu pi pika pi pikachu pika pikachu pika pi pi pika pi pi pikachu pi pikachu pikachu pika pi pikachu pi pi pika pi pikachu pi pi pika pi pi pikachu pika pikachu pika pikachu pika pi pikachu pikachu pi pi pika pika pikachu
pikachu pikachu pi pikachu
pikachu pikachu pika pikachu
|
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
|
#SenseTalk
|
SenseTalk
|
// ExponentialGenerator.script
to initialize
set my base to 0
if my exponent is empty then set my exponent to 1 -- default if not given
end initialize
to handle nextValue
add 1 to my base
return my base to the power of my exponent
end nextValue
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#FunL
|
FunL
|
import math.{sin, asin}
def compose( f, g ) = x -> f( g(x) )
sin_asin = compose( sin, asin )
println( sin_asin(0.5) )
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#F.C5.8Drmul.C3.A6
|
Fōrmulæ
|
Composition := function(f, g)
return x -> f(g(x));
end;
h := Composition(x -> x+1, x -> x*x);
h(5);
# 26
|
http://rosettacode.org/wiki/Fractal_tree
|
Fractal tree
|
Generate and draw a fractal tree.
Draw the trunk
At the end of the trunk, split by some angle and draw two branches
Repeat at the end of each branch until a sufficient level of branching is reached
Related tasks
Pythagoras Tree
|
#Lingo
|
Lingo
|
----------------------------------------
-- Creates an image of a fractal tree
-- @param {integer} width
-- @param {integer} height
-- @param {integer} fractalDepth
-- @param {integer|float} initSize
-- @param {float} spreadAngle
-- @param {float} [scaleFactor=1.0]
-- @return {image}
----------------------------------------
on fractalTree (width, height, fractalDepth, initSize, spreadAngle, scaleFactor)
if voidP(scaleFactor) then scaleFactor = 1.0
img = image(width, height, 24)
img.fill(img.rect, rgb(0,0,0))
_drawTree(img, width/2, height, -PI/2, fractalDepth, initSize, spreadAngle, scaleFactor)
return img
end
on _drawTree (img, x1, y1, angle, depth, size, spreadAngle, scaleFactor)
if (depth) then
x2 = x1 + cos(angle)*depth*size
y2 = y1 + sin(angle)*depth*size
img.draw(x1, y1, x2, y2, [#color:rgb(255,255,255)])
_drawTree(img, x2, y2, angle-spreadAngle, depth-1, size*ScaleFactor, spreadAngle, scaleFactor)
_drawTree(img, x2, y2, angle+spreadAngle, depth-1, size*ScaleFactor, spreadAngle, scaleFactor)
end if
end
|
http://rosettacode.org/wiki/Fractal_tree
|
Fractal tree
|
Generate and draw a fractal tree.
Draw the trunk
At the end of the trunk, split by some angle and draw two branches
Repeat at the end of each branch until a sufficient level of branching is reached
Related tasks
Pythagoras Tree
|
#Logo
|
Logo
|
to tree :depth :length :scale :angle
if :depth=0 [stop]
setpensize round :depth/2
forward :length
right :angle
tree :depth-1 :length*:scale :scale :angle
left 2*:angle
tree :depth-1 :length*:scale :scale :angle
right :angle
back :length
end
clearscreen
tree 10 80 0.7 30
|
http://rosettacode.org/wiki/Fraction_reduction
|
Fraction reduction
|
There is a fine line between numerator and denominator. ─── anonymous
A method to "reduce" some reducible fractions is to cross out a digit from the
numerator and the denominator. An example is:
16 16
──── and then (simply) cross─out the sixes: ────
64 64
resulting in:
1
───
4
Naturally, this "method" of reduction must reduce to the proper value (shown as a fraction).
This "method" is also known as anomalous cancellation and also accidental cancellation.
(Of course, this "method" shouldn't be taught to impressionable or gullible minds.) 😇
Task
Find and show some fractions that can be reduced by the above "method".
show 2-digit fractions found (like the example shown above)
show 3-digit fractions
show 4-digit fractions
show 5-digit fractions (and higher) (optional)
show each (above) n-digit fractions separately from other different n-sized fractions, don't mix different "sizes" together
for each "size" fraction, only show a dozen examples (the 1st twelve found)
(it's recognized that not every programming solution will have the same generation algorithm)
for each "size" fraction:
show a count of how many reducible fractions were found. The example (above) is size 2
show a count of which digits were crossed out (one line for each different digit)
for each "size" fraction, show a count of how many were found. The example (above) is size 2
show each n-digit example (to be shown on one line):
show each n-digit fraction
show each reduced n-digit fraction
show what digit was crossed out for the numerator and the denominator
Task requirements/restrictions
only proper fractions and their reductions (the result) are to be used (no vulgar fractions)
only positive fractions are to be used (no negative signs anywhere)
only base ten integers are to be used for the numerator and denominator
no zeros (decimal digit) can be used within the numerator or the denominator
the numerator and denominator should be composed of the same number of digits
no digit can be repeated in the numerator
no digit can be repeated in the denominator
(naturally) there should be a shared decimal digit in the numerator and the denominator
fractions can be shown as 16/64 (for example)
Show all output here, on this page.
Somewhat related task
Farey sequence (It concerns fractions.)
References
Wikipedia entry: proper and improper fractions.
Wikipedia entry: anomalous cancellation and/or accidental cancellation.
|
#MiniZinc
|
MiniZinc
|
%Fraction Reduction. Nigel Galloway, September 5th., 2019
include "alldifferent.mzn"; include "member.mzn";
int: S;
array [1..9] of int: Pn=[1,10,100,1000,10000,100000,1000000,10000000,100000000];
array [1..S] of var 1..9: Nz; constraint alldifferent(Nz);
array [1..S] of var 1..9: Gz; constraint alldifferent(Gz);
var int: n; constraint n=sum(n in 1..S)(Nz[n]*Pn[n]);
var int: i; constraint i=sum(n in 1..S)(Gz[n]*Pn[n]); constraint n<i; constraint n*g=i*e;
var int: g; constraint g=sum(n in 1..S)(if n=a then 0 elseif n>a then Gz[n]*Pn[n-1] else Gz[n]*Pn[n] endif);
var int: e; constraint e=sum(n in 1..S)(if n=l then 0 elseif n>l then Nz[n]*Pn[n-1] else Nz[n]*Pn[n] endif);
var 1..S: l; constraint Nz[l]=w;
var 1..S: a; constraint Gz[a]=w;
var 1..9: w; constraint member(Nz,w) /\ member(Gz,w);
output [show(n)++"/"++show(i)++" becomes "++show(e)++"/"++show(g)++" when "++show(w)++" is omitted"]
|
http://rosettacode.org/wiki/Fractran
|
Fractran
|
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway.
A FRACTRAN program is an ordered list of positive fractions
P
=
(
f
1
,
f
2
,
…
,
f
m
)
{\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})}
, together with an initial positive integer input
n
{\displaystyle n}
.
The program is run by updating the integer
n
{\displaystyle n}
as follows:
for the first fraction,
f
i
{\displaystyle f_{i}}
, in the list for which
n
f
i
{\displaystyle nf_{i}}
is an integer, replace
n
{\displaystyle n}
with
n
f
i
{\displaystyle nf_{i}}
;
repeat this rule until no fraction in the list produces an integer when multiplied by
n
{\displaystyle n}
, then halt.
Conway gave a program for primes in FRACTRAN:
17
/
91
{\displaystyle 17/91}
,
78
/
85
{\displaystyle 78/85}
,
19
/
51
{\displaystyle 19/51}
,
23
/
38
{\displaystyle 23/38}
,
29
/
33
{\displaystyle 29/33}
,
77
/
29
{\displaystyle 77/29}
,
95
/
23
{\displaystyle 95/23}
,
77
/
19
{\displaystyle 77/19}
,
1
/
17
{\displaystyle 1/17}
,
11
/
13
{\displaystyle 11/13}
,
13
/
11
{\displaystyle 13/11}
,
15
/
14
{\displaystyle 15/14}
,
15
/
2
{\displaystyle 15/2}
,
55
/
1
{\displaystyle 55/1}
Starting with
n
=
2
{\displaystyle n=2}
, this FRACTRAN program will change
n
{\displaystyle n}
to
15
=
2
×
(
15
/
2
)
{\displaystyle 15=2\times (15/2)}
, then
825
=
15
×
(
55
/
1
)
{\displaystyle 825=15\times (55/1)}
, generating the following sequence of integers:
2
{\displaystyle 2}
,
15
{\displaystyle 15}
,
825
{\displaystyle 825}
,
725
{\displaystyle 725}
,
1925
{\displaystyle 1925}
,
2275
{\displaystyle 2275}
,
425
{\displaystyle 425}
,
390
{\displaystyle 390}
,
330
{\displaystyle 330}
,
290
{\displaystyle 290}
,
770
{\displaystyle 770}
,
…
{\displaystyle \ldots }
After 2, this sequence contains the following powers of 2:
2
2
=
4
{\displaystyle 2^{2}=4}
,
2
3
=
8
{\displaystyle 2^{3}=8}
,
2
5
=
32
{\displaystyle 2^{5}=32}
,
2
7
=
128
{\displaystyle 2^{7}=128}
,
2
11
=
2048
{\displaystyle 2^{11}=2048}
,
2
13
=
8192
{\displaystyle 2^{13}=8192}
,
2
17
=
131072
{\displaystyle 2^{17}=131072}
,
2
19
=
524288
{\displaystyle 2^{19}=524288}
,
…
{\displaystyle \ldots }
which are the prime powers of 2.
Task
Write a program that reads a list of fractions in a natural format from the keyboard or from a string,
to parse it into a sequence of fractions (i.e. two integers),
and runs the FRACTRAN starting from a provided integer, writing the result at each step.
It is also required that the number of steps is limited (by a parameter easy to find).
Extra credit
Use this program to derive the first 20 or so prime numbers.
See also
For more on how to program FRACTRAN as a universal programming language, see:
J. H. Conway (1987). Fractran: A Simple Universal Programming Language for Arithmetic. In: Open Problems in Communication and Computation, pages 4–26. Springer.
J. H. Conway (2010). "FRACTRAN: A simple universal programming language for arithmetic". In Jeffrey C. Lagarias. The Ultimate Challenge: the 3x+1 problem. American Mathematical Society. pp. 249–264. ISBN 978-0-8218-4940-8. Zbl 1216.68068.
Number Pathology: Fractran by Mark C. Chu-Carroll; October 27, 2006.
|
#F.C5.8Drmul.C3.A6
|
Fōrmulæ
|
package main
import (
"fmt"
"log"
"math/big"
"os"
"strconv"
"strings"
)
func compile(src string) ([]big.Rat, bool) {
s := strings.Fields(src)
r := make([]big.Rat, len(s))
for i, s1 := range s {
if _, ok := r[i].SetString(s1); !ok {
return nil, false
}
}
return r, true
}
func exec(p []big.Rat, n *big.Int, limit int) {
var q, r big.Int
rule:
for i := 0; i < limit; i++ {
fmt.Printf("%d ", n)
for j := range p {
q.QuoRem(n, p[j].Denom(), &r)
if r.BitLen() == 0 {
n.Mul(&q, p[j].Num())
continue rule
}
}
break
}
fmt.Println()
}
func usage() {
log.Fatal("usage: ft <limit> <n> <prog>")
}
func main() {
if len(os.Args) != 4 {
usage()
}
limit, err := strconv.Atoi(os.Args[1])
if err != nil {
usage()
}
var n big.Int
_, ok := n.SetString(os.Args[2], 10)
if !ok {
usage()
}
p, ok := compile(os.Args[3])
if !ok {
usage()
}
exec(p, &n, limit)
}
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#AutoHotkey
|
AutoHotkey
|
MsgBox % multiply(10,2)
multiply(multiplicand, multiplier) {
Return (multiplicand * multiplier)
}
|
http://rosettacode.org/wiki/Fusc_sequence
|
Fusc sequence
|
Definitions
The fusc integer sequence is defined as:
fusc(0) = 0
fusc(1) = 1
for n>1, the nth term is defined as:
if n is even; fusc(n) = fusc(n/2)
if n is odd; fusc(n) = fusc((n-1)/2) + fusc((n+1)/2)
Note that MathWorld's definition starts with unity, not zero. This task will be using the OEIS' version (above).
An observation
fusc(A) = fusc(B)
where A is some non-negative integer expressed in binary, and
where B is the binary value of A reversed.
Fusc numbers are also known as:
fusc function (named by Dijkstra, 1982)
Stern's Diatomic series (although it starts with unity, not zero)
Stern-Brocot sequence (although it starts with unity, not zero)
Task
show the first 61 fusc numbers (starting at zero) in a horizontal format.
show the fusc number (and its index) whose length is greater than any previous fusc number length.
(the length is the number of decimal digits when the fusc number is expressed in base ten.)
show all numbers with commas (if appropriate).
show all output here.
Related task
RosettaCode Stern-Brocot sequence
Also see
the MathWorld entry: Stern's Diatomic Series.
the OEIS entry: A2487.
|
#Perl
|
Perl
|
use strict;
use warnings;
use feature 'say';
sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }
sub stern_diatomic {
my ($p,$q,$i) = (0,1,shift);
while ($i) {
if ($i & 1) { $p += $q; } else { $q += $p; }
$i >>= 1;
}
$p;
}
say "First 61 terms of the Fusc sequence:\n" . join ' ', map { stern_diatomic($_) } 0..60;
say "\nIndex and value for first term longer than any previous:";
my $i = 0;
my $l = -1;
while ($l < 5) {
my $v = stern_diatomic($i);
printf("%15s : %s\n", comma($i), comma($v)) and $l = length $v if length $v > $l;
$i++;
}
|
http://rosettacode.org/wiki/Gamma_function
|
Gamma function
|
Task
Implement one algorithm (or more) to compute the Gamma (
Γ
{\displaystyle \Gamma }
) function (in the real field only).
If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function.
The Gamma function can be defined as:
Γ
(
x
)
=
∫
0
∞
t
x
−
1
e
−
t
d
t
{\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt}
This suggests a straightforward (but inefficient) way of computing the
Γ
{\displaystyle \Gamma }
through numerical integration.
Better suggested methods:
Lanczos approximation
Stirling's approximation
|
#jq
|
jq
|
def gamma:
[
1.00000000000000000000, 0.57721566490153286061, -0.65587807152025388108, -0.04200263503409523553,
0.16653861138229148950, -0.04219773455554433675, -0.00962197152787697356, 0.00721894324666309954,
-0.00116516759185906511, -0.00021524167411495097, 0.00012805028238811619, -0.00002013485478078824,
-0.00000125049348214267, 0.00000113302723198170, -0.00000020563384169776, 0.00000000611609510448,
0.00000000500200764447, -0.00000000118127457049, 0.00000000010434267117, 0.00000000000778226344,
-0.00000000000369680562, 0.00000000000051003703, -0.00000000000002058326, -0.00000000000000534812,
0.00000000000000122678, -0.00000000000000011813, 0.00000000000000000119, 0.00000000000000000141,
-0.00000000000000000023, 0.00000000000000000002
] as $a
| (. - 1) as $y
| ($a|length) as $n
| reduce range(2; 1+$n) as $an
($a[$n-1]; (. * $y) + $a[$n - $an])
| 1 / . ;
|
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
|
#REXX
|
REXX
|
/*REXX program computes and displays a series of gapful numbers starting at some number.*/
numeric digits 20 /*ensure enough decimal digits gapfuls.*/
parse arg gapfuls /*obtain optional arguments from the CL*/
if gapfuls='' then gapfuls= 30 25@7123 15@1000000 10@1000000000 /*assume defaults.*/
do until gapfuls=''; parse var gapfuls stuff gapfuls; call gapful stuff
end /*until*/
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
gapful: procedure; parse arg n "@" sp; if sp=='' then sp= 100 /*get args; use default.*/
say center(' 'n " gapful numbers starting at: " sp' ', 125, "═")
$=; #= 0 /*initialize the $ list.*/
do j=sp until #==n /*SP: starting point. */
parse var j a 2 '' -1 b /*get 1st and last digit*/
if j // (a||b) \== 0 then iterate /*perform ÷ into J. */
#= # + 1; $= $ j /*bump #; append ──► $ */
end /*j*/
say strip($); say; return
|
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
|
#PowerShell
|
PowerShell
|
function gauss($a,$b) {
$n = $a.count
for ($k = 0; $k -lt $n; $k++) {
$lmax, $max = $k, [Math]::Abs($a[$k][$k])
for ($l = $k+1; $l -lt $n; $l++) {
$tmp = [Math]::Abs($a[$l][$k])
if($max -lt $tmp) {
$max, $lmax = $tmp, $l
}
}
if ($k -ne $lmax) {
$a[$k], $a[$lmax] = $a[$lmax], $a[$k]
$b[$k], $b[$lmax] = $b[$lmax], $b[$k]
}
$akk = $a[$k][$k]
for ($i = $k+1; $i -lt $n; $i++){
$aik = $a[$i][$k]
for ($j = $k; $j -lt $n; $j++) {
$a[$i][$j] = $a[$i][$j]*$akk - $a[$k][$j]*$aik
}
$b[$i] = $b[$i]*$akk - $b[$k]*$aik
}
}
for ($i = $n-1; $i -ge 0; $i--) {
for ($j = $i+1; $j -lt $n; $j++) {
$b[$i] -= $b[$j]*$a[$i][$j]
}
$b[$i] = $b[$i]/$a[$i][$i]
}
$b
}
function show($a) {
if($a) {
0..($a.Count - 1) | foreach{ if($a[$_]){"$($a[$_][0..($a[$_].count -1)])"}else{""} }
}
}
$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)
)
"a ="
show $a
""
$b = @(-0.01, 0.61, 0.91, 0.99, 0.60, 0.02)
"b ="
$b
""
"x ="
gauss $a $b
|
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
|
#VBScript
|
VBScript
|
'The Function
Function FizzBuzz(range, mapping)
data = Array()
'Parse the mapping and put to "data" array
temp = Split(mapping, ",")
ReDim data(UBound(temp),1)
For i = 0 To UBound(temp)
map = Split(temp(i), " ")
data(i, 0) = map(0)
data(i, 1) = map(1)
Next
'Do the loop
For i = 1 to range
noMatch = True
For j = 0 to UBound(data, 1)
If (i Mod data(j, 0)) = 0 Then
WScript.StdOut.Write data(j, 1)
noMatch = False
End If
Next
If noMatch Then WScript.StdOut.Write i
WScript.StdOut.Write vbCrLf
Next
End Function
'The Main Thing
WScript.StdOut.Write "Range? "
x = WScript.StdIn.ReadLine
WScript.StdOut.Write "Mapping? "
y = WScript.StdIn.ReadLine
WScript.StdOut.WriteLine ""
FizzBuzz x, y
|
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
|
#Visual_Basic_.NET
|
Visual Basic .NET
|
Imports System.Globalization
Module Program
Sub Main()
Console.Write("Max: ")
Dim max = Integer.Parse(Console.ReadLine(), CultureInfo.InvariantCulture)
Dim factors As New SortedDictionary(Of Integer, String)
Const NUM_FACTORS = 3
For i = 1 To NUM_FACTORS
Console.Write("Factor {0}: ", i)
Dim input = Console.ReadLine().Split()
factors.Add(Integer.Parse(input(0), CultureInfo.InvariantCulture), input(1))
Next
For i = 1 To max
Dim anyMatches = False
For Each factor In factors
If i Mod factor.Key = 0 Then
Console.Write(factor.Value)
anyMatches = True
End If
Next
If Not anyMatches Then Console.Write(i)
Console.WriteLine()
Next
End Sub
End Module
|
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
|
#MUMPS
|
MUMPS
|
LOWASCMIN
set lowstr = ""
for i = 97:1:122 set delim = $select(i=97:"",1:",") set lowstr = lowstr_delim_$char(i)
write lowstr
quit
|
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
|
#Nanoquery
|
Nanoquery
|
lowercase = list()
for i in range(ord("a"), ord("z"))
lowercase.append(chr(i))
end
println lowercase
|
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
|
#Pike
|
Pike
|
int main(){
write("Hello world!\n");
}
|
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
|
#Sidef
|
Sidef
|
func gen_pow(m) {
var e = 0;
func { e++ ** m };
}
func gen_filter(g1, g2) {
var v2 = g2.run;
func {
loop {
var v1 = g1.run;
while (v1 > v2) { v2 = g2.run };
v1 == v2 || return v1;
}
}
}
# Create generators.
var squares = gen_pow(2);
var cubes = gen_pow(3);
var squares_without_cubes = gen_filter(squares, cubes);
# Drop 20 values.
20.times { squares_without_cubes() };
# Print 10 values.
var answer = [];
10.times { answer.append(squares_without_cubes()) };
say answer;
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#GAP
|
GAP
|
Composition := function(f, g)
return x -> f(g(x));
end;
h := Composition(x -> x+1, x -> x*x);
h(5);
# 26
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#Go
|
Go
|
// Go doesn't have generics, but sometimes a type definition helps
// readability and maintainability. This example is written to
// the following function type, which uses float64.
type ffType func(float64) float64
// compose function requested by task
func compose(f, g ffType) ffType {
return func(x float64) float64 {
return f(g(x))
}
}
|
http://rosettacode.org/wiki/Fractal_tree
|
Fractal tree
|
Generate and draw a fractal tree.
Draw the trunk
At the end of the trunk, split by some angle and draw two branches
Repeat at the end of each branch until a sufficient level of branching is reached
Related tasks
Pythagoras Tree
|
#Lua
|
Lua
|
g, angle = love.graphics, 26 * math.pi / 180
wid, hei = g.getWidth(), g.getHeight()
function rotate( x, y, a )
local s, c = math.sin( a ), math.cos( a )
local a, b = x * c - y * s, x * s + y * c
return a, b
end
function branches( a, b, len, ang, dir )
len = len * .76
if len < 5 then return end
g.setColor( len * 16, 255 - 2 * len , 0 )
if dir > 0 then ang = ang - angle
else ang = ang + angle
end
local vx, vy = rotate( 0, len, ang )
vx = a + vx; vy = b - vy
g.line( a, b, vx, vy )
branches( vx, vy, len, ang, 1 )
branches( vx, vy, len, ang, 0 )
end
function createTree()
local lineLen = 127
local a, b = wid / 2, hei - lineLen
g.setColor( 160, 40 , 0 )
g.line( wid / 2, hei, a, b )
branches( a, b, lineLen, 0, 1 )
branches( a, b, lineLen, 0, 0 )
end
function love.load()
canvas = g.newCanvas( wid, hei )
g.setCanvas( canvas )
createTree()
g.setCanvas()
end
function love.draw()
g.draw( canvas )
end
|
http://rosettacode.org/wiki/Fraction_reduction
|
Fraction reduction
|
There is a fine line between numerator and denominator. ─── anonymous
A method to "reduce" some reducible fractions is to cross out a digit from the
numerator and the denominator. An example is:
16 16
──── and then (simply) cross─out the sixes: ────
64 64
resulting in:
1
───
4
Naturally, this "method" of reduction must reduce to the proper value (shown as a fraction).
This "method" is also known as anomalous cancellation and also accidental cancellation.
(Of course, this "method" shouldn't be taught to impressionable or gullible minds.) 😇
Task
Find and show some fractions that can be reduced by the above "method".
show 2-digit fractions found (like the example shown above)
show 3-digit fractions
show 4-digit fractions
show 5-digit fractions (and higher) (optional)
show each (above) n-digit fractions separately from other different n-sized fractions, don't mix different "sizes" together
for each "size" fraction, only show a dozen examples (the 1st twelve found)
(it's recognized that not every programming solution will have the same generation algorithm)
for each "size" fraction:
show a count of how many reducible fractions were found. The example (above) is size 2
show a count of which digits were crossed out (one line for each different digit)
for each "size" fraction, show a count of how many were found. The example (above) is size 2
show each n-digit example (to be shown on one line):
show each n-digit fraction
show each reduced n-digit fraction
show what digit was crossed out for the numerator and the denominator
Task requirements/restrictions
only proper fractions and their reductions (the result) are to be used (no vulgar fractions)
only positive fractions are to be used (no negative signs anywhere)
only base ten integers are to be used for the numerator and denominator
no zeros (decimal digit) can be used within the numerator or the denominator
the numerator and denominator should be composed of the same number of digits
no digit can be repeated in the numerator
no digit can be repeated in the denominator
(naturally) there should be a shared decimal digit in the numerator and the denominator
fractions can be shown as 16/64 (for example)
Show all output here, on this page.
Somewhat related task
Farey sequence (It concerns fractions.)
References
Wikipedia entry: proper and improper fractions.
Wikipedia entry: anomalous cancellation and/or accidental cancellation.
|
#Nim
|
Nim
|
# Fraction reduction.
import strformat
import times
type Result = tuple[n: int, nine: array[1..9, int]]
template find[T; N: static int](a: array[1..N, T]; value: T): int =
## Return the one-based index of a value in an array.
## This is needed as "system.find" returns a 0-based index even if the
## array lower bound is not null.
system.find(a, value) + 1
func toNumber(digits: seq[int]; removeDigit: int = 0): int =
## Convert a list of digits into a number.
var digits = digits
if removeDigit != 0:
let idx = digits.find(removeDigit)
digits.delete(idx)
for d in digits:
result = 10 * result + d
func nDigits(n: int): seq[Result] =
var digits = newSeq[int](n + 1) # Allocating one more to work with one-based indexes.
var used: array[1..9, bool]
for i in 1..n:
digits[i] = i
used[i] = true
var terminated = false
while not terminated:
var nine: array[1..9, int]
for i in 1..9:
if used[i]:
nine[i] = digits.toNumber(i)
result &= (n: digits.toNumber(), nine: nine)
block searchLoop:
terminated = true
for i in countdown(n, 1):
let d = digits[i]
doAssert(used[d], "Encountered an inconsistency with 'used' array")
used[d] = false
for j in (d + 1)..9:
if not used[j]:
used[j] = true
digits[i] = j
for k in (i + 1)..n:
digits[k] = used.find(false)
used[digits[k]] = true
terminated = false
break searchLoop
let start = gettime()
for n in 2..6:
let rs = nDigits(n)
var count = 0
var omitted: array[1..9, int]
for i in 1..<rs.high:
let (xn, rn) = rs[i]
for j in (i + 1)..rs.high:
let (xd, rd) = rs[j]
for k in 1..9:
let yn = rn[k]
let yd = rd[k]
if yn != 0 and yd != 0 and xn * yd == yn * xd:
inc count
inc omitted[k]
if count <= 12:
echo &"{xn}/{xd} => {yn}/{yd} (removed {k})"
echo &"{n}-digit fractions found: {count}, omitted {omitted}\n"
echo &"Took {gettime() - start}"
|
http://rosettacode.org/wiki/Fractran
|
Fractran
|
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway.
A FRACTRAN program is an ordered list of positive fractions
P
=
(
f
1
,
f
2
,
…
,
f
m
)
{\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})}
, together with an initial positive integer input
n
{\displaystyle n}
.
The program is run by updating the integer
n
{\displaystyle n}
as follows:
for the first fraction,
f
i
{\displaystyle f_{i}}
, in the list for which
n
f
i
{\displaystyle nf_{i}}
is an integer, replace
n
{\displaystyle n}
with
n
f
i
{\displaystyle nf_{i}}
;
repeat this rule until no fraction in the list produces an integer when multiplied by
n
{\displaystyle n}
, then halt.
Conway gave a program for primes in FRACTRAN:
17
/
91
{\displaystyle 17/91}
,
78
/
85
{\displaystyle 78/85}
,
19
/
51
{\displaystyle 19/51}
,
23
/
38
{\displaystyle 23/38}
,
29
/
33
{\displaystyle 29/33}
,
77
/
29
{\displaystyle 77/29}
,
95
/
23
{\displaystyle 95/23}
,
77
/
19
{\displaystyle 77/19}
,
1
/
17
{\displaystyle 1/17}
,
11
/
13
{\displaystyle 11/13}
,
13
/
11
{\displaystyle 13/11}
,
15
/
14
{\displaystyle 15/14}
,
15
/
2
{\displaystyle 15/2}
,
55
/
1
{\displaystyle 55/1}
Starting with
n
=
2
{\displaystyle n=2}
, this FRACTRAN program will change
n
{\displaystyle n}
to
15
=
2
×
(
15
/
2
)
{\displaystyle 15=2\times (15/2)}
, then
825
=
15
×
(
55
/
1
)
{\displaystyle 825=15\times (55/1)}
, generating the following sequence of integers:
2
{\displaystyle 2}
,
15
{\displaystyle 15}
,
825
{\displaystyle 825}
,
725
{\displaystyle 725}
,
1925
{\displaystyle 1925}
,
2275
{\displaystyle 2275}
,
425
{\displaystyle 425}
,
390
{\displaystyle 390}
,
330
{\displaystyle 330}
,
290
{\displaystyle 290}
,
770
{\displaystyle 770}
,
…
{\displaystyle \ldots }
After 2, this sequence contains the following powers of 2:
2
2
=
4
{\displaystyle 2^{2}=4}
,
2
3
=
8
{\displaystyle 2^{3}=8}
,
2
5
=
32
{\displaystyle 2^{5}=32}
,
2
7
=
128
{\displaystyle 2^{7}=128}
,
2
11
=
2048
{\displaystyle 2^{11}=2048}
,
2
13
=
8192
{\displaystyle 2^{13}=8192}
,
2
17
=
131072
{\displaystyle 2^{17}=131072}
,
2
19
=
524288
{\displaystyle 2^{19}=524288}
,
…
{\displaystyle \ldots }
which are the prime powers of 2.
Task
Write a program that reads a list of fractions in a natural format from the keyboard or from a string,
to parse it into a sequence of fractions (i.e. two integers),
and runs the FRACTRAN starting from a provided integer, writing the result at each step.
It is also required that the number of steps is limited (by a parameter easy to find).
Extra credit
Use this program to derive the first 20 or so prime numbers.
See also
For more on how to program FRACTRAN as a universal programming language, see:
J. H. Conway (1987). Fractran: A Simple Universal Programming Language for Arithmetic. In: Open Problems in Communication and Computation, pages 4–26. Springer.
J. H. Conway (2010). "FRACTRAN: A simple universal programming language for arithmetic". In Jeffrey C. Lagarias. The Ultimate Challenge: the 3x+1 problem. American Mathematical Society. pp. 249–264. ISBN 978-0-8218-4940-8. Zbl 1216.68068.
Number Pathology: Fractran by Mark C. Chu-Carroll; October 27, 2006.
|
#Go
|
Go
|
package main
import (
"fmt"
"log"
"math/big"
"os"
"strconv"
"strings"
)
func compile(src string) ([]big.Rat, bool) {
s := strings.Fields(src)
r := make([]big.Rat, len(s))
for i, s1 := range s {
if _, ok := r[i].SetString(s1); !ok {
return nil, false
}
}
return r, true
}
func exec(p []big.Rat, n *big.Int, limit int) {
var q, r big.Int
rule:
for i := 0; i < limit; i++ {
fmt.Printf("%d ", n)
for j := range p {
q.QuoRem(n, p[j].Denom(), &r)
if r.BitLen() == 0 {
n.Mul(&q, p[j].Num())
continue rule
}
}
break
}
fmt.Println()
}
func usage() {
log.Fatal("usage: ft <limit> <n> <prog>")
}
func main() {
if len(os.Args) != 4 {
usage()
}
limit, err := strconv.Atoi(os.Args[1])
if err != nil {
usage()
}
var n big.Int
_, ok := n.SetString(os.Args[2], 10)
if !ok {
usage()
}
p, ok := compile(os.Args[3])
if !ok {
usage()
}
exec(p, &n, limit)
}
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#AutoIt
|
AutoIt
|
#AutoIt Version: 3.2.10.0
$I=11
$J=12
MsgBox(0,"Multiply", $I &" * "& $J &" = " & product($I,$J))
Func product($a,$b)
Return $a * $b
EndFunc
|
http://rosettacode.org/wiki/Fusc_sequence
|
Fusc sequence
|
Definitions
The fusc integer sequence is defined as:
fusc(0) = 0
fusc(1) = 1
for n>1, the nth term is defined as:
if n is even; fusc(n) = fusc(n/2)
if n is odd; fusc(n) = fusc((n-1)/2) + fusc((n+1)/2)
Note that MathWorld's definition starts with unity, not zero. This task will be using the OEIS' version (above).
An observation
fusc(A) = fusc(B)
where A is some non-negative integer expressed in binary, and
where B is the binary value of A reversed.
Fusc numbers are also known as:
fusc function (named by Dijkstra, 1982)
Stern's Diatomic series (although it starts with unity, not zero)
Stern-Brocot sequence (although it starts with unity, not zero)
Task
show the first 61 fusc numbers (starting at zero) in a horizontal format.
show the fusc number (and its index) whose length is greater than any previous fusc number length.
(the length is the number of decimal digits when the fusc number is expressed in base ten.)
show all numbers with commas (if appropriate).
show all output here.
Related task
RosettaCode Stern-Brocot sequence
Also see
the MathWorld entry: Stern's Diatomic Series.
the OEIS entry: A2487.
|
#Phix
|
Phix
|
constant limit = 20_000_000
sequence fuscs = repeat(0,limit); -- NB 1-based indexing; fusc(0)===fuscs[1]
fuscs[2] = 1 -- ie fusc(1):=1
for n=3 to limit do
fuscs[n] = iff(remainder(n-1,2)?fuscs[n/2]+fuscs[n/2+1]:fuscs[(n+1)/2])
end for
--printf(1,"First 61 terms of the Fusc sequence:\n%v\n",{fuscs[1..61]})
string s = ""
for n=1 to 61 do s&=sprintf("%,d ",fuscs[n]) end for
printf(1,"First 61 terms of the Fusc sequence:\n%s\n\n",{s})
printf(1,"Elements with more digits than any previous items:\n")
printf(1," Index : Value\n")
integer d = 0
for n=1 to length(fuscs) do
if fuscs[n]>=d then
printf(1,"%,15d : %,d\n",{n-1,fuscs[n]})
d = iff(d=0?10:d*10)
end if
end for
|
http://rosettacode.org/wiki/Gamma_function
|
Gamma function
|
Task
Implement one algorithm (or more) to compute the Gamma (
Γ
{\displaystyle \Gamma }
) function (in the real field only).
If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function.
The Gamma function can be defined as:
Γ
(
x
)
=
∫
0
∞
t
x
−
1
e
−
t
d
t
{\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt}
This suggests a straightforward (but inefficient) way of computing the
Γ
{\displaystyle \Gamma }
through numerical integration.
Better suggested methods:
Lanczos approximation
Stirling's approximation
|
#Jsish
|
Jsish
|
#!/usr/bin/env jsish
/* Gamma function, in Jsish, using the Lanczos approximation */
function gamma(x) {
var p = [0.99999999999980993, 676.5203681218851, -1259.1392167224028,
771.32342877765313, -176.61502916214059, 12.507343278686905,
-0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7
];
var g = 7;
if (x < 0.5) {
return Math.PI / (Math.sin(Math.PI * x) * gamma(1 - x));
}
x -= 1;
var a = p[0];
var t = x + g + 0.5;
for (var i = 1; i < p.length; i++) {
a += p[i] / (x + i);
}
return Math.sqrt(2 * Math.PI) * Math.pow(t, x + 0.5) * Math.exp(-t) * a;
}
if (Interp.conf('unitTest')) {
for (var i=-5.5; i <= 5.5; i += 0.5) {
printf('%2.1f %+e\n', i, gamma(i));
}
}
/*
=!EXPECTSTART!=
-5.5 +1.091265e-02
-5.0 -4.275508e+13
-4.5 -6.001960e-02
-4.0 +2.672193e+14
-3.5 +2.700882e-01
-3.0 -1.425169e+15
-2.5 -9.453087e-01
-2.0 +6.413263e+15
-1.5 +2.363272e+00
-1.0 -2.565305e+16
-0.5 -3.544908e+00
0.0 +inf
0.5 +1.772454e+00
1.0 +1.000000e+00
1.5 +8.862269e-01
2.0 +1.000000e+00
2.5 +1.329340e+00
3.0 +2.000000e+00
3.5 +3.323351e+00
4.0 +6.000000e+00
4.5 +1.163173e+01
5.0 +2.400000e+01
5.5 +5.234278e+01
=!EXPECTEND!=
*/
|
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
|
#Ring
|
Ring
|
nr = 0
gapful1 = 99
gapful2 = 999999
gapful3 = 999999999
limit1 = 30
limit2 = 15
limit3 = 10
see "First 30 gapful numbers >= 100:" + nl
while nr < limit1
gapful1 = gapful1 + 1
gap1 = left((string(gapful1)),1)
gap2 = right((string(gapful1)),1)
gap = number(gap1 +gap2)
if gapful1 % gap = 0
nr = nr + 1
see "" + nr + ". " + gapful1 + nl
ok
end
see nl
see "First 15 gapful numbers >= 1000000:" + nl
nr = 0
while nr < limit2
gapful2 = gapful2 + 1
gap1 = left((string(gapful2)),1)
gap2 = right((string(gapful2)),1)
gap = number(gap1 +gap2)
if (nr < limit2) and gapful2 % gap = 0
nr = nr + 1
see "" + nr + ". " + gapful2 + nl
ok
end
see nl
see "First 10 gapful numbers >= 1000000000:" + nl
nr = 0
while nr < limit3
gapful3 = gapful3 + 1
gap1 = left((string(gapful3)),1)
gap2 = right((string(gapful3)),1)
gap = number(gap1 +gap2)
if (nr < limit2) and gapful3 % gap = 0
nr = nr + 1
see "" + nr + ". " + gapful3 + nl
ok
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
|
#Ruby
|
Ruby
|
class Integer
def gapful?
a = digits
self % (a.last*10 + a.first) == 0
end
end
specs = {100 => 30, 1_000_000 => 15, 1_000_000_000 => 10, 7123 => 25}
specs.each do |start, num|
puts "first #{num} gapful numbers >= #{start}:"
p (start..).lazy.select(&:gapful?).take(num).to_a
end
|
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
|
#Python
|
Python
|
# The 'gauss' function takes two matrices, 'a' and 'b', with 'a' square, and it return the determinant of 'a' and a matrix 'x' such that a*x = b.
# If 'b' is the identity, then 'x' is the inverse of 'a'.
import copy
from fractions import Fraction
def gauss(a, b):
a = copy.deepcopy(a)
b = copy.deepcopy(b)
n = len(a)
p = len(b[0])
det = 1
for i in range(n - 1):
k = i
for j in range(i + 1, n):
if abs(a[j][i]) > abs(a[k][i]):
k = j
if k != i:
a[i], a[k] = a[k], a[i]
b[i], b[k] = b[k], b[i]
det = -det
for j in range(i + 1, n):
t = a[j][i]/a[i][i]
for k in range(i + 1, n):
a[j][k] -= t*a[i][k]
for k in range(p):
b[j][k] -= t*b[i][k]
for i in range(n - 1, -1, -1):
for j in range(i + 1, n):
t = a[i][j]
for k in range(p):
b[i][k] -= t*b[j][k]
t = 1/a[i][i]
det *= a[i][i]
for j in range(p):
b[i][j] *= t
return det, b
def zeromat(p, q):
return [[0]*q for i in range(p)]
def matmul(a, b):
n, p = len(a), len(a[0])
p1, q = len(b), len(b[0])
if p != p1:
raise ValueError("Incompatible dimensions")
c = zeromat(n, q)
for i in range(n):
for j in range(q):
c[i][j] = sum(a[i][k]*b[k][j] for k in range(p))
return c
def mapmat(f, a):
return [list(map(f, v)) for v in a]
def ratmat(a):
return mapmat(Fraction, a)
# As an example, compute the determinant and inverse of 3x3 magic square
a = [[2, 9, 4], [7, 5, 3], [6, 1, 8]]
b = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
det, c = gauss(a, b)
det
-360.0
c
[[-0.10277777777777776, 0.18888888888888888, -0.019444444444444438],
[0.10555555555555554, 0.02222222222222223, -0.061111111111111116],
[0.0638888888888889, -0.14444444444444446, 0.14722222222222223]]
# Check product
matmul(a, c)
[[1.0, 0.0, 0.0], [5.551115123125783e-17, 1.0, 0.0],
[1.1102230246251565e-16, -2.220446049250313e-16, 1.0]]
# Same with fractions, so the result is exact
det, c = gauss(ratmat(a), ratmat(b))
det
Fraction(-360, 1)
c
[[Fraction(-37, 360), Fraction(17, 90), Fraction(-7, 360)],
[Fraction(19, 180), Fraction(1, 45), Fraction(-11, 180)],
[Fraction(23, 360), Fraction(-13, 90), Fraction(53, 360)]]
matmul(a, c)
[[Fraction(1, 1), Fraction(0, 1), Fraction(0, 1)],
[Fraction(0, 1), Fraction(1, 1), Fraction(0, 1)],
[Fraction(0, 1), Fraction(0, 1), Fraction(1, 1)]]
|
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
|
#Vlang
|
Vlang
|
import os
fn main() {
max := os.input('Max: ').int()
f1 := os.input('Starting factor (#) and word: ').fields()
f2 := os.input('Next factor (#) and word: ').fields()
f3 := os.input('Next factor (#) and word: ').fields()
//using the provided data
words := {
f1[0].int(): f1[1],
f2[0].int(): f2[1],
f3[0].int(): f3[1],
}
keys := words.keys()
mut divisible := false
for i := 1; i <= max; i++ {
for n in keys {
if i % n == 0 {
print(words[n])
divisible = true
}
}
if !divisible {
print(i)
}
println('')
divisible = false
}
}
|
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
|
#Wren
|
Wren
|
import "io" for Stdin, Stdout
import "/sort" for Sort
var n
while (true) {
System.write("Maximum number : ")
Stdout.flush()
n = Num.fromString(Stdin.readLine())
if (!n || !n.isInteger || n < 3) {
System.print("Must be an integer > 2, try again.")
} else {
break
}
}
var factors = []
var words = {}
for (i in 0..2) {
while (true) {
System.write("Factor %(i+1) : ")
Stdout.flush()
var factor = Num.fromString(Stdin.readLine())
if (!factor || !factor.isInteger || factor < 2 || factors.contains(factor)) {
System.print("Must be an unused integer > 1, try again.")
} else {
factors.add(factor)
var outer = false
while (true) {
System.write(" Word %(i+1) : ")
Stdout.flush()
var word = Stdin.readLine()
if (word.count == 0) {
System.print("Must have at least one character, try again.")
} else {
words[factor] = word
outer = true
break
}
}
if (outer) break
}
}
}
Sort.insertion(factors)
System.print()
for (i in 1..n) {
var s = ""
for (j in 0..2) {
var factor = factors[j]
if (i % factor == 0) s = s + words[factor]
}
if (s == "") s = i.toString
System.print(s)
}
|
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
|
#Neko
|
Neko
|
/**
<doc>Generate lower case ASCII, in Neko</doc>
**/
var slot = 25
var generated = $smake(slot + 1)
var lower_a = $sget("a", 0)
/* 'a'+25 down to 'a'+0 */
while slot >= 0 {
$sset(generated, slot, slot + lower_a)
slot -= 1
}
$print(generated, "\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
|
#NESL
|
NESL
|
lower_case_ascii = {code_char(c) : c in [97:123]};
|
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
|
#PILOT
|
PILOT
|
T:Hello world!
|
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
|
#SuperCollider
|
SuperCollider
|
f = { |m| {:x, x<-(0..) } ** m };
g = f.(2);
g.nextN(10); // answers [ 0, 1, 4, 9, 16, 25, 36, 49, 64, 81 ]
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#Groovy
|
Groovy
|
final times2 = { it * 2 }
final plus1 = { it + 1 }
final plus1_then_times2 = times2 << plus1
final times2_then_plus1 = times2 >> plus1
assert plus1_then_times2(3) == 8
assert times2_then_plus1(3) == 7
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#Haskell
|
Haskell
|
Prelude> let sin_asin = sin . asin
Prelude> sin_asin 0.5
0.49999999999999994
|
http://rosettacode.org/wiki/Fractal_tree
|
Fractal tree
|
Generate and draw a fractal tree.
Draw the trunk
At the end of the trunk, split by some angle and draw two branches
Repeat at the end of each branch until a sufficient level of branching is reached
Related tasks
Pythagoras Tree
|
#Mathematica_.2F_Wolfram_Language
|
Mathematica / Wolfram Language
|
fractalTree[
pt : {_, _}, \[Theta]orient_: \[Pi]/2, \[Theta]sep_: \[Pi]/9,
depth_Integer: 9] := Module[{pt2},
If[depth == 0, Return[]];
pt2 = pt + {Cos[\[Theta]orient], Sin[\[Theta]orient]}*depth;
DeleteCases[
Flatten@{
Line[{pt, pt2}],
fractalTree[pt2, \[Theta]orient - \[Theta]sep, \[Theta]sep,
depth - 1],
fractalTree[pt2, \[Theta]orient + \[Theta]sep, \[Theta]sep,
depth - 1]
},
Null
]
]
Graphics[fractalTree[{0, 0}, \[Pi]/2, \[Pi]/9]]
|
http://rosettacode.org/wiki/Fractal_tree
|
Fractal tree
|
Generate and draw a fractal tree.
Draw the trunk
At the end of the trunk, split by some angle and draw two branches
Repeat at the end of each branch until a sufficient level of branching is reached
Related tasks
Pythagoras Tree
|
#NetRexx
|
NetRexx
|
/* NetRexx */
options replace format comments java crossref symbols binary
import java.awt.Color
import java.awt.Graphics
import javax.swing.JFrame
class RFractalTree public extends JFrame
properties constant
isTrue = (1 == 1)
isFalse = \isTrue
-- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
method RFractalTree() public
super('Fractal Tree')
setBounds(100, 100, 800, 600)
setResizable(isFalse)
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
return
-- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
method drawTree(g = Graphics, x1 = int, y1 = int, angle = double, depth = int) private
if depth \= 0 then do
x2 = x1 + (int Math.cos(Math.toRadians(angle)) * depth * 10.0)
y2 = y1 + (int Math.sin(Math.toRadians(angle)) * depth * 10.0)
g.drawLine(x1, y1, x2, y2)
drawTree(g, x2, y2, angle - 20, depth - 1)
drawTree(g, x2, y2, angle + 20, depth - 1)
end
return
-- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
method paint(g = Graphics) public
g.setColor(Color.BLACK)
drawTree(g, 400, 500, -90, 9)
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method main(args = String[])public static
RFractalTree().setVisible(isTrue)
return
|
http://rosettacode.org/wiki/Fraction_reduction
|
Fraction reduction
|
There is a fine line between numerator and denominator. ─── anonymous
A method to "reduce" some reducible fractions is to cross out a digit from the
numerator and the denominator. An example is:
16 16
──── and then (simply) cross─out the sixes: ────
64 64
resulting in:
1
───
4
Naturally, this "method" of reduction must reduce to the proper value (shown as a fraction).
This "method" is also known as anomalous cancellation and also accidental cancellation.
(Of course, this "method" shouldn't be taught to impressionable or gullible minds.) 😇
Task
Find and show some fractions that can be reduced by the above "method".
show 2-digit fractions found (like the example shown above)
show 3-digit fractions
show 4-digit fractions
show 5-digit fractions (and higher) (optional)
show each (above) n-digit fractions separately from other different n-sized fractions, don't mix different "sizes" together
for each "size" fraction, only show a dozen examples (the 1st twelve found)
(it's recognized that not every programming solution will have the same generation algorithm)
for each "size" fraction:
show a count of how many reducible fractions were found. The example (above) is size 2
show a count of which digits were crossed out (one line for each different digit)
for each "size" fraction, show a count of how many were found. The example (above) is size 2
show each n-digit example (to be shown on one line):
show each n-digit fraction
show each reduced n-digit fraction
show what digit was crossed out for the numerator and the denominator
Task requirements/restrictions
only proper fractions and their reductions (the result) are to be used (no vulgar fractions)
only positive fractions are to be used (no negative signs anywhere)
only base ten integers are to be used for the numerator and denominator
no zeros (decimal digit) can be used within the numerator or the denominator
the numerator and denominator should be composed of the same number of digits
no digit can be repeated in the numerator
no digit can be repeated in the denominator
(naturally) there should be a shared decimal digit in the numerator and the denominator
fractions can be shown as 16/64 (for example)
Show all output here, on this page.
Somewhat related task
Farey sequence (It concerns fractions.)
References
Wikipedia entry: proper and improper fractions.
Wikipedia entry: anomalous cancellation and/or accidental cancellation.
|
#Pascal
|
Pascal
|
program FracRedu;
{$IFDEF FPC}
{$MODE DELPHI}
{$OPTIMIZATION ON,ALL}
{$ELSE}
{$APPTYPE CONSOLE}
{$ENDIF}
uses
SysUtils;
type
tdigit = 0..9;
const
cMaskDgt: array [tdigit] of Uint32 = (1, 2, 4, 8, 16, 32, 64, 128, 256, 512
{,1024,2048,4096,8193,16384,32768});
cMaxDigits = High(tdigit);
type
tPermfield = array[tdigit] of uint32;
tpPermfield = ^tPermfield;
tDigitCnt = array[tdigit] of Uint32;
tErg = record
numUsedDigits : Uint32;
numUnusedDigit : array[tdigit] of Uint32;
numNormal : Uint64;// so sqr of number stays in Uint64
dummy : array[0..7] of byte;//-> sizeof(tErg) = 64
end;
tpErg = ^tErg;
var
Erg: array of tErg;
pf_x, pf_y: tPermfield;
DigitCnt :tDigitCnt;
permcnt, UsedDigits,Anzahl: NativeUint;
function Fakultaet(i: integer): integer;
begin
Result := 1;
while i > 1 do
begin
Result := Result * i;
Dec(i);
end;
end;
procedure OutErg(dgt: Uint32;pi,pJ:tpErg);
begin
writeln(dgt:3,' ', pi^.numUnusedDigit[dgt],'/',pj^.numUnusedDigit[dgt]
,' = ',pi^.numNormal,'/',pj^.numNormal);
end;
function Check(pI,pJ : tpErg;Nud :Word):integer;
var
dgt: NativeInt;
Begin
result := 0;
dgt := 1;
NUD := NUD SHR 1;
repeat
IF NUD AND 1 <> 0 then
Begin
If pI^.numNormal*pJ^.numUnusedDigit[dgt] = pJ^.numNormal*pI^.numUnusedDigit[dgt] then
Begin
inc(result);
inc(DigitCnt[dgt]);
IF Anzahl < 110 then
OutErg(dgt,pI,pJ);
end;
end;
inc(dgt);
NUD := NUD SHR 1;
until NUD = 0;
end;
procedure CheckWithOne(pI : tpErg;j,Nud:Uint32);
var
pJ : tpErg;
l : NativeUInt;
Begin
pJ := pI;
if UsedDigits <5 then
Begin
for j := j+1 to permcnt do
begin
inc(pJ);
//digits used by both numbers
l := NUD AND pJ^.numUsedDigits;
IF l <> 0 then
inc(Anzahl,Check(pI,pJ,l));
end;
end
else
Begin
for j := j+1 to permcnt do
begin
inc(pJ);
l := NUD AND pJ^.numUsedDigits;
inc(Anzahl,Check(pI,pJ,l));
end;
end;
end;
procedure SearchMultiple;
var
pI : tpErg;
i : NativeUInt;
begin
pI := @Erg[0];
for i := 0 to permcnt do
Begin
CheckWithOne(pI,i,pI^.numUsedDigits);
inc(pI);
end;
end;
function BinomCoeff(n, k: byte): longint;
var
i: longint;
begin
{n ueber k = n ueber (n-k) , also kuerzere Version waehlen}
if k > n div 2 then
k := n - k;
Result := 1;
if k <= n then
for i := 1 to k do
Result := Result * (n - i + 1) div i;{geht immer ohne Rest }
end;
procedure InsertToErg(var E: tErg; const x: tPermfield);
var
n : Uint64;
k,i,j,dgt,nud: NativeInt;
begin
// k of PermKoutofN is reduced by one for 9 digits
k := UsedDigits;
n := 0;
nud := 0;
for i := 1 to k do
begin
dgt := x[i];
nud := nud or cMaskDgt[dgt];
n := n * 10 + dgt;
end;
with E do
begin
numUsedDigits := nud;
numNormal := n;
end;
//calc all numbers with one removed digit
For J := k downto 1 do
Begin
n := 0;
for i := 1 to j-1 do
n := n * 10 + x[i];
for i := j+1 to k do
n := n * 10 + x[i];
E.numUnusedDigit[x[j]] := n;
end;
end;
procedure PermKoutofN(k, n: nativeInt);
var
x, y: tpPermfield;
i, yi, tmp: NativeInt;
begin
//initialise
x := @pf_x;
y := @pf_y;
permcnt := 0;
if k > n then
k := n;
if k = n then
k := k - 1;
for i := 1 to n do
x^[i] := i;
for i := 1 to k do
y^[i] := i;
InserttoErg(Erg[permcnt], x^);
i := k;
repeat
yi := y^[i];
if yi < n then
begin
Inc(permcnt);
Inc(yi);
y^[i] := yi;
tmp := x^[i];
x^[i] := x^[yi];
x^[yi] := tmp;
i := k;
InserttoErg(Erg[permcnt], x^);
end
else
begin
repeat
tmp := x^[i];
x^[i] := x^[yi];
x^[yi] := tmp;
Dec(yi);
until yi <= i;
y^[i] := yi;
Dec(i);
end;
until (i = 0);
end;
procedure OutDigitCount;
var
i : tDigit;
Begin
writeln('omitted digits 1 to 9');
For i := 1 to 9do
write(DigitCnt[i]:UsedDigits);
writeln;
end;
procedure ClearDigitCount;
var
i : tDigit;
Begin
For i := low(DigitCnt) to high(DigitCnt) do
DigitCnt[i] := 0;
end;
var
t1, t0: TDateTime;
begin
For UsedDigits := 8 to 9 do
Begin
writeln('Used digits ',UsedDigits);
T0 := now;
ClearDigitCount;
setlength(Erg, Fakultaet(UsedDigits) * BinomCoeff(cMaxDigits, UsedDigits));
Anzahl := 0;
permcnt := 0;
PermKoutOfN(UsedDigits, cMaxDigits);
SearchMultiple;
T1 := now;
writeln('Found solutions ',Anzahl);
OutDigitCount;
writeln('time taken ',FormatDateTime('HH:NN:SS.zzz', T1 - T0));
setlength(Erg, 0);
writeln;
end;
end.
|
http://rosettacode.org/wiki/Fractran
|
Fractran
|
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway.
A FRACTRAN program is an ordered list of positive fractions
P
=
(
f
1
,
f
2
,
…
,
f
m
)
{\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})}
, together with an initial positive integer input
n
{\displaystyle n}
.
The program is run by updating the integer
n
{\displaystyle n}
as follows:
for the first fraction,
f
i
{\displaystyle f_{i}}
, in the list for which
n
f
i
{\displaystyle nf_{i}}
is an integer, replace
n
{\displaystyle n}
with
n
f
i
{\displaystyle nf_{i}}
;
repeat this rule until no fraction in the list produces an integer when multiplied by
n
{\displaystyle n}
, then halt.
Conway gave a program for primes in FRACTRAN:
17
/
91
{\displaystyle 17/91}
,
78
/
85
{\displaystyle 78/85}
,
19
/
51
{\displaystyle 19/51}
,
23
/
38
{\displaystyle 23/38}
,
29
/
33
{\displaystyle 29/33}
,
77
/
29
{\displaystyle 77/29}
,
95
/
23
{\displaystyle 95/23}
,
77
/
19
{\displaystyle 77/19}
,
1
/
17
{\displaystyle 1/17}
,
11
/
13
{\displaystyle 11/13}
,
13
/
11
{\displaystyle 13/11}
,
15
/
14
{\displaystyle 15/14}
,
15
/
2
{\displaystyle 15/2}
,
55
/
1
{\displaystyle 55/1}
Starting with
n
=
2
{\displaystyle n=2}
, this FRACTRAN program will change
n
{\displaystyle n}
to
15
=
2
×
(
15
/
2
)
{\displaystyle 15=2\times (15/2)}
, then
825
=
15
×
(
55
/
1
)
{\displaystyle 825=15\times (55/1)}
, generating the following sequence of integers:
2
{\displaystyle 2}
,
15
{\displaystyle 15}
,
825
{\displaystyle 825}
,
725
{\displaystyle 725}
,
1925
{\displaystyle 1925}
,
2275
{\displaystyle 2275}
,
425
{\displaystyle 425}
,
390
{\displaystyle 390}
,
330
{\displaystyle 330}
,
290
{\displaystyle 290}
,
770
{\displaystyle 770}
,
…
{\displaystyle \ldots }
After 2, this sequence contains the following powers of 2:
2
2
=
4
{\displaystyle 2^{2}=4}
,
2
3
=
8
{\displaystyle 2^{3}=8}
,
2
5
=
32
{\displaystyle 2^{5}=32}
,
2
7
=
128
{\displaystyle 2^{7}=128}
,
2
11
=
2048
{\displaystyle 2^{11}=2048}
,
2
13
=
8192
{\displaystyle 2^{13}=8192}
,
2
17
=
131072
{\displaystyle 2^{17}=131072}
,
2
19
=
524288
{\displaystyle 2^{19}=524288}
,
…
{\displaystyle \ldots }
which are the prime powers of 2.
Task
Write a program that reads a list of fractions in a natural format from the keyboard or from a string,
to parse it into a sequence of fractions (i.e. two integers),
and runs the FRACTRAN starting from a provided integer, writing the result at each step.
It is also required that the number of steps is limited (by a parameter easy to find).
Extra credit
Use this program to derive the first 20 or so prime numbers.
See also
For more on how to program FRACTRAN as a universal programming language, see:
J. H. Conway (1987). Fractran: A Simple Universal Programming Language for Arithmetic. In: Open Problems in Communication and Computation, pages 4–26. Springer.
J. H. Conway (2010). "FRACTRAN: A simple universal programming language for arithmetic". In Jeffrey C. Lagarias. The Ultimate Challenge: the 3x+1 problem. American Mathematical Society. pp. 249–264. ISBN 978-0-8218-4940-8. Zbl 1216.68068.
Number Pathology: Fractran by Mark C. Chu-Carroll; October 27, 2006.
|
#Haskell
|
Haskell
|
import Data.List (find)
import Data.Ratio (Ratio, (%), denominator)
fractran :: (Integral a) => [Ratio a] -> a -> [a]
fractran fracts n = n :
case find (\f -> n `mod` denominator f == 0) fracts of
Nothing -> []
Just f -> fractran fracts $ truncate (fromIntegral n * f)
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#AWK
|
AWK
|
function multiply(a, b)
{
return a*b
}
BEGIN {
print multiply(5, 6)
}
|
http://rosettacode.org/wiki/Fusc_sequence
|
Fusc sequence
|
Definitions
The fusc integer sequence is defined as:
fusc(0) = 0
fusc(1) = 1
for n>1, the nth term is defined as:
if n is even; fusc(n) = fusc(n/2)
if n is odd; fusc(n) = fusc((n-1)/2) + fusc((n+1)/2)
Note that MathWorld's definition starts with unity, not zero. This task will be using the OEIS' version (above).
An observation
fusc(A) = fusc(B)
where A is some non-negative integer expressed in binary, and
where B is the binary value of A reversed.
Fusc numbers are also known as:
fusc function (named by Dijkstra, 1982)
Stern's Diatomic series (although it starts with unity, not zero)
Stern-Brocot sequence (although it starts with unity, not zero)
Task
show the first 61 fusc numbers (starting at zero) in a horizontal format.
show the fusc number (and its index) whose length is greater than any previous fusc number length.
(the length is the number of decimal digits when the fusc number is expressed in base ten.)
show all numbers with commas (if appropriate).
show all output here.
Related task
RosettaCode Stern-Brocot sequence
Also see
the MathWorld entry: Stern's Diatomic Series.
the OEIS entry: A2487.
|
#Picat
|
Picat
|
main =>
println("First 61 fusc numbers:"),
println([fusc(I) : I in 0..60]),
nl,
println("Points in the sequence whose length is greater than any previous fusc number length:\n"),
println(" Index fusc Len"),
largest_fusc_string(20_000_000).
table
fusc(0) = 0.
fusc(1) = 1.
fusc(N) = fusc(N//2), even(N) => true.
fusc(N) = fusc((N-1)//2) + fusc((N+1)//2) => true.
largest_fusc_string(Limit) =>
largest_fusc_string(0,Limit,0).
largest_fusc_string(Limit,Limit,_).
largest_fusc_string(N,Limit,LargestLen) :-
N <= Limit,
F = fusc(N),
Len = F.to_string.len,
(Len > LargestLen ->
printf("%8d %8d %4d\n",N,F,Len),
LargestLen1 = Len
;
LargestLen1 = LargestLen
),
largest_fusc_string(N+1,Limit,LargestLen1).
|
http://rosettacode.org/wiki/Fusc_sequence
|
Fusc sequence
|
Definitions
The fusc integer sequence is defined as:
fusc(0) = 0
fusc(1) = 1
for n>1, the nth term is defined as:
if n is even; fusc(n) = fusc(n/2)
if n is odd; fusc(n) = fusc((n-1)/2) + fusc((n+1)/2)
Note that MathWorld's definition starts with unity, not zero. This task will be using the OEIS' version (above).
An observation
fusc(A) = fusc(B)
where A is some non-negative integer expressed in binary, and
where B is the binary value of A reversed.
Fusc numbers are also known as:
fusc function (named by Dijkstra, 1982)
Stern's Diatomic series (although it starts with unity, not zero)
Stern-Brocot sequence (although it starts with unity, not zero)
Task
show the first 61 fusc numbers (starting at zero) in a horizontal format.
show the fusc number (and its index) whose length is greater than any previous fusc number length.
(the length is the number of decimal digits when the fusc number is expressed in base ten.)
show all numbers with commas (if appropriate).
show all output here.
Related task
RosettaCode Stern-Brocot sequence
Also see
the MathWorld entry: Stern's Diatomic Series.
the OEIS entry: A2487.
|
#Processing
|
Processing
|
void setup() {
println("First 61 terms:");
for (int i = 0; i < 60; i++) {
print(fusc(i) + " ");
}
println(fusc(60));
println();
println("Sequence elements where number of digits of the value increase:");
int max_len = 0;
for (int i = 0; i < 700000; i++) {
int temp = fusc(i);
if (str(temp).length() > max_len) {
max_len = str(temp).length();
println("(" + i + ", " + temp + ")");
}
}
}
int fusc(int n) {
if (n <= 1) {
return n;
} else if (n % 2 == 0) {
return fusc(n / 2);
} else {
return fusc((n - 1) / 2) + fusc((n + 1) / 2);
}
}
|
http://rosettacode.org/wiki/Gamma_function
|
Gamma function
|
Task
Implement one algorithm (or more) to compute the Gamma (
Γ
{\displaystyle \Gamma }
) function (in the real field only).
If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function.
The Gamma function can be defined as:
Γ
(
x
)
=
∫
0
∞
t
x
−
1
e
−
t
d
t
{\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt}
This suggests a straightforward (but inefficient) way of computing the
Γ
{\displaystyle \Gamma }
through numerical integration.
Better suggested methods:
Lanczos approximation
Stirling's approximation
|
#Julia
|
Julia
|
@show gamma(1)
|
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
|
#Scheme
|
Scheme
|
(define (first-digit n) (string->number (string (string-ref (number->string n) 0))))
(define (last-digit n) (modulo n 10))
(define (bookend-number n) (+ (* 10 (first-digit n)) (last-digit n)))
(define (gapful? n) (and (>= n 100) (zero? (modulo n (bookend-number n)))))
(define (gapfuls-in-range start size)
(let ((found 0) (result '()))
(do ((n start (+ n 1))) ((>= found size) (reverse result))
(if (gapful? n)
(begin (set! result (cons n result)) (set! found (+ found 1)))))))
(define (report-range range)
(apply (lambda (start size)
(newline)
(display "The first ")(display size)(display " gapful numbers >= ")
(display start)(display ":")(newline)
(display (gapfuls-in-range start size))(newline)) range))
(map report-range '((100 30) (1000000 15) (1000000000 10)))
|
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
|
#R
|
R
|
gauss <- function(a, b) {
n <- nrow(a)
det <- 1
for (i in seq_len(n - 1)) {
j <- which.max(a[i:n, i]) + i - 1
if (j != i) {
a[c(i, j), i:n] <- a[c(j, i), i:n]
b[c(i, j), ] <- b[c(j, i), ]
det <- -det
}
k <- seq(i + 1, n)
for (j in k) {
s <- a[[j, i]] / a[[i, i]]
a[j, k] <- a[j, k] - s * a[i, k]
b[j, ] <- b[j, ] - s * b[i, ]
}
}
for (i in seq(n, 1)) {
if (i < n) {
for (j in seq(i + 1, n)) {
b[i, ] <- b[i, ] - a[[i, j]] * b[j, ]
}
}
b[i, ] <- b[i, ] / a[[i, i]]
det <- det * a[[i, i]]
}
list(x=b, det=det)
}
a <- matrix(c(2, 9, 4, 7, 5, 3, 6, 1, 8), 3, 3, byrow=T)
gauss(a, diag(3))
|
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
|
#zkl
|
zkl
|
stop:=ask("Count: ").toInt();
fizzBuzzers:=List();
do(3){ n,txt:=ask(">").split(); fizzBuzzers.append(T(n.toInt(),txt)) }
foreach n in ([1..stop]){
s:=fizzBuzzers.filter('wrap([(fb,txt)]){ n%fb==0 }).apply("get",1).concat();
println(s or n);
}
|
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
|
#ZX_Spectrum_Basic
|
ZX Spectrum Basic
|
10 INPUT "Maximum number: ";max
20 INPUT "Number of factors: ";n
30 DIM f(n): DIM w$(n,4)
40 FOR i=1 TO n
50 INPUT "Input value-ENTER-word: ";f(i);w$(i)
60 NEXT i
70 FOR i=1 TO max
80 LET matched=0
90 FOR j=1 TO n
100 IF FN m(i,f(j))=0 THEN LET matched=1: PRINT w$(j);
110 NEXT j
120 IF NOT matched THEN PRINT ;i: GO TO 140
130 PRINT
140 NEXT i
150 DEF FN m(a,b)=a-INT (a/b)*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
|
#Nim
|
Nim
|
# A slice just contains the first and last value
let alpha: Slice[char] = 'a'..'z'
echo alpha # (a: a, b: z)
# but can be used to check if a character is in it:
echo 'f' in alpha # true
echo 'G' in alpha # false
# A set contains all elements as a bitvector:
let alphaSet: set[char] = {'a'..'z'}
echo alphaSet # {a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z}
echo 'f' in alphaSet # true
var someChars = {'a','f','g'}
echo someChars <= alphaSet # true
import sequtils
# A sequence:
let alphaSeq = toSeq 'a'..'z'
echo alphaSeq # @[a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z]
echo alphaSeq[10] # k
|
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
|
#OCaml
|
OCaml
|
# Array.make 26 'a' |> Array.mapi (fun i c -> int_of_char c + i |> char_of_int);;
- : char array =
[|'a'; 'b'; 'c'; 'd'; 'e'; 'f'; 'g'; 'h'; 'i'; 'j'; 'k'; 'l'; 'm'; 'n'; 'o';
'p'; 'q'; 'r'; 's'; 't'; 'u'; 'v'; 'w'; 'x'; 'y'; 'z'|]
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#PIR
|
PIR
|
.sub hello_world_text :main
print "Hello world!\n"
.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
|
#Swift
|
Swift
|
func powGen(m: Int) -> GeneratorOf<Int> {
let power = Double(m)
var cur: Double = 0
return GeneratorOf { Int(pow(cur++, power)) }
}
var squares = powGen(2)
var cubes = powGen(3)
var nCube = cubes.next()
var filteredSqs = GeneratorOf<Int> {
for var nSq = squares.next() ;; nCube = cubes.next() {
if nCube > nSq {
return nSq
} else if nCube == nSq {
nSq = squares.next()
}
}
}
extension GeneratorOf {
func drop(n: Int) -> GeneratorOf<T> {
var g = self
for _ in 0..<n {g.next()}
return GeneratorOf{g.next()}
}
func take(n: Int) -> GeneratorOf<T> {
var (i, g) = (0, self)
return GeneratorOf{++i > n ? nil : g.next()}
}
}
for num in filteredSqs.drop(20).take(10) {
print(num)
}
//529
//576
//625
//676
//784
//841
//900
//961
//1024
//1089
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#Hy
|
Hy
|
(defn compose [f g]
(fn [x]
(f (g x))))
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#Icon_and_Unicon
|
Icon and Unicon
|
x @ f # use this syntax in Icon instead of the Unicon f(x) to call co-expressions
every push(fL := [],!rfL) # use this instead of reverse(fL) as the Icon reverse applies only to strings
|
http://rosettacode.org/wiki/Fractal_tree
|
Fractal tree
|
Generate and draw a fractal tree.
Draw the trunk
At the end of the trunk, split by some angle and draw two branches
Repeat at the end of each branch until a sufficient level of branching is reached
Related tasks
Pythagoras Tree
|
#Nim
|
Nim
|
import math
import strformat
const
Width = 1000
Height = 1000
TrunkLength = 400
ScaleFactor = 0.6
StartingAngle = 1.5 * PI
DeltaAngle = 0.2 * PI
proc drawTree(outfile: File; x, y, len, theta: float) =
if len >= 1:
let x2 = x + len * cos(theta)
let y2 = y + len * sin(theta)
outfile.write(
fmt"<line x1='{x}' y1='{y}' x2='{x2}' y2='{y2}' style='stroke:white;stroke-width:1'/>\n")
outfile.drawTree(x2, y2, len * ScaleFactor, theta + DeltaAngle)
outFile.drawTree(x2, y2, len * ScaleFactor, theta - DeltaAngle)
let outsvg = open("tree.svg", fmWrite)
outsvg.write("""<?xml version='1.0' encoding='utf-8' standalone='no'?>
<!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN'
'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'>
<svg width='100%%' height='100%%' version='1.1'
xmlns='http://www.w3.org/2000/svg'>\n
<rect width="100%" height="100%" fill="black"/>\n""")
outsvg.drawTree(0.5 * Width, Height, TrunkLength, StartingAngle)
outsvg.write("</svg>\n") # View file tree.svg in browser.
|
http://rosettacode.org/wiki/Fractal_tree
|
Fractal tree
|
Generate and draw a fractal tree.
Draw the trunk
At the end of the trunk, split by some angle and draw two branches
Repeat at the end of each branch until a sufficient level of branching is reached
Related tasks
Pythagoras Tree
|
#OCaml
|
OCaml
|
#directory "+cairo"
#load "bigarray.cma"
#load "cairo.cma"
let img_name = "/tmp/fractree.png"
let width = 480
let height = 640
let level = 9
let line_width = 4.0
let color = (1.0, 0.5, 0.0)
let pi = 4.0 *. atan 1.0
let angle_split = pi *. 0.12
let angle_rand = pi *. 0.12
let () =
Random.self_init();
let surf = Cairo.image_surface_create Cairo.FORMAT_RGB24 ~width ~height in
let ctx = Cairo.create surf in
Cairo.set_antialias ctx Cairo.ANTIALIAS_SUBPIXEL;
Cairo.set_line_cap ctx Cairo.LINE_CAP_ROUND;
let draw_line (x,y) (dx,dy) =
Cairo.move_to ctx x (float height -. y);
Cairo.line_to ctx dx (float height -. dy);
Cairo.stroke ctx;
in
let set_color (r,g,b) v =
Cairo.set_source_rgb ctx ~red:(r *. v) ~green:(g *. v) ~blue:(b *. v);
in
let trans_pos (x,y) len angle =
let _x = cos angle
and _y = sin angle in
(x +. (_x *. len),
y +. (_y *. len))
in
let rec loop ~level ~pos ~line_width ~line_len
~angle ~angle_split ~angle_rand ~intc =
if level > 0 then begin
(* draw the current segment *)
Cairo.set_line_width ctx line_width;
set_color color intc;
let pos_to = trans_pos pos line_len angle in
draw_line pos pos_to;
(* evolution of the parameters *)
let line_width = line_width *. 0.8
and line_len = line_len *. 0.62
and angle_split = angle_split *. 1.02
and angle_rand = angle_rand *. 1.02
and intc = intc *. 0.9
in
let next_loop =
loop ~level:(pred level) ~pos:pos_to ~intc
~line_width ~line_len ~angle_split ~angle_rand
in
(* split *)
let angle_left = angle +. angle_split +. Random.float angle_rand
and angle_right = angle -. angle_split -. Random.float angle_rand
in
next_loop ~angle:angle_left;
next_loop ~angle:angle_right
end
in
let pos = (float width *. 0.5, float height *. 0.1)
and line_len = float height *. 0.3
in
loop ~level ~pos ~angle:(pi /. 2.0)
~angle_split ~angle_rand
~line_width ~line_len ~intc:1.0;
Cairo_png.surface_write_to_file surf img_name
(*Cairo_png.surface_write_to_channel surf stdout*)
|
http://rosettacode.org/wiki/Fraction_reduction
|
Fraction reduction
|
There is a fine line between numerator and denominator. ─── anonymous
A method to "reduce" some reducible fractions is to cross out a digit from the
numerator and the denominator. An example is:
16 16
──── and then (simply) cross─out the sixes: ────
64 64
resulting in:
1
───
4
Naturally, this "method" of reduction must reduce to the proper value (shown as a fraction).
This "method" is also known as anomalous cancellation and also accidental cancellation.
(Of course, this "method" shouldn't be taught to impressionable or gullible minds.) 😇
Task
Find and show some fractions that can be reduced by the above "method".
show 2-digit fractions found (like the example shown above)
show 3-digit fractions
show 4-digit fractions
show 5-digit fractions (and higher) (optional)
show each (above) n-digit fractions separately from other different n-sized fractions, don't mix different "sizes" together
for each "size" fraction, only show a dozen examples (the 1st twelve found)
(it's recognized that not every programming solution will have the same generation algorithm)
for each "size" fraction:
show a count of how many reducible fractions were found. The example (above) is size 2
show a count of which digits were crossed out (one line for each different digit)
for each "size" fraction, show a count of how many were found. The example (above) is size 2
show each n-digit example (to be shown on one line):
show each n-digit fraction
show each reduced n-digit fraction
show what digit was crossed out for the numerator and the denominator
Task requirements/restrictions
only proper fractions and their reductions (the result) are to be used (no vulgar fractions)
only positive fractions are to be used (no negative signs anywhere)
only base ten integers are to be used for the numerator and denominator
no zeros (decimal digit) can be used within the numerator or the denominator
the numerator and denominator should be composed of the same number of digits
no digit can be repeated in the numerator
no digit can be repeated in the denominator
(naturally) there should be a shared decimal digit in the numerator and the denominator
fractions can be shown as 16/64 (for example)
Show all output here, on this page.
Somewhat related task
Farey sequence (It concerns fractions.)
References
Wikipedia entry: proper and improper fractions.
Wikipedia entry: anomalous cancellation and/or accidental cancellation.
|
#Perl
|
Perl
|
use strict;
use warnings;
use feature 'say';
use List::Util qw<sum uniq uniqnum head tail>;
for my $exp (map { $_ - 1 } <2 3 4>) {
my %reduced;
my $start = sum map { 10 ** $_ * ($exp - $_ + 1) } 0..$exp;
my $end = 10**($exp+1) - -1 + sum map { 10 ** $_ * ($exp - $_) } 0..$exp-1;
for my $den ($start .. $end-1) {
next if $den =~ /0/ or (uniqnum split '', $den) <= $exp;
for my $num ($start .. $den-1) {
next if $num =~ /0/ or (uniqnum split '', $num) <= $exp;
my %i;
map { $i{$_}++ } (uniq head -1, split '',$den), uniq tail -1, split '',$num;
my @set = grep { $_ if $i{$_} > 1 } keys %i;
next if @set < 1;
for (@set) {
(my $ne = $num) =~ s/$_//;
(my $de = $den) =~ s/$_//;
if ($ne/$de == $num/$den) {
$reduced{"$num/$den:$_"} = "$ne/$de";
}
}
}
}
my $digit = $exp + 1;
say "\n" . +%reduced . " $digit-digit reducible fractions:";
for my $n (1..9) {
my $cnt = scalar grep { /:$n/ } keys %reduced;
say "$cnt with removed $n" if $cnt;
}
say "\n 12 (or all, if less) $digit-digit reducible fractions:";
for my $f (head 12, sort keys %reduced) {
printf " %s => %s removed %s\n", substr($f,0,$digit*2+1), $reduced{$f}, substr($f,-1)
}
}
|
http://rosettacode.org/wiki/Fractran
|
Fractran
|
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway.
A FRACTRAN program is an ordered list of positive fractions
P
=
(
f
1
,
f
2
,
…
,
f
m
)
{\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})}
, together with an initial positive integer input
n
{\displaystyle n}
.
The program is run by updating the integer
n
{\displaystyle n}
as follows:
for the first fraction,
f
i
{\displaystyle f_{i}}
, in the list for which
n
f
i
{\displaystyle nf_{i}}
is an integer, replace
n
{\displaystyle n}
with
n
f
i
{\displaystyle nf_{i}}
;
repeat this rule until no fraction in the list produces an integer when multiplied by
n
{\displaystyle n}
, then halt.
Conway gave a program for primes in FRACTRAN:
17
/
91
{\displaystyle 17/91}
,
78
/
85
{\displaystyle 78/85}
,
19
/
51
{\displaystyle 19/51}
,
23
/
38
{\displaystyle 23/38}
,
29
/
33
{\displaystyle 29/33}
,
77
/
29
{\displaystyle 77/29}
,
95
/
23
{\displaystyle 95/23}
,
77
/
19
{\displaystyle 77/19}
,
1
/
17
{\displaystyle 1/17}
,
11
/
13
{\displaystyle 11/13}
,
13
/
11
{\displaystyle 13/11}
,
15
/
14
{\displaystyle 15/14}
,
15
/
2
{\displaystyle 15/2}
,
55
/
1
{\displaystyle 55/1}
Starting with
n
=
2
{\displaystyle n=2}
, this FRACTRAN program will change
n
{\displaystyle n}
to
15
=
2
×
(
15
/
2
)
{\displaystyle 15=2\times (15/2)}
, then
825
=
15
×
(
55
/
1
)
{\displaystyle 825=15\times (55/1)}
, generating the following sequence of integers:
2
{\displaystyle 2}
,
15
{\displaystyle 15}
,
825
{\displaystyle 825}
,
725
{\displaystyle 725}
,
1925
{\displaystyle 1925}
,
2275
{\displaystyle 2275}
,
425
{\displaystyle 425}
,
390
{\displaystyle 390}
,
330
{\displaystyle 330}
,
290
{\displaystyle 290}
,
770
{\displaystyle 770}
,
…
{\displaystyle \ldots }
After 2, this sequence contains the following powers of 2:
2
2
=
4
{\displaystyle 2^{2}=4}
,
2
3
=
8
{\displaystyle 2^{3}=8}
,
2
5
=
32
{\displaystyle 2^{5}=32}
,
2
7
=
128
{\displaystyle 2^{7}=128}
,
2
11
=
2048
{\displaystyle 2^{11}=2048}
,
2
13
=
8192
{\displaystyle 2^{13}=8192}
,
2
17
=
131072
{\displaystyle 2^{17}=131072}
,
2
19
=
524288
{\displaystyle 2^{19}=524288}
,
…
{\displaystyle \ldots }
which are the prime powers of 2.
Task
Write a program that reads a list of fractions in a natural format from the keyboard or from a string,
to parse it into a sequence of fractions (i.e. two integers),
and runs the FRACTRAN starting from a provided integer, writing the result at each step.
It is also required that the number of steps is limited (by a parameter easy to find).
Extra credit
Use this program to derive the first 20 or so prime numbers.
See also
For more on how to program FRACTRAN as a universal programming language, see:
J. H. Conway (1987). Fractran: A Simple Universal Programming Language for Arithmetic. In: Open Problems in Communication and Computation, pages 4–26. Springer.
J. H. Conway (2010). "FRACTRAN: A simple universal programming language for arithmetic". In Jeffrey C. Lagarias. The Ultimate Challenge: the 3x+1 problem. American Mathematical Society. pp. 249–264. ISBN 978-0-8218-4940-8. Zbl 1216.68068.
Number Pathology: Fractran by Mark C. Chu-Carroll; October 27, 2006.
|
#Icon_and_Unicon
|
Icon and Unicon
|
record fract(n,d)
procedure main(A)
fractran("17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1", 2)
end
procedure fractran(s, n, limit)
execute(parse(s),n, limit)
end
procedure parse(s)
f := []
s ? while not pos(0) do {
tab(upto(' ')|0) ? put(f,fract(tab(upto('/')), (move(1),tab(0))))
move(1)
}
return f
end
procedure execute(f,d,limit)
/limit := 15
every !limit do {
if d := (d%f[i := !*f].d == 0, (writes(" ",d)/f[i].d)*f[i].n) then {}
else break write()
}
write()
end
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#Axe
|
Axe
|
Lbl MULT
r₁*r₂
Return
|
http://rosettacode.org/wiki/Fusc_sequence
|
Fusc sequence
|
Definitions
The fusc integer sequence is defined as:
fusc(0) = 0
fusc(1) = 1
for n>1, the nth term is defined as:
if n is even; fusc(n) = fusc(n/2)
if n is odd; fusc(n) = fusc((n-1)/2) + fusc((n+1)/2)
Note that MathWorld's definition starts with unity, not zero. This task will be using the OEIS' version (above).
An observation
fusc(A) = fusc(B)
where A is some non-negative integer expressed in binary, and
where B is the binary value of A reversed.
Fusc numbers are also known as:
fusc function (named by Dijkstra, 1982)
Stern's Diatomic series (although it starts with unity, not zero)
Stern-Brocot sequence (although it starts with unity, not zero)
Task
show the first 61 fusc numbers (starting at zero) in a horizontal format.
show the fusc number (and its index) whose length is greater than any previous fusc number length.
(the length is the number of decimal digits when the fusc number is expressed in base ten.)
show all numbers with commas (if appropriate).
show all output here.
Related task
RosettaCode Stern-Brocot sequence
Also see
the MathWorld entry: Stern's Diatomic Series.
the OEIS entry: A2487.
|
#Prolog
|
Prolog
|
:- dynamic fusc_cache/2.
fusc(0, 0):-!.
fusc(1, 1):-!.
fusc(N, F):-
fusc_cache(N, F),
!.
fusc(N, F):-
0 is N mod 2,
!,
M is N//2,
fusc(M, F),
assertz(fusc_cache(N, F)).
fusc(N, F):-
N1 is (N - 1)//2,
N2 is (N + 1)//2,
fusc(N1, F1),
fusc(N2, F2),
F is F1 + F2,
assertz(fusc_cache(N, F)).
print_fusc_sequence(N):-
writef('First %w fusc numbers:\n', [N]),
print_fusc_sequence(N, 0),
nl.
print_fusc_sequence(N, M):-
M >= N,
!.
print_fusc_sequence(N, M):-
fusc(M, F),
writef('%w ', [F]),
M1 is M + 1,
print_fusc_sequence(N, M1).
print_max_fusc(N):-
writef('Fusc numbers up to %w that are longer than any previous one:\n', [N]),
print_max_fusc(N, 0, 0).
print_max_fusc(N, M, _):-
M >= N,
!.
print_max_fusc(N, M, Max):-
fusc(M, F),
(F >= Max ->
writef('n = %w, fusc(n) = %w\n', [M, F]), Max1 = max(10, Max * 10)
;
Max1 = Max
),
M1 is M + 1,
print_max_fusc(N, M1, Max1).
main:-
print_fusc_sequence(61),
print_max_fusc(1000000).
|
http://rosettacode.org/wiki/Gamma_function
|
Gamma function
|
Task
Implement one algorithm (or more) to compute the Gamma (
Γ
{\displaystyle \Gamma }
) function (in the real field only).
If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function.
The Gamma function can be defined as:
Γ
(
x
)
=
∫
0
∞
t
x
−
1
e
−
t
d
t
{\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt}
This suggests a straightforward (but inefficient) way of computing the
Γ
{\displaystyle \Gamma }
through numerical integration.
Better suggested methods:
Lanczos approximation
Stirling's approximation
|
#Kotlin
|
Kotlin
|
// version 1.0.6
fun gammaStirling(x: Double): Double = Math.sqrt(2.0 * Math.PI / x) * Math.pow(x / Math.E, x)
fun gammaLanczos(x: Double): Double {
var xx = x
val p = doubleArrayOf(
0.99999999999980993,
676.5203681218851,
-1259.1392167224028,
771.32342877765313,
-176.61502916214059,
12.507343278686905,
-0.13857109526572012,
9.9843695780195716e-6,
1.5056327351493116e-7
)
val g = 7
if (xx < 0.5) return Math.PI / (Math.sin(Math.PI * xx) * gammaLanczos(1.0 - xx))
xx--
var a = p[0]
val t = xx + g + 0.5
for (i in 1 until p.size) a += p[i] / (xx + i)
return Math.sqrt(2.0 * Math.PI) * Math.pow(t, xx + 0.5) * Math.exp(-t) * a
}
fun main(args: Array<String>) {
println(" x\tStirling\t\tLanczos\n")
for (i in 1 .. 20) {
val d = i / 10.0
print("%4.2f\t".format(d))
print("%17.15f\t".format(gammaStirling(d)))
println("%17.15f".format(gammaLanczos(d)))
}
}
|
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
|
#Sidef
|
Sidef
|
func is_gapful(n, base=10) {
n.is_div(base*floor(n / base**n.ilog(base)) + n%base)
}
var task = [
"(Required) The first %s gapful numbers (>= %s)", 30, 1e2, 10,
"(Required) The first %s gapful numbers (>= %s)", 15, 1e6, 10,
"(Required) The first %s gapful numbers (>= %s)", 10, 1e9, 10,
"(Extra) The first %s gapful numbers (>= %s)", 10, 987654321, 10,
"(Extra) The first %s gapful numbers (>= %s)", 10, 987654321, 12,
]
task.each_slice(4, {|title, n, from, b|
say sprintf("\n#{title} for base #{b}:", n, from.commify)
say (from..Inf -> lazy.grep{ is_gapful(_,b) }.first(n).join(' '))
})
|
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
|
#Racket
|
Racket
|
#lang racket
(require math/matrix)
(define A
(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]]))
(define b (col-matrix [-0.01 0.61 0.91 0.99 0.60 0.02]))
(matrix-solve A 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
|
#Oforth
|
Oforth
|
'a' 'z' seqFrom
|
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
|
#PARI.2FGP
|
PARI/GP
|
Strchr(Vecsmall([97..122]))
|
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
|
#Pixilang
|
Pixilang
|
fputs("Hello world!\n")
|
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
|
#Tcl
|
Tcl
|
package require Tcl 8.6
proc powers m {
yield
for {set n 0} true {incr n} {
yield [expr {$n ** $m}]
}
}
coroutine squares powers 2
coroutine cubes powers 3
coroutine filtered apply {{s1 s2} {
yield
set f [$s2]
set v [$s1]
while true {
if {$v > $f} {
set f [$s2]
continue
} elseif {$v < $f} {
yield $v
}
set v [$s1]
}
}} squares cubes
# Drop 20
for {set i 0} {$i<20} {incr i} {filtered}
# Take/print 10
for {} {$i<30} {incr i} {
puts [filtered]
}
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#J
|
J
|
compose =: @
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#Java
|
Java
|
public class Compose {
// Java doesn't have function type so we define an interface
// of function objects instead
public interface Fun<A,B> {
B call(A x);
}
public static <A,B,C> Fun<A,C> compose(final Fun<B,C> f, final Fun<A,B> g) {
return new Fun<A,C>() {
public C call(A x) {
return f.call(g.call(x));
}
};
}
public static void main(String[] args) {
Fun<Double,Double> sin = new Fun<Double,Double>() {
public Double call(Double x) {
return Math.sin(x);
}
};
Fun<Double,Double> asin = new Fun<Double,Double>() {
public Double call(Double x) {
return Math.asin(x);
}
};
Fun<Double,Double> sin_asin = compose(sin, asin);
System.out.println(sin_asin.call(0.5)); // prints "0.5"
}
}
|
http://rosettacode.org/wiki/Fractal_tree
|
Fractal tree
|
Generate and draw a fractal tree.
Draw the trunk
At the end of the trunk, split by some angle and draw two branches
Repeat at the end of each branch until a sufficient level of branching is reached
Related tasks
Pythagoras Tree
|
#PARI.2FGP
|
PARI/GP
|
\\ Fractal tree (w/recursion)
\\ 4/10/16 aev
plotline(x1,y1,x2,y2)={plotmove(0, x1,y1);plotrline(0,x2-x1,y2-y1);}
plottree(x,y,a,d)={
my(x2,y2,d2r=Pi/180.0,a1=a*d2r,d1);
if(d<=0, return(););
if(d>0, d1=d*10.0;
x2=x+cos(a1)*d1;
y2=y+sin(a1)*d1;
plotline(x,y,x2,y2);
plottree(x2,y2,a-20,d-1);
plottree(x2,y2,a+20,d-1),
return();
);
}
FractalTree(depth,size)={
my(dx=1,dy=0,ttlb="Fractal Tree, depth ",ttl=Str(ttlb,depth));
print1(" *** ",ttl); print(", size ",size);
plotinit(0);
plotcolor(0,6); \\green
plotscale(0, -size,size, 0,size);
plotmove(0, 0,0);
plottree(0,0,90,depth);
plotdraw([0,size,size]);
}
{\\ Executing:
FractalTree(9,500); \\FracTree1.png
FractalTree(12,1100); \\FracTree2.png
FractalTree(15,1500); \\FracTree3.png
}
|
http://rosettacode.org/wiki/Fraction_reduction
|
Fraction reduction
|
There is a fine line between numerator and denominator. ─── anonymous
A method to "reduce" some reducible fractions is to cross out a digit from the
numerator and the denominator. An example is:
16 16
──── and then (simply) cross─out the sixes: ────
64 64
resulting in:
1
───
4
Naturally, this "method" of reduction must reduce to the proper value (shown as a fraction).
This "method" is also known as anomalous cancellation and also accidental cancellation.
(Of course, this "method" shouldn't be taught to impressionable or gullible minds.) 😇
Task
Find and show some fractions that can be reduced by the above "method".
show 2-digit fractions found (like the example shown above)
show 3-digit fractions
show 4-digit fractions
show 5-digit fractions (and higher) (optional)
show each (above) n-digit fractions separately from other different n-sized fractions, don't mix different "sizes" together
for each "size" fraction, only show a dozen examples (the 1st twelve found)
(it's recognized that not every programming solution will have the same generation algorithm)
for each "size" fraction:
show a count of how many reducible fractions were found. The example (above) is size 2
show a count of which digits were crossed out (one line for each different digit)
for each "size" fraction, show a count of how many were found. The example (above) is size 2
show each n-digit example (to be shown on one line):
show each n-digit fraction
show each reduced n-digit fraction
show what digit was crossed out for the numerator and the denominator
Task requirements/restrictions
only proper fractions and their reductions (the result) are to be used (no vulgar fractions)
only positive fractions are to be used (no negative signs anywhere)
only base ten integers are to be used for the numerator and denominator
no zeros (decimal digit) can be used within the numerator or the denominator
the numerator and denominator should be composed of the same number of digits
no digit can be repeated in the numerator
no digit can be repeated in the denominator
(naturally) there should be a shared decimal digit in the numerator and the denominator
fractions can be shown as 16/64 (for example)
Show all output here, on this page.
Somewhat related task
Farey sequence (It concerns fractions.)
References
Wikipedia entry: proper and improper fractions.
Wikipedia entry: anomalous cancellation and/or accidental cancellation.
|
#Phix
|
Phix
|
with javascript_semantics
function to_n(sequence digits, integer remove_digit=0)
if remove_digit!=0 then
digits = deep_copy(digits)
integer d = find(remove_digit,digits)
digits[d..d] = {}
end if
integer res = digits[1]
for i=2 to length(digits) do
res = res*10+digits[i]
end for
return res
end function
function ndigits(integer n)
-- generate numbers with unique digits efficiently
-- and store them in an array for multiple re-use,
-- along with an array of the removed-digit values.
sequence res = {},
digits = tagset(n),
used = repeat(1,n)&repeat(0,9-n)
while true do
sequence nine = repeat(0,9)
for i=1 to length(used) do
if used[i] then
nine[i] = to_n(digits,i)
end if
end for
res = append(res,{to_n(digits),nine})
bool found = false
for i=n to 1 by -1 do
integer d = digits[i]
if not used[d] then ?9/0 end if
used[d] = 0
for j=d+1 to 9 do
if not used[j] then
used[j] = 1
digits[i] = j
for k=i+1 to n do
digits[k] = find(0,used)
used[digits[k]] = 1
end for
found = true
exit
end if
end for
if found then exit end if
end for
if not found then exit end if
end while
return res
end function
atom t0 = time(),
t1 = time()+1
--for n=2 to 6 do
for n=2 to 4 do
sequence d = ndigits(n)
integer count = 0
sequence omitted = repeat(0,9)
for i=1 to length(d)-1 do
{integer xn, sequence rn} = d[i]
for j=i+1 to length(d) do
{integer xd, sequence rd} = d[j]
for k=1 to 9 do
integer yn = rn[k], yd = rd[k]
if yn!=0 and yd!=0 and xn/xd = yn/yd then
count += 1
omitted[k] += 1
if count<=12 then
printf(1,"%d/%d => %d/%d (removed %d)\n",{xn,xd,yn,yd,k})
elsif time()>t1 and platform()!=JS then
printf(1,"working (%d/%d)...\r",{i,length(d)})
t1 = time()+1
end if
end if
end for
end for
end for
printf(1,"%d-digit fractions found:%d, omitted %v\n\n",{n,count,omitted})
end for
?elapsed(time()-t0)
|
http://rosettacode.org/wiki/Fractran
|
Fractran
|
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway.
A FRACTRAN program is an ordered list of positive fractions
P
=
(
f
1
,
f
2
,
…
,
f
m
)
{\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})}
, together with an initial positive integer input
n
{\displaystyle n}
.
The program is run by updating the integer
n
{\displaystyle n}
as follows:
for the first fraction,
f
i
{\displaystyle f_{i}}
, in the list for which
n
f
i
{\displaystyle nf_{i}}
is an integer, replace
n
{\displaystyle n}
with
n
f
i
{\displaystyle nf_{i}}
;
repeat this rule until no fraction in the list produces an integer when multiplied by
n
{\displaystyle n}
, then halt.
Conway gave a program for primes in FRACTRAN:
17
/
91
{\displaystyle 17/91}
,
78
/
85
{\displaystyle 78/85}
,
19
/
51
{\displaystyle 19/51}
,
23
/
38
{\displaystyle 23/38}
,
29
/
33
{\displaystyle 29/33}
,
77
/
29
{\displaystyle 77/29}
,
95
/
23
{\displaystyle 95/23}
,
77
/
19
{\displaystyle 77/19}
,
1
/
17
{\displaystyle 1/17}
,
11
/
13
{\displaystyle 11/13}
,
13
/
11
{\displaystyle 13/11}
,
15
/
14
{\displaystyle 15/14}
,
15
/
2
{\displaystyle 15/2}
,
55
/
1
{\displaystyle 55/1}
Starting with
n
=
2
{\displaystyle n=2}
, this FRACTRAN program will change
n
{\displaystyle n}
to
15
=
2
×
(
15
/
2
)
{\displaystyle 15=2\times (15/2)}
, then
825
=
15
×
(
55
/
1
)
{\displaystyle 825=15\times (55/1)}
, generating the following sequence of integers:
2
{\displaystyle 2}
,
15
{\displaystyle 15}
,
825
{\displaystyle 825}
,
725
{\displaystyle 725}
,
1925
{\displaystyle 1925}
,
2275
{\displaystyle 2275}
,
425
{\displaystyle 425}
,
390
{\displaystyle 390}
,
330
{\displaystyle 330}
,
290
{\displaystyle 290}
,
770
{\displaystyle 770}
,
…
{\displaystyle \ldots }
After 2, this sequence contains the following powers of 2:
2
2
=
4
{\displaystyle 2^{2}=4}
,
2
3
=
8
{\displaystyle 2^{3}=8}
,
2
5
=
32
{\displaystyle 2^{5}=32}
,
2
7
=
128
{\displaystyle 2^{7}=128}
,
2
11
=
2048
{\displaystyle 2^{11}=2048}
,
2
13
=
8192
{\displaystyle 2^{13}=8192}
,
2
17
=
131072
{\displaystyle 2^{17}=131072}
,
2
19
=
524288
{\displaystyle 2^{19}=524288}
,
…
{\displaystyle \ldots }
which are the prime powers of 2.
Task
Write a program that reads a list of fractions in a natural format from the keyboard or from a string,
to parse it into a sequence of fractions (i.e. two integers),
and runs the FRACTRAN starting from a provided integer, writing the result at each step.
It is also required that the number of steps is limited (by a parameter easy to find).
Extra credit
Use this program to derive the first 20 or so prime numbers.
See also
For more on how to program FRACTRAN as a universal programming language, see:
J. H. Conway (1987). Fractran: A Simple Universal Programming Language for Arithmetic. In: Open Problems in Communication and Computation, pages 4–26. Springer.
J. H. Conway (2010). "FRACTRAN: A simple universal programming language for arithmetic". In Jeffrey C. Lagarias. The Ultimate Challenge: the 3x+1 problem. American Mathematical Society. pp. 249–264. ISBN 978-0-8218-4940-8. Zbl 1216.68068.
Number Pathology: Fractran by Mark C. Chu-Carroll; October 27, 2006.
|
#J
|
J
|
toFrac=: '/r' 0&".@charsub ] NB. read fractions from string
fractran15=: ({~ (= <.) i. 1:)@(toFrac@[ * ]) ^:(<15) NB. return first 15 Fractran results
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.