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/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
|
#Java
|
Java
|
public class FizzBuzz {
public static void main(String[] args) {
Sound[] sounds = {new Sound(3, "Fizz"), new Sound(5, "Buzz"), new Sound(7, "Baxx")};
for (int i = 1; i <= 20; i++) {
StringBuilder sb = new StringBuilder();
for (Sound sound : sounds) {
sb.append(sound.generate(i));
}
System.out.println(sb.length() == 0 ? i : sb.toString());
}
}
private static class Sound {
private final int trigger;
private final String onomatopoeia;
public Sound(int trigger, String onomatopoeia) {
this.trigger = trigger;
this.onomatopoeia = onomatopoeia;
}
public String generate(int i) {
return i % trigger == 0 ? onomatopoeia : "";
}
}
}
|
http://rosettacode.org/wiki/Hailstone_sequence
|
Hailstone sequence
|
The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.
This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):
hailstone sequence, hailstone numbers
3x + 2 mapping, 3n + 1 problem
Collatz sequence
Hasse's algorithm
Kakutani's problem
Syracuse algorithm, Syracuse problem
Thwaites conjecture
Ulam's problem
The hailstone sequence is also known as hailstone numbers (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).
Task
Create a routine to generate the hailstone sequence for a number.
Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
(But don't show the actual sequence!)
See also
xkcd (humourous).
The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).
The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
|
#Z80_Assembly
|
Z80 Assembly
|
;;;;;;;;;;;;;;;;;;; HEADER ;;;;;;;;;;;;;;;;;;;
read "\SrcCPC\winape_macros.asm"
read "\SrcCPC\MemoryMap.asm"
read "\SrcALL\winapeBuildCompat.asm"
;;;;;;;;;;;;;;;;;;; PROGRAM ;;;;;;;;;;;;;;;;;;;
org &8000
ld de,27
call doHailstone
;returns length of sequence, and writes each entry in the sequence
; to RAM
;print the sequence length (in hex)
ld a,h
call ShowHex
ld a,l
ld (memdump_smc),a
;just to prove I didn't need to know the sequence length at
; compile time, I'll store the calculated length as the operand
; of "doMemDump" which normally takes a constant embedded after
; it as the number of bytes to display.
; If that doesn't make sense, don't worry.
; This has nothing to do with calculating the hailstone sequence, just showing the results.
call ShowHex
call NewLine ;prints CRLF
call NewLine
call doMemDump
memdump_smc:
byte 0 ;operand of "doMemDump" (gets overwritten with the sequence length)
word HailstoneBuffer ;operand of "doMemDump"
ret
;;;;;;;;;;;;;;;;;;; LIBRARY ;;;;;;;;;;;;;;;;;;;
read "\SrcCPC\winape_stringop.asm"
read "\SrcCPC\winape_showhex.asm"
doHailstone:
;you need the proper input for the function "hailstone"
;returns addr. of last element in IX.
call hailstone
ld de,HailstoneBuffer
or a ;clear carry
push ix
pop hl ;returns element count in HL.
sbc hl,de ;subtract the two to get the length of the array.
SRL H
RR L ;divide array size by 2, since each entry is 2 bytes.
INC L
ret nz ;if no carry, don't increment H.
INC H
ret
hailstone:
;input - de = n
ld ix,HailstoneBuffer
ld a,d
or e
ret z ;zero is not allowed.
loop_hailstone:
ld (IX+0),e
ld (IX+1),d
ld a,e
cp 1
jr nz,continue_hailstone
ld a,d
or a
ret z ;if de = 1, stop.
continue_hailstone:
bit 0,e
jr z,DE_IS_EVEN
;de is odd
push de
pop hl ;ld hl,de
SLA E
RL D
add hl,de ;hl = de*3
ld de,1
add hl,de
push hl
pop de ;ld de,hl
inc ix
inc ix
jr loop_hailstone
DE_IS_EVEN:
SRL D ;A/2
RR E
inc ix
inc ix
jr loop_hailstone
doMemDump:
;show the hailstone sequence to the screen. This is just needed to display the data, if you don't care about that
;you can stop reading here.
pop hl ;get PC
ld b,(hl) ;get byte count
inc hl
ld e,(hl) ;get low byte of start addr.
inc hl
ld d,(hl) ;get high byte of start addr.
inc hl
push hl ;now when we return we'll skip the data block.
ex de,hl
call NewLine
;we'll dump 8 words per line.
ld c,8
loop_doMemDump:
inc hl
ld a,(hl)
call ShowHex
dec hl
ld a,(hl)
call ShowHex
ld a,' '
call PrintChar
inc hl
inc hl
dec c
ld a,c
and %00001111
jr nz,continueMemdump
ld c,8
continueMemdump:
djnz loop_doMemDump
ret
HailstoneBuffer:
ds 512,0
|
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
|
#Delphi
|
Delphi
|
program atoz;
var
ch : char;
begin
for ch in ['a'..'z'] do
begin
write(ch);
end;
end.
|
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
|
Generate lower case ASCII alphabet
|
Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code.
During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code:
set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z}
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#Draco
|
Draco
|
/* Generate the lowercase alphabet and store it in a buffer */
proc alph(*char buf) *char:
channel output text ch;
char letter;
open(ch, buf);
for letter from 'a' upto 'z' do
write(ch; letter)
od;
close(ch);
buf
corp
/* Use the function to print the alphabet */
proc main() void:
[27] char buf; /* one byte extra for the string terminator */
writeln(alph(&buf[0]))
corp
|
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
|
#Ol
|
Ol
|
(print "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
|
#Kotlin
|
Kotlin
|
// version 1.1.0
// compiled with flag -Xcoroutines=enable to suppress 'experimental' warning
import kotlin.coroutines.experimental.buildSequence
fun generatePowers(m: Int) =
buildSequence {
var n = 0
val mm = m.toDouble()
while (true) yield(Math.pow((n++).toDouble(), mm).toLong())
}
fun generateNonCubicSquares(squares: Sequence<Long>, cubes: Sequence<Long>) =
buildSequence {
val iter2 = squares.iterator()
val iter3 = cubes.iterator()
var square = iter2.next()
var cube = iter3.next()
while (true) {
if (square > cube) {
cube = iter3.next()
continue
} else if (square < cube) {
yield(square)
}
square = iter2.next()
}
}
fun main(args: Array<String>) {
val squares = generatePowers(2)
val cubes = generatePowers(3)
val ncs = generateNonCubicSquares(squares, cubes)
print("Non-cubic squares (21st to 30th) : ")
ncs.drop(20).take(10).forEach { print("$it ") } // print 21st to 30th items
println()
}
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#XLISP
|
XLISP
|
(defun greatest-common-divisor (x y)
(if (= y 0)
x
(greatest-common-divisor y (mod x y)) ) )
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#XPL0
|
XPL0
|
include c:\cxpl\codes;
func GCD(U, V); \Return the greatest common divisor of U and V
int U, V;
int T;
[while V do \Euclid's method
[T:= U; U:= V; V:= rem(T/V)];
return abs(U);
];
\Display the GCD of two integers entered on command line
IntOut(0, GCD(IntIn(8), IntIn(8)))
|
http://rosettacode.org/wiki/Generate_Chess960_starting_position
|
Generate Chess960 starting position
|
Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints:
as in the standard chess game, all eight white pawns must be placed on the second rank.
White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints:
the bishops must be placed on opposite color squares (i.e. they must be an odd number of spaces apart or there must be an even number of spaces between them)
the King must be between two rooks (with any number of other pieces between them all)
Black pawns and pieces must be placed respectively on the seventh and eighth ranks, mirroring the white pawns and pieces, just as in the standard game. (That is, their positions are not independently randomized.)
With those constraints there are 960 possible starting positions, thus the name of the variant.
Task
The purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed with Chess symbols in Unicode: ♔♕♖♗♘ or with the letters King Queen Rook Bishop kNight.
|
#PicoLisp
|
PicoLisp
|
(load "@lib/simul.l")
(seed (in "/dev/urandom" (rd 8)))
(loop
(match
'(@A B @B B @C)
(shuffle '(Q B B N N 0 0 0)) )
(NIL (bit? 1 (length @B))) )
(let Rkr '(R K R)
(for I (append @A '(B) @B '(B) @C)
(prin (if (=0 I) (pop 'Rkr) I)) )
(prinl) )
(bye)
|
http://rosettacode.org/wiki/Generate_Chess960_starting_position
|
Generate Chess960 starting position
|
Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints:
as in the standard chess game, all eight white pawns must be placed on the second rank.
White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints:
the bishops must be placed on opposite color squares (i.e. they must be an odd number of spaces apart or there must be an even number of spaces between them)
the King must be between two rooks (with any number of other pieces between them all)
Black pawns and pieces must be placed respectively on the seventh and eighth ranks, mirroring the white pawns and pieces, just as in the standard game. (That is, their positions are not independently randomized.)
With those constraints there are 960 possible starting positions, thus the name of the variant.
Task
The purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed with Chess symbols in Unicode: ♔♕♖♗♘ or with the letters King Queen Rook Bishop kNight.
|
#PowerShell
|
PowerShell
|
function Get-RandomChess960Start
{
$Starts = @()
ForEach ( $Q in 0..3 ) {
ForEach ( $N1 in 0..4 ) {
ForEach ( $N2 in ($N1+1)..5 ) {
ForEach ( $B1 in 0..3 ) {
ForEach ( $B2 in 0..3 ) {
$BB = $B1 * 2 + ( $B1 -lt $B2 )
$BW = $B2 * 2
$Start = [System.Collections.ArrayList]( '♖', '♔', '♖' )
$Start.Insert( $Q , '♕' )
$Start.Insert( $N1, '♘' )
$Start.Insert( $N2, '♘' )
$Start.Insert( $BB, '♗' )
$Start.Insert( $BW, '♗' )
$Starts += ,$Start
}}}}}
$Index = Get-Random 960
$StartString = $Starts[$Index] -join ''
return $StartString
}
Get-RandomChess960Start
Get-RandomChess960Start
Get-RandomChess960Start
Get-RandomChess960Start
|
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.
|
#Agda
|
Agda
|
compose : ∀ {a b c} {A : Set a} {B : Set b} {C : Set c}
→ (B → C)
→ (A → B)
→ A → C
compose f g 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.
|
#Aikido
|
Aikido
|
import math
function compose (f, g) {
return function (x) { return f(g(x)) }
}
var func = compose(Math.sin, Math.asin)
println (func(0.5)) // 0.5
|
http://rosettacode.org/wiki/FTP
|
FTP
|
Task
Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
|
#C.2B.2B
|
C++
|
/* client.cpp
libftp++ C++ classes for ftplib C ftp library
compile:
clang++ -std=c++11 -o client client.cpp -lftp++
*/
#include <iostream>
#include <string>
#include <cstring>
#include <fstream>
#include <sys/stat.h> // stat
#include <ftplib.h> // libftp
#include <ftp++.hpp> // libftp++
/* C++ classes:
Connection main ftp connection (user class)
ConnectionBase base class for Connection (internal)
DataConnection connection type, (internal)
read bytes from server,
write bytes to server
ConnectionException custom exception (thrown by Connection)
*/
/** ftp::Connection class API
data members:
A Connection instance contains only a pointer as a data member
{
protected:
netbuf * conn; // pointer to ftplib netbuf struct
}
member functions:
connect:
Connection(const char * host); // constructor
void setConnectionMode(Mode mode); // passive or port
void login(const char * user, const char * password); // Log in
info:
const char * getLastResponse(); // last server response
std::string getSystemType(); // server type
std::string getDirectory(); // remote pwd
void getList(const char * filename, const char * path); // short dir list
unsigned size(const char * path, TransferMode mode);
file transfer:
void get(const char * local, const char * remote, TransferMode mode);
void put(const char * local, const char * remote, TransferMode mode);
**/
// libc functions
int stat(const char *pathname, struct stat *buf); // local file info
char *strerror(int errnum); // explanation of error
char *basename(char *path); // filename at end of path
// STL classes and functions used
namespace stl
{
using std::cout; // stdout
using std::cerr; // stderr
using std::string; // string
using std::ifstream; // files on disk
using std::remove; // delete file on disk
};
using namespace stl;
// connection modes
using Mode = ftp::Connection::Mode;
Mode PASV = Mode::PASSIVE;
Mode PORT = Mode::PORT;
//file transfer modes
using TransferMode = ftp::Connection::TransferMode;
TransferMode BINARY = TransferMode::BINARY;
TransferMode TEXT = TransferMode::TEXT;
/* ********************** */
// ftp session parameters
struct session
{
const string server; // server name
const string port; // usually 21
const string user; // username
const string pass; // password
Mode mode; // PASV, PORT
TransferMode txmode; // BINARY, TEXT
string dir; // current or default dir
};
/* ********************** */
// local helper functions
ftp::Connection connect_ftp( const session& sess);
size_t get_ftp( ftp::Connection& conn, string const& path);
string readFile( const string& filename);
string login_ftp(ftp::Connection& conn, const session& sess);
string dir_listing( ftp::Connection& conn, const string& path);
/* ******************************** */
// Read a file into one long string
string readFile( const string& filename)
{
struct stat stat_buf;
string contents;
errno = 0;
if (stat(filename.c_str() , &stat_buf) != -1) // file stats
{
size_t len = stat_buf.st_size; // size of file
string bytes(len+1, '\0'); // string big enough
ifstream ifs(filename); // open for input
ifs.read(&bytes[0], len); // read all bytes as chars into string
if (! ifs.fail() ) contents.swap(bytes); // swap into contents
ifs.close();
}
else
{
cerr << "stat error: " << strerror(errno);
}
return contents;
}
/* *************** */
// start a session
ftp::Connection connect_ftp( const session& sess)
try
{
string constr = sess.server + ":" + sess.port;
cerr << "connecting to " << constr << " ...\n";
ftp::Connection conn{ constr.c_str() };
cerr << "connected to " << constr << "\n";
conn.setConnectionMode(sess.mode);
return conn;
}
catch (ftp::ConnectException e)
{
cerr << "FTP error: could not connect to server" << "\n";
}
/* ***** */
// login
string login_ftp(ftp::Connection& conn, const session& sess)
{
conn.login(sess.user.c_str() , sess.pass.c_str() );
return conn.getLastResponse();
}
/* ***************************** */
// get remote directory listing
// ftplib writes to file for dir contents
// convert file contents to string
string dir_listing( ftp::Connection& conn, const string& path)
try
{
// file on disk to write to
const char* dirdata = "/dev/shm/dirdata";
conn.getList(dirdata, path.c_str() );
// conn.getFullList(dirdata, path.c_str() );
// conn.getFullList(NULL, path.c_str() ); // to stdout
string dir_string = readFile(dirdata);
cerr << conn.getLastResponse() << "\n";
errno = 0;
if ( remove(dirdata) != 0 ) // delete file on disk
{
cerr << "error: " << strerror(errno) << "\n";
}
return dir_string;
}
catch (...) {
cerr << "error: getting dir contents: \n"
<< strerror(errno) << "\n";
}
/* ************************* */
// retrieve file from server
size_t get_ftp( ftp::Connection& conn, const string& r_path)
{
size_t received = 0;
const char* path = r_path.c_str();
unsigned remotefile_size = conn.size(path , BINARY);
const char* localfile = basename(path);
conn.get(localfile, path, BINARY); // get file
cerr << conn.getLastResponse() << "\n";
// get local file size
struct stat stat_buf;
errno = 0;
if (stat(localfile, &stat_buf) != -1)
received = stat_buf.st_size;
else
cerr << strerror(errno);
return received;
}
/* ******************** */
// default test session
const session sonic
{
"mirrors.sonic.net",
"21" ,
"anonymous",
"[email protected]",
PASV,
BINARY,
"/pub/OpenBSD"
};
/* **** */
// main
int main(int argc, char* argv[], char * env[] )
{
const session remote = sonic; // copy session info
try
{
// open an ftp connection
ftp::Connection conn = connect_ftp(remote);
// login with username and passwd
cerr << login_ftp(conn, remote);
// what type system
cout << "System type: " << conn.getSystemType() << "\n";
cerr << conn.getLastResponse() << "\n";
// cd to default session dir
conn.cd(remote.dir.c_str()); // change to dir on server
cerr << conn.getLastResponse() << "\n";
// get current remote directory
string pwdstr = conn.getDirectory();
cout << "PWD: " << pwdstr << "\n";
cerr << conn.getLastResponse() << "\n";
// get file listing
string dirlist = dir_listing(conn, pwdstr.c_str() );
cout << dirlist << "\n";
string filename = "ftplist"; // small text file
auto pos = dirlist.find(filename); // find filename in dir list
auto notfound = string::npos;
if (pos != notfound) // found filename
{
// get file
size_t received = get_ftp(conn, filename.c_str() );
if (received == 0)
cerr << "got 0 bytes\n";
else
cerr << "got " << filename
<< " (" << received << " bytes)\n";
}
else
{
cerr << "file " << filename
<< "not found on server. \n";
}
}
catch (ftp::ConnectException e)
{
cerr << "FTP error: could not connect to server" << "\n";
}
catch (ftp::Exception e)
{
cerr << "FTP error: " << e << "\n";
}
catch (...)
{
cerr << "error: " << strerror(errno) << "\n";
}
// logout, connection closes automatically when conn destructs
return 0;
}
/* END */
|
http://rosettacode.org/wiki/Function_prototype
|
Function prototype
|
Some languages provide the facility to declare functions and subroutines through the use of function prototyping.
Task
Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include:
An explanation of any placement restrictions for prototype declarations
A prototype declaration for a function that does not require arguments
A prototype declaration for a function that requires two arguments
A prototype declaration for a function that utilizes varargs
A prototype declaration for a function that utilizes optional arguments
A prototype declaration for a function that utilizes named parameters
Example of prototype declarations for subroutines or procedures (if these differ from functions)
An explanation and example of any special forms of prototyping not covered by the above
Languages that do not provide function prototyping facilities should be omitted from this task.
|
#JavaScript
|
JavaScript
|
// A prototype declaration for a function that does not require arguments
function List() {}
List.prototype.push = function() {
return [].push.apply(this, arguments);
};
List.prototype.pop = function() {
return [].pop.call(this);
};
var l = new List();
l.push(5);
l.length; // 1
l[0]; 5
l.pop(); // 5
l.length; // 0
// A prototype declaration for a function that utilizes varargs
function List() {
this.push.apply(this, arguments);
}
List.prototype.push = function() {
return [].push.apply(this, arguments);
};
List.prototype.pop = function() {
return [].pop.call(this);
};
var l = new List(5, 10, 15);
l.length; // 3
l[0]; 5
l.pop(); // 15
l.length; // 2
|
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
|
#360_Assembly
|
360 Assembly
|
DEFFUN CSECT
USING DEFFUN,R13
SAVEAREA B PROLOG-SAVEAREA(R15)
DC 17F'0'
PROLOG STM R14,R12,12(R13)
ST R13,4(R15)
ST R15,8(R13)
LR R13,R15 set base register
BEGIN L R2,=F'13'
ST R2,X X=13
L R2,=F'17'
ST R2,Y Y=17
LA R1,PARMLIST R1->PARMLIST
B SKIPPARM
PARMLIST DS 0F
DC A(X)
DC A(Y)
SKIPPARM BAL R14,MULTPLIC call MULTPLIC
ST R0,Z Z=MULTPLIC(X,Y)
RETURN L R13,4(0,R13) epilog
LM R14,R12,12(R13)
XR R15,R15 set return code
BR R14 return to caller
*
MULTPLIC EQU * function MULTPLIC(X,Y)
L R2,0(R1) R2=(A(X),A(Y))
XR R4,R4 R4=0
L R5,0(R2) R5=X
L R6,4(R2) R6=Y
MR R4,R6 R4R5=R4R5*R6
LR R0,R5 R0=X*Y (R0 return value)
BR R14 end function MULTPLIC
*
X DS F
Y DS F
Z DS F
YREGS
END DEFFUN
|
http://rosettacode.org/wiki/French_Republican_calendar
|
French Republican calendar
|
Write a program to convert dates between the Gregorian calendar and the French Republican calendar.
The year 1 of the Republican calendar began on 22 September 1792. There were twelve months (Vendémiaire, Brumaire, Frimaire, Nivôse, Pluviôse, Ventôse, Germinal, Floréal, Prairial, Messidor, Thermidor, and Fructidor) of 30 days each, followed by five intercalary days or Sansculottides (Fête de la vertu / Virtue Day, Fête du génie / Talent Day, Fête du travail / Labour Day, Fête de l'opinion / Opinion Day, and Fête des récompenses / Honours Day). In leap years (the years 3, 7, and 11) a sixth Sansculottide was added: Fête de la Révolution / Revolution Day.
As a minimum, your program should give correct results for dates in the range from 1 Vendémiaire 1 = 22 September 1792 to 10 Nivôse 14 = 31 December 1805 (the last day when the Republican calendar was officially in use). If you choose to accept later dates, be aware that there are several different methods (described on the Wikipedia page) about how to determine leap years after the year 14. You should indicate which method you are using. (Because of these different methods, correct programs may sometimes give different results for dates after 1805.)
Test your program by converting the following dates both from Gregorian to Republican and from Republican to Gregorian:
• 1 Vendémiaire 1 = 22 September 1792
• 1 Prairial 3 = 20 May 1795
• 27 Messidor 7 = 15 July 1799 (Rosetta Stone discovered)
• Fête de la Révolution 11 = 23 September 1803
• 10 Nivôse 14 = 31 December 1805
|
#FreeBASIC
|
FreeBASIC
|
' version 18 Pluviose 227
' compile with: fbc -s console
' retained the original comments for then BBC BASIC entry
#Macro rep_leap (_year)
' see comment at the beginning of rep_to_day
((_year +1) Mod 4 = 0 And ((_year +1) Mod 100 <> 0 Or (_year +1) Mod 400 = 0))
#EndMacro
#Macro gre_leap (_year)
(_year Mod 4 = 0 And (_year Mod 100 <> 0 Or _year Mod 400 = 0))
#EndMacro
Dim Shared As UInteger gregorian(11) => {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
Dim Shared As String gregorian_s(11), republican(11), sanscolottides(5)
' 7-bit ASCII encoding, so no accents on French words
Data "January", "February", "March", "April", "May", "June"
Data "July", "August", "September", "October", "November", "December"
Data "Vendemiaire", "Brumaire", "Frimaire","Nivose", "Pluviose", "Ventose"
Data "Germinal", "Floreal", "Prairial", "Messidor", "Thermidor", "Fructidor"
Data "Fete de la Vertu", "Fete du Genie", "Fete du Travail", "Fete de l'Opinion"
Data "Fete des Recompenses","Fete de la Revolution"
Restore
For i As UInteger = 0 To 11
Read gregorian_s(i)
Next
For i As UInteger = 0 To 11
Read republican(i)
Next
For i As UInteger = 0 To 5
Read sanscolottides(i)
Next
Sub split(s As String, ByRef d As UInteger, ByRef m As UInteger, ByRef y As UInteger)
Dim As String month_and_year, Month
Dim As UInteger i
s = LCase(Trim(s)) : d = 0 : m = 0 : y = 0
If Left(s,4) = "fete" Then
m = 13
For i = 0 To 5
If Left(s, Len(sanscolottides(i))) = LCase(sanscolottides(i)) Then
d = i +1
y = Val(Right(s, Len(s) - Len(sanscolottides(i)) -1))
End If
Next
Else
d = Val(Left(s, InStr(s, " ") -1))
month_and_year = Mid(s, InStr(s, " ") +1)
Month = Left(month_and_year, InStr(month_and_year, " ") -1)
y = Val(Mid(month_and_year, InStr(month_and_year, " ") +1))
If y < 1792 Then
For i = 0 To 11
If LCase(republican(i)) = Month Then m = i +1
Next
Else
For i = 0 To 11
If LCase(gregorian_s(i)) = Month Then m = i +1
Next
End If
End If
End Sub
Sub day_to_gre(Day As UInteger, ByRef d As UInteger, ByRef m As UInteger, ByRef y As UInteger)
y = Fix(Day / 365.25)
d = Day - Fix(365.25 * y) + 21
y += 1792
d += y \ 100 - y \ 400 - 13
m = 8
While d > gregorian(m)
d -= gregorian(m)
m += 1
If m = 12 Then
m = 0
y += 1
If gre_leap(y) Then gregorian(1) = 29 Else gregorian(1) = 28
End If
Wend
gregorian(1) = 28
m += 1
End Sub
Function gre_to_day(d As UInteger, m As UInteger, y As UInteger) As UInteger
' modified & repurposed from code given at
' https://www.staff.science.uu.nl/~gent0113/calendar/isocalendar_text5.htm
If m < 3 Then
y -= 1
m += 12
End If
Return Fix(365.25 * y) - y \ 100 + y \ 400 + Fix(30.6 * (m +1)) + d - 654842
End Function
Function rep_to_day(d As UInteger, m As UInteger, y As UInteger) As UInteger
' assume that a year is a leap year iff the _following_ year is
' divisible by 4, but not by 100 unless also by 400
'
' other methods for computing republican leap years exist
If m = 13 Then
m -= 1
d += 30
End If
If rep_leap(y) Then d -= 1
Return 365 * y + (y +1) \ 4 - (y +1) \ 100 + (y +1) \ 400 + 30 * m + d - 395
End Function
Sub day_to_rep(Day As UInteger, ByRef d As UInteger, ByRef m As UInteger, ByRef y As UInteger)
Dim As UInteger sansculottides = 5
y = Fix(Day / 365.25)
If rep_leap(y) Then y -= 1
d = Day - Fix(365.25 * y) + (y +1) \ 100 - (y +1) \ 400
y += 1
m = 1
If rep_leap(y) Then sansculottides = 6
While d > 30
d -= 30
m += 1
If m = 13 Then
If d > sansculottides Then
d -= sansculottides
m = 1
y += 1
If rep_leap(y) Then sansculottides = 6 Else sansculottides = 5
End If
End If
Wend
End Sub
' ------=< main >=------
Dim As UInteger Day, Month, Year
Dim As String src
Print "*** French Republican ***"
Print "*** calendar converter ***"
Print "Enter a date to convert, in the format 'day month year'"
Print "e.g.: 1 Prairial 3,"
Print " 20 May 1795."
Print "For Sansculottides, use 'day year'"
Print "e.g.: Fete de l'opinion 9."
Print "Or just press 'RETURN' to exit the program."
Print
Do
Line Input "> ", src
If src <> "" Then
split(src, Day, Month, Year)
If Day = 0 Or Month = 0 Or Year <= 0 Then
Print "Error in input"
Continue Do
End If
' for simplicity, we assume that years up to 1791 are republican
' and years from 1792 onwards are gregorian
If Year < 1792 Then
' convert republican date to number of days elapsed
' since 21 september 1792, then convert that number
' to the gregorian date
day_to_gre(rep_to_day(Day, Month, Year),Day, Month, Year)
Print; Day; " "; gregorian_s(Month -1); " "; Year
Else
' convert gregorian date to republican, via
' number of days elapsed since 21 september 1792
day_to_rep(gre_to_day(Day, Month, Year), Day, Month, Year)
If Month = 13 Then
Print sanscolottides(Day -1); " "; Year
Else
Print ; Day; " "; republican(Month -1); " "; Year
End If
End If
End If
Loop Until src = ""
End
|
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.
|
#Arturo
|
Arturo
|
fusc: function [n][
if? or? n=0 n=1 -> n
else [
if? 0=n%2 -> fusc n/2
else -> (fusc (n-1)/2) + fusc (n+1)/2
]
]
print "The first 61 Fusc numbers:"
print map 0..61 => fusc
print "\nThe Fusc numbers whose lengths are greater than those of previous Fusc numbers:"
print " n fusc(n)"
print "--------- ---------"
maxLength: 0
loop 0..40000 'i [
f: fusc i
l: size to :string f
if l > maxLength [
maxLength: l
print [
pad to :string i 9
pad to :string f 9
]
]
]
|
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.
|
#AutoHotkey
|
AutoHotkey
|
fusc:=[], fusc[0]:=0, fusc[1]:=1, n:=1, l:=0, result:=""
while (StrLen(fusc[n]) < 5)
fusc[++n] := Mod(n, 2) ? fusc[floor((n-1)/2)] + fusc[Floor((n+1)/2)] : fusc[floor(n/2)]
while (A_Index <= 61)
result .= (result = "" ? "" : ",") fusc[A_Index-1]
result .= "`n`nfusc number whose length is greater than any previous fusc number length:`nindex`tnumber`n"
for i, v in fusc
if (l < StrLen(v))
l := StrLen(v), result .= i "`t" v "`n"
MsgBox % result
|
http://rosettacode.org/wiki/Functional_coverage_tree
|
Functional coverage tree
|
Functional coverage is a measure of how much a particular function of a system
has been verified as correct. It is used heavily in tracking the completeness
of the verification of complex System on Chip (SoC) integrated circuits, where
it can also be used to track how well the functional requirements of the
system have been verified.
This task uses a sub-set of the calculations sometimes used in tracking
functional coverage but uses a more familiar(?) scenario.
Task Description
The head of the clean-up crews for "The Men in a very dark shade of grey when
viewed at night" has been tasked with managing the cleansing of two properties
after an incident involving aliens.
She arranges the task hierarchically with a manager for the crews working on
each house who return with a breakdown of how they will report on progress in
each house.
The overall hierarchy of (sub)tasks is as follows,
cleaning
house1
bedrooms
bathrooms
bathroom1
bathroom2
outside lavatory
attic
kitchen
living rooms
lounge
dining room
conservatory
playroom
basement
garage
garden
house2
upstairs
bedrooms
suite 1
suite 2
bedroom 3
bedroom 4
bathroom
toilet
attics
groundfloor
kitchen
living rooms
lounge
dining room
conservatory
playroom
wet room & toilet
garage
garden
hot tub suite
basement
cellars
wine cellar
cinema
The head of cleanup knows that her managers will report fractional completion of leaf tasks (tasks with no child tasks of their own), and she knows that she will want to modify the weight of values of completion as she sees fit.
Some time into the cleaning, and some coverage reports have come in and she thinks see needs to weight the big house2 60-40 with respect to coverage from house1 She prefers a tabular view of her data where missing weights are assumed to be 1.0 and missing coverage 0.0.
NAME_HIERARCHY |WEIGHT |COVERAGE |
cleaning | | |
house1 |40 | |
bedrooms | |0.25 |
bathrooms | | |
bathroom1 | |0.5 |
bathroom2 | | |
outside_lavatory | |1 |
attic | |0.75 |
kitchen | |0.1 |
living_rooms | | |
lounge | | |
dining_room | | |
conservatory | | |
playroom | |1 |
basement | | |
garage | | |
garden | |0.8 |
house2 |60 | |
upstairs | | |
bedrooms | | |
suite_1 | | |
suite_2 | | |
bedroom_3 | | |
bedroom_4 | | |
bathroom | | |
toilet | | |
attics | |0.6 |
groundfloor | | |
kitchen | | |
living_rooms | | |
lounge | | |
dining_room | | |
conservatory | | |
playroom | | |
wet_room_&_toilet | | |
garage | | |
garden | |0.9 |
hot_tub_suite | |1 |
basement | | |
cellars | |1 |
wine_cellar | |1 |
cinema | |0.75 |
Calculation
The coverage of a node in the tree is calculated as the weighted average of the coverage of its children evaluated bottom-upwards in the tree.
The task is to calculate the overall coverage of the cleaning task and display the coverage at all levels of the hierarchy on this page, in a manner that visually shows the hierarchy, weights and coverage of all nodes.
Extra Credit
After calculating the coverage for all nodes, one can also calculate the additional/delta top level coverage that would occur if any (sub)task were to be fully covered from its current fractional coverage. This is done by multiplying the extra coverage that could be gained
1
−
c
o
v
e
r
a
g
e
{\displaystyle 1-coverage}
for any node, by the product of the `powers` of its parent nodes from the top down to the node.
The power of a direct child of any parent is given by the power of the parent multiplied by the weight of the child divided by the sum of the weights of all the direct children.
The pseudo code would be:
method delta_calculation(this, power):
sum_of_weights = sum(node.weight for node in children)
this.delta = (1 - this.coverage) * power
for node in self.children:
node.delta_calculation(power * node.weight / sum_of_weights)
return this.delta
Followed by a call to:
top.delta_calculation(power=1)
Note: to aid in getting the data into your program you might want to use an alternative, more functional description of the starting data given on the discussion page.
|
#Phix
|
Phix
|
--
-- demo\rosetta\Functional_coverage_tree.exw
-- =========================================
--
with javascript_semantics
constant data = """
NAME_HIERARCHY | WEIGHT | COVERAGE |
cleaning | | |
house1 |40 | |
bedrooms | |0.25 |
bathrooms | | |
bathroom1 | |0.5 |
bathroom2 | | |
outside_lavatory | |1 |
attic | |0.75 |
kitchen | |0.1 |
living_rooms | | |
lounge | | |
dining_room | | |
conservatory | | |
playroom | |1 |
basement | | |
garage | | |
garden | |0.8 |
house2 |60 | |
upstairs | | |
bedrooms | | |
suite_1 | | |
suite_2 | | |
bedroom_3 | | |
bedroom_4 | | |
bathroom | | |
toilet | | |
attics | |0.6 |
groundfloor | | |
kitchen | | |
living_rooms | | |
lounge | | |
dining_room | | |
conservatory | | |
playroom | | |
wet_room_&_toilet | | |
garage | | |
garden | |0.9 |
hot_tub_suite | |1 |
basement | | |
cellars | |1 |
wine_cellar | |1 |
cinema | |0.75 |
"""
sequence lines = split(data,"\n"),
pi = {}, -- indents (to locate parents)
pdx = {}, -- indexes for ""
children
string desc, weights, covers
integer parent, child
atom weight, coverage, childw = 0
enum DESC, WEIGHT, COVERAGE, PARENT, CHILDREN, CHILDW
lines[1] &= " SHARE OF RESIDUE"
for i=2 to length(lines) do
-- decode text to useable data, link up parents & children
{desc,weights,covers} = split(lines[i],"|")
-- (nb this assumes /totally/ consistent indenting)
integer indent = length(desc)-length(trim_head(desc)),
k = find(indent,pi)
if k=0 then
pi = append(pi,indent)
pdx = append(pdx,0)
k = length(pi)
end if
pdx[k] = i
parent = 0
if k>1 then
parent = pdx[k-1]
-- lines[parent][CHILDREN] &= i
lines[parent][CHILDREN] = deep_copy(lines[parent][CHILDREN]) & i
end if
children = {}
weight = to_number(trim(weights),1)
coverage = to_number(trim(covers),0)
lines[i] = {desc, weight, coverage, parent, children, childw}
end for
for i=length(lines) to 2 by -1 do
-- calculate the parent coverages, and save child weight sums
children = lines[i][CHILDREN]
if length(children) then
coverage = 0
childw = 0
for c=1 to length(children) do
child = children[c]
atom w = lines[child][WEIGHT]
coverage += lines[child][COVERAGE]*w
childw += w
end for
lines[i][COVERAGE] = coverage/childw
lines[i][CHILDW] = childw -- (save for next loop)
end if
end for
for i=length(lines) to 2 by -1 do
-- calculate the share of residue, and format lines
child = i
{desc, weight, coverage, parent} = lines[i]
atom residue = 1-coverage
while parent do
residue *= lines[child][WEIGHT]/lines[parent][CHILDW]
{child, parent} = {parent, lines[parent][PARENT]}
end while
lines[i] = sprintf("%-32s| %6d | %-8g | %g",{desc,weight,coverage,residue})
end for
puts(1,join(lines,"\n")&"\n")
{} = wait_key()
|
http://rosettacode.org/wiki/Function_frequency
|
Function frequency
|
Display - for a program or runtime environment (whatever suits the style of your language) - the top ten most frequently occurring functions (or also identifiers or tokens, if preferred).
This is a static analysis: The question is not how often each function is
actually executed at runtime, but how often it is used by the programmer.
Besides its practical usefulness, the intent of this task is to show how to do self-inspection within the language.
|
#Factor
|
Factor
|
USING: accessors kernel math.statistics prettyprint sequences
sequences.deep source-files vocabs words ;
"resource:core/sequences/sequences.factor" "sequences"
[ path>source-file top-level-form>> ]
[ vocab-words [ def>> ] [ ] map-as ] bi* compose [ word? ]
deep-filter sorted-histogram <reversed> 7 head .
|
http://rosettacode.org/wiki/Function_frequency
|
Function frequency
|
Display - for a program or runtime environment (whatever suits the style of your language) - the top ten most frequently occurring functions (or also identifiers or tokens, if preferred).
This is a static analysis: The question is not how often each function is
actually executed at runtime, but how often it is used by the programmer.
Besides its practical usefulness, the intent of this task is to show how to do self-inspection within the language.
|
#Forth
|
Forth
|
' noop is bootmessage
\ --- LIST OF CONSTANTS
\ WORD# maximum word size
\ RING# size of `Rings' element
\ DEFS definitions
\ KEYS
\
\ --- LIST OF VARIABLES
\ cmpl? is compiling?
\ cword current compiled word
wordlist constant DEFS
wordlist constant KEYS
\ --- Compiling
50 constant WORD#
: >>fPAD ( ca u -- ; u < 51 )
PAD 80 blank s" create " PAD swap MOVE
s" 1 , DOES> 1 swap +! ;" PAD 57 + swap MOVE
WORD# min PAD 7 + swap MOVE ;
: funcmpl ( ca u -- )
>>fPAD current @ DEFS current !
PAD 80 evaluate current ! ;
: >>kPAD ( ca u -- ; )
PAD 80 blank s" : " PAD swap MOVE
s" parse-name funcmpl ;" PAD 59 + swap MOVE
WORD# min PAD 2 + swap MOVE ;
: keycmpl ( ca u -- )
>>kPAD current @ KEYS current !
PAD 80 evaluate current ! ;
\ --- Interpreter
: intp BEGIN parse-name dup
WHILE ( ca u )
2dup KEYS search-wordlist
IF execute 2drop
ELSE DEFS search-wordlist IF execute THEN
THEN
REPEAT 2drop ;
: run BEGIN refill WHILE intp REPEAT ;
\ --- Lists&Rings
warnings OFF
: LIST ( node -- ) ]] BEGIN @ dup WHILE >R [[ ; immediate
warnings ON
: LOOP-LIST ( -- ) ]] R> REPEAT drop [[ ; immediate
: empty-ring? ( node -- f ) dup @ = ;
: RING ( node -- ) ]] dup BEGIN @ 2dup <> WHILE 2>R [[ ; immediate
: LOOP-RING ( -- ) ]] 2R> REPEAT 2drop [[ ; immediate
: new-node ( -- node )
here dup , ;
: do-link ( node new-node -- ; do link after current node )
over @ over ! swap ! ;
\ --- Sorting..
: nt>freq ( nt -- n ;frequency of uses )
name>int >BODY @ ;
: @maxfreq ( wid -- n ;maximum frequency )
0 swap cell+
LIST ( max )
I nt>freq 2dup <
IF nip ELSE drop THEN
LOOP-LIST ;
2 cells constant RING#
: rings-vec ( u -- a size ; create vector of rings )
here over 1+ 0
DO new-node drop 0 , LOOP
swap RING# * ;
: populate-by ( a wid -- )
cell+
LIST
dup I nt>freq RING# * + \ root-node
new-node I , \ new-node
do-link
LOOP-LIST drop ;
\ --- Display TOP
: node>nt cell+ @ ;
: .ring ( root-node -- )
0 swap
RING
dup 0= IF I node>nt nt>freq . THEN
space I node>nt name>string type
1+
LOOP-RING drop cr ;
: .top ( a size n -- )
-rot BOUNDS swap
?DO ( n )
I empty-ring? 0= IF 1- I .ring THEN
dup 0= IF drop UNLOOP EXIT THEN
[ RING# negate ] LITERAL +LOOP drop ;
: args>top# ( -- n )
1 arg 2dup 0 0 d<>
IF >float
IF f>d d>s dup 0= IF drop 4 THEN
ELSE 4 THEN
ELSE 2drop 4 THEN ;
\ --- KEYS behaviour
variable cmpl? cmpl? OFF
2variable cword
here WORD# allot 0 cword 2!
current @ KEYS current !
: create
cmpl? @
IF cword 2@ keycmpl
ELSE parse-name funcmpl THEN ;
: constant
cmpl? @
IF cword 2@ keycmpl
ELSE parse-name funcmpl THEN ;
: variable parse-name funcmpl ;
: value parse-name funcmpl ;
: defer parse-name funcmpl ;
: ( BEGIN >in @ [char] ) parse nip >in @ rot - =
WHILE refill 0= IF exit THEN REPEAT ;
: \ 10 parse 2drop ;
: \G 10 parse 2drop ;
: S" [char] " parse 2drop ;
: ." [char] " parse 2drop ;
: [']
parse-name DEFS search-wordlist IF execute THEN ;
: postpone
parse-name DEFS search-wordlist IF execute THEN ;
: ; cmpl? OFF ;
: : warnings OFF
parse-name
cword 2@ drop WORD# rot umin dup >R MOVE
cword 2@ drop R> cword 2!
cword 2@ cmpl? @
IF keycmpl \ `:' inside def. = a defining word
ELSE funcmpl THEN
cmpl? ON
warnings ON
;
current !
\ Run, ruuun!
stdin ' run execute-parsing-file DEFS @maxfreq rings-vec over DEFS populate-by args>top# .top bye
|
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
|
#BASIC256
|
BASIC256
|
print " x Stirling Lanczos"
print
for i = 1 to 20
d = i / 10.0
print d;
print chr(9); ljust(string(gammaStirling(d)), 13, "0");
print chr(9); ljust(string(gammaLanczos(d)), 13, "0")
next i
end
function gammaStirling (x)
e = exp(1) # e is not predefined in BASIC256
return sqr(2.0 * pi / x) * ((x / e) ^ x)
end function
function gammaLanczos (x)
dim p = {0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7}
g = 7
if x < 0.5 then return pi / (sin(pi * x) * gammaLanczos(1-x))
x -= 1
a = p[0]
t = x + g + 0.5
for i = 1 to 8
a += p[i] / (x + i)
next i
return sqr(2.0 * pi) * (t ^ (x + 0.5)) * exp(-t) * a
end function
|
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.
|
#Go
|
Go
|
package main
import (
"fmt"
"math/rand"
"time"
)
const boxW = 41 // Galton box width
const boxH = 37 // Galton box height.
const pinsBaseW = 19 // Pins triangle base.
const nMaxBalls = 55 // Number of balls.
const centerH = pinsBaseW + (boxW-pinsBaseW*2+1)/2 - 1
const (
empty = ' '
ball = 'o'
wall = '|'
corner = '+'
floor = '-'
pin = '.'
)
type Ball struct{ x, y int }
func newBall(x, y int) *Ball {
if box[y][x] != empty {
panic("Tried to create a new ball in a non-empty cell. Program terminated.")
}
b := Ball{x, y}
box[y][x] = ball
return &b
}
func (b *Ball) doStep() {
if b.y <= 0 {
return // Reached the bottom of the box.
}
cell := box[b.y-1][b.x]
switch cell {
case empty:
box[b.y][b.x] = empty
b.y--
box[b.y][b.x] = ball
case pin:
box[b.y][b.x] = empty
b.y--
if box[b.y][b.x-1] == empty && box[b.y][b.x+1] == empty {
b.x += rand.Intn(2)*2 - 1
box[b.y][b.x] = ball
return
} else if box[b.y][b.x-1] == empty {
b.x++
} else {
b.x--
}
box[b.y][b.x] = ball
default:
// It's frozen - it always piles on other balls.
}
}
type Cell = byte
/* Galton box. Will be printed upside down. */
var box [boxH][boxW]Cell
func initializeBox() {
// Set ceiling and floor
box[0][0] = corner
box[0][boxW-1] = corner
for i := 1; i < boxW-1; i++ {
box[0][i] = floor
}
for i := 0; i < boxW; i++ {
box[boxH-1][i] = box[0][i]
}
// Set walls
for r := 1; r < boxH-1; r++ {
box[r][0] = wall
box[r][boxW-1] = wall
}
// Set rest to empty initially
for i := 1; i < boxH-1; i++ {
for j := 1; j < boxW-1; j++ {
box[i][j] = empty
}
}
// Set pins
for nPins := 1; nPins <= pinsBaseW; nPins++ {
for p := 0; p < nPins; p++ {
box[boxH-2-nPins][centerH+1-nPins+p*2] = pin
}
}
}
func drawBox() {
for r := boxH - 1; r >= 0; r-- {
for c := 0; c < boxW; c++ {
fmt.Printf("%c", box[r][c])
}
fmt.Println()
}
}
func main() {
rand.Seed(time.Now().UnixNano())
initializeBox()
var balls []*Ball
for i := 0; i < nMaxBalls+boxH; i++ {
fmt.Println("\nStep", i, ":")
if i < nMaxBalls {
balls = append(balls, newBall(centerH, boxH-2)) // add ball
}
drawBox()
// Next step for the simulation.
// Frozen balls are kept in balls slice for simplicity
for _, b := range balls {
b.doStep()
}
}
}
|
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
|
#FreeBASIC
|
FreeBASIC
|
function is_gapful( n as uinteger ) as boolean
if n<100 then return false
dim as string ns = str(n)
dim as uinteger gap = 10*val(mid(ns,1,1)) + val(mid(ns,len(ns),1))
if n mod gap = 0 then return true else return false
end function
dim as ulongint i = 100
dim as ushort c
print "The first thirty gapful numbers:"
while c<30
if is_gapful(i) then
c += 1
print i;" ";
end if
i += 1
wend
print : print
i = 1000000 : c = 0
print "The first fifteen gapful numbers above 999,999:"
while c<15
if is_gapful(i) then
c += 1
print i;" ";
end if
i += 1
wend
print : print
i = 1000000000 : c = 0
print "The first ten gapful numbers above 999,999,999:"
while c<10
if is_gapful(i) then
c += 1
print i;" ";
end if
i += 1
wend
print
|
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
|
#Generic
|
Generic
|
generic coordinaat
{
ecs;
uuii;
coordinaat() { ecs=+a;uuii=+a;}
coordinaat(ecs_set,uuii_set) { ecs = ecs_set; uuii=uuii_set;}
operaator<(c)
{
iph ecs < c.ecs return troo;
iph c.ecs < ecs return phals;
iph uuii < c.uuii return troo;
return phals;
}
operaator==(connpair) // eecuuols and not eecuuols deriiu phronn operaator<
{
iph this < connpair return phals;
iph connpair < this return phals;
return troo;
}
operaator!=(connpair)
{
iph this < connpair return troo;
iph connpair < this return troo;
return phals;
}
too_string()
{
return "(" + ecs.too_string() + "," + uuii.too_string() + ")";
}
print()
{
str = too_string();
str.print();
}
println()
{
str = too_string();
str.println();
}
}
generic nnaatrics
{
s; // this is a set of coordinaat/ualioo pairs.
iteraator; // this field holds an iteraator phor the nnaatrics.
nnaatrics() // no parameters required phor nnaatrics construction.
{
s = nioo set(); // create a nioo set of coordinaat/ualioo pairs.
iteraator = nul; // the iteraator is initially set to nul.
}
nnaatrics(copee) // copee the nnaatrics.
{
s = nioo set(); // create a nioo set of coordinaat/ualioo pairs.
iteraator = nul; // the iteraator is initially set to nul.
r = copee.rouus;
c = copee.cols;
i = 0;
uuiil i < r
{
j = 0;
uuiil j < c
{
this[i,j] = copee[i,j];
j++;
}
i++;
}
}
begin { get { return s.begin; } } // property: used to commence manual iteraashon.
end { get { return s.end; } } // property: used to dephiin the end itenn of iteraashon
operaator<(a) // les than operaator is corld bii the avl tree algorithnns
{ // this operaator innpliis phor instance that you could potenshalee hav sets ou nnaatricss.
iph cees < a.cees // connpair the cee sets phurst.
return troo;
els iph a.cees < cees
return phals;
els // the cee sets are eecuuol thairphor connpair nnaatrics elennents.
{
phurst1 = begin;
lahst1 = end;
phurst2 = a.begin;
lahst2 = a.end;
uuiil phurst1 != lahst1 && phurst2 != lahst2
{
iph phurst1.daata.ualioo < phurst2.daata.ualioo
return troo;
els
{
iph phurst2.daata.ualioo < phurst1.daata.ualioo
return phals;
els
{
phurst1 = phurst1.necst;
phurst2 = phurst2.necst;
}
}
}
return phals;
}
}
operaator==(connpair) // eecuuols and not eecuuols deriiu phronn operaator<
{
iph this < connpair return phals;
iph connpair < this return phals;
return troo;
}
operaator!=(connpair)
{
iph this < connpair return troo;
iph connpair < this return troo;
return phals;
}
operaator[](cee_a,cee_b) // this is the nnaatrics indexer.
{
set
{
trii { s >> nioo cee_ualioo(new coordinaat(cee_a,cee_b)); } catch {}
s << nioo cee_ualioo(new coordinaat(nioo integer(cee_a),nioo integer(cee_b)),ualioo);
}
get
{
d = s.get(nioo cee_ualioo(new coordinaat(cee_a,cee_b)));
return d.ualioo;
}
}
operaator>>(coordinaat) // this operaator reennoous an elennent phronn the nnaatrics.
{
s >> nioo cee_ualioo(coordinaat);
return this;
}
iteraat() // and this is how to iterate on the nnaatrics.
{
iph iteraator.nul()
{
iteraator = s.lepht_nnohst;
iph iteraator == s.heder
return nioo iteraator(phals,nioo nun());
els
return nioo iteraator(troo,iteraator.daata.ualioo);
}
els
{
iteraator = iteraator.necst;
iph iteraator == s.heder
{
iteraator = nul;
return nioo iteraator(phals,nioo nun());
}
els
return nioo iteraator(troo,iteraator.daata.ualioo);
}
}
couunt // this property returns a couunt ou elennents in the nnaatrics.
{
get
{
return s.couunt;
}
}
ennptee // is the nnaatrics ennptee?
{
get
{
return s.ennptee;
}
}
lahst // returns the ualioo of the lahst elennent in the nnaatrics.
{
get
{
iph ennptee
throuu "ennptee nnaatrics";
els
return s.lahst.ualioo;
}
}
too_string() // conuerts the nnaatrics too aa string
{
return s.too_string();
}
print() // prints the nnaatrics to the consohl.
{
out = too_string();
out.print();
}
println() // prints the nnaatrics as a liin too the consohl.
{
out = too_string();
out.println();
}
cees // return the set ou cees ou the nnaatrics (a set of coordinaats).
{
get
{
k = nioo set();
phor e : s k << e.cee;
return k;
}
}
operaator+(p)
{
ouut = nioo nnaatrics();
phurst1 = begin;
lahst1 = end;
phurst2 = p.begin;
lahst2 = p.end;
uuiil phurst1 != lahst1 && phurst2 != lahst2
{
ouut[phurst1.daata.cee.ecs,phurst1.daata.cee.uuii] = phurst1.daata.ualioo + phurst2.daata.ualioo;
phurst1 = phurst1.necst;
phurst2 = phurst2.necst;
}
return ouut;
}
operaator-(p)
{
ouut = nioo nnaatrics();
phurst1 = begin;
lahst1 = end;
phurst2 = p.begin;
lahst2 = p.end;
uuiil phurst1 != lahst1 && phurst2 != lahst2
{
ouut[phurst1.daata.cee.ecs,phurst1.daata.cee.uuii] = phurst1.daata.ualioo - phurst2.daata.ualioo;
phurst1 = phurst1.necst;
phurst2 = phurst2.necst;
}
return ouut;
}
rouus
{
get
{
r = +a;
phurst1 = begin;
lahst1 = end;
uuiil phurst1 != lahst1
{
iph r < phurst1.daata.cee.ecs r = phurst1.daata.cee.ecs;
phurst1 = phurst1.necst;
}
return r + +b;
}
}
cols
{
get
{
c = +a;
phurst1 = begin;
lahst1 = end;
uuiil phurst1 != lahst1
{
iph c < phurst1.daata.cee.uuii c = phurst1.daata.cee.uuii;
phurst1 = phurst1.necst;
}
return c + +b;
}
}
operaator*(o)
{
iph cols != o.rouus throw "rouus-cols nnisnnatch";
reesult = nioo nnaatrics();
rouu_couunt = rouus;
colunn_couunt = o.cols;
loop = cols;
i = +a;
uuiil i < rouu_couunt
{
g = +a;
uuiil g < colunn_couunt
{
sunn = +a.a;
h = +a;
uuiil h < loop
{
a = this[i, h];
b = o[h, g];
nn = a * b;
sunn = sunn + nn;
h++;
}
reesult[i, g] = sunn;
g++;
}
i++;
}
return reesult;
}
suuop_rouus(a, b)
{
c = cols;
i = 0;
uuiil u < cols
{
suuop = this[a, i];
this[a, i] = this[b, i];
this[b, i] = suuop;
i++;
}
}
suuop_colunns(a, b)
{
r = rouus;
i = 0;
uuiil i < rouus
{
suuopp = this[i, a];
this[i, a] = this[i, b];
this[i, b] = suuop;
i++;
}
}
transpohs
{
get
{
reesult = new nnaatrics();
r = rouus;
c = cols;
i=0;
uuiil i < r
{
g = 0;
uuiil g < c
{
reesult[g, i] = this[i, g];
g++;
}
i++;
}
return reesult;
}
}
deternninant
{
get
{
rouu_couunt = rouus;
colunn_count = cols;
if rouu_couunt != colunn_count
throw "not a scuuair nnaatrics";
if rouu_couunt == 0
throw "the nnaatrics is ennptee";
if rouu_couunt == 1
return this[0, 0];
if rouu_couunt == 2
return this[0, 0] * this[1, 1] -
this[0, 1] * this[1, 0];
temp = nioo nnaatrics();
det = 0.0;
parity = 1.0;
j = 0;
uuiil j < rouu_couunt
{
k = 0;
uuiil k < rouu_couunt-1
{
skip_col = phals;
l = 0;
uuiil l < rouu_couunt-1
{
if l == j skip_col = troo;
if skip_col
n = l + 1;
els
n = l;
temp[k, l] = this[k + 1, n];
l++;
}
k++;
}
det = det + parity * this[0, j] * temp.deeternninant;
parity = 0.0 - parity;
j++;
}
return det;
}
}
ad_rouu(a, b)
{
c = cols;
i = 0;
uuiil i < c
{
this[a, i] = this[a, i] + this[b, i];
i++;
}
}
ad_colunn(a, b)
{
c = rouus;
i = 0;
uuiil i < c
{
this[i, a] = this[i, a] + this[i, b];
i++;
}
}
subtract_rouu(a, b)
{
c = cols;
i = 0;
uuiil i < c
{
this[a, i] = this[a, i] - this[b, i];
i++;
}
}
subtract_colunn(a, b)
{
c = rouus;
i = 0;
uuiil i < c
{
this[i, a] = this[i, a] - this[i, b];
i++;
}
}
nnultiplii_rouu(rouu, scalar)
{
c = cols;
i = 0;
uuiil i < c
{
this[rouu, i] = this[rouu, i] * scalar;
i++;
}
}
nnultiplii_colunn(colunn, scalar)
{
r = rouus;
i = 0;
uuiil i < r
{
this[i, colunn] = this[i, colunn] * scalar;
i++;
}
}
diuiid_rouu(rouu, scalar)
{
c = cols;
i = 0;
uuiil i < c
{
this[rouu, i] = this[rouu, i] / scalar;
i++;
}
}
diuiid_colunn(colunn, scalar)
{
r = rouus;
i = 0;
uuiil i < r
{
this[i, colunn] = this[i, colunn] / scalar;
i++;
}
}
connbiin_rouus_ad(a,b,phactor)
{
c = cols;
i = 0;
uuiil i < c
{
this[a, i] = this[a, i] + phactor * this[b, i];
i++;
}
}
connbiin_rouus_subtract(a,b,phactor)
{
c = cols;
i = 0;
uuiil i < c
{
this[a, i] = this[a, i] - phactor * this[b, i];
i++;
}
}
connbiin_colunns_ad(a,b,phactor)
{
r = rouus;
i = 0;
uuiil i < r
{
this[i, a] = this[i, a] + phactor * this[i, b];
i++;
}
}
connbiin_colunns_subtract(a,b,phactor)
{
r = rouus;
i = 0;
uuiil i < r
{
this[i, a] = this[i, a] - phactor * this[i, b];
i++;
}
}
inuers
{
get
{
rouu_couunt = rouus;
colunn_couunt = cols;
iph rouu_couunt != colunn_couunt
throw "nnatrics not scuuair";
els iph rouu_couunt == 0
throw "ennptee nnatrics";
els iph rouu_couunt == 1
{
r = nioo nnaatrics();
r[0, 0] = 1.0 / this[0, 0];
return r;
}
gauss = nioo nnaatrics(this);
i = 0;
uuiil i < rouu_couunt
{
j = 0;
uuiil j < rouu_couunt
{
iph i == j
gauss[i, j + rouu_couunt] = 1.0;
els
gauss[i, j + rouu_couunt] = 0.0;
j++;
}
i++;
}
j = 0;
uuiil j < rouu_couunt
{
iph gauss[j, j] == 0.0
{
k = j + 1;
uuiil k < rouu_couunt
{
if gauss[k, j] != 0.0 {gauss.nnaat.suuop_rouus(j, k); break; }
k++;
}
if k == rouu_couunt throw "nnatrics is singioolar";
}
phactor = gauss[j, j];
iph phactor != 1.0 gauss.diuiid_rouu(j, phactor);
i = j+1;
uuiil i < rouu_couunt
{
gauss.connbiin_rouus_subtract(i, j, gauss[i, j]);
i++;
}
j++;
}
i = rouu_couunt - 1;
uuiil i > 0
{
k = i - 1;
uuiil k >= 0
{
gauss.connbiin_rouus_subtract(k, i, gauss[k, i]);
k--;
}
i--;
}
reesult = nioo nnaatrics();
i = 0;
uuiil i < rouu_couunt
{
j = 0;
uuiil j < rouu_couunt
{
reesult[i, j] = gauss[i, j + rouu_couunt];
j++;
}
i++;
}
return reesult;
}
}
}
|
http://rosettacode.org/wiki/Gauss-Jordan_matrix_inversion
|
Gauss-Jordan matrix inversion
|
Task
Invert matrix A using Gauss-Jordan method.
A being an n × n matrix.
|
#Lambdatalk
|
Lambdatalk
|
{require lib_matrix}
{M.gaussJordan
{M.new [[1,2,3],
[4,5,6],
[7,8,-9]]}}
->
[[-1.722222222222222,0.7777777777777777,-0.05555555555555555],
[1.4444444444444444,-0.5555555555555556,0.1111111111111111],
[-0.05555555555555555,0.1111111111111111,-0.05555555555555555]]
|
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
|
#JavaScript
|
JavaScript
|
function fizz(d, e) {
return function b(a) {
return a ? b(a - 1).concat(a) : [];
}(e).reduce(function (b, a) {
return b + (d.reduce(function (b, c) {
return b + (a % c[0] ? "" : c[1]);
}, "") || a.toString()) + "\n";
}, "");
}
|
http://rosettacode.org/wiki/Hailstone_sequence
|
Hailstone sequence
|
The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.
This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):
hailstone sequence, hailstone numbers
3x + 2 mapping, 3n + 1 problem
Collatz sequence
Hasse's algorithm
Kakutani's problem
Syracuse algorithm, Syracuse problem
Thwaites conjecture
Ulam's problem
The hailstone sequence is also known as hailstone numbers (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).
Task
Create a routine to generate the hailstone sequence for a number.
Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
(But don't show the actual sequence!)
See also
xkcd (humourous).
The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).
The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
|
#zkl
|
zkl
|
fcn collatz(n,z=L()){ z.append(n); if(n==1) return(z);
if(n.isEven) return(self.fcn(n/2,z)); return(self.fcn(n*3+1,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
|
#DUP
|
DUP
|
0"abcdefghijklmnopqrstuvwxyz" {store character values of string in cells 0..length of string-1}
26[$][^^-;,1-]# {Loop from 26-26 to 26-0, print the respective cell contents to STDOUT}
|
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
|
#Dyalect
|
Dyalect
|
print << ('a'..'z').ToArray()
|
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
|
#Onyx
|
Onyx
|
`Hello world!\n' print flush
|
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
|
#Lingo
|
Lingo
|
squares = script("generator.power").new(2)
cubes = script("generator.power").new(3)
filter = script("generator.filter").new(squares, cubes)
filter.skip(20)
res = []
i = 0
repeat while filter.exec(res)
i = i + 1
if i>10 then exit repeat
put res[1]
end repeat
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#Yabasic
|
Yabasic
|
sub gcd(u, v)
local t
u = int(abs(u))
v = int(abs(v))
while(v)
t = u
u = v
v = mod(t, v)
wend
return u
end sub
print "Greatest common divisor: ", gcd(12345, 9876)
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#Z80_Assembly
|
Z80 Assembly
|
; Inputs: a, b
; Outputs: a = gcd(a, b)
; Destroys: c
; Assumes: a and b are positive one-byte integers
gcd:
cp b
ret z ; while a != b
jr c, else ; if a > b
sub b ; a = a - b
jr gcd
else:
ld c, a ; Save a
ld a, b ; Swap b into a so we can do the subtraction
sub c ; b = b - a
ld b, a ; Put a and b back where they belong
ld a, c
jr gcd
|
http://rosettacode.org/wiki/Generate_Chess960_starting_position
|
Generate Chess960 starting position
|
Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints:
as in the standard chess game, all eight white pawns must be placed on the second rank.
White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints:
the bishops must be placed on opposite color squares (i.e. they must be an odd number of spaces apart or there must be an even number of spaces between them)
the King must be between two rooks (with any number of other pieces between them all)
Black pawns and pieces must be placed respectively on the seventh and eighth ranks, mirroring the white pawns and pieces, just as in the standard game. (That is, their positions are not independently randomized.)
With those constraints there are 960 possible starting positions, thus the name of the variant.
Task
The purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed with Chess symbols in Unicode: ♔♕♖♗♘ or with the letters King Queen Rook Bishop kNight.
|
#Python
|
Python
|
>>> from itertools import permutations
>>> pieces = 'KQRrBbNN'
>>> starts = {''.join(p).upper() for p in permutations(pieces)
if p.index('B') % 2 != p.index('b') % 2 # Bishop constraint
and ( p.index('r') < p.index('K') < p.index('R') # King constraint
or p.index('R') < p.index('K') < p.index('r') ) }
>>> len(starts)
960
>>> starts.pop()
'QNBRNKRB'
>>>
|
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.
|
#Aime
|
Aime
|
compose_i(,,)
{
($0)(($1)($2));
}
compose(,)
{
compose_i.apply($0, $1);
}
double(real a)
{
2 * a;
}
square(real a)
{
a * a;
}
main(void)
{
o_(compose(square, double)(40), "\n");
0;
}
|
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.
|
#ALGOL_68
|
ALGOL 68
|
MODE F = PROC(REAL)REAL; # ALGOL 68 is strong typed #
# As a procedure for real to real functions #
PROC compose = (F f, g)F: (REAL x)REAL: f(g(x));
OP (F,F)F O = compose; # or an OPerator that can be overloaded #
# Example use: #
F sin arc sin = compose(sin, arc sin);
print((sin arc sin(0.5), (sin O arc sin)(0.5), new line))
|
http://rosettacode.org/wiki/FTP
|
FTP
|
Task
Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
|
#Common_Lisp
|
Common Lisp
|
(use-package :ftp)
(with-ftp-connection (conn :hostname "ftp.hq.nasa.gov"
:passive-ftp-p t)
(send-cwd-command conn "/pub/issoutreach/Living in Space Stories (MP3 Files)")
(send-list-command conn t)
(let ((filename "Gravity in the Brain.mp3"))
(retrieve-file conn filename filename :type :binary)))
|
http://rosettacode.org/wiki/FTP
|
FTP
|
Task
Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
|
#Erlang
|
Erlang
|
%%%-------------------------------------------------------------------
%%% To execute in shell, Run the following commands:-
%%% >c("ftp_example").
%%% >ftp_example:run().
%%%-------------------------------------------------------------------
-module(ftp_example).
-export([run/0]).
run() ->
Host = "ftp.easynet.fr",
Opts = [{mode, passive}],
User = "anonymous",
Password = "",
Directory = "/debian/",
File = "README.html",
%%% Open connection with FTP Server
io:format("Opening connection with host ~p ~n", [Host]),
{ok, Pid} = ftp:open(Host, Opts),
%%% Login as Anonymous user
io:format("Logging in as user ~p ~n", [User]),
ftp:user(Pid, User, Password),
%%% Change Directory to "/debian/"
io:format("Changing Directory to ~p ~n", [Directory]),
ftp:cd(Pid, Directory),
%%% Listing contents of current Directory
io:format("Contents of Current Directory ~n"),
{ok, Listing} = ftp:ls(Pid),
io:format("~p ~n", [Listing]),
%%% Download file "README.html"
io:format("Downloading File ~p to current directory ~n", [File]),
ftp:recv(Pid, File),
%%% Close connection
io:format("Closing connection to FTP Server"),
ftp:close(Pid).
|
http://rosettacode.org/wiki/Function_prototype
|
Function prototype
|
Some languages provide the facility to declare functions and subroutines through the use of function prototyping.
Task
Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include:
An explanation of any placement restrictions for prototype declarations
A prototype declaration for a function that does not require arguments
A prototype declaration for a function that requires two arguments
A prototype declaration for a function that utilizes varargs
A prototype declaration for a function that utilizes optional arguments
A prototype declaration for a function that utilizes named parameters
Example of prototype declarations for subroutines or procedures (if these differ from functions)
An explanation and example of any special forms of prototyping not covered by the above
Languages that do not provide function prototyping facilities should be omitted from this task.
|
#Julia
|
Julia
|
julia > function mycompare(a, b)::Cint
(a < b) ? -1 : ((a > b) ? +1 : 0)
end
mycompare (generic function with 1 method)
|
http://rosettacode.org/wiki/Function_prototype
|
Function prototype
|
Some languages provide the facility to declare functions and subroutines through the use of function prototyping.
Task
Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include:
An explanation of any placement restrictions for prototype declarations
A prototype declaration for a function that does not require arguments
A prototype declaration for a function that requires two arguments
A prototype declaration for a function that utilizes varargs
A prototype declaration for a function that utilizes optional arguments
A prototype declaration for a function that utilizes named parameters
Example of prototype declarations for subroutines or procedures (if these differ from functions)
An explanation and example of any special forms of prototyping not covered by the above
Languages that do not provide function prototyping facilities should be omitted from this task.
|
#Kotlin
|
Kotlin
|
// version 1.0.6
interface MyInterface {
fun foo() // no arguments, no return type
fun goo(i: Int, j: Int) // two arguments, no return type
fun voo(vararg v: Int) // variable number of arguments, no return type
fun ooo(o: Int = 1): Int // optional argument with default value and return type Int
fun roo(): Int // no arguments with return type Int
val poo: Int // read only property of type Int
}
abstract class MyAbstractClass {
abstract fun afoo() // abstract member function, no arguments or return type
abstract var apoo: Int // abstract read/write member property of type Int
}
class Derived : MyAbstractClass(), MyInterface {
override fun afoo() {}
override var apoo: Int = 0
override fun foo() {}
override fun goo(i: Int, j: Int) {}
override fun voo(vararg v: Int) {}
override fun ooo(o: Int): Int = o // can't specify default argument again here but same as in interface
override fun roo(): Int = 2
override val poo: Int = 3
}
fun main(args: Array<String>) {
val d = Derived()
println(d.apoo)
println(d.ooo()) // default argument of 1 inferred
println(d.roo())
println(d.poo)
}
|
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
|
#6502_Assembly
|
6502 Assembly
|
MULTIPLY: STX MULN ; 6502 has no "acc += xreg" instruction,
TXA ; so use a memory address
MULLOOP: DEY
CLC ; remember to clear the carry flag before
ADC MULN ; doing addition or subtraction
CPY #$01
BNE MULLOOP
RTS
|
http://rosettacode.org/wiki/French_Republican_calendar
|
French Republican calendar
|
Write a program to convert dates between the Gregorian calendar and the French Republican calendar.
The year 1 of the Republican calendar began on 22 September 1792. There were twelve months (Vendémiaire, Brumaire, Frimaire, Nivôse, Pluviôse, Ventôse, Germinal, Floréal, Prairial, Messidor, Thermidor, and Fructidor) of 30 days each, followed by five intercalary days or Sansculottides (Fête de la vertu / Virtue Day, Fête du génie / Talent Day, Fête du travail / Labour Day, Fête de l'opinion / Opinion Day, and Fête des récompenses / Honours Day). In leap years (the years 3, 7, and 11) a sixth Sansculottide was added: Fête de la Révolution / Revolution Day.
As a minimum, your program should give correct results for dates in the range from 1 Vendémiaire 1 = 22 September 1792 to 10 Nivôse 14 = 31 December 1805 (the last day when the Republican calendar was officially in use). If you choose to accept later dates, be aware that there are several different methods (described on the Wikipedia page) about how to determine leap years after the year 14. You should indicate which method you are using. (Because of these different methods, correct programs may sometimes give different results for dates after 1805.)
Test your program by converting the following dates both from Gregorian to Republican and from Republican to Gregorian:
• 1 Vendémiaire 1 = 22 September 1792
• 1 Prairial 3 = 20 May 1795
• 27 Messidor 7 = 15 July 1799 (Rosetta Stone discovered)
• Fête de la Révolution 11 = 23 September 1803
• 10 Nivôse 14 = 31 December 1805
|
#F.23
|
F#
|
// French Republican Calander: Nigel Galloway. April 16th., 2021
let firstDay=System.DateTime.Parse("22/9/1792")
type monthsFRC= Vendemiaire = 0
|Brumaire = 30
|Frimaire = 60
|Nivose = 90
|Pluviose = 120
|Ventose = 150
|Germinal = 180
|Floral = 210
|Prairial = 240
|Messidor = 270
|Thermidor = 300
|Fructidor = 330
|Virtue = 360
|Talent = 361
|Labour = 362
|Opinion = 363
|Honours = 364
|Revolution = 365
type months= January = 1
|February = 2
|March = 3
|April = 4
|May = 5
|June = 6
|July = 7
|August = 8
|September = 9
|October = 10
|November = 11
|December = 12
let frc2Greg n (g:monthsFRC) l=firstDay+System.TimeSpan.FromDays(float((l-1)*365+l/4+(int g)+n-1))
let rec fG n g=let i=match g with 3 |7 |11->366 |_->365 in if n<i then (n,g) else fG(n-i)(g+1)
let Greg2FRC n=let n,g=fG((n-firstDay).Days) 1
match n/30,n%30 with (12,n)->(1,enum<monthsFRC>(360+n),g) |(n,l)->(l+1,enum<monthsFRC>(n*30),g)
let n=(frc2Greg 1 monthsFRC.Vendemiaire 1) in printfn "%d %s %d -> %d %A %d" 1 "Vendemiaire" 1 n.Day (enum<months> n.Month) n.Year
let n=(frc2Greg 27 monthsFRC.Messidor 7) in printfn "%d %s %d -> %d %A %d" 27 "Messidor" 7 n.Day (enum<months> n.Month) n.Year
let n=(frc2Greg 1 monthsFRC.Revolution 11) in printfn "%d %s %d -> %d %A %d" 1 "Revolution" 11 n.Day (enum<months> n.Month) n.Year
let n=(frc2Greg 10 monthsFRC.Nivose 14) in printfn "%d %s %d -> %d %A %d" 10 "Nivose" 14 n.Day (enum<months> n.Month) n.Year
let n,g,l=Greg2FRC(System.DateTime(1792,9,22)) in printfn "%d %s %d -> %d %A %d" 22 "September" 1792 n g l
let n,g,l=Greg2FRC(System.DateTime(1799,7,15)) in printfn "%d %s %d -> %d %A %d" 15 "July" 1799 n g l
let n,g,l=Greg2FRC(System.DateTime(1803,9,23)) in printfn "%d %s %d -> %d %A %d" 23 "September" 1803 n g l
let n,g,l=Greg2FRC(System.DateTime(1805,12,31)) in printfn "%d %s %d -> %d %A %d" 31 "December" 1805 n g l
|
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.
|
#AWK
|
AWK
|
# syntax: GAWK -f FUSC_SEQUENCE.AWK
# converted from C
BEGIN {
for (i=0; i<61; i++) {
printf("%d ",fusc(i))
}
printf("\n")
print("fusc numbers whose length is greater than any previous fusc number length")
printf("%9s %9s\n","fusc","index")
for (i=0; i<=700000; i++) {
f = fusc(i)
leng = num_leng(f)
if (leng > max_leng) {
max_leng = leng
printf("%9s %9s\n",commatize(f),commatize(i))
}
}
exit(0)
}
function commatize(x, num) {
if (x < 0) {
return "-" commatize(-x)
}
x = int(x)
num = sprintf("%d.",x)
while (num ~ /^[0-9][0-9][0-9][0-9]/) {
sub(/[0-9][0-9][0-9][,.]/,",&",num)
}
sub(/\.$/,"",num)
return(num)
}
function fusc(n) {
if (n == 0 || n == 1) {
return(n)
}
else if (n % 2 == 0) {
return fusc(n/2)
}
else {
return fusc((n-1)/2) + fusc((n+1)/2)
}
}
function num_leng(n, sum) {
sum = 1
while (n > 9) {
n = int(n/10)
sum++
}
return(sum)
}
|
http://rosettacode.org/wiki/Functional_coverage_tree
|
Functional coverage tree
|
Functional coverage is a measure of how much a particular function of a system
has been verified as correct. It is used heavily in tracking the completeness
of the verification of complex System on Chip (SoC) integrated circuits, where
it can also be used to track how well the functional requirements of the
system have been verified.
This task uses a sub-set of the calculations sometimes used in tracking
functional coverage but uses a more familiar(?) scenario.
Task Description
The head of the clean-up crews for "The Men in a very dark shade of grey when
viewed at night" has been tasked with managing the cleansing of two properties
after an incident involving aliens.
She arranges the task hierarchically with a manager for the crews working on
each house who return with a breakdown of how they will report on progress in
each house.
The overall hierarchy of (sub)tasks is as follows,
cleaning
house1
bedrooms
bathrooms
bathroom1
bathroom2
outside lavatory
attic
kitchen
living rooms
lounge
dining room
conservatory
playroom
basement
garage
garden
house2
upstairs
bedrooms
suite 1
suite 2
bedroom 3
bedroom 4
bathroom
toilet
attics
groundfloor
kitchen
living rooms
lounge
dining room
conservatory
playroom
wet room & toilet
garage
garden
hot tub suite
basement
cellars
wine cellar
cinema
The head of cleanup knows that her managers will report fractional completion of leaf tasks (tasks with no child tasks of their own), and she knows that she will want to modify the weight of values of completion as she sees fit.
Some time into the cleaning, and some coverage reports have come in and she thinks see needs to weight the big house2 60-40 with respect to coverage from house1 She prefers a tabular view of her data where missing weights are assumed to be 1.0 and missing coverage 0.0.
NAME_HIERARCHY |WEIGHT |COVERAGE |
cleaning | | |
house1 |40 | |
bedrooms | |0.25 |
bathrooms | | |
bathroom1 | |0.5 |
bathroom2 | | |
outside_lavatory | |1 |
attic | |0.75 |
kitchen | |0.1 |
living_rooms | | |
lounge | | |
dining_room | | |
conservatory | | |
playroom | |1 |
basement | | |
garage | | |
garden | |0.8 |
house2 |60 | |
upstairs | | |
bedrooms | | |
suite_1 | | |
suite_2 | | |
bedroom_3 | | |
bedroom_4 | | |
bathroom | | |
toilet | | |
attics | |0.6 |
groundfloor | | |
kitchen | | |
living_rooms | | |
lounge | | |
dining_room | | |
conservatory | | |
playroom | | |
wet_room_&_toilet | | |
garage | | |
garden | |0.9 |
hot_tub_suite | |1 |
basement | | |
cellars | |1 |
wine_cellar | |1 |
cinema | |0.75 |
Calculation
The coverage of a node in the tree is calculated as the weighted average of the coverage of its children evaluated bottom-upwards in the tree.
The task is to calculate the overall coverage of the cleaning task and display the coverage at all levels of the hierarchy on this page, in a manner that visually shows the hierarchy, weights and coverage of all nodes.
Extra Credit
After calculating the coverage for all nodes, one can also calculate the additional/delta top level coverage that would occur if any (sub)task were to be fully covered from its current fractional coverage. This is done by multiplying the extra coverage that could be gained
1
−
c
o
v
e
r
a
g
e
{\displaystyle 1-coverage}
for any node, by the product of the `powers` of its parent nodes from the top down to the node.
The power of a direct child of any parent is given by the power of the parent multiplied by the weight of the child divided by the sum of the weights of all the direct children.
The pseudo code would be:
method delta_calculation(this, power):
sum_of_weights = sum(node.weight for node in children)
this.delta = (1 - this.coverage) * power
for node in self.children:
node.delta_calculation(power * node.weight / sum_of_weights)
return this.delta
Followed by a call to:
top.delta_calculation(power=1)
Note: to aid in getting the data into your program you might want to use an alternative, more functional description of the starting data given on the discussion page.
|
#Python
|
Python
|
from itertools import zip_longest
fc2 = '''\
cleaning,,
house1,40,
bedrooms,,.25
bathrooms,,
bathroom1,,.5
bathroom2,,
outside_lavatory,,1
attic,,.75
kitchen,,.1
living_rooms,,
lounge,,
dining_room,,
conservatory,,
playroom,,1
basement,,
garage,,
garden,,.8
house2,60,
upstairs,,
bedrooms,,
suite_1,,
suite_2,,
bedroom_3,,
bedroom_4,,
bathroom,,
toilet,,
attics,,.6
groundfloor,,
kitchen,,
living_rooms,,
lounge,,
dining_room,,
conservatory,,
playroom,,
wet_room_&_toilet,,
garage,,
garden,,.9
hot_tub_suite,,1
basement,,
cellars,,1
wine_cellar,,1
cinema,,.75
'''
NAME, WT, COV = 0, 1, 2
def right_type(txt):
try:
return float(txt)
except ValueError:
return txt
def commas_to_list(the_list, lines, start_indent=0):
'''
Output format is a nest of lists and tuples
lists are for coverage leaves without children items in the list are name, weight, coverage
tuples are 2-tuples for nodes with children. The first element is a list representing the
name, weight, coverage of the node (some to be calculated); the second element is a list of
child elements which may be 2-tuples or lists as above.
the_list is modified in-place
lines must be a generator of successive lines of input like fc2
'''
for n, line in lines:
indent = 0
while line.startswith(' ' * (4 * indent)):
indent += 1
indent -= 1
fields = [right_type(f) for f in line.strip().split(',')]
if indent == start_indent:
the_list.append(fields)
elif indent > start_indent:
lst = [fields]
sub = commas_to_list(lst, lines, indent)
the_list[-1] = (the_list[-1], lst)
if sub not in (None, ['']) :
the_list.append(sub)
else:
return fields if fields else None
return None
def pptreefields(lst, indent=0, widths=['%-32s', '%-8g', '%-10g']):
'''
Pretty prints the format described from function commas_to_list as a table with
names in the first column suitably indented and all columns having a fixed
minimum column width.
'''
lhs = ' ' * (4 * indent)
for item in lst:
if type(item) != tuple:
name, *rest = item
print(widths[0] % (lhs + name), end='|')
for width, item in zip_longest(widths[1:len(rest)], rest, fillvalue=widths[-1]):
if type(item) == str:
width = width[:-1] + 's'
print(width % item, end='|')
print()
else:
item, children = item
name, *rest = item
print(widths[0] % (lhs + name), end='|')
for width, item in zip_longest(widths[1:len(rest)], rest, fillvalue=widths[-1]):
if type(item) == str:
width = width[:-1] + 's'
print(width % item, end='|')
print()
pptreefields(children, indent+1)
def default_field(node_list):
node_list[WT] = node_list[WT] if node_list[WT] else 1.0
node_list[COV] = node_list[COV] if node_list[COV] else 0.0
def depth_first(tree, visitor=default_field):
for item in tree:
if type(item) == tuple:
item, children = item
depth_first(children, visitor)
visitor(item)
def covercalc(tree):
'''
Depth first weighted average of coverage
'''
sum_covwt, sum_wt = 0, 0
for item in tree:
if type(item) == tuple:
item, children = item
item[COV] = covercalc(children)
sum_wt += item[WT]
sum_covwt += item[COV] * item[WT]
cov = sum_covwt / sum_wt
return cov
if __name__ == '__main__':
lstc = []
commas_to_list(lstc, ((n, ln) for n, ln in enumerate(fc2.split('\n'))))
#pp(lstc, width=1, indent=4, compact=1)
#print('\n\nEXPANDED DEFAULTS\n')
depth_first(lstc)
#pptreefields(['NAME_HIERARCHY WEIGHT COVERAGE'.split()] + lstc)
print('\n\nTOP COVERAGE = %f\n' % covercalc(lstc))
depth_first(lstc)
pptreefields(['NAME_HIERARCHY WEIGHT COVERAGE'.split()] + lstc)
|
http://rosettacode.org/wiki/Function_frequency
|
Function frequency
|
Display - for a program or runtime environment (whatever suits the style of your language) - the top ten most frequently occurring functions (or also identifiers or tokens, if preferred).
This is a static analysis: The question is not how often each function is
actually executed at runtime, but how often it is used by the programmer.
Besides its practical usefulness, the intent of this task is to show how to do self-inspection within the language.
|
#Go
|
Go
|
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"io/ioutil"
"os"
"sort"
)
func main() {
if len(os.Args) != 2 {
fmt.Println("usage ff <go source filename>")
return
}
src, err := ioutil.ReadFile(os.Args[1])
if err != nil {
fmt.Println(err)
return
}
fs := token.NewFileSet()
a, err := parser.ParseFile(fs, os.Args[1], src, 0)
if err != nil {
fmt.Println(err)
return
}
f := fs.File(a.Pos())
m := make(map[string]int)
ast.Inspect(a, func(n ast.Node) bool {
if ce, ok := n.(*ast.CallExpr); ok {
start := f.Offset(ce.Pos())
end := f.Offset(ce.Lparen)
m[string(src[start:end])]++
}
return true
})
cs := make(calls, 0, len(m))
for k, v := range m {
cs = append(cs, &call{k, v})
}
sort.Sort(cs)
for i, c := range cs {
fmt.Printf("%-20s %4d\n", c.expr, c.count)
if i == 9 {
break
}
}
}
type call struct {
expr string
count int
}
type calls []*call
func (c calls) Len() int { return len(c) }
func (c calls) Swap(i, j int) { c[i], c[j] = c[j], c[i] }
func (c calls) Less(i, j int) bool { return c[i].count > c[j].count }
|
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
|
#BBC_BASIC
|
BBC BASIC
|
*FLOAT64
INSTALL @lib$+"FNUSING"
FOR x = 0.1 TO 2.05 STEP 0.1
PRINT FNusing("#.#",x), FNusing("##.############", FNgamma(x))
NEXT
END
DEF FNgamma(z) = EXP(FNlngamma(z))
DEF FNlngamma(z)
LOCAL a, b, i%, lz()
DIM lz(6)
lz() = 1.000000000190015, 76.18009172947146, -86.50532032941677, \
\ 24.01409824083091, -1.231739572450155, 0.0012086509738662, -0.000005395239385
IF z < 0.5 THEN = LN(PI / SIN(PI * z)) - FNlngamma(1.0 - z)
z -= 1.0
b = z + 5.5
a = lz(0)
FOR i% = 1 TO 6
a += lz(i%) / (z + i%)
NEXT
= (LNSQR(2*PI) + LN(a) - b) + LN(b) * (z+0.5)
|
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.
|
#Haskell
|
Haskell
|
import Data.Map hiding (map, filter)
import Graphics.Gloss
import Control.Monad.Random
data Ball = Ball { position :: (Int, Int), turns :: [Int] }
type World = ( Int -- number of rows of pins
, [Ball] -- sequence of balls
, Map Int Int ) -- counting bins
updateWorld :: World -> World
updateWorld (nRows, balls, bins)
| y < -nRows-5 = (nRows, map update bs, bins <+> x)
| otherwise = (nRows, map update balls, bins)
where
(Ball (x,y) _) : bs = balls
b <+> x = unionWith (+) b (singleton x 1)
update (Ball (x,y) turns)
| -nRows <= y && y < 0 = Ball (x + head turns, y - 1) (tail turns)
| otherwise = Ball (x, y - 1) turns
drawWorld :: World -> Picture
drawWorld (nRows, balls, bins) = pictures [ color red ballsP
, color black binsP
, color blue pinsP ]
where ballsP = foldMap (disk 1) $ takeWhile ((3 >).snd) $ map position balls
binsP = foldMapWithKey drawBin bins
pinsP = foldMap (disk 0.2) $ [1..nRows] >>= \i ->
[1..i] >>= \j -> [(2*j-i-1, -i-1)]
disk r pos = trans pos $ circleSolid (r*10)
drawBin x h = trans (x,-nRows-7)
$ rectangleUpperSolid 20 (-fromIntegral h)
trans (x,y) = Translate (20 * fromIntegral x) (20 * fromIntegral y)
startSimulation :: Int -> [Ball] -> IO ()
startSimulation nRows balls = simulate display white 50 world drawWorld update
where display = InWindow "Galton box" (400, 400) (0, 0)
world = (nRows, balls, empty)
update _ _ = updateWorld
main = evalRandIO balls >>= startSimulation 10
where balls = mapM makeBall [1..]
makeBall y = Ball (0, y) <$> randomTurns
randomTurns = filter (/=0) <$> getRandomRs (-1, 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
|
#Frink
|
Frink
|
// Create function to calculate gapful number
gapful[num,totalCounter] :=
{
// Display a line explaining the current calculation.
println["First $totalCounter gapful numbers over $num:"]
// Start a counter to compare with the total count.
counter = 0
while counter < totalCounter
{
numStr = toString[num] // Convert the integer to a string
gapfulNumStr = left[numStr,1] + right[numStr,1] // Concatenate the first and last character of the number to form a two digit number
gapfulNumInt = parseInt[gapfulNumStr] // Turn the concatenated string back into an integer.
// If the concatenated two digit integer divides into the current num variable with no remainder, print it to the list and increase our counter
if num mod gapfulNumInt == 0
{
print[numStr + " "]
counter = counter + 1
}
// Increase the current number for the next cycle.
num = num + 1
}
println[] // Linkbreak
}
// Print the first 30 gapful numbers over 100, the top 15 over 1,000,000 and the first 10 over 1,000,000,000.
gapful[100,30]
gapful[1000000,15]
gapful[1000000000,10]
|
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
|
#F.C5.8Drmul.C3.A6
|
Fōrmulæ
|
package main
import "fmt"
func commatize(n uint64) string {
s := fmt.Sprintf("%d", n)
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
return s
}
func main() {
starts := []uint64{1e2, 1e6, 1e7, 1e9, 7123}
counts := []int{30, 15, 15, 10, 25}
for i := 0; i < len(starts); i++ {
count := 0
j := starts[i]
pow := uint64(100)
for {
if j < pow*10 {
break
}
pow *= 10
}
fmt.Printf("First %d gapful numbers starting at %s:\n", counts[i], commatize(starts[i]))
for count < counts[i] {
fl := (j/pow)*10 + (j % 10)
if j%fl == 0 {
fmt.Printf("%d ", j)
count++
}
j++
if j >= 10*pow {
pow *= 10
}
}
fmt.Println("\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
|
#Go
|
Go
|
package main
import (
"errors"
"fmt"
"log"
"math"
)
type testCase struct {
a [][]float64
b []float64
x []float64
}
var tc = testCase{
// common RC example. Result x computed with rational arithmetic then
// converted to float64, and so should be about as close to correct as
// float64 represention allows.
a: [][]float64{
{1.00, 0.00, 0.00, 0.00, 0.00, 0.00},
{1.00, 0.63, 0.39, 0.25, 0.16, 0.10},
{1.00, 1.26, 1.58, 1.98, 2.49, 3.13},
{1.00, 1.88, 3.55, 6.70, 12.62, 23.80},
{1.00, 2.51, 6.32, 15.88, 39.90, 100.28},
{1.00, 3.14, 9.87, 31.01, 97.41, 306.02}},
b: []float64{-0.01, 0.61, 0.91, 0.99, 0.60, 0.02},
x: []float64{-0.01, 1.602790394502114, -1.6132030599055613,
1.2454941213714368, -0.4909897195846576, 0.065760696175232},
}
// result from above test case turns out to be correct to this tolerance.
const ε = 1e-13
func main() {
x, err := GaussPartial(tc.a, tc.b)
if err != nil {
log.Fatal(err)
}
fmt.Println(x)
for i, xi := range x {
if math.Abs(tc.x[i]-xi) > ε {
log.Println("out of tolerance")
log.Fatal("expected", tc.x)
}
}
}
func GaussPartial(a0 [][]float64, b0 []float64) ([]float64, error) {
// make augmented matrix
m := len(b0)
a := make([][]float64, m)
for i, ai := range a0 {
row := make([]float64, m+1)
copy(row, ai)
row[m] = b0[i]
a[i] = row
}
// WP algorithm from Gaussian elimination page
// produces row-eschelon form
for k := range a {
// Find pivot for column k:
iMax := k
max := math.Abs(a[k][k])
for i := k + 1; i < m; i++ {
if abs := math.Abs(a[i][k]); abs > max {
iMax = i
max = abs
}
}
if a[iMax][k] == 0 {
return nil, errors.New("singular")
}
// swap rows(k, i_max)
a[k], a[iMax] = a[iMax], a[k]
// Do for all rows below pivot:
for i := k + 1; i < m; i++ {
// Do for all remaining elements in current row:
for j := k + 1; j <= m; j++ {
a[i][j] -= a[k][j] * (a[i][k] / a[k][k])
}
// Fill lower triangular matrix with zeros:
a[i][k] = 0
}
}
// end of WP algorithm.
// now back substitute to get result.
x := make([]float64, m)
for i := m - 1; i >= 0; i-- {
x[i] = a[i][m]
for j := i + 1; j < m; j++ {
x[i] -= a[i][j] * x[j]
}
x[i] /= a[i][i]
}
return x, nil
}
|
http://rosettacode.org/wiki/Gauss-Jordan_matrix_inversion
|
Gauss-Jordan matrix inversion
|
Task
Invert matrix A using Gauss-Jordan method.
A being an n × n matrix.
|
#Mathematica_.2F_Wolfram_Language
|
Mathematica / Wolfram Language
|
a = N@{{1, 7, 5, 0}, {5, 8, 6, 9}, {2, 1, 6, 4}, {8, 1, 2, 4}};
elimmat = RowReduce[Join[a, IdentityMatrix[Length[a]], 2]];
inv = elimmat[[All, -Length[a] ;;]]
|
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
|
#Julia
|
Julia
|
function fizzbuzz(triggers :: Vector{Tuple{Int, ASCIIString}}, upper :: Int)
for i = 1 : upper
triggered = false
for trigger in triggers
if i % trigger[1] == 0
triggered = true
print(trigger[2])
end
end
!triggered && print(i)
println()
end
end
print("Enter upper limit:\n> ")
upper = parse(Int, readline())
triggers = Tuple{Int, ASCIIString}[]
print("Enter factor/string pairs (space delimited; ^D when done):\n> ")
while (r = readline()) != ""
input = split(r)
push!(triggers, (parse(Int, input[1]), input[2]))
print("> ")
end
println("EOF\n")
fizzbuzz(triggers, upper)
|
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
|
#Kotlin
|
Kotlin
|
fun main(args: Array<String>) {
//Read the maximum number, set to 0 if it couldn't be read
val max = readLine()?.toInt() ?: 0
val words = mutableMapOf<Int, String>()
//Read input three times for a factor and a word
(1..3).forEach {
readLine()?.let {
val tokens = it.split(' ')
words.put(tokens[0].toInt(), tokens[1])
}
}
//Sort the words so they will be output in arithmetic order
val sortedWords = words.toSortedMap()
//Find the words with matching factors and print them, print the number if no factors match
for (i in 1..max) {
val wordsToPrint = sortedWords.filter { i % it.key == 0 }.map { it.value }
if (wordsToPrint.isNotEmpty()) {
wordsToPrint.forEach { print(it) }
println()
}
else
println(i)
}
}
|
http://rosettacode.org/wiki/Hailstone_sequence
|
Hailstone sequence
|
The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.
This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):
hailstone sequence, hailstone numbers
3x + 2 mapping, 3n + 1 problem
Collatz sequence
Hasse's algorithm
Kakutani's problem
Syracuse algorithm, Syracuse problem
Thwaites conjecture
Ulam's problem
The hailstone sequence is also known as hailstone numbers (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).
Task
Create a routine to generate the hailstone sequence for a number.
Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
(But don't show the actual sequence!)
See also
xkcd (humourous).
The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).
The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
|
#ZX_Spectrum_Basic
|
ZX Spectrum Basic
|
10 LET n=27: LET s=1
20 GO SUB 1000
30 PRINT '"Sequence length = ";seqlen
40 LET maxlen=0: LET s=0
50 FOR m=2 TO 100000
60 LET n=m
70 GO SUB 1000
80 IF seqlen>maxlen THEN LET maxlen=seqlen: LET maxnum=m
90 NEXT m
100 PRINT "The number with the longest hailstone sequence is ";maxnum
110 PRINT "Its sequence length is ";maxlen
120 STOP
1000 REM Hailstone
1010 LET l=0
1020 IF s THEN PRINT n;" ";
1030 IF n=1 THEN LET seqlen=l+1: RETURN
1040 IF FN m(n,2)=0 THEN LET n=INT (n/2): GO TO 1060
1050 LET n=3*n+1
1060 LET l=l+1
1070 GO TO 1020
2000 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
|
#EchoLisp
|
EchoLisp
|
;; 1)
(define \a (first (string->unicode "a")))
(for/list ((i 25)) (unicode->string (+ i \a)))
→ (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)
;;2) using a sequence
(lib 'sequences)
(take ["a" .. "z"] 26)
→ (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)
; or
(for/string ((letter ["a" .. "z"])) letter)
→ abcdefghijklmnopqrstuvwxyz
|
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
|
#OOC
|
OOC
|
main: func {
"Hello world!" println()
}
|
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
|
#Lua
|
Lua
|
--could be done with a coroutine, but a simple closure works just as well.
local function powgen(m)
local count = 0
return function()
count = count + 1
return count^m
end
end
local squares = powgen(2)
local cubes = powgen(3)
local cowrap,coyield = coroutine.wrap, coroutine.yield
local function filter(f,g)
return cowrap(function()
local ff,gg = f(), g()
while true do
if ff == gg then
ff,gg = f(), g()
elseif ff < gg then
coyield(ff)
ff = f()
else
gg = g()
end
end
end)
end
filter = filter(squares,cubes)
for i = 1,30 do
local result = filter()
if i > 20 then
print(result)
end
end
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#zkl
|
zkl
|
(123456789).gcd(987654321) //-->9
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#ZX_Spectrum_Basic
|
ZX Spectrum Basic
|
10 FOR n=1 TO 3
20 READ a,b
30 PRINT "GCD of ";a;" and ";b;" = ";
40 GO SUB 70
50 NEXT n
60 STOP
70 IF b=0 THEN PRINT ABS (a): RETURN
80 LET c=a: LET a=b: LET b=FN m(c,b): GO TO 70
90 DEF FN m(a,b)=a-INT (a/b)*b
100 DATA 12,16,22,33,45,67
|
http://rosettacode.org/wiki/Generate_Chess960_starting_position
|
Generate Chess960 starting position
|
Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints:
as in the standard chess game, all eight white pawns must be placed on the second rank.
White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints:
the bishops must be placed on opposite color squares (i.e. they must be an odd number of spaces apart or there must be an even number of spaces between them)
the King must be between two rooks (with any number of other pieces between them all)
Black pawns and pieces must be placed respectively on the seventh and eighth ranks, mirroring the white pawns and pieces, just as in the standard game. (That is, their positions are not independently randomized.)
With those constraints there are 960 possible starting positions, thus the name of the variant.
Task
The purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed with Chess symbols in Unicode: ♔♕♖♗♘ or with the letters King Queen Rook Bishop kNight.
|
#R
|
R
|
pieces <- c("R","B","N","Q","K","N","B","R")
generateFirstRank <- function() {
attempt <- paste0(sample(pieces), collapse = "")
while (!check_position(attempt)) {
attempt <- paste0(sample(pieces), collapse = "")
}
return(attempt)
}
check_position <- function(position) {
if (regexpr('.*R.*K.*R.*', position) == -1) return(FALSE)
if (regexpr('.*B(..|....|......|)B.*', position) == -1) return(FALSE)
TRUE
}
convert_to_unicode <- function(s) {
s <- sub("K","\u2654", s)
s <- sub("Q","\u2655", s)
s <- gsub("R","\u2656", s)
s <- gsub("B","\u2657", s)
s <- gsub("N","\u2658", s)
}
cat(convert_to_unicode(generateFirstRank()), "\n")
|
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.
|
#AntLang
|
AntLang
|
/Apply g to exactly one argument
compose1: {f: x; g: y; {f[g[x]]}}
/Extra: apply to multiple arguments
compose: {f: x; g: y; {f[g apply args]}}
|
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.
|
#AppleScript
|
AppleScript
|
-- Compose two functions where each function is
-- a script object with a call(x) handler.
on compose(f, g)
script
on call(x)
f's call(g's call(x))
end call
end script
end compose
script sqrt
on call(x)
x ^ 0.5
end call
end script
script twice
on call(x)
2 * x
end call
end script
compose(sqrt, twice)'s call(32)
-- Result: 8.0
|
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.
|
#11l
|
11l
|
F fractran(prog, =val, limit)
V fracts = prog.split(‘ ’).map(p -> p.split(‘/’).map(i -> Int(i)))
[Float] r
L(n) 0 .< limit
r [+]= val
L(p) fracts
I val % p[1] == 0
val = p[0] * val / p[1]
L.break
R r
print(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, 15))
|
http://rosettacode.org/wiki/FTP
|
FTP
|
Task
Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
|
#Go
|
Go
|
package main
import (
"fmt"
"io"
"log"
"os"
"github.com/stacktic/ftp"
)
func main() {
// Hard-coded demonstration values
const (
hostport = "localhost:21"
username = "anonymous"
password = "anonymous"
dir = "pub"
file = "somefile.bin"
)
conn, err := ftp.Connect(hostport)
if err != nil {
log.Fatal(err)
}
defer conn.Quit()
fmt.Println(conn)
if err = conn.Login(username, password); err != nil {
log.Fatal(err)
}
if err = conn.ChangeDir(dir); err != nil {
log.Fatal(err)
}
fmt.Println(conn.CurrentDir())
files, err := conn.List(".")
if err != nil {
log.Fatal(err)
}
for _, f := range files {
fmt.Printf("%v %12d %v %v\n", f.Time, f.Size, f.Type, f.Name)
}
r, err := conn.Retr(file)
if err != nil {
log.Fatal(err)
}
defer r.Close()
f, err := os.Create(file)
if err != nil {
log.Fatal(err)
}
defer f.Close()
n, err := io.Copy(f, r)
if err != nil {
log.Fatal(err)
}
fmt.Println("Wrote", n, "bytes to", file)
}
|
http://rosettacode.org/wiki/FTP
|
FTP
|
Task
Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
|
#Groovy
|
Groovy
|
@Grab(group='commons-net', module='commons-net', version='2.0')
import org.apache.commons.net.ftp.FTPClient
println("About to connect....");
new FTPClient().with {
connect "ftp.easynet.fr"
enterLocalPassiveMode()
login "anonymous", "[email protected]"
changeWorkingDirectory "/debian/"
def incomingFile = new File("README.html")
incomingFile.withOutputStream { ostream -> retrieveFile "README.html", ostream }
disconnect()
}
println(" ...Done.");
|
http://rosettacode.org/wiki/Function_prototype
|
Function prototype
|
Some languages provide the facility to declare functions and subroutines through the use of function prototyping.
Task
Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include:
An explanation of any placement restrictions for prototype declarations
A prototype declaration for a function that does not require arguments
A prototype declaration for a function that requires two arguments
A prototype declaration for a function that utilizes varargs
A prototype declaration for a function that utilizes optional arguments
A prototype declaration for a function that utilizes named parameters
Example of prototype declarations for subroutines or procedures (if these differ from functions)
An explanation and example of any special forms of prototyping not covered by the above
Languages that do not provide function prototyping facilities should be omitted from this task.
|
#Lua
|
Lua
|
function Func() -- Does not require arguments
return 1
end
function Func(a,b) -- Requires arguments
return a + b
end
function Func(a,b) -- Arguments are optional
return a or 4 + b or 2
end
function Func(a,...) -- One argument followed by varargs
return a,{...} -- Returns both arguments, varargs as table
end
|
http://rosettacode.org/wiki/Function_prototype
|
Function prototype
|
Some languages provide the facility to declare functions and subroutines through the use of function prototyping.
Task
Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include:
An explanation of any placement restrictions for prototype declarations
A prototype declaration for a function that does not require arguments
A prototype declaration for a function that requires two arguments
A prototype declaration for a function that utilizes varargs
A prototype declaration for a function that utilizes optional arguments
A prototype declaration for a function that utilizes named parameters
Example of prototype declarations for subroutines or procedures (if these differ from functions)
An explanation and example of any special forms of prototyping not covered by the above
Languages that do not provide function prototyping facilities should be omitted from this task.
|
#Luck
|
Luck
|
function noargs(): int = ? ;;
function twoargs(x:int, y:int): int = ? ;;
/* underscore means ignore and is not bound to lexical scope */
function twoargs(_:bool, _:bool): int = ? ;;
function anyargs(xs: ...): int = ? ;;
function plusargs(x:int, xs: ...): int = ? ;;
|
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
|
#68000_Assembly
|
68000 Assembly
|
MOVE.L D0,#$0200
MOVE.L D1,#$0400
JSR doMultiply
;rest of program
JMP $ ;halt
;;;;; somewhere far away from the code above
doMultiply:
MULU D0,D1
RTS
|
http://rosettacode.org/wiki/French_Republican_calendar
|
French Republican calendar
|
Write a program to convert dates between the Gregorian calendar and the French Republican calendar.
The year 1 of the Republican calendar began on 22 September 1792. There were twelve months (Vendémiaire, Brumaire, Frimaire, Nivôse, Pluviôse, Ventôse, Germinal, Floréal, Prairial, Messidor, Thermidor, and Fructidor) of 30 days each, followed by five intercalary days or Sansculottides (Fête de la vertu / Virtue Day, Fête du génie / Talent Day, Fête du travail / Labour Day, Fête de l'opinion / Opinion Day, and Fête des récompenses / Honours Day). In leap years (the years 3, 7, and 11) a sixth Sansculottide was added: Fête de la Révolution / Revolution Day.
As a minimum, your program should give correct results for dates in the range from 1 Vendémiaire 1 = 22 September 1792 to 10 Nivôse 14 = 31 December 1805 (the last day when the Republican calendar was officially in use). If you choose to accept later dates, be aware that there are several different methods (described on the Wikipedia page) about how to determine leap years after the year 14. You should indicate which method you are using. (Because of these different methods, correct programs may sometimes give different results for dates after 1805.)
Test your program by converting the following dates both from Gregorian to Republican and from Republican to Gregorian:
• 1 Vendémiaire 1 = 22 September 1792
• 1 Prairial 3 = 20 May 1795
• 27 Messidor 7 = 15 July 1799 (Rosetta Stone discovered)
• Fête de la Révolution 11 = 23 September 1803
• 10 Nivôse 14 = 31 December 1805
|
#Go
|
Go
|
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
var (
gregorianStr = []string{"January", "February", "March",
"April", "May", "June",
"July", "August", "September",
"October", "November", "December"}
gregorian = []int{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
republicanStr = []string{"Vendemiaire", "Brumaire", "Frimaire",
"Nivose", "Pluviose", "Ventose",
"Germinal", "Floreal", "Prairial",
"Messidor", "Thermidor", "Fructidor"}
sansculottidesStr = []string{"Fete de la vertu", "Fete du genie",
"Fete du travail", "Fete de l'opinion",
"Fete des recompenses", "Fete de la Revolution"}
)
func main() {
fmt.Println("*** French Republican ***")
fmt.Println("*** calendar converter ***")
fmt.Println("Enter a date to convert, in the format 'day month year'")
fmt.Println("e.g.: 1 Prairial 3,")
fmt.Println(" 20 May 1795.")
fmt.Println("For Sansculottides, use 'day year'")
fmt.Println("e.g.: Fete de l'opinion 9.")
fmt.Println("Or just press 'RETURN' to exit the program.")
fmt.Println()
for sc := bufio.NewScanner(os.Stdin); ; {
fmt.Print("> ")
sc.Scan()
src := sc.Text()
if src == "" {
return
}
day, month, year := split(src)
if year < 1792 {
day, month, year = dayToGre(repToDay(day, month, year))
fmt.Println(day, gregorianStr[month-1], year)
} else {
day, month, year := dayToRep(greToDay(day, month, year))
if month == 13 {
fmt.Println(sansculottidesStr[day-1], year)
} else {
fmt.Println(day, republicanStr[month-1], year)
}
}
}
}
func split(s string) (d, m, y int) {
if strings.HasPrefix(s, "Fete") {
m = 13
for i, sc := range sansculottidesStr {
if strings.HasPrefix(s, sc) {
d = i + 1
y, _ = strconv.Atoi(s[len(sc)+1:])
}
}
} else {
d, _ = strconv.Atoi(s[:strings.Index(s, " ")])
my := s[strings.Index(s, " ")+1:]
mStr := my[:strings.Index(my, " ")]
y, _ = strconv.Atoi(my[strings.Index(my, " ")+1:])
months := gregorianStr
if y < 1792 {
months = republicanStr
}
for i, mn := range months {
if mn == mStr {
m = i + 1
}
}
}
return
}
func greToDay(d, m, y int) int {
if m < 3 {
y--
m += 12
}
return y*36525/100 - y/100 + y/400 + 306*(m+1)/10 + d - 654842
}
func repToDay(d, m, y int) int {
if m == 13 {
m--
d += 30
}
if repLeap(y) {
d--
}
return 365*y + (y+1)/4 - (y+1)/100 + (y+1)/400 + 30*m + d - 395
}
func dayToGre(day int) (d, m, y int) {
y = day * 100 / 36525
d = day - y*36525/100 + 21
y += 1792
d += y/100 - y/400 - 13
m = 8
for d > gregorian[m] {
d -= gregorian[m]
m++
if m == 12 {
m = 0
y++
if greLeap(y) {
gregorian[1] = 29
} else {
gregorian[1] = 28
}
}
}
m++
return
}
func dayToRep(day int) (d, m, y int) {
y = (day-1) * 100 / 36525
if repLeap(y) {
y--
}
d = day - (y+1)*36525/100 + 365 + (y+1)/100 - (y+1)/400
y++
m = 1
sansculottides := 5
if repLeap(y) {
sansculottides = 6
}
for d > 30 {
d -= 30
m += 1
if m == 13 {
if d > sansculottides {
d -= sansculottides
m = 1
y++
sansculottides = 5
if repLeap(y) {
sansculottides = 6
}
}
}
}
return
}
func repLeap(year int) bool {
return (year+1)%4 == 0 && ((year+1)%100 != 0 || (year+1)%400 == 0)
}
func greLeap(year int) bool {
return year%4 == 0 && (year%100 != 0 || year%400 == 0)
}
|
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.
|
#BASIC256
|
BASIC256
|
global f, max
max = 36000
dim f(max)
call fusc()
for i = 0 to 60
print f[i]; " ";
next i
print : print
print " Index Value"
d = 0
for i = 0 to max-1
if f[i] >= d then
print rjust(string(i),10," "), rjust(string(f[i]),10," ")
if d = 0 then d = 1
d *= 10
end if
next i
end
subroutine fusc()
f[0] = 0 : f[1] = 1
for n = 2 to max-1
if (n mod 2) then
f[n] = f[(n-1)/2] + f[(n+1)/2]
else
f[n] = f[n/2]
end if
next n
end subroutine
|
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.
|
#BQN
|
BQN
|
Fusc ← {
{
𝕩∾+´(⍷(⌈∾⌊)2÷˜≠𝕩)⊑¨<𝕩
}⍟(𝕩-2)↕2
}
•Show Fusc 61
•Show >⟨"Index"‿"Number"⟩∾{((1+↕4)⊐˜(⌊1+10⋆⁼1⌈|)¨𝕩){𝕨∾𝕨⊑𝕩}¨<𝕩} Fusc 99999
|
http://rosettacode.org/wiki/Functional_coverage_tree
|
Functional coverage tree
|
Functional coverage is a measure of how much a particular function of a system
has been verified as correct. It is used heavily in tracking the completeness
of the verification of complex System on Chip (SoC) integrated circuits, where
it can also be used to track how well the functional requirements of the
system have been verified.
This task uses a sub-set of the calculations sometimes used in tracking
functional coverage but uses a more familiar(?) scenario.
Task Description
The head of the clean-up crews for "The Men in a very dark shade of grey when
viewed at night" has been tasked with managing the cleansing of two properties
after an incident involving aliens.
She arranges the task hierarchically with a manager for the crews working on
each house who return with a breakdown of how they will report on progress in
each house.
The overall hierarchy of (sub)tasks is as follows,
cleaning
house1
bedrooms
bathrooms
bathroom1
bathroom2
outside lavatory
attic
kitchen
living rooms
lounge
dining room
conservatory
playroom
basement
garage
garden
house2
upstairs
bedrooms
suite 1
suite 2
bedroom 3
bedroom 4
bathroom
toilet
attics
groundfloor
kitchen
living rooms
lounge
dining room
conservatory
playroom
wet room & toilet
garage
garden
hot tub suite
basement
cellars
wine cellar
cinema
The head of cleanup knows that her managers will report fractional completion of leaf tasks (tasks with no child tasks of their own), and she knows that she will want to modify the weight of values of completion as she sees fit.
Some time into the cleaning, and some coverage reports have come in and she thinks see needs to weight the big house2 60-40 with respect to coverage from house1 She prefers a tabular view of her data where missing weights are assumed to be 1.0 and missing coverage 0.0.
NAME_HIERARCHY |WEIGHT |COVERAGE |
cleaning | | |
house1 |40 | |
bedrooms | |0.25 |
bathrooms | | |
bathroom1 | |0.5 |
bathroom2 | | |
outside_lavatory | |1 |
attic | |0.75 |
kitchen | |0.1 |
living_rooms | | |
lounge | | |
dining_room | | |
conservatory | | |
playroom | |1 |
basement | | |
garage | | |
garden | |0.8 |
house2 |60 | |
upstairs | | |
bedrooms | | |
suite_1 | | |
suite_2 | | |
bedroom_3 | | |
bedroom_4 | | |
bathroom | | |
toilet | | |
attics | |0.6 |
groundfloor | | |
kitchen | | |
living_rooms | | |
lounge | | |
dining_room | | |
conservatory | | |
playroom | | |
wet_room_&_toilet | | |
garage | | |
garden | |0.9 |
hot_tub_suite | |1 |
basement | | |
cellars | |1 |
wine_cellar | |1 |
cinema | |0.75 |
Calculation
The coverage of a node in the tree is calculated as the weighted average of the coverage of its children evaluated bottom-upwards in the tree.
The task is to calculate the overall coverage of the cleaning task and display the coverage at all levels of the hierarchy on this page, in a manner that visually shows the hierarchy, weights and coverage of all nodes.
Extra Credit
After calculating the coverage for all nodes, one can also calculate the additional/delta top level coverage that would occur if any (sub)task were to be fully covered from its current fractional coverage. This is done by multiplying the extra coverage that could be gained
1
−
c
o
v
e
r
a
g
e
{\displaystyle 1-coverage}
for any node, by the product of the `powers` of its parent nodes from the top down to the node.
The power of a direct child of any parent is given by the power of the parent multiplied by the weight of the child divided by the sum of the weights of all the direct children.
The pseudo code would be:
method delta_calculation(this, power):
sum_of_weights = sum(node.weight for node in children)
this.delta = (1 - this.coverage) * power
for node in self.children:
node.delta_calculation(power * node.weight / sum_of_weights)
return this.delta
Followed by a call to:
top.delta_calculation(power=1)
Note: to aid in getting the data into your program you might want to use an alternative, more functional description of the starting data given on the discussion page.
|
#Racket
|
Racket
|
#lang racket/base
(require racket/list racket/string racket/match racket/format racket/file)
(struct Coverage (name weight coverage weighted-coverage children) #:transparent #:mutable)
;; -| read/parse |------------------------------------------------------------------------------------
(define (build-hierarchies parsed-lines)
(define inr
(match-lambda
['() (values null null)]
[`((,head-indent . ,C) ,tail-lines ...)
(define child? (match-lambda [(cons i _) #:when (> i head-indent) #t] [_ #f]))
(define-values (chlds rels) (splitf-at tail-lines child?))
(define-values (rels-tree rels-rem) (inr rels))
(values (cons (struct-copy Coverage C (children (build-hierarchies chlds))) rels-tree)
rels-rem)]))
(define-values (hierarchies remaining-lines) (inr parsed-lines))
hierarchies)
(define report-line->indent.c/e-line
(match-lambda
[(regexp #px"^( *)([^ ]*) *\\| *([^ ]*) *\\| *([^ ]*) *\\|$"
(list _
(app string-length indent-length)
name
(or (and (not "") (app string->number wght)) (app (λ (x) 1) wght))
(or (and (not "") (app string->number cvrg)) (app (λ (x) 0) cvrg))))
(cons indent-length (Coverage name wght cvrg 0 #f))]))
(define (report->indent.c/e-list rprt)
(map report-line->indent.c/e-line (drop (string-split rprt "\n") 1)))
;; -| evaluate |--------------------------------------------------------------------------------------
(define find-wght-cvrg
(match-lambda
[(and e (Coverage _ w c _ '())) (struct-copy Coverage e (weighted-coverage (* w c)))]
[(and e (Coverage _ _ _ _ `(,(app find-wght-cvrg (and cdn+ (Coverage _ c-ws _ c-w/cs _))) ...)))
(define chld-wghtd-avg (for/sum ((w (in-list c-ws)) (w/c (in-list c-w/cs))) (* w w/c)))
(struct-copy Coverage e (weighted-coverage (/ chld-wghtd-avg (apply + c-ws))) (children cdn+))]))
;; -| printing |--------------------------------------------------------------------------------------
(define max-description-length
(match-lambda
[(Coverage (app string-length name-length) _ _ _
(list (app max-description-length children-lengths) ...))
(apply max name-length (map add1 children-lengths))]))
(define (~a/right w x)
(~a x #:width w #:align 'right))
(define (~a/decimal n dec-dgts)
(~a/right (+ dec-dgts 3) (if (zero? n) "" (real->decimal-string n dec-dgts))))
(define (print-coverage-tree tree)
(define mdl (max-description-length tree))
(printf "| ~a |WEIGT| COVER |WGHTD CVRG|~%" (~a "NAME" #:width mdl #:align 'center))
(let inr ((depth 0) (tree tree))
(unless (null? tree)
(match tree
[(Coverage name w c w/c chlds)
(printf "| ~a | ~a | ~a | ~a |~%"
(~a (string-append (make-string depth #\space) name) #:width mdl)
(~a/right 3 w) (~a/decimal c 2) (~a/decimal w/c 5))
(for ((c chlds)) (inr (add1 depth) c))]))))
;; ---------------------------------------------------------------------------------------------------
(module+ main
;; data/functional-coverage.txt contains a verbatim copy of
;; the table in the task's description
(for-each
(compose print-coverage-tree find-wght-cvrg)
(build-hierarchies (report->indent.c/e-list (file->string "data/functional-coverage.txt")))))
|
http://rosettacode.org/wiki/Functional_coverage_tree
|
Functional coverage tree
|
Functional coverage is a measure of how much a particular function of a system
has been verified as correct. It is used heavily in tracking the completeness
of the verification of complex System on Chip (SoC) integrated circuits, where
it can also be used to track how well the functional requirements of the
system have been verified.
This task uses a sub-set of the calculations sometimes used in tracking
functional coverage but uses a more familiar(?) scenario.
Task Description
The head of the clean-up crews for "The Men in a very dark shade of grey when
viewed at night" has been tasked with managing the cleansing of two properties
after an incident involving aliens.
She arranges the task hierarchically with a manager for the crews working on
each house who return with a breakdown of how they will report on progress in
each house.
The overall hierarchy of (sub)tasks is as follows,
cleaning
house1
bedrooms
bathrooms
bathroom1
bathroom2
outside lavatory
attic
kitchen
living rooms
lounge
dining room
conservatory
playroom
basement
garage
garden
house2
upstairs
bedrooms
suite 1
suite 2
bedroom 3
bedroom 4
bathroom
toilet
attics
groundfloor
kitchen
living rooms
lounge
dining room
conservatory
playroom
wet room & toilet
garage
garden
hot tub suite
basement
cellars
wine cellar
cinema
The head of cleanup knows that her managers will report fractional completion of leaf tasks (tasks with no child tasks of their own), and she knows that she will want to modify the weight of values of completion as she sees fit.
Some time into the cleaning, and some coverage reports have come in and she thinks see needs to weight the big house2 60-40 with respect to coverage from house1 She prefers a tabular view of her data where missing weights are assumed to be 1.0 and missing coverage 0.0.
NAME_HIERARCHY |WEIGHT |COVERAGE |
cleaning | | |
house1 |40 | |
bedrooms | |0.25 |
bathrooms | | |
bathroom1 | |0.5 |
bathroom2 | | |
outside_lavatory | |1 |
attic | |0.75 |
kitchen | |0.1 |
living_rooms | | |
lounge | | |
dining_room | | |
conservatory | | |
playroom | |1 |
basement | | |
garage | | |
garden | |0.8 |
house2 |60 | |
upstairs | | |
bedrooms | | |
suite_1 | | |
suite_2 | | |
bedroom_3 | | |
bedroom_4 | | |
bathroom | | |
toilet | | |
attics | |0.6 |
groundfloor | | |
kitchen | | |
living_rooms | | |
lounge | | |
dining_room | | |
conservatory | | |
playroom | | |
wet_room_&_toilet | | |
garage | | |
garden | |0.9 |
hot_tub_suite | |1 |
basement | | |
cellars | |1 |
wine_cellar | |1 |
cinema | |0.75 |
Calculation
The coverage of a node in the tree is calculated as the weighted average of the coverage of its children evaluated bottom-upwards in the tree.
The task is to calculate the overall coverage of the cleaning task and display the coverage at all levels of the hierarchy on this page, in a manner that visually shows the hierarchy, weights and coverage of all nodes.
Extra Credit
After calculating the coverage for all nodes, one can also calculate the additional/delta top level coverage that would occur if any (sub)task were to be fully covered from its current fractional coverage. This is done by multiplying the extra coverage that could be gained
1
−
c
o
v
e
r
a
g
e
{\displaystyle 1-coverage}
for any node, by the product of the `powers` of its parent nodes from the top down to the node.
The power of a direct child of any parent is given by the power of the parent multiplied by the weight of the child divided by the sum of the weights of all the direct children.
The pseudo code would be:
method delta_calculation(this, power):
sum_of_weights = sum(node.weight for node in children)
this.delta = (1 - this.coverage) * power
for node in self.children:
node.delta_calculation(power * node.weight / sum_of_weights)
return this.delta
Followed by a call to:
top.delta_calculation(power=1)
Note: to aid in getting the data into your program you might want to use an alternative, more functional description of the starting data given on the discussion page.
|
#Raku
|
Raku
|
sub walktree ($data) {
my (@parts, $cnt);
while ($data ~~ m:nth(++$cnt)/$<head>=[(\s*) \N+\n ] # split off one level as 'head' (or terminal 'leaf')
$<body>=[[$0 \s+ \N+\n]*]/ ) { # next sub-level is 'body' (defined by extra depth of indentation)
my ($head, $body) = ($<head>, $<body>);
$head ~~ /'|' $<weight>=[\S*] \s* '|' $<coverage>=[\S*]/; # save values of weight and coverage (if any) for later
my ($w, $wsum) = (0, 0);
$head ~= .[0],
$w += .[1],
$wsum += .[1] * .[2]
for walktree $body;
my $weight = (~$<weight> or 1).fmt('%-8s');
my $coverage = $w == 0
?? (~$<coverage> or 0).fmt('%-10s')
!! ($wsum/$w) .fmt('%-10.2g');
@parts.push: [$head.subst(/'|' \N+/, "|$weight|$coverage|"), $weight, $coverage ];
}
return @parts;
}
(say .[0] for walktree $_) given
q:to/END/
NAME_HIERARCHY |WEIGHT |COVERAGE |
cleaning | | |
house1 |40 | |
bedrooms | |0.25 |
bathrooms | | |
bathroom1 | |0.5 |
bathroom2 | | |
outside_lavatory | |1 |
attic | |0.75 |
kitchen | |0.1 |
living_rooms | | |
lounge | | |
dining_room | | |
conservatory | | |
playroom | |1 |
basement | | |
garage | | |
garden | |0.8 |
house2 |60 | |
upstairs | | |
bedrooms | | |
suite_1 | | |
suite_2 | | |
bedroom_3 | | |
bedroom_4 | | |
bathroom | | |
toilet | | |
attics | |0.6 |
groundfloor | | |
kitchen | | |
living_rooms | | |
lounge | | |
dining_room | | |
conservatory | | |
playroom | | |
wet_room_&_toilet | | |
garage | | |
garden | |0.9 |
hot_tub_suite | |1 |
basement | | |
cellars | |1 |
wine_cellar | |1 |
cinema | |0.75 |
END
|
http://rosettacode.org/wiki/Function_frequency
|
Function frequency
|
Display - for a program or runtime environment (whatever suits the style of your language) - the top ten most frequently occurring functions (or also identifiers or tokens, if preferred).
This is a static analysis: The question is not how often each function is
actually executed at runtime, but how often it is used by the programmer.
Besides its practical usefulness, the intent of this task is to show how to do self-inspection within the language.
|
#Haskell
|
Haskell
|
import Language.Haskell.Parser (parseModule)
import Data.List.Split (splitOn)
import Data.List (nub, sortOn, elemIndices)
findApps src = freq $ concat [apps, comps]
where
ast = show $ parseModule src
apps = extract <$> splitApp ast
comps = extract <$> concat (splitComp <$> splitInfix ast)
splitApp = tail . splitOn "(HsApp (HsVar (UnQual (HsIdent \""
splitInfix = tail . splitOn "(HsInfixApp (HsVar (UnQual (HsIdent \""
splitComp = take 1 . splitOn "(HsQVarOp (UnQual (HsSymbol \""
extract = takeWhile (/= '\"')
freq lst = [ (count x lst, x) | x <- nub lst ]
count x = length . elemIndices x
main = do
src <- readFile "CountFunctions.hs"
let res = sortOn (negate . fst) $ findApps src
mapM_ (\(n, f) -> putStrLn $ show n ++ "\t" ++ f) res
|
http://rosettacode.org/wiki/Function_frequency
|
Function frequency
|
Display - for a program or runtime environment (whatever suits the style of your language) - the top ten most frequently occurring functions (or also identifiers or tokens, if preferred).
This is a static analysis: The question is not how often each function is
actually executed at runtime, but how often it is used by the programmer.
Besides its practical usefulness, the intent of this task is to show how to do self-inspection within the language.
|
#J
|
J
|
IGNORE=: ;:'y(0)1',CR
Filter=: (#~`)(`:6)
NB. extract tokens from a large body newline terminated of text
roughparse=: ;@(<@;: ::(''"_);._2)
NB. count frequencies and get the top x
top=: top=: {. \:~@:((#;{.)/.~)
NB. read all installed script (.ijs) files and concatenate them
JSOURCE=: ;fread each 1&e.@('.ijs'&E.)@>Filter {."1 dirtree jpath '~install'
10 top (roughparse JSOURCE)-.IGNORE
┌─────┬──┐
│49591│, │
├─────┼──┤
│40473│=:│
├─────┼──┤
│35593│; │
├─────┼──┤
│34096│=.│
├─────┼──┤
│24757│+ │
├─────┼──┤
│18726│" │
├─────┼──┤
│18564│< │
├─────┼──┤
│18446│/ │
├─────┼──┤
│16984│> │
├─────┼──┤
│14655│@ │
└─────┴──┘
|
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
|
#C
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_sf_gamma.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
/* very simple approximation */
double st_gamma(double x)
{
return sqrt(2.0*M_PI/x)*pow(x/M_E, x);
}
#define A 12
double sp_gamma(double z)
{
const int a = A;
static double c_space[A];
static double *c = NULL;
int k;
double accm;
if ( c == NULL ) {
double k1_factrl = 1.0; /* (k - 1)!*(-1)^k with 0!==1*/
c = c_space;
c[0] = sqrt(2.0*M_PI);
for(k=1; k < a; k++) {
c[k] = exp(a-k) * pow(a-k, k-0.5) / k1_factrl;
k1_factrl *= -k;
}
}
accm = c[0];
for(k=1; k < a; k++) {
accm += c[k] / ( z + k );
}
accm *= exp(-(z+a)) * pow(z+a, z+0.5); /* Gamma(z+1) */
return accm/z;
}
int main()
{
double x;
printf("%15s%15s%15s%15s\n", "Stirling", "Spouge", "GSL", "libm");
for(x=1.0; x <= 10.0; x+=1.0) {
printf("%15.8lf%15.8lf%15.8lf%15.8lf\n", st_gamma(x/3.0), sp_gamma(x/3.0),
gsl_sf_gamma(x/3.0), tgamma(x/3.0));
}
return 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.
|
#Icon_and_Unicon
|
Icon and Unicon
|
link graphics
global pegsize, pegsize2, height, width, delay
procedure main(args) # galton box simulation from Unicon book
pegsize2 := (pegsize := 10) * 2 # pegs & steps
delay := 2 # ms delay
setup_galtonwindow(pegsize)
n := integer(args[1]) | 100 # balls to drop
every 1 to n do galton(pegsize)
WDone()
end
procedure setup_galtonwindow(n) # Draw n levels of pegs,
local xpos, ypos, i, j
# Pegboard size is 2n-1 square
# Expected max value of histogram is (n, n/2)/2^n
# ... approximate with something simpler?
height := n*n/2*pegsize + (width := (2*n+1)*pegsize)
Window("size=" || width || "," || height, "fg=grayish-white")
WAttrib("fg=dark-grey")
every ypos := (i := 1 to n) * pegsize2 do {
xpos := width/2 - (i - 1) * pegsize - pegsize/2 - pegsize2
every 1 to i do
FillArc(xpos +:= pegsize2, ypos, pegsize, pegsize)
}
WAttrib("fg=black","drawop=reverse") # set drawing mode for balls
end
procedure galton(n) # drop a ball into the galton box
local xpos, ypos, oldx, oldy
xpos := oldx := width/2 - pegsize/2
ypos := oldy := pegsize
every 1 to n do { # For every ball...
xpos +:= ((?2 = 1) | -1) * pegsize # +/- pegsize
animate(.oldx, .oldy, oldx := xpos, oldy := ypos +:= pegsize2)
}
animate(xpos, ypos, xpos, ypos + 40) # Now the ball falls ...
animate(xpos, ypos+40, xpos, ypos + 200) # ... to the floor
draw_ball(xpos) # Record this ball
end
procedure animate(xfrom, yfrom, xto, yto)
animate_actual(xfrom, yfrom, xto, yfrom, 4)
animate_actual(xto, yfrom, xto, yto, 10)
end
procedure animate_actual(xfrom, yfrom, xto, yto, steps) # attribs already set
local x, y, xstep, ystep, lastx, lasty
x -:= xstep := (xto - (x := xfrom))/steps
y -:= ystep := (yto - (y := yfrom))/steps
every 1 to steps do {
FillArc(lastx := x +:= xstep, lasty := y +:= ystep, pegsize, pegsize)
WDelay(delay) # wait in ms
FillArc(x, y, pegsize, pegsize)
}
end
procedure draw_ball(x)
static ballcounts
initial ballcounts := table(0)
FillArc(x, height-(ballcounts[x] +:= 1)*pegsize, pegsize, pegsize)
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
|
#Go
|
Go
|
package main
import "fmt"
func commatize(n uint64) string {
s := fmt.Sprintf("%d", n)
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
return s
}
func main() {
starts := []uint64{1e2, 1e6, 1e7, 1e9, 7123}
counts := []int{30, 15, 15, 10, 25}
for i := 0; i < len(starts); i++ {
count := 0
j := starts[i]
pow := uint64(100)
for {
if j < pow*10 {
break
}
pow *= 10
}
fmt.Printf("First %d gapful numbers starting at %s:\n", counts[i], commatize(starts[i]))
for count < counts[i] {
fl := (j/pow)*10 + (j % 10)
if j%fl == 0 {
fmt.Printf("%d ", j)
count++
}
j++
if j >= 10*pow {
pow *= 10
}
}
fmt.Println("\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
|
#Haskell
|
Haskell
|
isMatrix xs = null xs || all ((== (length.head $ xs)).length) xs
isSquareMatrix xs = null xs || all ((== (length xs)).length) xs
mult:: Num a => [[a]] -> [[a]] -> [[a]]
mult uss vss = map ((\xs -> if null xs then [] else foldl1 (zipWith (+)) xs). zipWith (\vs u -> map (u*) vs) vss) uss
gauss::[[Double]] -> [[Double]] -> [[Double]]
gauss xs bs = map (map fromRational) $ solveGauss (toR xs) (toR bs)
where toR = map $ map toRational
solveGauss:: (Fractional a, Ord a) => [[a]] -> [[a]] -> [[a]]
solveGauss xs bs | null xs || null bs || length xs /= length bs || (not $ isSquareMatrix xs) || (not $ isMatrix bs) = []
| otherwise = uncurry solveTriangle $ triangle xs bs
solveTriangle::(Fractional a,Eq a) => [[a]] -> [[a]] -> [[a]]
solveTriangle us _ | not.null.dropWhile ((/= 0).head) $ us = []
solveTriangle ([c]:as) (b:bs) = go as bs [map (/c) b]
where
val us vs ws = let u = head us in map (/u) $ zipWith (-) vs (head $ mult [tail us] ws)
go [] _ zs = zs
go _ [] zs = zs
go (x:xs) (y:ys) zs = go xs ys $ (val x y zs):zs
triangle::(Num a, Ord a) => [[a]] -> [[a]] -> ([[a]],[[a]])
triangle xs bs = triang ([],[]) (xs,bs)
where
triang ts (_,[]) = ts
triang ts ([],_) = ts
triang (os,ps) zs = triang (us:os,cs:ps).unzip $ [(fun tus vs, fun cs es) | (v:vs,es) <- zip uss css,let fun = zipWith (\x y -> v*x - u*y)]
where ((us@(u:tus)):uss,cs:css) = bubble zs
bubble::(Num a, Ord a) => ([[a]],[[a]]) -> ([[a]],[[a]])
bubble (xs,bs) = (go xs, go bs)
where
idmax = snd.maximum.flip zip [0..].map (abs.head) $ xs
go ys = let (us,vs) = splitAt idmax ys in vs ++ us
main = do
let 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]]
let b = [[-0.01], [0.61], [0.91], [0.99], [0.60], [0.02]]
mapM_ print $ gauss a b
|
http://rosettacode.org/wiki/Gauss-Jordan_matrix_inversion
|
Gauss-Jordan matrix inversion
|
Task
Invert matrix A using Gauss-Jordan method.
A being an n × n matrix.
|
#MATLAB
|
MATLAB
|
function GaussInverse(M)
original = M;
[n,~] = size(M);
I = eye(n);
for j = 1:n
for i = j:n
if ~(M(i,j) == 0)
for k = 1:n
q = M(j,k); M(j,k) = M(i,k); M(i,k) = q;
q = I(j,k); I(j,k) = I(i,k); I(i,k) = q;
end
p = 1/M(j,j);
for k = 1:n
M(j,k) = p*M(j,k);
I(j,k) = p*I(j,k);
end
for L = 1:n
if ~(L == j)
p = -M(L,j);
for k = 1:n
M(L,k) = M(L,k) + p*M(j,k);
I(L,k) = I(L,k) + p*I(j,k);
end
end
end
end
end
inverted = I;
end
fprintf("Matrix:\n")
disp(original)
fprintf("Inverted matrix:\n")
disp(inverted)
fprintf("Inverted matrix calculated by built-in function:\n")
disp(inv(original))
fprintf("Product of matrix and inverse:\n")
disp(original*inverted)
end
A = [ 2, -1, 0;
-1, 2, -1;
0, -1, 2 ];
GaussInverse(A)
|
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
|
#LiveCode
|
LiveCode
|
function generalisedFizzBuzz m, f1, f2, f3
put f1 & cr & f2 & cr & f3 into factors
sort factors ascending numeric
repeat with i = 1 to m
put false into flag
if i mod (word 1 of line 1 of factors) = 0 then
put word 2 of line 1 of factors after fizzbuzz
put true into flag
end if
if i mod (word 1 of line 2 of factors) = 0 then
put word 2 of line 2 of factors after fizzbuzz
put true into flag
end if
if i mod (word 1 of line 3 of factors) = 0 then
put word 2 of line 3 of factors after fizzbuzz
put true into flag
end if
if flag is false then put i after fizzbuzz
put cr after fizzbuzz
end repeat
return fizzbuzz
end generalisedFizzBuzz
|
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
|
#Lua
|
Lua
|
function genFizz (param)
local response
print("\n")
for n = 1, param.limit do
response = ""
for i = 1, 3 do
if n % param.factor[i] == 0 then
response = response .. param.word[i]
end
end
if response == "" then print(n) else print(response) end
end
end
local param = {factor = {}, word = {}}
param.limit = io.read()
for i = 1, 3 do
param.factor[i], param.word[i] = io.read("*number", "*line")
end
genFizz(param)
|
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
|
#Elena
|
Elena
|
import extensions;
import system'collections;
singleton Alphabet : Enumerable
{
Enumerator enumerator() = new Enumerator
{
char current;
get() = current;
bool next()
{
if (nil==current)
{
current := $97
}
else if (current != $122)
{
current := (current.toInt() + 1).toChar()
}
else
{
^ false
};
^ true
}
reset()
{
current := nil
}
enumerable() = self;
};
}
public program()
{
console.printLine(Alphabet)
}
|
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
|
#Elixir
|
Elixir
|
iex(1)> Enum.to_list(?a .. ?z)
'abcdefghijklmnopqrstuvwxyz'
iex(2)> Enum.to_list(?a .. ?z) |> List.to_string
"abcdefghijklmnopqrstuvwxyz"
|
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
|
#ooRexx
|
ooRexx
|
/* Rexx */
say '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
|
#M2000_Interpreter
|
M2000 Interpreter
|
Module Generator {
PowGen = Lambda (e)-> {
=lambda i=0, e -> {
i++
=i**e
}
}
Squares=lambda PowGen=PowGen(2) ->{
=PowGen()
}
Cubes=Lambda PowGen=PowGen(3) -> {
=PowGen()
}
Filter=Lambda z=Squares(), Squares, m, Cubes->{
while m<Z {m=cubes()}
if z=m then z=Squares()
=z
z=Squares()
}
For i=1 to 20 : dropit=Filter() :Next i
Document doc$="Non-cubic squares (21st to 30th)"
Print doc$
\\ a new line to doc$
doc$={
}
For i=1 to 10 {
f=Filter()
Print Format$("I: {0::-2}, F: {1}",i+20, f)
doc$=Format$("I: {0::-2}, F: {1}",i+20, f)+{
}
}
Clipboard doc$
}
Generator
|
http://rosettacode.org/wiki/Generate_Chess960_starting_position
|
Generate Chess960 starting position
|
Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints:
as in the standard chess game, all eight white pawns must be placed on the second rank.
White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints:
the bishops must be placed on opposite color squares (i.e. they must be an odd number of spaces apart or there must be an even number of spaces between them)
the King must be between two rooks (with any number of other pieces between them all)
Black pawns and pieces must be placed respectively on the seventh and eighth ranks, mirroring the white pawns and pieces, just as in the standard game. (That is, their positions are not independently randomized.)
With those constraints there are 960 possible starting positions, thus the name of the variant.
Task
The purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed with Chess symbols in Unicode: ♔♕♖♗♘ or with the letters King Queen Rook Bishop kNight.
|
#Racket
|
Racket
|
#lang racket
(define white (match-lambda ['P #\♙] ['R #\♖] ['B #\♗] ['N #\♘] ['Q #\♕] ['K #\♔]))
(define black (match-lambda ['P #\♟] ['R #\♜] ['B #\♝] ['N #\♞] ['Q #\♛] ['K #\♚]))
(define (piece->unicode piece colour)
(match colour ('w white) ('b black)) piece)
(define (find/set!-random-slot vec val k (f values))
(define r (f (random k)))
(cond
[(vector-ref vec r)
(find/set!-random-slot vec val k f)]
[else
(vector-set! vec r val)
r]))
(define (chess960-start-position)
(define v (make-vector 8 #f))
;; Kings and Rooks
(let ((k (find/set!-random-slot v (white 'K) 6 add1)))
(find/set!-random-slot v (white 'R) k)
(find/set!-random-slot v (white 'R) (- 7 k) (curry + k 1)))
;; Bishops -- so far only three squares allocated, so there is at least one of each colour left
(find/set!-random-slot v (white 'B) 4 (curry * 2))
(find/set!-random-slot v (white 'B) 4 (compose add1 (curry * 2)))
;; Everyone else
(find/set!-random-slot v (white 'Q) 8)
(find/set!-random-slot v (white 'N) 8)
(find/set!-random-slot v (white 'N) 8)
(list->string (vector->list v)))
(chess960-start-position)
|
http://rosettacode.org/wiki/Generate_Chess960_starting_position
|
Generate Chess960 starting position
|
Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints:
as in the standard chess game, all eight white pawns must be placed on the second rank.
White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints:
the bishops must be placed on opposite color squares (i.e. they must be an odd number of spaces apart or there must be an even number of spaces between them)
the King must be between two rooks (with any number of other pieces between them all)
Black pawns and pieces must be placed respectively on the seventh and eighth ranks, mirroring the white pawns and pieces, just as in the standard game. (That is, their positions are not independently randomized.)
With those constraints there are 960 possible starting positions, thus the name of the variant.
Task
The purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed with Chess symbols in Unicode: ♔♕♖♗♘ or with the letters King Queen Rook Bishop kNight.
|
#Raku
|
Raku
|
repeat until m/ '♗' [..]* '♗' / { $_ = < ♖ ♖ ♖ ♕ ♗ ♗ ♘ ♘ >.pick(*).join }
s:2nd['♖'] = '♔';
say .comb;
|
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.
|
#Applesoft_BASIC
|
Applesoft BASIC
|
10 F$ = "SIN"
20 DEF FN A(P) = ATN(P/SQR(-P*P+1))
30 G$ = "FN A"
40 GOSUB 100"COMPOSE
50 SA$ = E$
60 X = .5 : E$ = SA$
70 GOSUB 200"EXEC
80 PRINT R
90 END
100 E$ = F$ + "(" + G$ + "(X))" : RETURN : REMCOMPOSE F$ G$
200 D$ = CHR$(4) : FI$ = "TEMPORARY.EX" : M$ = CHR$(13)
210 PRINT D$"OPEN"FI$M$D$"CLOSE"FI$M$D$"DELETE"FI$
220 PRINT D$"OPEN"FI$M$D$"WRITE"FI$
230 PRINT "CALL-998:CALL-958:R="E$":CONT"
240 PRINT D$"CLOSE"FI$M$D$"EXEC"FI$:CALL-998:END:RETURN
|
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.
|
#Argile
|
Argile
|
use std, math
let my_asin = new Function (.:<any,real x>:. -> real {asin x})
let my__sin = new Function (.:<any,real x>:. -> real { sin x})
let sinasin = my__sin o my_asin
print sin asin 0.5
print *my__sin 0.0
print *sinasin 0.5
~my_asin
~my__sin
~sinasin
=: <Function f> o <Function g> := -> Function {compose f g}
.:compose <Function f, Function g>:. -> Function
use array
let d = (new array of 2 Function)
(d[0]) = f ; (d[1]) = g
let c = new Function (.:<array of Function fg, real x>:. -> real {
*fg[0]( *fg[1](x) )
}) (d)
c.del = .:<any>:.{free any}
c
class Function
function(any)(real)->(real) func
any data
function(any) del
=: * <Function f> <real x> := -> real
Cgen "(*("(f.func)"))("(f.data)", "(x)")"
.: del Function <Function f> :.
unless f.del is nil
call f.del with f.data
free f
=: ~ <Function f> := {del Function f}
.: new Function <function(any)(real)-\>real func> (<any data>):. -> Function
let f = new Function
f.func = func
f.data = data
f
|
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.
|
#360_Assembly
|
360 Assembly
|
* FRACTRAN 17/02/2019
FRACTRAN CSECT
USING FRACTRAN,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
SAVE (14,12) save previous context
ST R13,4(R15) link backward
ST R15,8(R13) link forward
LR R13,R15 set addressability
LA R6,1 i=1
DO WHILE=(C,R6,LE,TERMS) do i=1 to terms
LA R7,1 j=1
DO WHILE=(C,R7,LE,=A(NF)) do j=1 to nfracs
LR R1,R7 j
SLA R1,3 ~
L R2,FRACS-4(R1) d(j)
L R4,NN nn
SRDA R4,32 ~
DR R4,R2 nn/d(j)
IF LTR,R4,Z,R4 THEN if mod(nn,d(j))=0 then
XDECO R6,XDEC edit i
MVC PG(3),XDEC+9 output i
L R1,NN nn
XDECO R1,PG+5 edit & output nn
XPRNT PG,L'PG print buffer
LR R1,R7 j
SLA R1,3 ~
L R3,FRACS-8(R1) n(j)
MR R4,R3 *n(j)
ST R5,NN nn=nn/d(j)*n(j)
B LEAVEJ leave j
ENDIF , end if
LA R7,1(R7) j++
ENDDO , end do j
LEAVEJ LA R6,1(R6) i++
ENDDO , end do i
L R13,4(0,R13) restore previous savearea pointer
RETURN (14,12),RC=0 restore registers from calling sav
NF EQU (TERMS-FRACS)/8 number of fracs
NN DC F'2' nn
FRACS DC F'17',F'91',F'78',F'85',F'19',F'51',F'23',F'38',F'29',F'33'
DC F'77',F'29',F'95',F'23',F'77',F'19',F'1',F'17',F'11',F'13'
DC F'13',F'11',F'15',F'14',F'15',F'2',F'55',F'1'
TERMS DC F'100' terms
PG DC CL80'*** :' buffer
XDEC DS CL12 temp
REGEQU
END FRACTRAN
|
http://rosettacode.org/wiki/FTP
|
FTP
|
Task
Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
|
#Haskell
|
Haskell
|
module Main (main) where
import Control.Exception (bracket)
import Control.Monad (void)
import Data.Foldable (for_)
import Network.FTP.Client
( cwd
, easyConnectFTP
, getbinary
, loginAnon
, nlst
, quit
, setPassive
)
main :: IO ()
main = bracket ((flip setPassive) True <$> easyConnectFTP "ftp.kernel.org") quit $ \h -> do
-- Log in anonymously
void $ loginAnon h
-- Change directory
void $ cwd h "/pub/linux/kernel/Historic"
-- List current directory
fileNames <- nlst h Nothing
for_ fileNames $ \fileName ->
putStrLn fileName
-- Download in binary mode
(fileData, _) <- getbinary h "linux-0.01.tar.gz.sign"
print fileData
|
http://rosettacode.org/wiki/FTP
|
FTP
|
Task
Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
|
#J
|
J
|
require 'web/gethttp'
gethttp 'ftp://anonymous:[email protected]/pub/issoutreach/Living%20in%20Space%20Stories%20(MP3%20Files)/'
-rw-rw-r-- 1 109 space-station 2327118 May 9 2005 09sept_spacepropulsion.mp3
-rw-rw-r-- 1 109 space-station 1260304 May 9 2005 Can People go to Mars.mp3
-rw-rw-r-- 1 109 space-station 1350270 May 9 2005 Distill some water.mp3
-rw-rw-r-- 1 109 space-station 1290888 May 9 2005 Good Vibrations.mp3
-rw-rw-r-- 1 109 space-station 1431834 May 9 2005 Gravity Hurts_So good.mp3
-rw-rw-r-- 1 109 space-station 1072644 May 9 2005 Gravity in the Brain.mp3
-rw-rw-r-- 1 109 space-station 1230594 May 9 2005 Power to the ISS.mp3
-rw-rw-r-- 1 109 space-station 1309062 May 9 2005 Space Bones.mp3
-rw-rw-r-- 1 109 space-station 2292715 May 9 2005 Space Power.mp3
-rw-rw-r-- 1 109 space-station 772075 May 9 2005 We have a solution.mp3
-rw-rw-r-- 1 109 space-station 1134654 May 9 2005 When Space Makes you Dizzy.mp3
#file=: gethttp rplc&(' ';'%20') 'ftp://anonymous:[email protected]/pub/issoutreach/Living in Space Stories (MP3 Files)/We have a solution.mp3'
772075
|
http://rosettacode.org/wiki/Function_prototype
|
Function prototype
|
Some languages provide the facility to declare functions and subroutines through the use of function prototyping.
Task
Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include:
An explanation of any placement restrictions for prototype declarations
A prototype declaration for a function that does not require arguments
A prototype declaration for a function that requires two arguments
A prototype declaration for a function that utilizes varargs
A prototype declaration for a function that utilizes optional arguments
A prototype declaration for a function that utilizes named parameters
Example of prototype declarations for subroutines or procedures (if these differ from functions)
An explanation and example of any special forms of prototyping not covered by the above
Languages that do not provide function prototyping facilities should be omitted from this task.
|
#M2000_Interpreter
|
M2000 Interpreter
|
Module Check {
Module MyBeta (a) {
Print "MyBeta", a/2
}
Module TestMe {
Module Beta (x) {
Print "TestMeBeta", x
}
Beta 100
}
TestMe ; Beta as MyBeta
}
Check
|
http://rosettacode.org/wiki/Function_prototype
|
Function prototype
|
Some languages provide the facility to declare functions and subroutines through the use of function prototyping.
Task
Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include:
An explanation of any placement restrictions for prototype declarations
A prototype declaration for a function that does not require arguments
A prototype declaration for a function that requires two arguments
A prototype declaration for a function that utilizes varargs
A prototype declaration for a function that utilizes optional arguments
A prototype declaration for a function that utilizes named parameters
Example of prototype declarations for subroutines or procedures (if these differ from functions)
An explanation and example of any special forms of prototyping not covered by the above
Languages that do not provide function prototyping facilities should be omitted from this task.
|
#Nim
|
Nim
|
# Procedure declarations. All are named
proc noargs(): int
proc twoargs(a, b: int): int
proc anyargs(x: varargs[int]): int
proc optargs(a, b: int = 10): int
# Usage
discard noargs()
discard twoargs(1,2)
discard anyargs(1,2,3,4,5,6,7,8)
discard optargs(5)
# Procedure definitions
proc noargs(): int = echo "noargs"
proc twoargs(a, b: int): int = echo "twoargs"
proc anyargs(x: varargs[int]): int = echo "anyargs"
proc optargs(a: int, b = 10): int = echo "optargs"
|
http://rosettacode.org/wiki/Function_prototype
|
Function prototype
|
Some languages provide the facility to declare functions and subroutines through the use of function prototyping.
Task
Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include:
An explanation of any placement restrictions for prototype declarations
A prototype declaration for a function that does not require arguments
A prototype declaration for a function that requires two arguments
A prototype declaration for a function that utilizes varargs
A prototype declaration for a function that utilizes optional arguments
A prototype declaration for a function that utilizes named parameters
Example of prototype declarations for subroutines or procedures (if these differ from functions)
An explanation and example of any special forms of prototyping not covered by the above
Languages that do not provide function prototyping facilities should be omitted from this task.
|
#OCaml
|
OCaml
|
(* Usually prototype declarations are put in an interface file,
a file with .mli filename extension *)
(* A prototype declaration for a function that does not require arguments *)
val no_arg : unit -> unit
(* A prototype declaration for a function that requires two arguments *)
val two_args : int -> int -> unit
(* A prototype declaration for a function that utilizes optional arguments *)
val opt_arg : ?param:int -> unit -> unit
(* in this case we add a unit parameter in order to omit the argument,
because ocaml supports partial application *)
(* A prototype declaration for a function that utilizes named parameters *)
val named_arg : param1:int -> param2:int -> unit
(* An explanation and example of any special forms of prototyping not covered by the above *)
(* A prototype declaration for a function that requires a function argument *)
val fun_arg : (int -> int) -> unit
(* A prototype declaration for a function with polymorphic argument *)
val poly_arg : 'a -> unit
|
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
|
#8051_Assembly
|
8051 Assembly
|
ORG RESET
mov a, #100
mov b, #10
call multiply
; at this point, the result of 100*10 = 1000 = 03e8h is stored in registers a and b
; a = e8
; b = 03
jmp $
multiply:
mul ab
ret
|
http://rosettacode.org/wiki/French_Republican_calendar
|
French Republican calendar
|
Write a program to convert dates between the Gregorian calendar and the French Republican calendar.
The year 1 of the Republican calendar began on 22 September 1792. There were twelve months (Vendémiaire, Brumaire, Frimaire, Nivôse, Pluviôse, Ventôse, Germinal, Floréal, Prairial, Messidor, Thermidor, and Fructidor) of 30 days each, followed by five intercalary days or Sansculottides (Fête de la vertu / Virtue Day, Fête du génie / Talent Day, Fête du travail / Labour Day, Fête de l'opinion / Opinion Day, and Fête des récompenses / Honours Day). In leap years (the years 3, 7, and 11) a sixth Sansculottide was added: Fête de la Révolution / Revolution Day.
As a minimum, your program should give correct results for dates in the range from 1 Vendémiaire 1 = 22 September 1792 to 10 Nivôse 14 = 31 December 1805 (the last day when the Republican calendar was officially in use). If you choose to accept later dates, be aware that there are several different methods (described on the Wikipedia page) about how to determine leap years after the year 14. You should indicate which method you are using. (Because of these different methods, correct programs may sometimes give different results for dates after 1805.)
Test your program by converting the following dates both from Gregorian to Republican and from Republican to Gregorian:
• 1 Vendémiaire 1 = 22 September 1792
• 1 Prairial 3 = 20 May 1795
• 27 Messidor 7 = 15 July 1799 (Rosetta Stone discovered)
• Fête de la Révolution 11 = 23 September 1803
• 10 Nivôse 14 = 31 December 1805
|
#Julia
|
Julia
|
using Dates
const GC_FORMAT = DateFormat("d U y")
const RC_FIRST_DAY = Date(1792, 9, 22)
const MAX_RC_DATE = Date(1805, 12, 31)
const RC_MONTHS = [
"Vendémiaire", "Brumaire", "Frimaire", "Nivôse", "Pluviôse", "Ventôse",
"Germinal", "Floréal", "Prairial", "Messidor", "Thermidor", "Fructidor"
]
const RC_DAYS_IN_MONTH = 30
const RC_SANSCULOTTIDES = [
"Fête de la vertu", "Fête du génie", "Fête du travail",
"Fête de l'opinion", "Fête des récompenses", "Fête de la Révolution"
]
additionaldaysforyear(yr) = yr > 11 ? 3 : yr > 7 ? 2 : yr > 3 ? 1 : 0
additionaldaysformonth(mo) = 30 * (mo - 1)
daysforFete(s) = findfirst(x -> x == s, RC_SANSCULOTTIDES) + 359
function togregorian(rc::String)
yearstring, firstpart = reverse.(split(reverse(strip(rc)), r"\s+", limit=2))
rcyear = parse(Int, yearstring)
pastyeardays = (rcyear - 1) * 365 + additionaldaysforyear(rcyear)
if isnumeric(firstpart[1])
daystring, monthstring = split(firstpart, r"\s+", limit=2)
nmonth = findfirst(x -> x == monthstring, RC_MONTHS)
pastmonthdays = 30 * (nmonth - 1)
furtherdays = parse(Int, daystring) + pastmonthdays + pastyeardays - 1
else
furtherdays = daysforFete(firstpart) + pastyeardays
end
gregorian = RC_FIRST_DAY + Day(furtherdays)
if furtherdays < 0 || gregorian > MAX_RC_DATE
throw(DomainError("French Republican Calendar date out of range"))
end
return Day(gregorian).value, monthname(Month(gregorian).value), Year(gregorian).value
end
function torepublican(gc::String)
date = Date(DateTime(gc, GC_FORMAT))
if date < RC_FIRST_DAY || date > MAX_RC_DATE
throw(DomainError("French Republican Calendar date out of range"))
end
rcyear, rcdays = divrem(((date - RC_FIRST_DAY).value + 366), 365)
rcdays -= additionaldaysforyear(rcyear)
if rcdays < 1
rcyear -= 1
rcdays += 366
end
if rcdays < 361
nmonth, rcday = divrem(rcdays, 30)
return rcday, RC_MONTHS[nmonth + 1], rcyear
else
return RC_SANSCULOTTIDES[rcdays - 360], rcyear
end
end
const republican = [
"1 Vendémiaire 1", "1 Prairial 3", "27 Messidor 7",
"Fête de la Révolution 11", "10 Nivôse 14"
]
const gregorian = [
"22 September 1792", "20 May 1795", "15 July 1799",
"23 September 1803", "31 December 1805"
]
function testrepublicancalendar()
println("French Republican to Gregorian")
for s in republican
println(lpad(s, 24), " => ", togregorian(s))
end
println("Gregorian to French Republican")
for s in gregorian
println(lpad(s, 24), " => ", torepublican(s))
end
end
testrepublicancalendar()
|
http://rosettacode.org/wiki/French_Republican_calendar
|
French Republican calendar
|
Write a program to convert dates between the Gregorian calendar and the French Republican calendar.
The year 1 of the Republican calendar began on 22 September 1792. There were twelve months (Vendémiaire, Brumaire, Frimaire, Nivôse, Pluviôse, Ventôse, Germinal, Floréal, Prairial, Messidor, Thermidor, and Fructidor) of 30 days each, followed by five intercalary days or Sansculottides (Fête de la vertu / Virtue Day, Fête du génie / Talent Day, Fête du travail / Labour Day, Fête de l'opinion / Opinion Day, and Fête des récompenses / Honours Day). In leap years (the years 3, 7, and 11) a sixth Sansculottide was added: Fête de la Révolution / Revolution Day.
As a minimum, your program should give correct results for dates in the range from 1 Vendémiaire 1 = 22 September 1792 to 10 Nivôse 14 = 31 December 1805 (the last day when the Republican calendar was officially in use). If you choose to accept later dates, be aware that there are several different methods (described on the Wikipedia page) about how to determine leap years after the year 14. You should indicate which method you are using. (Because of these different methods, correct programs may sometimes give different results for dates after 1805.)
Test your program by converting the following dates both from Gregorian to Republican and from Republican to Gregorian:
• 1 Vendémiaire 1 = 22 September 1792
• 1 Prairial 3 = 20 May 1795
• 27 Messidor 7 = 15 July 1799 (Rosetta Stone discovered)
• Fête de la Révolution 11 = 23 September 1803
• 10 Nivôse 14 = 31 December 1805
|
#Kotlin
|
Kotlin
|
// version 1.1.4-3
import java.time.format.DateTimeFormatter
import java.time.LocalDate
import java.time.temporal.ChronoUnit.DAYS
/* year = 1.. month = 1..13 day = 1..30 */
class FrenchRCDate(val year: Int, val month: Int, val day: Int) {
init {
require (year > 0 && month in 1..13)
if (month < 13) require (day in 1..30)
else {
val leap = isLeapYear(year)
require (day in (if (leap) 1..6 else 1..5))
}
}
override fun toString() =
if (month < 13) "$day ${months[month - 1]} $year"
else "${intercal[day - 1]} $year"
fun toLocalDate(): LocalDate {
var sumDays = 0L
for (i in 1 until year) sumDays += if (isLeapYear(i)) 366 else 365
val dayInYear = (month - 1) * 30 + day - 1
return introductionDate.plusDays(sumDays + dayInYear)
}
companion object {
/* uses the 'continuous method' for years after 1805 */
fun isLeapYear(y: Int): Boolean {
val yy = y + 1
return (yy % 4 == 0) && (yy % 100 != 0 || yy % 400 == 0)
}
fun parse(frcDate: String): FrenchRCDate {
val splits = frcDate.trim().split(' ')
if (splits.size == 3) {
val month = months.indexOf(splits[1]) + 1
require(month in 1..13)
val year = splits[2].toIntOrNull() ?: 0
require(year > 0)
val monthLength = if (month < 13) 30 else if (isLeapYear(year)) 6 else 5
val day = splits[0].toIntOrNull() ?: 0
require(day in 1..monthLength)
return FrenchRCDate(year, month, day)
}
else if (splits.size in 4..5) {
val yearStr = splits[splits.lastIndex]
val year = yearStr.toIntOrNull() ?: 0
require(year > 0)
val scDay = frcDate.trim().dropLast(yearStr.length + 1)
val day = intercal.indexOf(scDay) + 1
val maxDay = if (isLeapYear(year)) 6 else 5
require (day in 1..maxDay)
return FrenchRCDate(year, 13, day)
}
else throw IllegalArgumentException("Invalid French Republican date")
}
/* for convenience we treat 'Sansculottide' as an extra month with 5 or 6 days */
val months = arrayOf(
"Vendémiaire", "Brumaire", "Frimaire", "Nivôse", "Pluviôse", "Ventôse", "Germinal",
"Floréal", "Prairial", "Messidor", "Thermidor", "Fructidor", "Sansculottide"
)
val intercal = arrayOf(
"Fête de la vertu", "Fête du génie", "Fête du travail",
"Fête de l'opinion", "Fête des récompenses", "Fête de la Révolution"
)
val introductionDate = LocalDate.of(1792, 9, 22)
}
}
fun LocalDate.toFrenchRCDate(): FrenchRCDate {
val daysDiff = DAYS.between(FrenchRCDate.introductionDate, this).toInt() + 1
if (daysDiff <= 0) throw IllegalArgumentException("Date can't be before 22 September 1792")
var year = 1
var startDay = 1
while (true) {
val endDay = startDay + if (FrenchRCDate.isLeapYear(year)) 365 else 364
if (daysDiff in startDay..endDay) break
year++
startDay = endDay + 1
}
val remDays = daysDiff - startDay
val month = remDays / 30
val day = remDays - month * 30
return FrenchRCDate(year, month + 1, day + 1)
}
fun main(args: Array<String>) {
val formatter = DateTimeFormatter.ofPattern("d MMMM yyyy")
val dates = arrayOf("22 September 1792", "20 May 1795", "15 July 1799", "23 September 1803",
"31 December 1805", "18 March 1871", "25 August 1944", "19 September 2016",
"22 September 2017", "28 September 2017")
val frcDates = Array<String>(dates.size) { "" }
for ((i, date) in dates.withIndex()) {
val thisDate = LocalDate.parse(date, formatter)
val frcd = thisDate.toFrenchRCDate()
frcDates[i] = frcd.toString()
println("${date.padEnd(25)} => $frcd")
}
// now process the other way around
println()
for (frcDate in frcDates) {
val thisDate = FrenchRCDate.parse(frcDate)
val lds = formatter.format(thisDate.toLocalDate())
println("${frcDate.padEnd(25)} => $lds")
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.