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/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.
|
#C
|
C
|
#include<limits.h>
#include<stdio.h>
int fusc(int 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);
}
int numLen(int n){
int sum = 1;
while(n>9){
n = n/10;
sum++;
}
return sum;
}
void printLargeFuscs(int limit){
int i,f,len,maxLen = 1;
printf("\n\nPrinting all largest Fusc numbers upto %d \nIndex-------Value",limit);
for(i=0;i<=limit;i++){
f = fusc(i);
len = numLen(f);
if(len>maxLen){
maxLen = len;
printf("\n%5d%12d",i,f);
}
}
}
int main()
{
int i;
printf("Index-------Value");
for(i=0;i<61;i++)
printf("\n%5d%12d",i,fusc(i));
printLargeFuscs(INT_MAX);
return 0;
}
|
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.
|
#Swift
|
Swift
|
import Foundation
extension String {
func paddedLeft(totalLen: Int) -> String {
let needed = totalLen - count
guard needed > 0 else {
return self
}
return String(repeating: " ", count: needed) + self
}
}
class FCNode {
let name: String
let weight: Int
var coverage: Double {
didSet {
if oldValue != coverage {
parent?.updateCoverage()
}
}
}
weak var parent: FCNode?
var children = [FCNode]()
init(name: String, weight: Int = 1, coverage: Double = 0) {
self.name = name
self.weight = weight
self.coverage = coverage
}
func addChildren(_ children: [FCNode]) {
for child in children {
child.parent = self
}
self.children += children
updateCoverage()
}
func show(level: Int = 0) {
let indent = level * 4
let nameLen = name.count + indent
print(name.paddedLeft(totalLen: nameLen), terminator: "")
print("|".paddedLeft(totalLen: 32 - nameLen), terminator: "")
print(String(format: " %3d |", weight), terminator: "")
print(String(format: " %8.6f |", coverage))
for child in children {
child.show(level: level + 1)
}
}
func updateCoverage() {
let v1 = children.reduce(0.0, { $0 + $1.coverage * Double($1.weight) })
let v2 = children.reduce(0.0, { $0 + Double($1.weight) })
coverage = v1 / v2
}
}
let houses = [
FCNode(name: "house1", weight: 40),
FCNode(name: "house2", weight: 60)
]
let house1 = [
FCNode(name: "bedrooms", weight: 1, coverage: 0.25),
FCNode(name: "bathrooms"),
FCNode(name: "attic", weight: 1, coverage: 0.75),
FCNode(name: "kitchen", weight: 1, coverage: 0.1),
FCNode(name: "living_rooms"),
FCNode(name: "basement"),
FCNode(name: "garage"),
FCNode(name: "garden", weight: 1, coverage: 0.8)
]
let house2 = [
FCNode(name: "upstairs"),
FCNode(name: "groundfloor"),
FCNode(name: "basement")
]
let h1Bathrooms = [
FCNode(name: "bathroom1", weight: 1, coverage: 0.5),
FCNode(name: "bathroom2"),
FCNode(name: "outside_lavatory", weight: 1, coverage: 1.0)
]
let h1LivingRooms = [
FCNode(name: "lounge"),
FCNode(name: "dining_room"),
FCNode(name: "conservatory"),
FCNode(name: "playroom", weight: 1, coverage: 1.0)
]
let h2Upstairs = [
FCNode(name: "bedrooms"),
FCNode(name: "bathroom"),
FCNode(name: "toilet"),
FCNode(name: "attics", weight: 1, coverage: 0.6)
]
let h2Groundfloor = [
FCNode(name: "kitchen"),
FCNode(name: "living_rooms"),
FCNode(name: "wet_room_&_toilet"),
FCNode(name: "garage"),
FCNode(name: "garden", weight: 1, coverage: 0.9),
FCNode(name: "hot_tub_suite", weight: 1, coverage: 1.0)
]
let h2Basement = [
FCNode(name: "cellars", weight: 1, coverage: 1.0),
FCNode(name: "wine_cellar", weight: 1, coverage: 1.0),
FCNode(name: "cinema", weight: 1, coverage: 0.75)
]
let h2UpstairsBedrooms = [
FCNode(name: "suite_1"),
FCNode(name: "suite_2"),
FCNode(name: "bedroom_3"),
FCNode(name: "bedroom_4")
]
let h2GroundfloorLivingRooms = [
FCNode(name: "lounge"),
FCNode(name: "dining_room"),
FCNode(name: "conservatory"),
FCNode(name: "playroom")
]
let cleaning = FCNode(name: "cleaning")
house1[1].addChildren(h1Bathrooms)
house1[4].addChildren(h1LivingRooms)
houses[0].addChildren(house1)
h2Upstairs[0].addChildren(h2UpstairsBedrooms)
house2[0].addChildren(h2Upstairs)
h2Groundfloor[1].addChildren(h2GroundfloorLivingRooms)
house2[1].addChildren(h2Groundfloor)
house2[2].addChildren(h2Basement)
houses[1].addChildren(house2)
cleaning.addChildren(houses)
let top = cleaning.coverage
print("Top Coverage: \(String(format: "%8.6f", top))")
print("Name Hierarchy | Weight | Coverage |")
cleaning.show()
h2Basement[2].coverage = 1.0
let diff = cleaning.coverage - top
print("\nIf the coverage of the Cinema node were increased from 0.75 to 1.0")
print("the top level coverage would increase by ")
print("\(String(format: "%8.6f", diff)) to \(String(format: "%8.6f", top))")
|
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.
|
#Wren
|
Wren
|
import "/fmt" for Fmt
class FCNode {
construct new(name, weight, coverage) {
_name = name
_weight = weight
_coverage = coverage
_children = []
_parent = null
}
static new(name, weight) { new(name, weight, 0) }
static new(name) { new(name, 1, 0) }
name { _name }
weight { _weight }
coverage { _coverage }
coverage=(value) {
if (_coverage != value) {
_coverage = value
if (_parent) {
_parent.updateCoverage_() // update any parent's coverage
}
}
}
parent { _parent }
parent=(p) { _parent = p }
addChildren(nodes) {
_children.addAll(nodes)
for (node in nodes) node.parent = this
updateCoverage_()
}
updateCoverage_() {
var v1 = _children.reduce(0) { |acc, n| acc + n.weight * n.coverage }
var v2 = _children.reduce(0) { |acc, n| acc + n.weight }
coverage = v1 / v2
}
show(level) {
var indent = level * 4
var nl = _name.count + indent
Fmt.lprint("$*s$*s $3d | $8.6f |", [nl, _name, 32-nl, "|", _weight, _coverage])
if (_children.isEmpty) return
for (child in _children) child.show(level+1)
}
}
var houses = [
FCNode.new("house1", 40),
FCNode.new("house2", 60)
]
var house1 = [
FCNode.new("bedrooms", 1, 0.25),
FCNode.new("bathrooms"),
FCNode.new("attic", 1, 0.75),
FCNode.new("kitchen", 1, 0.1),
FCNode.new("living_rooms"),
FCNode.new("basement"),
FCNode.new("garage"),
FCNode.new("garden", 1, 0.8)
]
var house2 = [
FCNode.new("upstairs"),
FCNode.new("groundfloor"),
FCNode.new("basement")
]
var h1Bathrooms = [
FCNode.new("bathroom1", 1, 0.5),
FCNode.new("bathroom2"),
FCNode.new("outside_lavatory", 1, 1)
]
var h1LivingRooms = [
FCNode.new("lounge"),
FCNode.new("dining_room"),
FCNode.new("conservatory"),
FCNode.new("playroom", 1, 1)
]
var h2Upstairs = [
FCNode.new("bedrooms"),
FCNode.new("bathroom"),
FCNode.new("toilet"),
FCNode.new("attics", 1, 0.6)
]
var h2Groundfloor = [
FCNode.new("kitchen"),
FCNode.new("living_rooms"),
FCNode.new("wet_room_&_toilet"),
FCNode.new("garage"),
FCNode.new("garden", 1, 0.9),
FCNode.new("hot_tub_suite", 1, 1)
]
var h2Basement = [
FCNode.new("cellars", 1, 1),
FCNode.new("wine_cellar", 1, 1),
FCNode.new("cinema", 1, 0.75)
]
var h2UpstairsBedrooms = [
FCNode.new("suite_1"),
FCNode.new("suite_2"),
FCNode.new("bedroom_3"),
FCNode.new("bedroom_4")
]
var h2GroundfloorLivingRooms = [
FCNode.new("lounge"),
FCNode.new("dining_room"),
FCNode.new("conservatory"),
FCNode.new("playroom")
]
var cleaning = FCNode.new("cleaning")
house1[1].addChildren(h1Bathrooms)
house1[4].addChildren(h1LivingRooms)
houses[0].addChildren(house1)
h2Upstairs[0].addChildren(h2UpstairsBedrooms)
house2[0].addChildren(h2Upstairs)
h2Groundfloor[1].addChildren(h2GroundfloorLivingRooms)
house2[1].addChildren(h2Groundfloor)
house2[2].addChildren(h2Basement)
houses[1].addChildren(house2)
cleaning.addChildren(houses)
var topCoverage = cleaning.coverage
Fmt.print("TOP COVERAGE = $8.6f\n", topCoverage)
System.print("NAME HIERARCHY | WEIGHT | COVERAGE |")
cleaning.show(0)
h2Basement[2].coverage = 1 // change Cinema node coverage to 1
var diff = cleaning.coverage - topCoverage
System.print("\nIf the coverage of the Cinema node were increased from 0.75 to 1")
System.write("the top level coverage would increase by ")
Fmt.print("$8.6f to $8.6f", diff, topCoverage + diff)
h2Basement[2].coverage = 0.75 // restore to original value if required
|
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.
|
#Julia
|
Julia
|
using Printf, DataStructures
function funcfreqs(expr::Expr)
cnt = counter(Symbol)
expr.head == :call &&
push!(cnt, expr.args[1])
for e in expr.args
e isa Expr && merge!(cnt, funcfreqs(e))
end
return cnt
end
function parseall(str::AbstractString)
exs = Any[]
pos = start(str)
while !done(str, pos)
ex, pos = parse(str, pos) # returns next starting point as well as expr
ex.head == :toplevel ? append!(exs, ex.args) : push!(exs, ex)
end
if isempty(exs)
throw(ParseError("end of input"))
elseif length(exs) == 1
return exs[1]
else
return Expr(:block, exs...)
end
end
freqs = readstring("src/Function_frequency.jl") |> parseall |> funcfreqs
for (v, f) in freqs
@printf("%10s → %i\n", v, f)
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.
|
#LiveCode
|
LiveCode
|
function handlerNames pScript
put pScript into pScriptCopy
filter pScript with regex pattern "^(on|function).*"
-- add in the built-in commands & functions
put the commandNames & the functionnames into cmdfunc
repeat for each line builtin in cmdfunc
put 0 into handlers[builtin]
end repeat
-- add user defined handlers, remove this section of you do not want your own functions included
repeat with x = 1 to the number of lines of pScript
put word 2 of line x of pScript into handlername
put 0 into handlers[handlername]
end repeat
-- count handlers used
repeat with x = 1 to the number of lines of pScriptCopy
repeat for each key k in handlers
if k is among the tokens of line x of pScriptCopy then
add 1 to handlers[k]
end if
end repeat
end repeat
combine handlers using cr and space
sort lines of handlers descending by word 2 of each
put line 1 to 10 of handlers into handlers
return handlers
end handlerNames
|
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.
|
#Mathematica_.2F_Wolfram_Language
|
Mathematica / Wolfram Language
|
programCount[fn_] := Reverse[If[Length[#] > 10, Take[#, -10], #] &[SortBy[Tally[Cases[DownValues[fn], s_Symbol, \[Infinity], Heads -> True]], Last]]]
|
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.23
|
C#
|
using System;
using System.Numerics;
static int g = 7;
static double[] p = {0.99999999999980993, 676.5203681218851, -1259.1392167224028,
771.32342877765313, -176.61502916214059, 12.507343278686905,
-0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7};
Complex Gamma(Complex z)
{
// Reflection formula
if (z.Real < 0.5)
{
return Math.PI / (Complex.Sin( Math.PI * z) * Gamma(1 - z));
}
else
{
z -= 1;
Complex x = p[0];
for (var i = 1; i < g + 2; i++)
{
x += p[i]/(z+i);
}
Complex t = z + g + 0.5;
return Complex.Sqrt(2 * Math.PI) * (Complex.Pow(t, z + 0.5)) * Complex.Exp(-t) * x;
}
}
|
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.
|
#J
|
J
|
initpins=: '* ' {~ '1'&i.@(-@|. |."_1 [: ":@-.&0"1 <:~/~)@i.
|
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
|
#Groovy
|
Groovy
|
class GapfulNumbers {
private static String commatize(long n) {
StringBuilder sb = new StringBuilder(Long.toString(n))
int le = sb.length()
for (int i = le - 3; i >= 1; i -= 3) {
sb.insert(i, ',')
}
return sb.toString()
}
static void main(String[] args) {
List<Long> starts = [(long) 1e2, (long) 1e6, (long) 1e7, (long) 1e9, (long) 7123]
List<Integer> counts = [30, 15, 15, 10, 25]
for (int i = 0; i < starts.size(); ++i) {
println("First ${counts.get(i)} gapful numbers starting at ${commatize(starts.get(i))}")
long j = starts.get(i)
long pow = 100
while (j >= pow * 10) {
pow *= 10
}
int count = 0
while (count < counts.get(i)) {
long fl = ((long) (j / pow)) * 10 + (j % 10)
if (j % fl == 0) {
print("$j ")
count++
}
if (++j >= 10 * pow) {
pow *= 10
}
}
println()
println()
}
}
}
|
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
|
#J
|
J
|
f=: 6j2&": NB. formatting verb
sin=: 1&o. NB. verb to evaluate circle function 1, the sine
add_noise=: ] + (* (_0.5 + 0 ?@:#~ #)) NB. AMPLITUDE add_noise SIGNAL
f RADIANS=: o.@:(%~ i.@:>:)5 NB. monadic circle function is pi times
0.00 0.63 1.26 1.88 2.51 3.14
f SINES=: sin RADIANS
0.00 0.59 0.95 0.95 0.59 0.00
f NOISY_SINES=: 0.1 add_noise SINES
_0.01 0.61 0.91 0.99 0.60 0.02
A=: (^/ i.@:#) RADIANS NB. A is the quintic coefficient matrix
NB. display the equation to solve
(f A) ; 'x' ; '=' ; f@:,. NOISY_SINES
┌────────────────────────────────────┬─┬─┬──────┐
│ 1.00 0.00 0.00 0.00 0.00 0.00│x│=│ _0.01│
│ 1.00 0.63 0.39 0.25 0.16 0.10│ │ │ 0.61│
│ 1.00 1.26 1.58 1.98 2.49 3.13│ │ │ 0.91│
│ 1.00 1.88 3.55 6.70 12.62 23.80│ │ │ 0.99│
│ 1.00 2.51 6.32 15.88 39.90100.28│ │ │ 0.60│
│ 1.00 3.14 9.87 31.01 97.41306.02│ │ │ 0.02│
└────────────────────────────────────┴─┴─┴──────┘
f QUINTIC_COEFFICIENTS=: NOISY_SINES %. A NB. %. solves the linear system
_0.01 1.71 _1.88 1.48 _0.58 0.08
quintic=: QUINTIC_COEFFICIENTS&p. NB. verb to evaluate the polynomial
NB. %. also solves the least squares fit for overdetermined system
quadratic=: (NOISY_SINES %. (^/ i.@:3:) RADIANS)&p. NB. verb to evaluate quadratic.
quadratic
_0.0200630695393961729 1.26066877804926536 _0.398275112136019516&p.
NB. The quintic is agrees with the noisy data, as it should
f@:(NOISY_SINES ,. sin ,. quadratic ,. quintic) RADIANS
_0.01 0.00 _0.02 _0.01
0.61 0.59 0.61 0.61
0.91 0.95 0.94 0.91
0.99 0.95 0.94 0.99
0.60 0.59 0.63 0.60
0.02 0.00 0.01 0.02
f MID_POINTS=: (+ -:@:(-/@:(2&{.)))RADIANS
_0.31 0.31 0.94 1.57 2.20 2.83
f@:(sin ,. quadratic ,. quintic) MID_POINTS
_0.31 _0.46 _0.79
0.31 0.34 0.38
0.81 0.81 0.77
1.00 0.98 1.00
0.81 0.83 0.86
0.31 0.36 0.27
|
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.
|
#Nim
|
Nim
|
import strformat, strutils
const Eps = 1e-10
type
Matrix[M, N: static Positive] = array[M, array[N, float]]
SquareMatrix[N: static Positive] = Matrix[N, N]
func toSquareMatrix[N: static Positive](a: array[N, array[N, int]]): SquareMatrix[N] =
## Convert a square matrix of integers to a square matrix of floats.
for i in 0..<N:
for j in 0..<N:
result[i][j] = a[i][j].toFloat
func transformToRref(mat: var Matrix) =
## Transform a matrix to reduced row echelon form.
var lead = 0
for r in 0..<mat.M:
if lead >= mat.N: return
var i = r
while mat[i][lead] == 0:
inc i
if i == mat.M:
i = r
inc lead
if lead == mat.N: return
swap mat[i], mat[r]
let d = mat[r][lead]
if abs(d) > Eps: # Checking "d != 0" will give wrong results in some cases.
for item in mat[r].mitems:
item /= d
for i in 0..<mat.M:
if i != r:
let m = mat[i][lead]
for c in 0..<mat.N:
mat[i][c] -= mat[r][c] * m
inc lead
func inverse(mat: SquareMatrix): SquareMatrix[mat.N] =
## Return the inverse of a matrix.
# Build augmented matrix.
var augmat: Matrix[mat.N, 2 * mat.N]
for i in 0..<mat.N:
augmat[i][0..<mat.N] = mat[i]
augmat[i][mat.N + i] = 1
# Transform it to reduced row echelon form.
augmat.transformToRref()
# Check if the first half is the identity matrix and extract second half.
for i in 0..<mat.N:
for j in 0..<mat.N:
if augmat[i][j] != float(i == j):
raise newException(ValueError, "matrix is singular")
result[i][j] = augmat[i][mat.N + j]
proc `$`(mat: Matrix): string =
## Display a matrix (which may be a square matrix).
for row in mat:
var line = ""
for val in row:
line.addSep(" ", 0)
line.add &"{val:9.5f}"
echo line
#———————————————————————————————————————————————————————————————————————————————————————————————————
template runTest(mat: SquareMatrix) =
## Run a test using square matrix "mat".
echo "Matrix:"
echo $mat
echo "Inverse:"
echo mat.inverse
echo ""
let m1 = [[1, 2, 3],
[4, 1, 6],
[7, 8, 9]].toSquareMatrix()
let m2 = [[ 2, -1, 0],
[-1, 2, -1],
[ 0, -1, 2]].toSquareMatrix()
let m3 = [[ -1, -2, 3, 2],
[ -4, -1, 6, 2],
[ 7, -8, 9, 1],
[ 1, -2, 1, 3]].toSquareMatrix()
runTest(m1)
runTest(m2)
runTest(m3)
|
http://rosettacode.org/wiki/General_FizzBuzz
|
General FizzBuzz
|
Task
Write a generalized version of FizzBuzz that works for any list of factors, along with their words.
This is basically a "fizzbuzz" implementation where the user supplies the parameters.
The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be printed.
For simplicity's sake, assume the user will input an integer as the max number and 3 factors, each with a word associated with them.
For example, given:
>20 #This is the maximum number, supplied by the user
>3 Fizz #The user now enters the starting factor (3) and the word they want associated with it (Fizz)
>5 Buzz #The user now enters the next factor (5) and the word they want associated with it (Buzz)
>7 Baxx #The user now enters the next factor (7) and the word they want associated with it (Baxx)
In other words: For this example, print the numbers 1 through 20, replacing every multiple of 3 with "Fizz", every multiple of 5 with "Buzz", and every multiple of 7 with "Baxx".
In the case where a number is a multiple of at least two factors, print each of the words associated with those factors in the order of least to greatest factor.
For instance, the number 15 is a multiple of both 3 and 5; print "FizzBuzz".
If the max number was 105 instead of 20, you would print "FizzBuzzBaxx" because it's a multiple of 3, 5, and 7.
Output:
1
2
Fizz
4
Buzz
Fizz
Baxx
8
Fizz
Buzz
11
Fizz
13
Baxx
FizzBuzz
16
17
Fizz
19
Buzz
|
#Maple
|
Maple
|
findNum := proc(str) #help parse input
local i;
i := 1:
while (true) do
if (StringTools:-IsAlpha(str[i])) then
return i-2:
end if:
i := i+1:
end do:
end proc:
path := "input.txt";
input := readline(path):
T := table():
maxnum := parse(input):
while (true) do
input := readline(path):
if input = 0 then break; end if:
pos := findNum(input):
num := parse(input[..pos]):
T[num] := input[pos+2..]:
end do:
for i from 1 to maxnum do
factored := false:
for j in [indices(T)] do
if i mod j[1] = 0 then
factored := true:
printf(T[j[1]]);
end if:
end do:
if (not factored) then printf("%d", i): end if:
printf("\n");
end do:
|
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
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
list={{5,"Buzz"},{3,"Fizz"},{7,"Baxx"}};
runTo=(*LCM@@list[[All,1]]+1*)20;
Column@Table[
Select[list,Mod[x,#[[1]]]==0&][[All,2]]/.{}->{x}
,{x,1,runTo}
]
|
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
|
#Erlang
|
Erlang
|
lists:seq($a,$z).
|
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
|
Generate lower case ASCII alphabet
|
Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code.
During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code:
set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z}
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#Excel
|
Excel
|
showAlphabet
=LAMBDA(az,
ENUMFROMTOCHAR(
MID(az, 1, 1)
)(
MID(az, 2, 1)
)
)
|
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
|
#OpenLisp
|
OpenLisp
|
#!/openlisp/uxlisp -shell
(format t "Hello world!~%")
(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
|
#Mathematica_.2F_Wolfram_Language
|
Mathematica / Wolfram Language
|
lastsquare = 1;
nextsquare = -1;
lastcube = -1;
midcube = 0;
nextcube = 1;
Gensquares[] := Module[{},
lastsquare += nextsquare;
nextsquare += 2;
squares = lastsquare;
squares
]
Gencubes[] := Module[{},
lastcube += nextcube;
nextcube += midcube;
midcube += 6;
cubes = lastcube
]
c = Gencubes[];
Do[
While[True,
s = Gensquares[];
While[c < s,
c = Gencubes[];
];
If[s =!= c,
Break[]
];
];
If[i > 20,
Print[s]
]
,
{i, 30}
]
|
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.
|
#REXX
|
REXX
|
/*REXX program generates a random starting position for the Chess960 game. */
parse arg seed . /*allow for (RANDOM BIF) repeatability.*/
if seed\=='' then call random ,,seed /*if SEED was specified, use the seed.*/
@.=. /*define the first rank as being empty.*/
r1=random(1,6) /*generate the first rook: rank 1. */
@.r1='R' /*place the first rook on rank1. */
do until r2\==r1 & r2\==r1-1 & r2\==r1+1
r2=random(1,8) /*find placement for the 2nd rook. */
end /*forever*/
@.r2='r' /*place the second rook on rank 1. */
k=random(min(r1, r2)+1, max(r1, r2)-1) /*find a random position for the king. */
@.k='K' /*place king between the two rooks. */
do _=0 ; b1=random(1,8); if @.b1\==. then iterate; c=b1//2
do forever; b2=random(1,8) /* c=color of bishop ►──┘ */
if @.b2\==. | b2==b1 | b2//2==c then iterate /*is a bad position?*/
leave _ /*found position for the 2 clergy*/
end /*forever*/ /* [↑] find a place for the 1st bishop*/
end /* _ */ /* [↑] " " " " " 2nd " */
@.b1='B' /*place the 1st bishop on rank 1. */
@.b2='b' /* " " 2nd " " " " */
/*place the two knights on rank 1. */
do until @._='N'; _=random(1,8); if @._\==. then iterate; @._='N'; end
do until @.!='n'; !=random(1,8); if @.!\==. then iterate; @.!='n'; end
_= /*only the queen is left to be placed. */
do i=1 for 8; _=_ || @.i; end /*construct the output: first rank only*/
say translate(translate(_, 'q', .)) /*stick a fork in it, we're all done. */
|
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.
|
#Arturo
|
Arturo
|
compose: function [f,g] ->
return function [x].import:[f,g][
call f @[call g @[x]]
]
splitupper: compose 'split 'upper
print call 'splitupper ["done"]
|
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.
|
#ATS
|
ATS
|
(*
The 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,
(let's call the argument x), which works like applying function
f to the result of applying function g to x.
In ATS, we have to choose whether to use non-linear closures
(cloref) or linear closures (cloptr). In the latter case, we also
have to choose between closures allocated with malloc (or similar)
and closures allocated on the stack.
For simplicity, we will use non-linear closures and assume there is
a garbage collector, or that the memory allocated for the closures
can be allowed to leak. (This is often the case in a program that
does not run continuously.)
*)
#include "share/atspre_staload.hats"
(* The following is actually a *template function*, rather than a
function proper. It is expanded during template processing. *)
fn {t1, t2, t3 : t@ype}
compose (f : t2 -<cloref1> t3,
g : t1 -<cloref1> t2) : t1 -<cloref1> t3 =
lam x => f (g (x))
implement
main0 () =
let
val one_hundred = 100.0
val char_zero = '0'
val f = (lam y =<cloref1> add_double_int (one_hundred, y))
val g = (lam x =<cloref1> char2i x - char2i char_zero)
val z = compose (f, g) ('5')
val fg = compose (f, g)
val w = fg ('7')
in
println! (z : double);
println! (w : double)
end
|
http://rosettacode.org/wiki/Fractal_tree
|
Fractal tree
|
Generate and draw a fractal tree.
Draw the trunk
At the end of the trunk, split by some angle and draw two branches
Repeat at the end of each branch until a sufficient level of branching is reached
Related tasks
Pythagoras Tree
|
#11l
|
11l
|
-V
Width = 1000
Height = 1000
TrunkLength = 400
ScaleFactor = 0.6
StartingAngle = 1.5 * math:pi
DeltaAngle = 0.2 * math:pi
F drawTree(outfile, Float x, Float y; len, theta) -> N
I len >= 1
V x2 = x + len * cos(theta)
V y2 = y + len * sin(theta)
outfile.write("<line x1='#.6' y1='#.6' x2='#.6' y2='#.6' style='stroke:white;stroke-width:1'/>\n".format(x, y, x2, y2))
drawTree(outfile, x2, y2, len * ScaleFactor, theta + DeltaAngle)
drawTree(outfile, x2, y2, len * ScaleFactor, theta - DeltaAngle)
V outsvg = File(‘tree.svg’, ‘w’)
outsvg.write(|‘<?xml version='1.0' encoding='utf-8' standalone='no'?>
<!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'>
<svg width='100%%' height='100%%' version='1.1' xmlns='http://www.w3.org/2000/svg'>
<rect width="100%" height="100%" fill="black"/>
’)
drawTree(outsvg, 0.5 * Width, Height, TrunkLength, StartingAngle)
outsvg.write("</svg>\n")
|
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.
|
#Ada
|
Ada
|
with Ada.Text_IO;
procedure Fractan is
type Fraction is record Nom: Natural; Denom: Positive; end record;
type Frac_Arr is array(Positive range <>) of Fraction;
function "/" (N: Natural; D: Positive) return Fraction is
Frac: Fraction := (Nom => N, Denom => D);
begin
return Frac;
end "/";
procedure F(List: Frac_Arr; Start: Positive; Max_Steps: Natural) is
N: Positive := Start;
J: Positive;
begin
Ada.Text_IO.Put(" 0:" & Integer'Image(N) & " ");
for I in 1 .. Max_Steps loop
J := List'First;
loop
if N mod List(J).Denom = 0 then
N := (N/List(J).Denom) * List(J).Nom;
exit; -- found fraction
elsif J >= List'Last then
return; -- did try out all fractions
else
J := J + 1; -- try the next fraction
end if;
end loop;
Ada.Text_IO.Put(Integer'Image(I) & ":" & Integer'Image(N) & " ");
end loop;
end F;
begin
-- F((2/3, 7/2, 1/5, 1/7, 1/9, 1/4, 1/8), 2, 100);
-- output would be "0: 2 1: 7 2: 1" and then terminate
F((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);
-- output is "0: 2 1: 15 2: 825 3: 725 ... 14: 132 15: 116"
end Fractan;
|
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.
|
#Java
|
Java
|
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
public class FTPconn {
public static void main(String[] args) throws IOException {
String server = "ftp.hq.nasa.gov";
int port = 21;
String user = "anonymous";
String pass = "[email protected]";
OutputStream output = null;
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
serverReply(ftpClient);
int replyCode = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
System.out.println("Failure. Server reply code: " + replyCode);
return;
}
serverReply(ftpClient);
if (!ftpClient.login(user, pass)) {
System.out.println("Could not login to the server.");
return;
}
String dir = "pub/issoutreach/Living in Space Stories (MP3 Files)/";
if (!ftpClient.changeWorkingDirectory(dir)) {
System.out.println("Change directory failed.");
return;
}
ftpClient.enterLocalPassiveMode();
for (FTPFile file : ftpClient.listFiles())
System.out.println(file);
String filename = "Can People go to Mars.mp3";
output = new FileOutputStream(filename);
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
if (!ftpClient.retrieveFile(filename, output)) {
System.out.println("Retrieving file failed");
return;
}
serverReply(ftpClient);
ftpClient.logout();
} finally {
if (output != null)
output.close();
}
}
private static void serverReply(FTPClient ftpClient) {
for (String reply : ftpClient.getReplyStrings()) {
System.out.println(reply);
}
}
}
|
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.
|
#Oforth
|
Oforth
|
Method new: myMethod
|
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.
|
#Ol
|
Ol
|
'DECLARE FUNCTION' ABBREVIATED TO '!'
! f() ' a procedure with no params
! f(int a) ' with 1 int param
! f(int *a) ' with 1 int pointer param
! f(int a, int b, inc c) ' with 3 int params
! f(int a,b,c) ' compaction with 3 int params
! f(string s, int a,b) ' with 1 string and 2 int params
! f() as string ' function returning a string
! f(string s) as string ' with 1 string param
! *f(string s) as string ' as a function pointer: @f=address
! f(string s, optional i) ' with opptional param
! f(string s = "Hello") ' optional param with default value
! f(int n, ...) ' 1 specific param and varargs
! f(...) ' any params or none
'TRADITIONAL BASIC DECLARATIONS
declare sub f( s as string, i as long, j as long) ' byref by default
declare function f( byref s as string, byval i as long, byval j as long) as string
'C-STYLE DECLARATIONS
void f(string *s, long i, long j)
string f(string *s, long i, long j)
'BLOCK DIRECTIVES FOR FUNCTION PROTOTYPES:
extern ' shareable stdcall functions
extern lib "xyz.dll" ' for accessing functions in xyz Dynamic Link Library
extern export ' functions to be exported if this is a DLL
extern virtual ' for accssing interfaces and other virtual classes
end extern ' revert to internal function mode
|
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.
|
#OxygenBasic
|
OxygenBasic
|
'DECLARE FUNCTION' ABBREVIATED TO '!'
! f() ' a procedure with no params
! f(int a) ' with 1 int param
! f(int *a) ' with 1 int pointer param
! f(int a, int b, inc c) ' with 3 int params
! f(int a,b,c) ' compaction with 3 int params
! f(string s, int a,b) ' with 1 string and 2 int params
! f() as string ' function returning a string
! f(string s) as string ' with 1 string param
! *f(string s) as string ' as a function pointer: @f=address
! f(string s, optional i) ' with opptional param
! f(string s = "Hello") ' optional param with default value
! f(int n, ...) ' 1 specific param and varargs
! f(...) ' any params or none
'TRADITIONAL BASIC DECLARATIONS
declare sub f( s as string, i as long, j as long) ' byref by default
declare function f( byref s as string, byval i as long, byval j as long) as string
'C-STYLE DECLARATIONS
void f(string *s, long i, long j)
string f(string *s, long i, long j)
'BLOCK DIRECTIVES FOR FUNCTION PROTOTYPES:
extern ' shareable stdcall functions
extern lib "xyz.dll" ' for accessing functions in xyz Dynamic Link Library
extern export ' functions to be exported if this is a DLL
extern virtual ' for accssing interfaces and other virtual classes
end extern ' revert to internal function mode
|
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
|
#8086_Assembly
|
8086 Assembly
|
start:
mov al, 0x04
mov bl, 0x05
call multiply
;at this point in execution, the AX register contains 0x0900.
;more code goes here, ideally with some sort of guard against "fallthrough" into multiply.
; somewhere far away from start
multiply:
mul bl ;outputs 0x0014 to ax
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
|
#Nim
|
Nim
|
import strformat, strscans, strutils, times
const
RcMonths = ["Vendémiaire", "Brumaire", "Frimaire", "Nivôse", "Pluviôse", "Ventôse",
"Germinal", "Floréal", "Prairial", "Messidor", "Thermidor", "Fructidor"]
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"]
let
# First and last dates of republican calendar expressed in gregorian calendar.
FirstRcDate = initDateTime(22, mSep, 1792, 0, 0, 0)
LastRcDate = initDateTime(31, mDec, 1805, 0, 0, 0)
type
# French republican date representation.
RcDayRange = 1..30
RcMonthRange = 1..13
RcYearRange = 1..14
RepublicanDate = tuple[year: RcYearRange, month: RcMonthRange, day: RcDayRange]
# Last dates of republican calendar expressed in republican calendar.
const RcLastDate: RepublicanDate = (RcYearRange(14), RcMonthRange(4), RcDayRange(10))
proc notnum(input: string; str: var string; start: int): int =
# Parsing procedure to extract non numerical part of a date.
var i = start
while i <= input.high:
if input[i] in '0'..'9': break
str.add input[i]
inc i
if str.len == 0 or str[^1] != ' ': return -1 # Not terminated by a space.
str.setLen(str.len - 1) # Back before the space.
result = str.len
proc parseRepublicanDate(rdate: string): RepublicanDate =
## Parse a French republican date and return its representation.
let date = rdate.strip()
var day, month, year: int
var monthString, dayString: string
if date.scanf("$i $+ $i", day, monthString, year):
# Normal day.
if day notin 1..30:
raise newException(ValueError, "wrong day number: $1.".format(day))
month = RcMonths.find(monthString) + 1
if month == 0:
raise newException(ValueError, "unknown French republican month: $1." % monthString)
elif date.scanf("${notnum} $i", dayString, year):
# Sans-culottide day (also known as “jour complémentaire”).
month = 13 # Value used for sans-culottide days.
day = SansCulottides.find(dayString) + 1
if day == 0:
raise newException(ValueError, "wrong “sans-culottide” day: « $1 »." % dayString)
if day == 6 and year mod 4 != 3:
raise newException(ValueError, "republican year $1 is not a leap year".format(year))
else:
raise newException(ValueError, "invalid French republican date: « $1 »." % date)
result = (RcYearRange(year), RcMonthRange(month), RcDayRange(day))
if result > RcLastDate:
raise newException(ValueError, "republican date out of range: « $1 »." % date)
proc `$`(date: RepublicanDate): string =
## Return the string representation of a French republican date.
if date.month != 13:
# Normal day.
result = "$1 $2 $3".format(date.day, RcMonths[date.month - 1], date.year)
else:
# Supplementary day.
result = "$1 $2".format(SansCulottides[date.day - 1], date.year)
proc toGregorian(rdate: RepublicanDate): DateTime =
## Convert a republican date tuple to a gregorian date (DateTime object).
let day = (rdate.day - 1) + (rdate.month - 1) * 30 + (rdate.year - 1) * 365 + rdate.year div 4
result = FirstRcDate + initTimeInterval(days = day)
proc toGregorian(rdate: string): string =
## Convert a republican date string to a gregorian date string.
let date = rdate.parseRepublicanDate()
result = date.toGregorian().format("dd MMMM yyyy")
proc toRepublican(gdate: DateTime): RepublicanDate =
## Convert a gregorian date (DateTime object) to a republican date tuple.
if gdate notin FirstRcDate..LastRcDate:
raise newException(ValueError, "impossible conversion to republican date.")
let d = gdate - FirstRcDate
# Add a dummy year before year 1 in order to use a four years period.
let dayNumber = d.inDays + 365
let periodNum = dayNumber div 1461
let dayInPeriod = dayNumber mod 1461
# Compute year and day in year.
let yearInPeriod = min(dayInPeriod div 365, 3)
result.year = periodNum * 4 + yearInPeriod
let dayInYear = dayInPeriod - yearInPeriod * 365
# Compute month and day.
result.month = dayInYear div 30 + 1
result.day = dayInYear mod 30 + 1
proc toRepublican(gdate: string): string =
## Convert a gregorian date string to a republican date string.
let date = gdate.parse("d MMMM yyyy")
result = $(date.toRepublican())
when isMainModule:
const
RepublicanDates = ["1 Vendémiaire 1", "1 Prairial 3", "27 Messidor 7",
"Fête de la Révolution 11", "10 Nivôse 14"]
GregorianDates = ["22 September 1792", "20 May 1795", "15 July 1799",
"23 September 1803", "31 December 1805"]
echo "From French republican dates to gregorian dates:"
for rdate in RepublicanDates:
echo &"{rdate:>24} → {rdate.toGregorian()}"
echo()
echo "From gregorian dates to French republican dates:"
for gdate in GregorianDates:
echo &"{gdate:>24} → {gdate.toRepublican()}"
|
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
|
#Perl
|
Perl
|
use feature 'state';
use DateTime;
my @month_names = qw{
Vendémiaire Brumaire Frimaire Nivôse Pluviôse Ventôse
Germinal Floréal Prairial Messidor Thermidor Fructidor
};
my @intercalary = (
'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',
);
my %month_nums = map { $month_names[$_] => $_+1 } 0 .. $#month_names;
my %i_cal_nums = map { $intercalary[$_] => $_+1 } 0 .. $#intercalary;
my $i_cal_month = 13;
my $epoch = DateTime->new( year => 1792, month => 9, day => 22 );
sub is_republican_leap_year {
my $y = $_[0] + 1;
return !!( ($y % 4)==0 and (($y % 100)!=0 or ($y % 400)==0) );
}
sub Republican_to_Gregorian {
my ($rep_date) = @_;
state $months = join '|', map { quotemeta } @month_names;
state $intercal = join '|', map { quotemeta } @intercalary;
state $re = qr{
\A
\s* (?:
(?<ic> $intercal)
| (?<day> \d+) \s+ (?<month> $months)
)
\s+ (?<year> \d+)
\s*
\z
}msx;
$rep_date =~ /$re/
or die "Republican date not recognized: '$rep_date'";
my $day1 = $+{ic} ? $i_cal_nums{$+{ic}} : $+{day};
my $month1 = $+{month} ? $month_nums{$+{month}} : $i_cal_month;
my $year1 = $+{year};
my $days_since_epoch = ($year1-1) * 365 + ($month1-1) * 30 + ($day1-1);
my $leap_days = grep { is_republican_leap_year($_) } 1 .. $year1-1;
return $epoch->clone->add( days => ($days_since_epoch + $leap_days) );
}
sub Gregorian_to_Republican {
my ($greg_date) = @_;
my $days_since_epoch = $epoch->delta_days($greg_date)->in_units('days');
die if $days_since_epoch < 0;
my ( $year, $days ) = ( 1, $days_since_epoch );
while (1) {
my $year_length = 365 + ( is_republican_leap_year($year) ? 1 : 0 );
last if $days < $year_length;
$days -= $year_length;
$year += 1;
}
my $day0 = $days % 30;
my $month0 = ($days - $day0) / 30;
my ( $day1, $month1 ) = ( $day0 + 1, $month0 + 1 );
return $month1 == $i_cal_month
? "$intercalary[$day0 ] $year"
: "$day1 $month_names[$month0] $year";
}
while (<DATA>) {
s{\s*\#.+\n?\z}{};
/^(\d{4})-(\d{2})-(\d{2})\s+(\S.+?\S)\s*$/ or die;
my $g = DateTime->new( year => $1, month => $2, day => $3 );
my $r = $4;
die if Republican_to_Gregorian($r) != $g
or Gregorian_to_Republican($g) ne $r;
die if Gregorian_to_Republican(Republican_to_Gregorian($r)) ne $r
or Republican_to_Gregorian(Gregorian_to_Republican($g)) != $g;
}
say 'All tests successful.';
__DATA__
1792-09-22 1 Vendémiaire 1
1795-05-20 1 Prairial 3
1799-07-15 27 Messidor 7
1803-09-23 Fête de la Révolution 11
1805-12-31 10 Nivôse 14
1871-03-18 27 Ventôse 79
1944-08-25 7 Fructidor 152
2016-09-19 Fête du travail 224
1871-05-06 16 Floréal 79 # Paris Commune begins
1871-05-23 3 Prairial 79 # Paris Commune ends
1799-11-09 18 Brumaire 8 # Revolution ends by Napoléon coup
1804-12-02 11 Frimaire 13 # Republic ends by Napoléon coronation
1794-10-30 9 Brumaire 3 # École Normale Supérieure established
1794-07-27 9 Thermidor 2 # Robespierre falls
1799-05-27 8 Prairial 7 # Fromental Halévy born
1792-09-22 1 Vendémiaire 1
1793-09-22 1 Vendémiaire 2
1794-09-22 1 Vendémiaire 3
1795-09-23 1 Vendémiaire 4
1796-09-22 1 Vendémiaire 5
1797-09-22 1 Vendémiaire 6
1798-09-22 1 Vendémiaire 7
1799-09-23 1 Vendémiaire 8
1800-09-23 1 Vendémiaire 9
1801-09-23 1 Vendémiaire 10
1802-09-23 1 Vendémiaire 11
1803-09-24 1 Vendémiaire 12
1804-09-23 1 Vendémiaire 13
1805-09-23 1 Vendémiaire 14
1806-09-23 1 Vendémiaire 15
1807-09-24 1 Vendémiaire 16
1808-09-23 1 Vendémiaire 17
1809-09-23 1 Vendémiaire 18
1810-09-23 1 Vendémiaire 19
1811-09-24 1 Vendémiaire 20
2015-09-23 1 Vendémiaire 224
2016-09-22 1 Vendémiaire 225
2017-09-22 1 Vendémiaire 226
|
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.
|
#C.23
|
C#
|
using System;
using System.Collections.Generic;
static class program
{
static int n = 61;
static List<int> l = new List<int>() { 0, 1 };
static int fusc(int n)
{
if (n < l.Count) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.Add(f); return f;
}
static void Main(string[] args)
{
bool lst = true; int w = -1, c = 0, t;
string fs = "{0,11:n0} {1,-9:n0}", res = "";
Console.WriteLine("First {0} numbers in the fusc sequence:", n);
for (int i = 0; i < int.MaxValue; i++)
{
int f = fusc(i); if (lst)
{
if (i < 61) Console.Write("{0} ", f);
else
{
lst = false;
Console.WriteLine();
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:");
Console.WriteLine(fs, "Index\\", "/Value"); Console.WriteLine(res); res = "";
}
}
if ((t = f.ToString().Length) > w)
{
w = t; res += (res == "" ? "" : "\n") + string.Format(fs, i, f);
if (!lst) { Console.WriteLine(res); res = ""; } if (++c > 5) break;
}
}
l.Clear();
}
}
|
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.
|
#Nim
|
Nim
|
# naive function calling counter
# TODO consider a more sophisticated condition on counting function callings
# without parenthesis which are common in nim lang. Be aware that the AST of
# object accessor and procedure calling without parenthesis are same.
import macros, tables, strformat, os
proc visitCall(node: NimNode, table: CountTableRef) =
if node.kind == nnkCall:
if node[0].kind == nnkDotExpr:
table.inc($node[0][1])
visitCall(node[0][0], table)
else:
if node[0].kind == nnkBracketExpr:
if node[0][0].kind == nnkDotExpr:
table.inc($node[0][0][1])
visitCall(node[0][0][0], table)
return
else:
table.inc($node[0][0])
if len(node[0]) > 1:
for child in node[0][1..^1]:
visitCall(child, table)
elif node[0].kind == nnkPar:
visitCall(node[0], table)
else:
table.inc($node[0])
if len(node) > 1:
for child in node[1..^1]:
visitCall(child, table)
else:
for child in node.children():
visitCall(child, table)
static:
const code = staticRead(expandTilde(&"~/.choosenim/toolchains/nim-{NimVersion}/lib/system.nim"))
var
ast = parseStmt(code)
callCounts = newCountTable[string]()
ast.visitCall(callCounts)
sort(callCounts)
var total = 10
for ident, times in callCounts.pairs():
echo(&"{ident} called {times} times")
total-=1
if total == 0:
break
|
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.
|
#Perl
|
Perl
|
use PPI::Tokenizer;
my $Tokenizer = PPI::Tokenizer->new( '/path/to/your/script.pl' );
my %counts;
while (my $token = $Tokenizer->get_token) {
# We consider all Perl identifiers. The following regex is close enough.
if ($token =~ /\A[\$\@\%*[:alpha:]]/) {
$counts{$token}++;
}
}
my @desc_by_occurrence =
sort {$counts{$b} <=> $counts{$a} || $a cmp $b}
keys(%counts);
my @top_ten_by_occurrence = @desc_by_occurrence[0 .. 9];
foreach my $token (@top_ten_by_occurrence) {
print $counts{$token}, "\t", $token, "\n";
}
|
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.2B.2B
|
C++
|
#include <math.h>
#include <numbers>
#include <stdio.h>
#include <vector>
// Calculate the coefficients used by Spouge's approximation (based on the C
// implemetation)
std::vector<double> CalculateCoefficients(int numCoeff)
{
std::vector<double> c(numCoeff);
double k1_factrl = 1.0;
c[0] = sqrt(2.0 * std::numbers::pi);
for(size_t k=1; k < numCoeff; k++)
{
c[k] = exp(numCoeff-k) * pow(numCoeff-k, k-0.5) / k1_factrl;
k1_factrl *= -(double)k;
}
return c;
}
// The Spouge approximation
double Gamma(const std::vector<double>& coeffs, double x)
{
const size_t numCoeff = coeffs.size();
double accm = coeffs[0];
for(size_t k=1; k < numCoeff; k++)
{
accm += coeffs[k] / ( x + k );
}
accm *= exp(-(x+numCoeff)) * pow(x+numCoeff, x+0.5);
return accm/x;
}
int main()
{
// estimate the gamma function with 1, 4, and 10 coefficients
const auto coeff1 = CalculateCoefficients(1);
const auto coeff4 = CalculateCoefficients(4);
const auto coeff10 = CalculateCoefficients(10);
const auto inputs = std::vector<double>{
0.001, 0.01, 0.1, 0.5, 1.0,
1.461632145, // minimum of the gamma function
2, 2.5, 3, 4, 5, 6, 7, 8, 9, 10, 50, 100,
150 // causes overflow for this implemetation
};
printf("%16s%16s%16s%16s%16s\n", "gamma( x ) =", "Spouge 1", "Spouge 4", "Spouge 10", "built-in");
for(auto x : inputs)
{
printf("gamma(%7.3f) = %16.10g %16.10g %16.10g %16.10g\n",
x,
Gamma(coeff1, x),
Gamma(coeff4, x),
Gamma(coeff10, x),
std::tgamma(x)); // built-in gamma 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.
|
#Java
|
Java
|
import java.util.Random;
import java.util.List;
import java.util.ArrayList;
public class GaltonBox {
public static void main( final String[] args ) {
new GaltonBox( 8, 200 ).run();
}
private final int m_pinRows;
private final int m_startRow;
private final Position[] m_balls;
private final Random m_random = new Random();
public GaltonBox( final int pinRows, final int ballCount ) {
m_pinRows = pinRows;
m_startRow = pinRows + 1;
m_balls = new Position[ ballCount ];
for ( int ball = 0; ball < ballCount; ball++ )
m_balls[ ball ] = new Position( m_startRow, 0, 'o' );
}
private static class Position {
int m_row;
int m_col;
char m_char;
Position( final int row, final int col, final char ch ) {
m_row = row;
m_col = col;
m_char = ch;
}
}
public void run() {
for ( int ballsInPlay = m_balls.length; ballsInPlay > 0; ) {
ballsInPlay = dropBalls();
print();
}
}
private int dropBalls() {
int ballsInPlay = 0;
int ballToStart = -1;
// Pick a ball to start dropping
for ( int ball = 0; ball < m_balls.length; ball++ )
if ( m_balls[ ball ].m_row == m_startRow )
ballToStart = ball;
// Drop balls that are already in play
for ( int ball = 0; ball < m_balls.length; ball++ )
if ( ball == ballToStart ) {
m_balls[ ball ].m_row = m_pinRows;
ballsInPlay++;
}
else if ( m_balls[ ball ].m_row > 0 && m_balls[ ball ].m_row != m_startRow ) {
m_balls[ ball ].m_row -= 1;
m_balls[ ball ].m_col += m_random.nextInt( 2 );
if ( 0 != m_balls[ ball ].m_row )
ballsInPlay++;
}
return ballsInPlay;
}
private void print() {
for ( int row = m_startRow; row --> 1; ) {
for ( int ball = 0; ball < m_balls.length; ball++ )
if ( m_balls[ ball ].m_row == row )
printBall( m_balls[ ball ] );
System.out.println();
printPins( row );
}
printCollectors();
System.out.println();
}
private static void printBall( final Position pos ) {
for ( int col = pos.m_row + 1; col --> 0; )
System.out.print( ' ' );
for ( int col = 0; col < pos.m_col; col++ )
System.out.print( " " );
System.out.print( pos.m_char );
}
private void printPins( final int row ) {
for ( int col = row + 1; col --> 0; )
System.out.print( ' ' );
for ( int col = m_startRow - row; col --> 0; )
System.out.print( ". " );
System.out.println();
}
private void printCollectors() {
final List<List<Position>> collectors = new ArrayList<List<Position>>();
for ( int col = 0; col < m_startRow; col++ ) {
final List<Position> collector = new ArrayList<Position>();
collectors.add( collector );
for ( int ball = 0; ball < m_balls.length; ball++ )
if ( m_balls[ ball ].m_row == 0 && m_balls[ ball ].m_col == col )
collector.add( m_balls[ ball ] );
}
for ( int row = 0, rows = longest( collectors ); row < rows; row++ ) {
for ( int col = 0; col < m_startRow; col++ ) {
final List<Position> collector = collectors.get( col );
final int pos = row + collector.size() - rows;
System.out.print( '|' );
if ( pos >= 0 )
System.out.print( collector.get( pos ).m_char );
else
System.out.print( ' ' );
}
System.out.println( '|' );
}
}
private static final int longest( final List<List<Position>> collectors ) {
int result = 0;
for ( final List<Position> collector : collectors )
result = Math.max( collector.size(), result );
return result;
}
}
|
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
|
#Haskell
|
Haskell
|
{-# LANGUAGE NumericUnderscores #-}
gapful :: Int -> Bool
gapful n = n `rem` firstLastDigit == 0
where
firstLastDigit = read [head asDigits, last asDigits]
asDigits = show n
main :: IO ()
main = do
putStrLn $ "\nFirst 30 Gapful numbers >= 100 :\n" ++ r 30 [100,101..]
putStrLn $ "\nFirst 15 Gapful numbers >= 1,000,000 :\n" ++ r 15 [1_000_000,1_000_001..]
putStrLn $ "\nFirst 10 Gapful numbers >= 1,000,000,000 :\n" ++ r 10 [1_000_000_000,1_000_000_001..]
where r n = show . take n . filter gapful
|
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
|
#Java
|
Java
|
import java.util.Locale;
public class GaussianElimination {
public static double solve(double[][] a, double[][] b) {
if (a == null || b == null || a.length == 0 || b.length == 0) {
throw new IllegalArgumentException("Invalid dimensions");
}
int n = b.length, p = b[0].length;
if (a.length != n || a[0].length != n) {
throw new IllegalArgumentException("Invalid dimensions");
}
double det = 1.0;
for (int i = 0; i < n - 1; i++) {
int k = i;
for (int j = i + 1; j < n; j++) {
if (Math.abs(a[j][i]) > Math.abs(a[k][i])) {
k = j;
}
}
if (k != i) {
det = -det;
for (int j = i; j < n; j++) {
double s = a[i][j];
a[i][j] = a[k][j];
a[k][j] = s;
}
for (int j = 0; j < p; j++) {
double s = b[i][j];
b[i][j] = b[k][j];
b[k][j] = s;
}
}
for (int j = i + 1; j < n; j++) {
double s = a[j][i] / a[i][i];
for (k = i + 1; k < n; k++) {
a[j][k] -= s * a[i][k];
}
for (k = 0; k < p; k++) {
b[j][k] -= s * b[i][k];
}
}
}
for (int i = n - 1; i >= 0; i--) {
for (int j = i + 1; j < n; j++) {
double s = a[i][j];
for (int k = 0; k < p; k++) {
b[i][k] -= s * b[j][k];
}
}
double s = a[i][i];
det *= s;
for (int k = 0; k < p; k++) {
b[i][k] /= s;
}
}
return det;
}
public static void main(String[] args) {
double[][] a = new double[][] {{4.0, 1.0, 0.0, 0.0, 0.0},
{1.0, 4.0, 1.0, 0.0, 0.0},
{0.0, 1.0, 4.0, 1.0, 0.0},
{0.0, 0.0, 1.0, 4.0, 1.0},
{0.0, 0.0, 0.0, 1.0, 4.0}};
double[][] b = new double[][] {{1.0 / 2.0},
{2.0 / 3.0},
{3.0 / 4.0},
{4.0 / 5.0},
{5.0 / 6.0}};
double[] x = {39.0 / 400.0,
11.0 / 100.0,
31.0 / 240.0,
37.0 / 300.0,
71.0 / 400.0};
System.out.println("det: " + solve(a, b));
for (int i = 0; i < 5; i++) {
System.out.printf(Locale.US, "%12.8f %12.4e\n", b[i][0], b[i][0] - x[i]);
}
}
}
|
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.
|
#Perl
|
Perl
|
sub rref {
our @m; local *m = shift;
@m or return;
my ($lead, $rows, $cols) = (0, scalar(@m), scalar(@{$m[0]}));
foreach my $r (0 .. $rows - 1) {
$lead < $cols or return;
my $i = $r;
until ($m[$i][$lead])
{++$i == $rows or next;
$i = $r;
++$lead == $cols and return;}
@m[$i, $r] = @m[$r, $i];
my $lv = $m[$r][$lead];
$_ /= $lv foreach @{ $m[$r] };
my @mr = @{ $m[$r] };
foreach my $i (0 .. $rows - 1)
{$i == $r and next;
($lv, my $n) = ($m[$i][$lead], -1);
$_ -= $lv * $mr[++$n] foreach @{ $m[$i] };}
++$lead;}
}
sub display { join("\n" => map join(" " => map(sprintf("%6.2f", $_), @$_)), @{+shift})."\n" }
sub gauss_jordan_invert {
my(@m) = @_;
my $rows = @m;
my @i = identity(scalar @m);
push @{$m[$_]}, @{$i[$_]} for 0..$rows-1;
rref(\@m);
map { splice @$_, 0, $rows } @m;
@m;
}
sub identity {
my($n) = @_;
map { [ (0) x $_, 1, (0) x ($n-1 - $_) ] } 0..$n-1
}
my @tests = (
[
[ 2, -1, 0 ],
[-1, 2, -1 ],
[ 0, -1, 2 ]
],
[
[ -1, -2, 3, 2 ],
[ -4, -1, 6, 2 ],
[ 7, -8, 9, 1 ],
[ 1, -2, 1, 3 ]
],
);
for my $matrix (@tests) {
print "Original Matrix:\n" . display(\@$matrix) . "\n";
my @gj = gauss_jordan_invert( @$matrix );
print "Gauss-Jordan Inverted Matrix:\n" . display(\@gj) . "\n";
my @rt = gauss_jordan_invert( @gj );
print "After round-trip:\n" . display(\@rt) . "\n";} . "\n"
}
|
http://rosettacode.org/wiki/General_FizzBuzz
|
General FizzBuzz
|
Task
Write a generalized version of FizzBuzz that works for any list of factors, along with their words.
This is basically a "fizzbuzz" implementation where the user supplies the parameters.
The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be printed.
For simplicity's sake, assume the user will input an integer as the max number and 3 factors, each with a word associated with them.
For example, given:
>20 #This is the maximum number, supplied by the user
>3 Fizz #The user now enters the starting factor (3) and the word they want associated with it (Fizz)
>5 Buzz #The user now enters the next factor (5) and the word they want associated with it (Buzz)
>7 Baxx #The user now enters the next factor (7) and the word they want associated with it (Baxx)
In other words: For this example, print the numbers 1 through 20, replacing every multiple of 3 with "Fizz", every multiple of 5 with "Buzz", and every multiple of 7 with "Baxx".
In the case where a number is a multiple of at least two factors, print each of the words associated with those factors in the order of least to greatest factor.
For instance, the number 15 is a multiple of both 3 and 5; print "FizzBuzz".
If the max number was 105 instead of 20, you would print "FizzBuzzBaxx" because it's a multiple of 3, 5, and 7.
Output:
1
2
Fizz
4
Buzz
Fizz
Baxx
8
Fizz
Buzz
11
Fizz
13
Baxx
FizzBuzz
16
17
Fizz
19
Buzz
|
#MiniScript
|
MiniScript
|
factorWords = {}
maxNr = val(input("Max number? "))
while true
factorInput = input("Factor? ")
if factorInput == "" then break
// Split input
parts = factorInput.split(" ")
factor = val(parts[0])
word = parts[1]
// Assign factor/word
factorWords[factor] = word
end while
for nr in range(1,maxNr)
matchingWords = ""
for factor in factorWords.indexes
if nr % factor == 0 then
matchingWords = matchingWords + factorWords[factor]
end if
end for
if matchingWords then print matchingWords else print nr
end for
|
http://rosettacode.org/wiki/General_FizzBuzz
|
General FizzBuzz
|
Task
Write a generalized version of FizzBuzz that works for any list of factors, along with their words.
This is basically a "fizzbuzz" implementation where the user supplies the parameters.
The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be printed.
For simplicity's sake, assume the user will input an integer as the max number and 3 factors, each with a word associated with them.
For example, given:
>20 #This is the maximum number, supplied by the user
>3 Fizz #The user now enters the starting factor (3) and the word they want associated with it (Fizz)
>5 Buzz #The user now enters the next factor (5) and the word they want associated with it (Buzz)
>7 Baxx #The user now enters the next factor (7) and the word they want associated with it (Baxx)
In other words: For this example, print the numbers 1 through 20, replacing every multiple of 3 with "Fizz", every multiple of 5 with "Buzz", and every multiple of 7 with "Baxx".
In the case where a number is a multiple of at least two factors, print each of the words associated with those factors in the order of least to greatest factor.
For instance, the number 15 is a multiple of both 3 and 5; print "FizzBuzz".
If the max number was 105 instead of 20, you would print "FizzBuzzBaxx" because it's a multiple of 3, 5, and 7.
Output:
1
2
Fizz
4
Buzz
Fizz
Baxx
8
Fizz
Buzz
11
Fizz
13
Baxx
FizzBuzz
16
17
Fizz
19
Buzz
|
#Modula-2
|
Modula-2
|
MODULE GeneralFizzBuzz;
FROM Conversions IMPORT StrToInt;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT Write,WriteString,WriteLn,ReadChar;
TYPE
Word = ARRAY[0..63] OF CHAR;
PROCEDURE WriteInt(i : INTEGER);
VAR buf : Word;
BEGIN
FormatString("%i", buf, i);
WriteString(buf);
END WriteInt;
PROCEDURE ReadInt() : INTEGER;
VAR
buf : ARRAY[0..9] OF CHAR;
c : CHAR;
i : INTEGER;
BEGIN
i := 0;
LOOP
c := ReadChar();
IF (c=0C) OR (i>9) THEN
BREAK
ELSIF (c=012C) OR (c=015C) THEN
WriteLn;
buf[i] := 0C;
BREAK
ELSIF (c<'0') OR (c>'9') THEN
Write(c);
buf[i] := 0C;
BREAK
ELSE
Write(c);
buf[i] := c;
INC(i)
END
END;
StrToInt(buf, i);
RETURN i
END ReadInt;
PROCEDURE ReadLine() : Word;
VAR
buf : Word;
i : INTEGER;
c : CHAR;
BEGIN
i := 0;
WHILE i<HIGH(buf) DO
c := ReadChar();
IF (c=0C) OR (c=012C) OR (c=015C) THEN
WriteLn;
buf[i] := 0C;
BREAK
ELSE
Write(c);
buf[i] := c;
INC(i)
END
END;
RETURN buf;
END ReadLine;
VAR
i,max : INTEGER;
fa,fb,fc : INTEGER;
wa,wb,wc : Word;
done : BOOLEAN;
BEGIN
max := ReadInt();
fa := ReadInt();
wa := ReadLine();
fb := ReadInt();
wb := ReadLine();
fc := ReadInt();
wc := ReadLine();
FOR i:=1 TO max DO
done := FALSE;
IF i MOD fa = 0 THEN
done := TRUE;
WriteString(wa);
END;
IF i MOD fb = 0 THEN
done := TRUE;
WriteString(wb);
END;
IF i MOD fc = 0 THEN
done := TRUE;
WriteString(wc);
END;
IF NOT done THEN
WriteInt(i)
END;
WriteLn;
END;
ReadChar
END GeneralFizzBuzz.
|
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
|
#F.23
|
F#
|
let lower = ['a'..'z']
printfn "%A" lower
|
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
|
#Factor
|
Factor
|
USING: spelling ; ! ALPHABET
ALPHABET print
0x61 0x7A [a,b] >string print
: russian-alphabet-without-io ( -- str ) 0x0430 0x0450 [a,b) >string ;
: russian-alphabet ( -- str ) 0x0451 6 russian-alphabet-without-io insert-nth ;
russian-alphabet print
|
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
|
#Openscad
|
Openscad
|
echo("Hello world!"); // writes to the console
text("Hello world!"); // creates 2D text in the object space
linear_extrude(height=10) text("Hello world!"); // creates 3D text in the object space
|
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
|
#Nim
|
Nim
|
type Iterator = iterator(): int
proc `^`*(base: Natural; exp: Natural): int =
var (base, exp) = (base, exp)
result = 1
while exp != 0:
if (exp and 1) != 0:
result *= base
exp = exp shr 1
base *= base
proc next(s: Iterator): int =
for n in s(): return n
proc powers(m: Natural): Iterator =
iterator it(): int {.closure.} =
for n in 0 ..< int.high:
yield n ^ m
result = it
iterator filtered(s1, s2: Iterator): int =
var v = next(s1)
var f = next(s2)
while true:
if v > f:
f = next(s2)
continue
elif v < f:
yield v
v = next(s1)
var
squares = powers(2)
cubes = powers(3)
i = 1
for x in filtered(squares, cubes):
if i > 20: echo x
if i >= 30: break
inc i
|
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.
|
#Ruby
|
Ruby
|
pieces = %i(♔ ♕ ♘ ♘ ♗ ♗ ♖ ♖)
regexes = [/♗(..)*♗/, /♖.*♔.*♖/]
row = pieces.shuffle.join until regexes.all?{|re| re.match(row)}
puts row
|
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.
|
#Rust
|
Rust
|
use std::collections::BTreeSet;
struct Chess960 ( BTreeSet<String> );
impl Chess960 {
fn invoke(&mut self, b: &str, e: &str) {
if e.len() <= 1 {
let s = b.to_string() + e;
if Chess960::is_valid(&s) { self.0.insert(s); }
} else {
for (i, c) in e.char_indices() {
let mut b = b.to_string();
b.push(c);
let mut e = e.to_string();
e.remove(i);
self.invoke(&b, &e);
}
}
}
fn is_valid(s: &str) -> bool {
let k = s.find('K').unwrap();
k > s.find('R').unwrap() && k < s.rfind('R').unwrap() && s.find('B').unwrap() % 2 != s.rfind('B').unwrap() % 2
}
}
// Program entry point.
fn main() {
let mut chess960 = Chess960(BTreeSet::new());
chess960.invoke("", "KQRRNNBB");
for (i, p) in chess960.0.iter().enumerate() {
println!("{}: {}", i, p);
}
}
|
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.
|
#AutoHotkey
|
AutoHotkey
|
MsgBox % compose("sin","cos",1.5)
compose(f,g,x) { ; function composition
Return %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.
|
#BBC_BASIC
|
BBC BASIC
|
REM Create some functions for testing:
DEF FNsqr(a) = SQR(a)
DEF FNabs(a) = ABS(a)
REM Create the function composition:
SqrAbs = FNcompose(FNsqr(), FNabs())
REM Test calling the composition:
x = -2 : PRINT ; x, FN(SqrAbs)(x)
END
DEF FNcompose(RETURN f%, RETURN g%)
LOCAL f$, p% : DIM p% 7 : p%!0 = f% : p%!4 = g%
f$ = "(x)=" + CHR$&A4 + "(&" + STR$~p% + ")(" + \
\ CHR$&A4 + "(&" + STR$~(p%+4) + ")(x))"
DIM p% LEN(f$) + 4 : $(p%+4) = f$ : !p% = p%+4
= p%
|
http://rosettacode.org/wiki/Fractal_tree
|
Fractal tree
|
Generate and draw a fractal tree.
Draw the trunk
At the end of the trunk, split by some angle and draw two branches
Repeat at the end of each branch until a sufficient level of branching is reached
Related tasks
Pythagoras Tree
|
#Action.21
|
Action!
|
DEFINE MAXSIZE="12"
INT ARRAY SinTab=[
0 4 9 13 18 22 27 31 36 40 44 49 53 58 62 66 71 75 79 83
88 92 96 100 104 108 112 116 120 124 128 132 136 139 143
147 150 154 158 161 165 168 171 175 178 181 184 187 190
193 196 199 202 204 207 210 212 215 217 219 222 224 226
228 230 232 234 236 237 239 241 242 243 245 246 247 248
249 250 251 252 253 254 254 255 255 255 256 256 256 256]
INT ARRAY xStack(MAXSIZE),yStack(MAXSIZE),angleStack(MAXSIZE)
BYTE ARRAY lenStack(MAXSIZE),dirStack(MAXSIZE)
BYTE stacksize=[0]
INT FUNC Sin(INT a)
WHILE a<0 DO a==+360 OD
WHILE a>360 DO a==-360 OD
IF a<=90 THEN
RETURN (SinTab(a))
ELSEIF a<=180 THEN
RETURN (SinTab(180-a))
ELSEIF a<=270 THEN
RETURN (-SinTab(a-180))
ELSE
RETURN (-SinTab(360-a))
FI
RETURN (0)
INT FUNC Cos(INT a)
RETURN (Sin(a-90))
BYTE FUNC IsEmpty()
IF stacksize=0 THEN
RETURN (1)
FI
RETURN (0)
BYTE FUNC IsFull()
IF stacksize=MAXSIZE THEN
RETURN (1)
FI
RETURN (0)
PROC Push(INT x,y,angle BYTE len,dir)
IF IsFull() THEN Break() FI
xStack(stacksize)=x yStack(stacksize)=y
angleStack(stacksize)=angle lenStack(stacksize)=len
dirStack(stacksize)=dir
stacksize==+1
RETURN
PROC Pop(INT POINTER x,y,angle BYTE POINTER len,dir)
IF IsEmpty() THEN Break() FI
stacksize==-1
x^=xStack(stacksize) y^=yStack(stacksize)
angle^=angleStack(stacksize) len^=lenStack(stacksize)
dir^=dirStack(stacksize)
RETURN
PROC DrawTree(INT x,y,len,angle,leftAngle,rightAngle)
BYTE depth,dir
Plot(x,y)
x==+Cos(angle)*len/256
y==-Sin(angle)*len/256
DrawTo(x,y)
Push(x,y,angle,len,0)
WHILE IsEmpty()=0
DO
Pop(@x,@y,@angle,@len,@dir)
IF dir<2 THEN
Push(x,y,angle,len,dir+1)
IF dir=0 THEN
angle==-leftAngle
ELSE
angle==+rightAngle
FI
len=13*len/16
Plot(x,y)
x==+Cos(angle)*len/256
y==-Sin(angle)*len/256
DrawTo(x,y)
IF IsFull()=0 THEN
Push(x,y,angle,len,0)
FI
FI
OD
RETURN
PROC Main()
BYTE CH=$02FC,COLOR1=$02C5,COLOR2=$02C6
Graphics(8+16)
Color=1
COLOR1=$BA
COLOR2=$B2
DrawTree(140,191,40,110,35,15)
DO UNTIL CH#$FF OD
CH=$FF
RETURN
|
http://rosettacode.org/wiki/Fractal_tree
|
Fractal tree
|
Generate and draw a fractal tree.
Draw the trunk
At the end of the trunk, split by some angle and draw two branches
Repeat at the end of each branch until a sufficient level of branching is reached
Related tasks
Pythagoras Tree
|
#Ada
|
Ada
|
with Ada.Numerics.Elementary_Functions;
with SDL.Video.Windows.Makers;
with SDL.Video.Renderers.Makers;
with SDL.Video.Rectangles;
with SDL.Events.Events;
procedure Fractal_Tree is
Width : constant := 600;
Height : constant := 600;
Level : constant := 13;
Length : constant := 130.0;
X_Start : constant := 475.0;
Y_Start : constant := 580.0;
A_Start : constant := -1.54;
Angle_1 : constant := 0.10;
Angle_2 : constant := 0.35;
C_1 : constant := 0.71;
C_2 : constant := 0.87;
Window : SDL.Video.Windows.Window;
Renderer : SDL.Video.Renderers.Renderer;
Event : SDL.Events.Events.Events;
procedure Draw_Tree (Level : in Natural;
Length : in Float;
Angle : in Float;
X, Y : in Float)
is
use SDL;
use Ada.Numerics.Elementary_Functions;
Pi : constant := Ada.Numerics.Pi;
X_2 : constant Float := X + Length * Cos (Angle, 2.0 * Pi);
Y_2 : constant Float := Y + Length * Sin (Angle, 2.0 * Pi);
Line : constant SDL.Video.Rectangles.Line_Segment
:= ((C.int (X), C.int (Y)), (C.int (X_2), C.int (Y_2)));
begin
if Level > 0 then
Renderer.Set_Draw_Colour (Colour => (0, 220, 0, 255));
Renderer.Draw (Line => Line);
Draw_Tree (Level - 1, C_1 * Length, Angle + Angle_1, X_2, Y_2);
Draw_Tree (Level - 1, C_2 * Length, Angle - Angle_2, X_2, Y_2);
end if;
end Draw_Tree;
procedure Wait is
use type SDL.Events.Event_Types;
begin
loop
while SDL.Events.Events.Poll (Event) loop
if Event.Common.Event_Type = SDL.Events.Quit then
return;
end if;
end loop;
delay 0.100;
end loop;
end Wait;
begin
if not SDL.Initialise (Flags => SDL.Enable_Screen) then
return;
end if;
SDL.Video.Windows.Makers.Create (Win => Window,
Title => "Fractal tree",
Position => SDL.Natural_Coordinates'(X => 10, Y => 10),
Size => SDL.Positive_Sizes'(Width, Height),
Flags => 0);
SDL.Video.Renderers.Makers.Create (Renderer, Window.Get_Surface);
Renderer.Set_Draw_Colour ((0, 0, 0, 255));
Renderer.Fill (Rectangle => (0, 0, Width, Height));
Draw_Tree (Level, Length, A_Start, X_Start, Y_Start);
Window.Update_Surface;
Wait;
Window.Finalize;
SDL.Finalise;
end Fractal_Tree;
|
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.
|
#ALGOL_68
|
ALGOL 68
|
# as the numbers required for finding the first 20 primes are quite large, #
# we use Algol 68G's LONG LONG INT with a precision of 100 digits #
PR precision 100 PR
# mode to hold fractions #
MODE FRACTION = STRUCT( INT numerator, INT denominator );
# define / between two INTs to yield a FRACTION #
OP / = ( INT a, b )FRACTION: ( a, b );
# mode to define a FRACTRAN progam #
MODE FRACTRAN = STRUCT( FLEX[0]FRACTION data
, LONG LONG INT n
, BOOL halted
);
# prepares a FRACTRAN program for use - sets the initial value of n and halted to FALSE #
PRIO STARTAT = 1;
OP STARTAT = ( REF FRACTRAN f, INT start )REF FRACTRAN:
BEGIN
halted OF f := FALSE;
n OF f := start;
f
END;
# sets n OF f to the next number in the sequence or sets halted OF f to TRUE if the sequence has ended #
OP NEXT = ( REF FRACTRAN f )LONG LONG INT:
IF halted OF f
THEN n OF f := 0
ELSE
BOOL found := FALSE;
LONG LONG INT result := 0;
FOR pos FROM LWB data OF f TO UPB data OF f WHILE NOT found DO
LONG LONG INT value = n OF f * numerator OF ( ( data OF f )[ pos ] );
INT denominator = denominator OF ( ( data OF f )[ pos ] );
IF found := ( value MOD denominator = 0 ) THEN result := value OVER denominator FI
OD;
IF NOT found THEN halted OF f := TRUE FI;
n OF f := result
FI ;
# generate and print the sequence of numbers from a FRACTRAN pogram #
PROC print fractran sequence = ( REF FRACTRAN f, INT start, INT limit )VOID:
BEGIN
VOID( f STARTAT start );
print( ( "0: ", whole( start, 0 ) ) );
FOR i TO limit
WHILE VOID( NEXT f );
NOT halted OF f
DO
print( ( " " + whole( i, 0 ) + ": " + whole( n OF f, 0 ) ) )
OD;
print( ( newline ) )
END ;
# print the first 16 elements from the primes FRACTRAN program #
FRACTRAN pf := ( ( 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 ), 0, FALSE );
print fractran sequence( pf, 2, 15 );
# find some primes using the pf FRACTRAN progam - n is prime for the members in the sequence that are 2^n #
INT primes found := 0;
VOID( pf STARTAT 2 );
INT pos := 0;
print( ( "seq position prime sequence value", newline ) );
WHILE primes found < 20 AND NOT halted OF pf DO
LONG LONG INT value := NEXT pf;
INT power of 2 := 0;
pos +:= 1;
WHILE value MOD 2 = 0 AND value > 0 DO power of 2 PLUSAB 1; value OVERAB 2 OD;
IF value = 1 THEN
# found a prime #
primes found +:= 1;
print( ( whole( pos, -12 ) + " " + whole( power of 2, -6 ) + " (" + whole( n OF pf, 0 ) + ")", newline ) )
FI
OD
|
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.
|
#Julia
|
Julia
|
using FTPClient
ftp = FTP(hostname = "ftp.ed.ac.uk", username = "anonymous")
cd(ftp, "pub/courses")
println(readdir(ftp))
bytes = read(download(ftp, "make.notes.tar"))
close(ftp)
|
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.
|
#Kotlin
|
Kotlin
|
headers = /usr/include/ftplib.h
linkerOpts.linux = -L/usr/lib -lftp
---
#include <sys/time.h>
struct NetBuf {
char *cput,*cget;
int handle;
int cavail,cleft;
char *buf;
int dir;
netbuf *ctrl;
netbuf *data;
int cmode;
struct timeval idletime;
FtpCallback idlecb;
void *idlearg;
int xfered;
int cbbytes;
int xfered1;
char response[256];
};
|
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.
|
#Lingo
|
Lingo
|
CURLOPT_URL = 10002
ch = xtra("Curl").new()
url = "ftp://domain.com"
-- change to remote dir "/foo/bar/"
put "/foo/bar/" after url
ch.setOption(CURLOPT_URL, url)
res = ch.exec(1)
-- print raw FTP listing as string
put res.readRawString(res.length)
-- download file "download.mp3" (passive mode is the internal default behavior)
filename = "download.mp3"
ch.setOption(CURLOPT_URL, url & filename)
ch.setDestinationFile(_movie.path & filename)
res = ch.exec()
|
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.
|
#LiveCode
|
LiveCode
|
libURLSetFTPMode "passive" --default is passive anyway
put url "ftp://ftp.hq.nasa.gov/" into listing
repeat for each line ftpln in listing
set itemdel to space
if the first char of (the first item of ftpln) is "d" then
-- is a directory
put the last item of ftpln after dirlist
else
put the last item of ftpln after filelist
end if
end repeat
put listing //(subset)
// -rw-r--r-- 1 ftpadmin ftp-adm 3997 May 26 1998 README
// drwxrwsr-x 17 ftpadmin ftp-adm 4096 Sep 10 16:08 pub
put dirlist
// armd
// chmgt
// incoming
// lost+found
// office
// pub
put filelist
// README
// ftp-exec
// index.html
// robots.txt
-- downloading a file (upload is same, but use put)
-- you don't have to cd manually
-- file up/down transfer is binary in livecode (always enforced by livecode)
put URL "ftp://ftp.hq.nasa.gov/pub/robots.txt" into URL "file:myFile.txt"
You can execute any ftp command using the libURLftpCommand command
e.g. to know the working directory, issue "pwd", we could issue "list" for above too,
but using an url with slash on the end with the ftp protocol causes a dir listing by default.
put libURLftpCommand("PWD",ftp.example.org)
|
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.
|
#PARI.2FGP
|
PARI/GP
|
long
foo(GEN a, GEN b)
|
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.
|
#Perl
|
Perl
|
sub noargs(); # Declare a function with no arguments
sub twoargs($$); # Declare a function with two scalar arguments. The two sigils act as argument type placeholders
sub noargs :prototype(); # Using the :attribute syntax instead
sub twoargs :prototype($$);
|
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.
|
#Phix
|
Phix
|
forward function noargs() -- Declare a function with no arguments
forward procedure twoargs(integer a, integer b) -- Declare a procedure with two arguments
forward procedure twoargs(integer, integer /*b*/) -- Parameter names are optional in forward (and actual) definitions
forward function anyargs(sequence s) -- varargs are [best/often] handled as a (single) sequence in Phix
forward function atleastonearg(integer a, integer b=1, ...); -- Default makes args optional (== actual defn)
|
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
|
#AArch64_Assembly
|
AArch64 Assembly
|
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program functMul64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/***********************/
/* Initialized data */
/***********************/
.data
szRetourLigne: .asciz "\n"
szMessResult: .asciz "Resultat : @ \n" // message result
/***********************
/* No Initialized data */
/***********************/
.bss
sZoneConv: .skip 24
.text
.global main
main:
// function multiply
mov x0,8
mov x1,50
bl multiply // call function
ldr x1,qAdrsZoneConv
bl conversion10S // call function with 2 parameter (x0,x1)
ldr x0,qAdrszMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess // display message
mov x0,0 // return code
100: // end of program
mov x8,EXIT // request to exit program
svc 0 // perform the system call
qAdrsZoneConv: .quad sZoneConv
qAdrszMessResult: .quad szMessResult
/******************************************************************/
/* Function multiply */
/******************************************************************/
/* x0 contains value 1 */
/* x1 contains value 2 */
/* x0 return résult */
multiply:
mul x0,x1,x0
ret // return function
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
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
|
#Phix
|
Phix
|
with javascript_semantics
constant gregorians = {"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"},
gregorian = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
republicans = {"Vendémiaire", "Brumaire", "Frimaire", "Nivôse", "Pluviôse",
"Ventôse", "Germinal", "Floréal", "Prairial", "Messidor",
"Thermidor", "Fructidor"},
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"}
function rep_leap(integer year)
return mod(year+1,4)==0 and (mod(year+1,100)!=0 or mod(year+1,400)==0)
end function
function rep_to_day(sequence dmy)
integer {d, m, y} = dmy
if m == 13 then
m -= 1
d += 30
end if
if rep_leap(y) then
d -= 1
end if
integer res = 365*(y-1) + floor((y+1)/4) - floor((y+1)/100) + floor((y+1)/400) + 30*(m-1) + d
return res
end function
function gre_leap(integer year)
return mod(year,4)==0 and (mod(year,100)!=0 or mod(year,400)==0)
end function
function gre_to_day(sequence dmy)
integer {d, m, y} = dmy
if m < 3 then
y -= 1
m += 12
end if
integer res = floor(y*365.25) - floor(y/100) + floor(y/400)
+ floor(30.6*(m+1)) + d - 654842
return res
end function
function day_to_rep(integer day)
integer y = floor((day-1)/365.25)
if not rep_leap(y) then
y += 1
end if
integer d = day - floor(y*365.25) + 365 + floor(y/100) - floor(y/400),
m = 1,
sansculottide = 5+rep_leap(y)
while d>30 do
d -= 30
m += 1
if m == 13 then
if d > sansculottide then
d -= sansculottide
m = 1
y += 1
sansculottide = 5 + rep_leap(y)
end if
end if
end while
return {d,m,y}
end function
function day_to_gre(integer day)
integer y = floor(day/365.25),
d = day - floor(y*365.25) + 21,
m = 9
y += 1792
d += floor(y/100) - floor(y/400) - 13
sequence gregoriam = deep_copy(gregorian) -- (modifiable copy)
while d>gregoriam[m] do
d -= gregoriam[m]
m += 1
if m == 13 then
m = 1
y += 1
gregoriam[2] = 28 + gre_leap(y)
end if
end while
return {d,m,y}
end function
function greg_to_frep(string greg)
{integer day, string months, integer year} = scanf(greg,"%d %s %d")[1]
integer month = find(months,gregorians)
{day,month,year} = day_to_rep(gre_to_day({day,month,year}))
string frep = iff(month=13?sprintf("%s %d",{sansculottides[day], year})
:sprintf("%d %s %d",{day, republicans[month], year}))
return frep
end function
function frep_to_greg(string frep)
integer day, month, year
string months, days
if frep[1]<='9' then
{day, months, year} = scanf(frep,"%d %s %d")[1]
month = find(months,republicans)
else
{days, year} = scanf(frep,"%s %d")[1]
day = find(days,sansculottides)
month = 13
end if
{day,month,year} = day_to_gre(rep_to_day({day, month, year}))
string greg = sprintf("%02d %s %d",{day, gregorians[month], year})
return greg
end function
constant test_data = {
{ "22 September 1792", "1 Vendémiaire 1" },
{ "20 May 1795", "1 Prairial 3" },
{ "15 July 1799", "27 Messidor 7" },
{ "23 September 1803", "Fête de la Révolution 11" },
{ "31 December 1805", "10 Nivôse 14" },
{ "18 March 1871", "27 Ventôse 79" },
{ "25 August 1944", "7 Fructidor 152" },
{ "19 September 2016", "Fête du travail 224" },
{ "06 May 1871", "16 Floréal 79" }, -- Paris Commune begins
{ "23 May 1871", "3 Prairial 79" }, -- Paris Commune ends
{ "09 November 1799", "18 Brumaire 8" }, -- Revolution ends by Napoléon coup
{ "02 December 1804", "11 Frimaire 13" }, -- Republic ends by Napoléon coronation
{ "30 October 1794", "9 Brumaire 3" }, -- École Normale Supérieure established
{ "27 July 1794", "9 Thermidor 2" }, -- Robespierre falls
{ "27 May 1799", "8 Prairial 7" }, -- Fromental Halévy born
{ "22 September 1792", "1 Vendémiaire 1" },
{ "22 September 1793", "1 Vendémiaire 2" },
{ "22 September 1794", "1 Vendémiaire 3" },
{ "23 September 1795", "1 Vendémiaire 4" },
{ "22 September 1796", "1 Vendémiaire 5" },
{ "22 September 1797", "1 Vendémiaire 6" },
{ "22 September 1798", "1 Vendémiaire 7" },
{ "23 September 1799", "1 Vendémiaire 8" },
{ "23 September 1800", "1 Vendémiaire 9" },
{ "23 September 1801", "1 Vendémiaire 10" },
{ "23 September 1802", "1 Vendémiaire 11" },
{ "24 September 1803", "1 Vendémiaire 12" },
{ "23 September 1804", "1 Vendémiaire 13" },
{ "23 September 1805", "1 Vendémiaire 14" },
{ "23 September 1806", "1 Vendémiaire 15" },
{ "24 September 1807", "1 Vendémiaire 16" },
{ "23 September 1808", "1 Vendémiaire 17" },
{ "23 September 1809", "1 Vendémiaire 18" },
{ "23 September 1810", "1 Vendémiaire 19" },
{ "24 September 1811", "1 Vendémiaire 20" },
{ "23 September 2015", "1 Vendémiaire 224" },
{ "21 September 2016", "Fête des récompenses 224" },
{ "22 September 2016", "1 Vendémiaire 225" },
{ "23 September 2016", "2 Vendémiaire 225" },
{ "22 September 2017", "1 Vendémiaire 226" },
{ "28 September 2017", "7 Vendémiaire 226" } }
for i=1 to length(test_data) do
string {greg, frep} = test_data[i],
frep2 = greg_to_frep(greg),
greg2 = frep_to_greg(frep),
ok = iff(frep=frep2 and greg=greg2?"ok":"**** ERROR ****")
if platform()=WINDOWS then
-- the windows console does not handle
-- non-basic-latin-ascii characters well...
frep = substitute_all(frep,"éêéô","eeeo")
end if
printf(1,"%18s <==> %-25s %s\n",{greg,frep,ok})
end for
--sanity test:
for i=1 to 150000 do -- (years 1792..~2203)
if rep_to_day(day_to_rep(i))!=i then ?9/0 end if
if gre_to_day(day_to_gre(i))!=i then ?9/0 end if
end for
|
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.
|
#C.2B.2B
|
C++
|
#include <iomanip>
#include <iostream>
#include <limits>
#include <sstream>
#include <vector>
const int n = 61;
std::vector<int> l{ 0, 1 };
int fusc(int n) {
if (n < l.size()) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.push_back(f);
return f;
}
int main() {
bool lst = true;
int w = -1;
int c = 0;
int t;
std::string res;
std::cout << "First " << n << " numbers in the fusc sequence:\n";
for (int i = 0; i < INT32_MAX; i++) {
int f = fusc(i);
if (lst) {
if (i < 61) {
std::cout << f << ' ';
} else {
lst = false;
std::cout << "\nPoints in the sequence where an item has more digits than any previous items:\n";
std::cout << std::setw(11) << "Index\\" << " " << std::left << std::setw(9) << "/Value\n";
std::cout << res << '\n';
res = "";
}
}
std::stringstream ss;
ss << f;
t = ss.str().length();
ss.str("");
ss.clear();
if (t > w) {
w = t;
res += (res == "" ? "" : "\n");
ss << std::setw(11) << i << " " << std::left << std::setw(9) << f;
res += ss.str();
if (!lst) {
std::cout << res << '\n';
res = "";
}
if (++c > 5) {
break;
}
}
}
return 0;
}
|
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.
|
#Phix
|
Phix
|
else -- rType=FUNC|TYPE
log_function_call(rtnNo)
|
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.
|
#PicoLisp
|
PicoLisp
|
(let Freq NIL
(for "L" (filter pair (extract getd (all)))
(for "F"
(filter atom
(fish '((X) (or (circ? X) (getd X)))
"L" ) )
(accu 'Freq "F" 1) ) )
(for X (head 10 (flip (by cdr sort Freq)))
(tab (-7 4) (car X) (cdr X)) ) )
|
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.
|
#Python
|
Python
|
import ast
class CallCountingVisitor(ast.NodeVisitor):
def __init__(self):
self.calls = {}
def visit_Call(self, node):
if isinstance(node.func, ast.Name):
fun_name = node.func.id
call_count = self.calls.get(fun_name, 0)
self.calls[fun_name] = call_count + 1
self.generic_visit(node)
filename = input('Enter a filename to parse: ')
with open(filename, encoding='utf-8') as f:
contents = f.read()
root = ast.parse(contents, filename=filename) #NOTE: this will throw a SyntaxError if the file isn't valid Python code
visitor = CallCountingVisitor()
visitor.visit(root)
top10 = sorted(visitor.calls.items(), key=lambda x: x[1], reverse=True)[:10]
for name, count in top10:
print(name,'called',count,'times')
|
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
|
#Clojure
|
Clojure
|
(defn gamma
"Returns Gamma(z + 1 = number) using Lanczos approximation."
[number]
(if (< number 0.5)
(/ Math/PI (* (Math/sin (* Math/PI number))
(gamma (- 1 number))))
(let [n (dec number)
c [0.99999999999980993 676.5203681218851 -1259.1392167224028
771.32342877765313 -176.61502916214059 12.507343278686905
-0.13857109526572012 9.9843695780195716e-6 1.5056327351493116e-7]]
(* (Math/sqrt (* 2 Math/PI))
(Math/pow (+ n 7 0.5) (+ n 0.5))
(Math/exp (- (+ n 7 0.5)))
(+ (first c)
(apply + (map-indexed #(/ %2 (+ n %1 1)) (next c))))))))
|
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.
|
#JavaScript
|
JavaScript
|
const readline = require('readline');
/**
* Galton Box animation
* @param {number} layers The number of layers in the board
* @param {number} balls The number of balls to pass through
*/
const galtonBox = (layers, balls) => {
const speed = 100;
const ball = 'o';
const peg = '.';
const result = [];
const sleep = ms => new Promise(resolve => {
setTimeout(resolve,ms)
});
/**
* The board is represented as a 2D array.
* @type {Array<Array<string>>}
*/
const board = [...Array(layers)]
.map((e, i) => {
const sides = Array(layers - i).fill(' ');
const a = Array(i + 1).fill(peg).join(' ').split('');
return [...sides, ...a, ...sides];
});
/**
* @return {Array<string>}
*/
const emptyRow = () => Array(board[0].length).fill(' ');
/**
* @param {number} i
* @returns {number}
*/
const bounce = i => Math.round(Math.random()) ? i - 1 : i + 1;
/**
* Prints the current state of the board and the collector
*/
const show = () => {
readline.cursorTo(process.stdout, 0, 0);
readline.clearScreenDown(process.stdout);
board.forEach(e => console.log(e.join('')));
result.reverse();
result.forEach(e => console.log(e.join('')));
result.reverse();
};
/**
* Collect the result.
* @param {number} idx
*/
const appendToResult = idx => {
const row = result.find(e => e[idx] === ' ');
if (row) {
row[idx] = ball;
} else {
const newRow = emptyRow();
newRow[idx] = ball;
result.push(newRow);
}
};
/**
* Move the balls through the board
* @returns {boolean} True if the there are balls in the board.
*/
const iter = () => {
let hasNext = false;
[...Array(bordSize)].forEach((e, i) => {
const rowIdx = (bordSize - 1) - i;
const idx = board[rowIdx].indexOf(ball);
if (idx > -1) {
board[rowIdx][idx] = ' ';
const nextRowIdx = rowIdx + 1;
if (nextRowIdx < bordSize) {
hasNext = true;
const nextRow = board[nextRowIdx];
nextRow[bounce(idx)] = ball;
} else {
appendToResult(idx);
}
}
});
return hasNext;
};
/**
* Add a ball to the board.
* @returns {number} The number of balls left to add.
*/
const addBall = () => {
board[0][apex] = ball;
balls = balls - 1;
return balls;
};
board.unshift(emptyRow());
result.unshift(emptyRow());
const bordSize = board.length;
const apex = board[1].indexOf(peg);
/**
* Run the animation
*/
(async () => {
while (addBall()) {
await sleep(speed).then(show);
iter();
}
await sleep(speed).then(show);
while (iter()) {
await sleep(speed).then(show);
}
await sleep(speed).then(show);
})();
};
galtonBox(12, 50);
|
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
|
#J
|
J
|
gapful =: 0 = (|~ ({.,{:)&.(10&#.inv))
task =: 100&$: :(dyad define) NB. MINIMUM task TALLY
gn =. y {. (#~ gapful&>) x + i. y * 25
assert 0 ~: {: gn
'The first ' , (": y) , ' gapful numbers exceeding ' , (":<:x) , ' are ' , (":gn)
)
|
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
|
#Java
|
Java
|
import java.util.List;
public class GapfulNumbers {
private static String commatize(long n) {
StringBuilder sb = new StringBuilder(Long.toString(n));
int le = sb.length();
for (int i = le - 3; i >= 1; i -= 3) {
sb.insert(i, ',');
}
return sb.toString();
}
public static void main(String[] args) {
List<Long> starts = List.of((long) 1e2, (long) 1e6, (long) 1e7, (long) 1e9, (long) 7123);
List<Integer> counts = List.of(30, 15, 15, 10, 25);
for (int i = 0; i < starts.size(); ++i) {
int count = 0;
Long j = starts.get(i);
long pow = 100;
while (j >= pow * 10) {
pow *= 10;
}
System.out.printf("First %d gapful numbers starting at %s:\n", counts.get(i), commatize(starts.get(i)));
while (count < counts.get(i)) {
long fl = (j / pow) * 10 + (j % 10);
if (j % fl == 0) {
System.out.printf("%d ", j);
count++;
}
j++;
if (j >= 10 * pow) {
pow *= 10;
}
}
System.out.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
|
#JavaScript
|
JavaScript
|
// Lower Upper Solver
function lusolve(A, b, update) {
var lu = ludcmp(A, update)
if (lu === undefined) return // Singular Matrix!
return lubksb(lu, b, update)
}
// Lower Upper Decomposition
function ludcmp(A, update) {
// A is a matrix that we want to decompose into Lower and Upper matrices.
var d = true
var n = A.length
var idx = new Array(n) // Output vector with row permutations from partial pivoting
var vv = new Array(n) // Scaling information
for (var i=0; i<n; i++) {
var max = 0
for (var j=0; j<n; j++) {
var temp = Math.abs(A[i][j])
if (temp > max) max = temp
}
if (max == 0) return // Singular Matrix!
vv[i] = 1 / max // Scaling
}
if (!update) { // make a copy of A
var Acpy = new Array(n)
for (var i=0; i<n; i++) {
var Ai = A[i]
Acpyi = new Array(Ai.length)
for (j=0; j<Ai.length; j+=1) Acpyi[j] = Ai[j]
Acpy[i] = Acpyi
}
A = Acpy
}
var tiny = 1e-20 // in case pivot element is zero
for (var i=0; ; i++) {
for (var j=0; j<i; j++) {
var sum = A[j][i]
for (var k=0; k<j; k++) sum -= A[j][k] * A[k][i];
A[j][i] = sum
}
var jmax = 0
var max = 0;
for (var j=i; j<n; j++) {
var sum = A[j][i]
for (var k=0; k<i; k++) sum -= A[j][k] * A[k][i];
A[j][i] = sum
var temp = vv[j] * Math.abs(sum)
if (temp >= max) {
max = temp
jmax = j
}
}
if (i <= jmax) {
for (var j=0; j<n; j++) {
var temp = A[jmax][j]
A[jmax][j] = A[i][j]
A[i][j] = temp
}
d = !d;
vv[jmax] = vv[i]
}
idx[i] = jmax;
if (i == n-1) break;
var temp = A[i][i]
if (temp == 0) A[i][i] = temp = tiny
temp = 1 / temp
for (var j=i+1; j<n; j++) A[j][i] *= temp
}
return {A:A, idx:idx, d:d}
}
// Lower Upper Back Substitution
function lubksb(lu, b, update) {
// solves the set of n linear equations A*x = b.
// lu is the object containing A, idx and d as determined by the routine ludcmp.
var A = lu.A
var idx = lu.idx
var n = idx.length
if (!update) { // make a copy of b
var bcpy = new Array(n)
for (var i=0; i<b.length; i+=1) bcpy[i] = b[i]
b = bcpy
}
for (var ii=-1, i=0; i<n; i++) {
var ix = idx[i]
var sum = b[ix]
b[ix] = b[i]
if (ii > -1)
for (var j=ii; j<i; j++) sum -= A[i][j] * b[j]
else if (sum)
ii = i
b[i] = sum
}
for (var i=n-1; i>=0; i--) {
var sum = b[i]
for (var j=i+1; j<n; j++) sum -= A[i][j] * b[j]
b[i] = sum / A[i][i]
}
return b // solution vector x
}
document.write(
lusolve(
[
[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]
],
[-0.01, 0.61, 0.91, 0.99, 0.60, 0.02]
)
)
|
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.
|
#Phix
|
Phix
|
with javascript_semantics
function ToReducedRowEchelonForm(sequence M)
integer lead = 1,
rowCount = length(M),
columnCount = length(M[1]),
i
for r=1 to rowCount do
if lead>=columnCount then exit end if
i = r
while M[i][lead]=0 do
i += 1
if i=rowCount then
i = r
lead += 1
if lead=columnCount then exit end if
end if
end while
object mr = sq_div(M[i],M[i][lead])
M[i] = M[r]
M[r] = mr
for j=1 to rowCount do
if j!=r then
M[j] = sq_sub(M[j],sq_mul(M[j][lead],M[r]))
end if
end for
lead += 1
end for
return M
end function
--</end of copy>
function inverse(sequence mat)
integer len = length(mat)
sequence aug = repeat(repeat(0,2*len),len)
for i=1 to len do
if length(mat[i])!=len then ?9/0 end if -- "Not a square matrix"
for j=1 to len do
aug[i][j] = mat[i][j]
end for
-- augment by identity matrix to right
aug[i][i + len] = 1
end for
aug = ToReducedRowEchelonForm(aug)
sequence inv = repeat(repeat(0,len),len)
-- remove identity matrix to left
for i=1 to len do
for j=len+1 to 2*len do
inv[i][j-len] = aug[i][j]
end for
end for
return inv
end function
constant test = {{ 2, -1, 0},
{-1, 2, -1},
{ 0, -1, 2}}
pp(inverse(test),{pp_Nest,1})
|
http://rosettacode.org/wiki/General_FizzBuzz
|
General FizzBuzz
|
Task
Write a generalized version of FizzBuzz that works for any list of factors, along with their words.
This is basically a "fizzbuzz" implementation where the user supplies the parameters.
The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be printed.
For simplicity's sake, assume the user will input an integer as the max number and 3 factors, each with a word associated with them.
For example, given:
>20 #This is the maximum number, supplied by the user
>3 Fizz #The user now enters the starting factor (3) and the word they want associated with it (Fizz)
>5 Buzz #The user now enters the next factor (5) and the word they want associated with it (Buzz)
>7 Baxx #The user now enters the next factor (7) and the word they want associated with it (Baxx)
In other words: For this example, print the numbers 1 through 20, replacing every multiple of 3 with "Fizz", every multiple of 5 with "Buzz", and every multiple of 7 with "Baxx".
In the case where a number is a multiple of at least two factors, print each of the words associated with those factors in the order of least to greatest factor.
For instance, the number 15 is a multiple of both 3 and 5; print "FizzBuzz".
If the max number was 105 instead of 20, you would print "FizzBuzzBaxx" because it's a multiple of 3, 5, and 7.
Output:
1
2
Fizz
4
Buzz
Fizz
Baxx
8
Fizz
Buzz
11
Fizz
13
Baxx
FizzBuzz
16
17
Fizz
19
Buzz
|
#Nanoquery
|
Nanoquery
|
factors = {}
words = {}
// get the max number
print ">"
max = int(input())
// get the factors
inp = " "
while inp != ""
print ">"
inp = input()
if " " in inp
factors.append(int(split(inp, " ")[0]))
words.append(split(inp, " ")[1])
end
end
// output all the numbers
for i in range(1, max)
foundfactor = false
for j in range(0, len(factors) - 1)
if (i % factors[j]) = 0
foundfactor = true
print words[j]
end
end
j = 0
if !foundfactor
print i
end
println
end
|
http://rosettacode.org/wiki/General_FizzBuzz
|
General FizzBuzz
|
Task
Write a generalized version of FizzBuzz that works for any list of factors, along with their words.
This is basically a "fizzbuzz" implementation where the user supplies the parameters.
The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be printed.
For simplicity's sake, assume the user will input an integer as the max number and 3 factors, each with a word associated with them.
For example, given:
>20 #This is the maximum number, supplied by the user
>3 Fizz #The user now enters the starting factor (3) and the word they want associated with it (Fizz)
>5 Buzz #The user now enters the next factor (5) and the word they want associated with it (Buzz)
>7 Baxx #The user now enters the next factor (7) and the word they want associated with it (Baxx)
In other words: For this example, print the numbers 1 through 20, replacing every multiple of 3 with "Fizz", every multiple of 5 with "Buzz", and every multiple of 7 with "Baxx".
In the case where a number is a multiple of at least two factors, print each of the words associated with those factors in the order of least to greatest factor.
For instance, the number 15 is a multiple of both 3 and 5; print "FizzBuzz".
If the max number was 105 instead of 20, you would print "FizzBuzzBaxx" because it's a multiple of 3, 5, and 7.
Output:
1
2
Fizz
4
Buzz
Fizz
Baxx
8
Fizz
Buzz
11
Fizz
13
Baxx
FizzBuzz
16
17
Fizz
19
Buzz
|
#Nim
|
Nim
|
import parseutils, strutils, algorithm
type FactorAndWord = tuple[factor:int, word: string]
var number: int
var factorAndWords: array[3, FactorAndWord]
#custom comparison proc for the FactorAndWord type
proc customCmp(x,y: FactorAndWord): int =
if x.factor < y.factor:
-1
elif x.factor > y.factor:
1
else:
0
echo "Enter max number:"
var input = readLine(stdin)
discard parseInt(input, number)
for i in 0..2:
echo "Enter a number and word separated by space:"
var input = readLine(stdin)
var tokens = input.split
discard parseInt(tokens[0], factorAndWords[i].factor)
factorAndWords[i].word = tokens[1]
#sort factors in ascending order
sort(factorAndWords, customCmp)
#implement fiz buz
for i in 1..number:
var written = false;
for item in items(factorAndWords):
if i mod item.factor == 0 :
write(stdout, item.word)
written = true
if written :
write(stdout, "\n")
else :
writeLine(stdout, i)
|
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
|
#FALSE
|
FALSE
|
'a[$'z>~][$,1+]#%
|
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
|
Generate lower case ASCII alphabet
|
Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code.
During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code:
set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z}
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#Fermat
|
Fermat
|
Array locase[1,26];
[locase]:=[<i=1,26>'a'+i-1];
!([locase:char);
|
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
|
#Oxygene
|
Oxygene
|
namespace HelloWorld;
interface
type
HelloClass = class
public
class method Main;
end;
implementation
class method HelloClass.Main;
begin
writeLn('Hello world!');
end;
end.
|
http://rosettacode.org/wiki/Generator/Exponential
|
Generator/Exponential
|
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided.
Generators are often built on top of coroutines or objects so that the internal state of the object is handled “naturally”.
Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state.
Task
Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size).
Use it to create a generator of:
Squares.
Cubes.
Create a new generator that filters all cubes from the generator of squares.
Drop the first 20 values from this last generator of filtered results, and then show the next 10 values.
Note that this task requires the use of generators in the calculation of the result.
Also see
Generator
|
#OCaml
|
OCaml
|
(* Task : Generator/Exponential
Version using the Seq module types, but transparently
*)
(*** Helper functions ***)
(* Generator type *)
type 'a gen = unit -> 'a node
and 'a node = Nil | Cons of 'a * 'a gen
(* Power function on integers *)
let power (base : int) (exp : int) : int =
let rec helper exp acc =
if exp = 0 then acc
else helper (exp - 1) (base * acc)
in
helper exp 1
(* Take (at most) n from generator *)
let rec take (n : int) (gen : 'a gen) : 'a list =
if n = 0 then []
else
match gen () with
| Nil -> []
| Cons (x, tl) -> x :: take (n - 1) tl
(* Stop existing generator at a given condition *)
let rec keep_while (p : 'a -> bool) (gen : 'a gen) : 'a gen = fun () ->
match gen () with
| Nil -> Nil
| Cons (x, tl) ->
if p x then Cons (x, keep_while p tl)
else Nil
(* Drop the first n elements of a generator *)
let rec drop (n : int) (gen : 'a gen) : 'a gen =
if n = 0 then gen
else
match gen () with
| Nil -> (fun () -> Nil)
| Cons (_, tl) -> drop (n - 1) tl
(* Filter based on predicate, lazily *)
let rec filter (p : 'a -> bool) (gen : 'a gen) : 'a gen = fun () ->
match gen () with
| Nil -> Nil
| Cons (x, tl) ->
if p x then Cons (x, filter p tl)
else filter p tl ()
(* Is this value inside this generator? Does not terminate for infinite streams! *)
let rec mem (val_ : 'a) (gen : 'a gen) : bool =
match gen () with
| Nil -> false
| Cons (x, tl) ->
if x = val_ then true
else mem val_ tl
(*** Task at hand ***)
(* 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).
*)
let power_gen k : int gen =
let rec generator n () =
Cons (power n k, generator (n + 1))
in
generator 0
(* Use it to create generators of squares and cubes *)
let squares = power_gen 2
let cubes = power_gen 3
(* Create a new generator that filters all cubes from the generator of squares. *)
let squares_no_cubes =
let filter_p square =
(* Get all cubes up to square *)
let cubes_up_to_n2 = keep_while ((>=) square) cubes in
not (mem square cubes_up_to_n2)
in
filter filter_p squares
(*** Output ***)
(* Drop the first 20 values from this last generator of filtered results, and then show the next 10 values. *)
let _ =
squares_no_cubes |> drop 20 |> take 10
|
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.
|
#Scala
|
Scala
|
import scala.annotation.tailrec
object Chess960 extends App {
private val pieces = List('♖', '♗', '♘', '♕', '♔', '♘', '♗', '♖')
@tailrec
private def generateFirstRank(pieces: List[Char]): List[Char] = {
def check(rank: String) =
rank.matches(".*♖.*♔.*♖.*") && rank.matches(".*♗(..|....|......|)♗.*")
val p = scala.util.Random.shuffle(pieces)
if (check(p.toString.replaceAll("[^\\p{Upper}]", "")))
generateFirstRank(pieces)
else p
}
loop(10)
@tailrec
private def loop(n: Int): Unit = {
println(generateFirstRank(pieces))
if (n <= 0) () else loop(n - 1)
}
}
|
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.
|
#Bori
|
Bori
|
double sin (double v) { return Math.sin(v); }
double asin (double v) { return Math.asin(v); }
Var compose (Func f, Func g, double d) { return f(g(d)); }
void button1_onClick (Widget widget)
{
double d = compose(sin, asin, 0.5);
label1.setText(d.toString(9));
}
|
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.
|
#BQN
|
BQN
|
_compose_ ← ∘
|
http://rosettacode.org/wiki/Fractal_tree
|
Fractal tree
|
Generate and draw a fractal tree.
Draw the trunk
At the end of the trunk, split by some angle and draw two branches
Repeat at the end of each branch until a sufficient level of branching is reached
Related tasks
Pythagoras Tree
|
#Arturo
|
Arturo
|
width: 1000
height: 1000
trunkLength: 400
scaleFactor: 0.6
startingAngle: 1.5 * pi
deltaAngle: 0.2 * pi
drawTree: function [out x y len theta][
if len < 1 -> return null
x2: x + len * cos theta
y2: y + len * sin theta
'out ++ ~"<line x1='|x|' y1='|y|' x2='|x2|' y2='|y2|' style='stroke: white; stroke-width:1'/>\n"
drawTree out x2 y2 len*scaleFactor theta+deltaAngle
drawTree out x2 y2 len*scaleFactor theta-deltaAngle
]
svg: {
<?xml version='1.0' encoding='utf-8' standalone='no'?>
<!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN'
'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'>
<svg width='100%%' height='100%%' version='1.1'
xmlns='http://www.w3.org/2000/svg'>
<rect width="100%" height="100%" fill="black"/>
}
drawTree svg 0.5*width height trunkLength startingAngle
'svg ++ "</svg>"
write "fractal.svg" svg
|
http://rosettacode.org/wiki/Fractal_tree
|
Fractal tree
|
Generate and draw a fractal tree.
Draw the trunk
At the end of the trunk, split by some angle and draw two branches
Repeat at the end of each branch until a sufficient level of branching is reached
Related tasks
Pythagoras Tree
|
#AutoHotkey
|
AutoHotkey
|
#SingleInstance, Force
#NoEnv
SetBatchLines, -1
; Uncomment if Gdip.ahk is not in your standard library
; #Include, Gdip.ahk
FileOut := A_Desktop "\MyNewFile.png"
TreeColor := 0xff0066ff ; ARGB
TrunkWidth := 10 ; Pixels
TrunkLength := 80 ; Pixels
Angle := 60 ; Degrees
ImageWidth := 670 ; Pixels
ImageHeight := 450 ; Pixels
Branches := 13
Decrease := 0.81
Angle := (Angle * 0.01745329252) / 2
, Points := {}
, Points[1, "Angle"] := 0
, Points[1, "X"] := ImageWidth // 2
, Points[1, "Y"] := ImageHeight - TrunkLength
if (!pToken := Gdip_Startup()) {
MsgBox, 48, Gdiplus error!, Gdiplus failed to start. Please ensure you have Gdiplus on your system.
ExitApp
}
OnExit, Exit
pBitmap := Gdip_CreateBitmap(ImageWidth, ImageHeight)
, G := Gdip_GraphicsFromImage(pBitmap)
, Gdip_SetSmoothingMode(G, 4)
, pBrush := Gdip_BrushCreateSolid(0xff000000)
, Gdip_FillRectangle(G, pBrush, -5, -5, ImageWidth + 10, ImageHeight + 10)
, Gdip_DeleteBrush(pBrush)
, pPen := Gdip_CreatePen(TreeColor, TrunkWidth/Decrease)
, Gdip_DrawLine(G, pPen, Points.1.X, Points.1.Y, Points.1.X, ImageHeight)
, Gdip_DeletePen(pPen)
Loop, % Branches {
NewPoints := {}
pPen := Gdip_CreatePen(TreeColor, TrunkWidth)
for Each, Point in Points {
N1 := A_Index * 2
, N2 := (A_Index * 2) + 1
, NewPoints[N1, "X"] := Point.X + (TrunkLength * Sin(NewPoints[N1, "Angle"] := Point.Angle - Angle))
, NewPoints[N1, "Y"] := Point.Y - (TrunkLength * Cos(NewPoints[N1].Angle))
, NewPoints[N2, "X"] := Point.X + (TrunkLength * Sin(NewPoints[N2, "Angle"] := Point.Angle + Angle))
, NewPoints[N2, "Y"] := Point.Y - (TrunkLength * Cos(NewPoints[N2].Angle))
, Gdip_DrawLine(G, pPen, Point.X, Point.Y, NewPoints[N1].X, NewPoints[N1].Y)
, Gdip_DrawLine(G, pPen, Point.X, Point.Y, NewPoints[N2].X, NewPoints[N2].Y)
}
TrunkWidth *= Decrease
, TrunkLength *= Decrease
, Points := NewPoints
, Gdip_DeletePen(pPen)
}
Gdip_SaveBitmapToFile(pBitmap, FileOut)
, Gdip_DisposeImage(pBitmap)
, Gdip_DeleteGraphics(G)
Run, % FileOut
Exit:
Gdip_Shutdown(pToken)
ExitApp
|
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.
|
#AutoHotkey
|
AutoHotkey
|
n := 2, steplimit := 15, numerator := [], denominator := []
s := "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"
Loop, Parse, s, % A_Space
if (!RegExMatch(A_LoopField, "^(\d+)/(\d+)$", m))
MsgBox, % "Invalid input string (" A_LoopField ")."
else
numerator[A_Index] := m1, denominator[A_Index] := m2
SetFormat, FloatFast, 0.0
Gui, Add, ListView, R10 W100 -Hdr, |
SysGet, VSBW, 2
LV_ModifyCol(1, 95 - VSBW), LV_Add( , 0 ": " n)
Gui, Show
Loop, % steplimit {
i := A_Index
Loop, % numerator.MaxIndex()
if (!Mod(nn := n * numerator[A_Index] / denominator[A_Index], 1)) {
LV_Modify(LV_Add( , i ": " (n := nn)), "Vis")
continue, 2
}
break
}
|
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.
|
#Nim
|
Nim
|
import asyncdispatch, asyncftpclient
const
Host = "speedtest.tele2.net"
Upload = "upload"
File = "1KB.zip"
proc main {.async.} =
# Create session and connect.
let ftp = newAsyncFtpClient(Host, user = "anonymous", pass = "anything")
await ftp.connect()
echo "Connected."
echo await ftp.send("PASV") # Switch to passive mode.
# Change directory and list its contents.
await ftp.cd(Upload)
echo "Changed to directory: ", Upload
echo "Contents of directory: ", Upload
for file in await ftp.listDirs():
echo " ", file
# Download a file.
await ftp.cd("/")
echo "Returned to root directory."
await ftp.retrFile(file = File, dest = File)
echo "Downloaded file: ", File
echo await ftp.send("QUIT") # Disconnect.
waitFor main()
|
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.
|
#Perl
|
Perl
|
use Net::FTP;
# set server and credentials
my $host = 'speedtest.tele2.net';
my $user = 'anonymous';
my $password = '';
# connect in passive mode
my $f = Net::FTP->new($host) or die "Can't open $host\n";
$f->login($user, $password) or die "Can't login as $user\n";
$f->passive();
# change remote directory, list contents
$f->cwd('upload');
@files = $f->ls();
printf "Currently %d files in the 'upload' directory.\n", @files;
# download file in binary mode
$f->cwd('/');
$f->type('binary');
$local = $f->get('512KB.zip');
print "Your file was stored as $local in the current directory\n";
|
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.
|
#Phix
|
Phix
|
without js -- libcurl, allocate, file i/o
include libcurl.e
constant url = "ftp://speedtest.tele2.net/"
curl_global_init()
atom curl = curl_easy_init(),
pErrorBuffer = allocate(CURL_ERROR_SIZE)
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, pErrorBuffer)
curl_easy_setopt(curl, CURLOPT_URL, url)
object res = curl_easy_perform_ex(curl)
if integer(res) then
?{res,peek_string(pErrorBuffer)}
else
puts(1,res)
end if
string filename = "1KB.zip"
{} = delete_file(filename)
res = curl_easy_get_file(url&filename, "", filename)
if res=CURLE_OK then
printf(1,"successfully downloaded %s (size %s)\n",{filename,get_file_size(filename,true)})
else
?{"error",res}
end if
|
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.
|
#PL.2FI
|
PL/I
|
declare s1 entry;
declare s2 entry (fixed);
declare s3 entry (fixed, float);
declare f1 entry returns (fixed);
declare f2 entry (float) returns (float);
declare f3 entry (character(*), character(*)) returns (character (20));
|
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.
|
#PureBasic
|
PureBasic
|
;Forward procedure declare defined with no arguments and that returns a string
Declare.s booTwo()
;Forward procedure declare defined with two arguments and that returns a float
Declare.f moo(x.f, y.f)
;Forward procedure declare with two arguments and an optional argument and that returns a float
Declare.f cmoo(x.f, y.f, m.f = 0)
;*** The following three procedures are defined before their first use.
;Procedure defined with no arguments and that returns a string
Procedure.s boo(): ProcedureReturn "boo": EndProcedure
;Procedure defined with two arguments and that returns an float
Procedure.f aoo(x.f, y.f): ProcedureReturn x + y: EndProcedure
;Procedure defined with two arguments and an optional argument and that returns a float
Procedure.f caoo(x.f, y.f, m.f = 1): ProcedureReturn (x + y) * m: EndProcedure
;ProtoType defined for any function with no arguments and that returns a string
Prototype.s showString()
;Prototype defined for any function with two float arguments and that returns a float
Prototype.f doMath(x.f, y.f)
;ProtoType defined for any function with two float arguments and an optional float argument and that returns a float
Prototype.f doMathWithOpt(x.f, y.f, m.f = 0)
Define a.f = 12, b.f = 5, c.f = 9
Define proc_1.showString, proc_2.doMath, proc_3.doMathWithOpt ;using defined ProtoTypes
If OpenConsole("ProtoTypes and Forward Declarations")
PrintN("Forward Declared procedures:")
PrintN(boo())
PrintN(StrF(a, 2) + " * " + StrF(b, 2) + " = " + StrF(moo(a, b), 2))
PrintN(StrF(a, 2) + " * " + StrF(b, 2) + " + " + StrF(c, 2) + " = " + StrF(cmoo(a, b, c), 2))
PrintN(StrF(a, 2) + " * " + StrF(b, 2) + " = " + StrF(cmoo(a, b), 2))
;set pointers to second set of functions
proc_1 = @boo()
proc_2 = @aoo()
proc_3 = @caoo()
PrintN("ProtoTyped procedures (set 1):")
PrintN(proc_1())
PrintN(StrF(a, 2) + " ? " + StrF(b, 2) + " = " + StrF(proc_2(a, b), 2))
PrintN(StrF(a, 2) + " ? " + StrF(b, 2) + " ? " + StrF(c, 2) + " = " + StrF(proc_3(a, b, c), 2))
PrintN(StrF(a, 2) + " ? " + StrF(b, 2) + " = " + StrF(proc_3(a, b), 2))
;set pointers to second set of functions
proc_1 = @booTwo()
proc_2 = @moo()
proc_3 = @cmoo()
PrintN("ProtoTyped procedures (set 2):")
PrintN(proc_1())
PrintN(StrF(a, 2) + " ? " + StrF(b, 2) + " = " + StrF(proc_2(a, b), 2))
PrintN(StrF(a, 2) + " ? " + StrF(b, 2) + " ? " + StrF(c, 2) + " = " + StrF(proc_3(a, b, c), 2))
PrintN(StrF(a, 2) + " ? " + StrF(b, 2) + " = " + StrF(proc_3(a, b), 2))
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf
;*** If the forward Declaration above are not used then the following Procedure
;definitions each have to be placed before the call to the respective procedure.
;Procedure defined with no arguments and that returns a string
Procedure.s booTwo()
ProcedureReturn "booTwo"
EndProcedure
;Procedure defined with two arguments and that returns an float
Procedure.f moo(x.f, y.f)
ProcedureReturn x * y
EndProcedure
;Procedure defined with two arguments and an optional argument and that returns an float
Procedure.f cmoo(x.f, y.f, m.f = 0)
ProcedureReturn (x * y) + m
EndProcedure
|
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
|
#ACL2
|
ACL2
|
(defun multiply (a b) (* a b))
|
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
|
#Raku
|
Raku
|
use v6;
constant @month_names = <
Vendémiaire Brumaire Frimaire Nivôse Pluviôse Ventôse
Germinal Floréal Prairial Messidor Thermidor Fructidor
>;
constant @intercalary =
'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',
;
constant %month_nums = %( @month_names Z=> 1..12 );
constant %i_cal_nums = %( @intercalary Z=> 1.. 6 );
constant $i_cal_month = 13;
constant $epoch = Date.new: '1792-09-22';
sub is_republican_leap_year ( Int:D $year --> Bool ) {
my $y := $year + 1;
return ?( $y %% 4 and ($y !%% 100 or $y %% 400) );
}
sub Republican_to_Gregorian ( Str:D $rep_date --> Date ) {
grammar Republican_date_text {
token day { \d+ }
token year { \d+ }
token ic { @intercalary }
token month { @month_names }
rule TOP { ^ [ <ic> | <day> <month> ] <year> $ }
}
Republican_date_text.parse($rep_date)
orelse die "Republican date not recognized: '$rep_date'";
my $day1 := $/<ic> ?? %i_cal_nums{~$/<ic>} !! +$/<day>;
my $month1 := $/<month> ?? %month_nums{~$/<month>} !! $i_cal_month;
my @ymd0 := ($/<year>, $month1, $day1) »-» 1;
my $days_since_epoch := [+] @ymd0 Z* (365, 30, 1);
my $leap_days := +grep &is_republican_leap_year, 1 ..^ $/<year>;
return $epoch + $days_since_epoch + $leap_days;
}
sub Gregorian_to_Republican ( Date:D $greg_date --> Str ) {
my $days_since_epoch := $greg_date - $epoch;
die if $days_since_epoch < 0;
my ( $year, $days ) = 1, $days_since_epoch;
loop {
my $year_length = 365 + (1 if $year.&is_republican_leap_year);
last if $days < $year_length;
$days -= $year_length;
$year += 1;
}
my ( $day0, $month0 ) = $days.polymod( 30 );
my ( $day1, $month1 ) = ($day0, $month0) X+ 1;
return $month1 == $i_cal_month
?? "@intercalary[$day0 ] $year"
!! "$day1 @month_names[$month0] $year";
}
my @test_data =
( '1792-09-22', '1 Vendémiaire 1' ),
( '1795-05-20', '1 Prairial 3' ),
( '1799-07-15', '27 Messidor 7' ),
( '1803-09-23', 'Fête de la Révolution 11' ),
( '1805-12-31', '10 Nivôse 14' ),
( '1871-03-18', '27 Ventôse 79' ),
( '1944-08-25', '7 Fructidor 152' ),
( '2016-09-19', 'Fête du travail 224' ),
( '1871-05-06', '16 Floréal 79' ), # Paris Commune begins
( '1871-05-23', '3 Prairial 79' ), # Paris Commune ends
( '1799-11-09', '18 Brumaire 8' ), # Revolution ends by Napoléon coup
( '1804-12-02', '11 Frimaire 13' ), # Republic ends by Napoléon coronation
( '1794-10-30', '9 Brumaire 3' ), # École Normale Supérieure established
( '1794-07-27', '9 Thermidor 2' ), # Robespierre falls
( '1799-05-27', '8 Prairial 7' ), # Fromental Halévy born
( '1792-09-22', '1 Vendémiaire 1' ),
( '1793-09-22', '1 Vendémiaire 2' ),
( '1794-09-22', '1 Vendémiaire 3' ),
( '1795-09-23', '1 Vendémiaire 4' ),
( '1796-09-22', '1 Vendémiaire 5' ),
( '1797-09-22', '1 Vendémiaire 6' ),
( '1798-09-22', '1 Vendémiaire 7' ),
( '1799-09-23', '1 Vendémiaire 8' ),
( '1800-09-23', '1 Vendémiaire 9' ),
( '1801-09-23', '1 Vendémiaire 10' ),
( '1802-09-23', '1 Vendémiaire 11' ),
( '1803-09-24', '1 Vendémiaire 12' ),
( '1804-09-23', '1 Vendémiaire 13' ),
( '1805-09-23', '1 Vendémiaire 14' ),
( '1806-09-23', '1 Vendémiaire 15' ),
( '1807-09-24', '1 Vendémiaire 16' ),
( '1808-09-23', '1 Vendémiaire 17' ),
( '1809-09-23', '1 Vendémiaire 18' ),
( '1810-09-23', '1 Vendémiaire 19' ),
( '1811-09-24', '1 Vendémiaire 20' ),
( '2015-09-23', '1 Vendémiaire 224' ),
( '2016-09-22', '1 Vendémiaire 225' ),
( '2017-09-22', '1 Vendémiaire 226' ),
;
for @test_data -> ( $g_text, $r ) {
my $g = Date.new: $g_text;
die if Republican_to_Gregorian($r) != $g
or Gregorian_to_Republican($g) ne $r;
die if Gregorian_to_Republican(Republican_to_Gregorian($r)) ne $r
or Republican_to_Gregorian(Gregorian_to_Republican($g)) != $g;
}
say 'All tests successful.';
|
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.
|
#CLU
|
CLU
|
fusc = iter () yields (int)
q: array[int] := array[int]$[1]
yield(0)
yield(1)
while true do
x: int := array[int]$reml(q)
array[int]$addh(q,x)
yield(x)
x := x + array[int]$bottom(q)
array[int]$addh(q,x)
yield(x)
end
end fusc
longest_fusc = iter () yields (int,int)
sofar: int := 0
count: int := 0
for f: int in fusc() do
if f >= sofar then
yield (count,f)
sofar := 10*sofar
if sofar=0 then sofar:=10 end
end
count := count + 1
end
end longest_fusc
start_up = proc ()
po: stream := stream$primary_output()
stream$putl(po, "First 61:")
n: int := 0
for f: int in fusc() do
stream$puts(po, int$unparse(f) || " ")
n := n + 1
if n = 61 then break end
end
stream$putl(po, "\nLength records:")
n := 0
for i, f: int in longest_fusc() do
stream$putl(po, "fusc(" || int$unparse(i) || ") = " || int$unparse(f))
n := n + 1
if n = 5 then break end
end
end start_up
|
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.
|
#D
|
D
|
import std.functional, std.stdio, std.format, std.conv;
ulong fusc(ulong n) =>
memoize!fuscImp(n);
ulong fuscImp(ulong n) =>
( n < 2 ) ? n :
( n % 2 == 0 ) ? memoize!fuscImp( n/2 ) :
memoize!fuscImp( (n-1)/2 ) + memoize!fuscImp( (n+1)/2 );
void main() {
const N_FIRST=61;
const MAX_N_DIGITS=5;
format!"First %d fusc numbers: "(N_FIRST).write;
foreach( n; 0..N_FIRST ) n.fusc.format!"%d ".write;
writeln;
format!"\nFusc numbers with more digits than any previous (1 to %d digits):"(MAX_N_DIGITS).writeln;
for(auto n=0, ndigits=0; ndigits<MAX_N_DIGITS; n++)
if( n.fusc.to!string.length > ndigits ){
format!"fusc(%d)=%d"( n, n.fusc ).writeln;
ndigits = n.fusc.to!string.length.to!int;
}
}
|
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.
|
#Racket
|
Racket
|
#lang racket
(require math)
(define in (open-input-file "function-frequency.rkt"))
(void (read-language in))
(define s-exprs (for/list ([s (in-port read in)]) s))
(define symbols (filter symbol? (flatten s-exprs)))
(define counts (sort (hash->list (samples->hash symbols)) >= #:key cdr))
(take counts (min 10 (length counts)))
|
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.
|
#Raku
|
Raku
|
my $text = qqx[raku --target=ast @*ARGS[]];
my %fun;
for $text.lines {
%fun{$0}++ if / '(call &' (.*?) ')' /
}
for %fun.invert.sort.reverse[^10] { .value.say }
|
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
|
#Common_Lisp
|
Common Lisp
|
; Taylor series coefficients
(defconstant tcoeff
'( 1.00000000000000000000 0.57721566490153286061 -0.65587807152025388108
-0.04200263503409523553 0.16653861138229148950 -0.04219773455554433675
-0.00962197152787697356 0.00721894324666309954 -0.00116516759185906511
-0.00021524167411495097 0.00012805028238811619 -0.00002013485478078824
-0.00000125049348214267 0.00000113302723198170 -0.00000020563384169776
0.00000000611609510448 0.00000000500200764447 -0.00000000118127457049
0.00000000010434267117 0.00000000000778226344 -0.00000000000369680562
0.00000000000051003703 -0.00000000000002058326 -0.00000000000000534812
0.00000000000000122678 -0.00000000000000011813 0.00000000000000000119
0.00000000000000000141 -0.00000000000000000023 0.00000000000000000002))
; number of coefficients
(defconstant numcoeff (length tcoeff))
(defun gamma (x)
(let ((y (- x 1.0))
(sum (nth (- numcoeff 1) tcoeff)))
(loop for i from (- numcoeff 2) downto 0 do
(setf sum (+ (* sum y) (nth i tcoeff))))
(/ 1.0 sum)))
(loop for i from 1 to 10
do (
format t "~12,10f~%" (gamma (/ i 3.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.
|
#Julia
|
Julia
|
using Random
function drawball(timer)
global r, c, d
print("\e[$r;$(c)H ") # clear last ball position (r,c)
if (r+=1) > 14
close(timer)
b = (bin[(c+2)>>2] += 1)# update count in bin
print("\e[$b;$(c)Ho") # lengthen bar of balls in bin
else
r in 3:2:13 && c in 17-r:4:11+r && (d = 2bitrand()-1)
print("\e[$r;$(c+=d)Ho")# show ball moving in direction d
end
end
print("\e[2J") # clear screen
for r = 3:2:13, c = 17-r:4:11+r # 6 pins in 6 rows
print("\e[$r;$(c)H^") # draw pins
end
print("\e[15;2H-------------------------")
bin = fill(15,7) # positions of top of bins
while "x" != readline() >= "" # x-Enter: exit, {keys..}Enter: next ball
global r,c,d = 0,14,0
t = Timer(drawball, 0, interval=0.1)
while r < 15 sleep(0.01) end
print("\e[40;1H") # move cursor far down
end
|
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.
|
#Kotlin
|
Kotlin
|
// version 1.2.10
import java.util.Random
val boxW = 41 // Galton box width.
val boxH = 37 // Galton box height.
val pinsBaseW = 19 // Pins triangle base.
val nMaxBalls = 55 // Number of balls.
val centerH = pinsBaseW + (boxW - pinsBaseW * 2 + 1) / 2 - 1
val rand = Random()
enum class Cell(val c: Char) {
EMPTY(' '),
BALL('o'),
WALL('|'),
CORNER('+'),
FLOOR('-'),
PIN('.')
}
/* Galton box. Will be printed upside down. */
val box = List(boxH) { Array<Cell>(boxW) { Cell.EMPTY } }
class Ball(var x: Int, var y: Int) {
init {
require(box[y][x] == Cell.EMPTY)
box[y][x] = Cell.BALL
}
fun doStep() {
if (y <= 0) return // Reached the bottom of the box.
val cell = box[y - 1][x]
when (cell) {
Cell.EMPTY -> {
box[y][x] = Cell.EMPTY
y--
box[y][x] = Cell.BALL
}
Cell.PIN -> {
box[y][x] = Cell.EMPTY
y--
if (box[y][x - 1] == Cell.EMPTY && box[y][x + 1] == Cell.EMPTY) {
x += rand.nextInt(2) * 2 - 1
box[y][x] = Cell.BALL
return
}
else if (box[y][x - 1] == Cell.EMPTY) x++
else x--
box[y][x] = Cell.BALL
}
else -> {
// It's frozen - it always piles on other balls.
}
}
}
}
fun initializeBox() {
// Set ceiling and floor:
box[0][0] = Cell.CORNER
box[0][boxW - 1] = Cell.CORNER
for (i in 1 until boxW - 1) box[0][i] = Cell.FLOOR
for (i in 0 until boxW) box[boxH - 1][i] = box[0][i]
// Set walls:
for (r in 1 until boxH - 1) {
box[r][0] = Cell.WALL
box[r][boxW - 1] = Cell.WALL
}
// Set pins:
for (nPins in 1..pinsBaseW) {
for (pin in 0 until nPins) {
box[boxH - 2 - nPins][centerH + 1 - nPins + pin * 2] = Cell.PIN
}
}
}
fun drawBox() {
for (row in box.reversed()) {
for (i in row.indices) print(row[i].c)
println()
}
}
fun main(args: Array<String>) {
initializeBox()
val balls = mutableListOf<Ball>()
for (i in 0 until nMaxBalls + boxH) {
println("\nStep $i:")
if (i < nMaxBalls) balls.add(Ball(centerH, boxH - 2)) // Add ball.
drawBox()
// Next step for the simulation.
// Frozen balls are kept in balls list for simplicity
for (b in 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
|
#JavaScript
|
JavaScript
|
// Function to construct a new integer from the first and last digits of another
function gapfulness_divisor (number) {
var digit_string = number.toString(10)
var digit_count = digit_string.length
var first_digit = digit_string.substring(0, 1)
var last_digit = digit_string.substring(digit_count - 1)
return parseInt(first_digit.concat(last_digit), 10)
}
// Divisibility test to determine gapfulness
function is_gapful (number) {
return number % gapfulness_divisor(number) == 0
}
// Function to search for the least gapful number greater than a given integer
function next_gapful (number) {
do {
++number
} while (!is_gapful(number))
return number
}
// Constructor for a list of gapful numbers starting from given lower bound
function gapful_numbers (start, amount) {
var list = [], count = 0, number = start
if (amount > 0 && is_gapful(start)) {
list.push(start)
}
while (list.length < amount) {
number = next_gapful(number)
list.push(number)
}
return list
}
// Formatter for a comma-separated list of gapful numbers
function single_line_gapfuls (start, amount) {
var list = gapful_numbers(start, amount)
return list.join(", ")
}
// Windows console output wrapper
function print(message) {
WScript.StdOut.WriteLine(message)
}
// Main algorithm
function print_gapfuls_with_header(start, amount) {
print("First " + start + " gapful numbers starting at " + amount)
print(single_line_gapfuls(start, amount))
}
print_gapfuls_with_header(100, 30)
print_gapfuls_with_header(1000000, 15)
print_gapfuls_with_header(1000000000, 10)
|
http://rosettacode.org/wiki/Gaussian_elimination
|
Gaussian elimination
|
Task
Solve Ax=b using Gaussian elimination then backwards substitution.
A being an n by n matrix.
Also, x and b are n by 1 vectors.
To improve accuracy, please use partial pivoting and scaling.
See also
the Wikipedia entry: Gaussian elimination
|
#jq
|
jq
|
def ta: [
[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]
];
def tb:[-0.01, 0.61, 0.91, 0.99, 0.60, 0.02];
# Expected values:
def tx:[
-0.01, 1.602790394502114, -1.6132030599055613,
1.2454941213714368, -0.4909897195846576, 0.065760696175232
];
# Input: an array or an object
def swap($i;$j):
.[$i] as $tmp | .[$i] = .[$j] | .[$j] = $tmp;
def gaussPartial(a0; b0):
(b0|length) as $m
| reduce range(0;a0|length) as $i (
{ a: [range(0;$m)|null] };
.a[$i] = a0[$i] + [b0[$i]] )
| reduce range(0; .a|length) as $k (.;
.iMax = 0
| .max = -1
| reduce range($k;$m) as $i (.;
.a[$i] as $row
# compute scale factor s = max abs in row
| .s = -1
| reduce range($k;$m) as $j (.;
($row[$j]|length) as $e
| if ($e > .s) then .s = $e else . end )
# scale the abs used to pick the pivot
| ( ($row[$k]|length) / .s) as $abs
| if $abs > .max
then .iMax = $i | .max = $abs
else .
end )
| if (.a[.iMax][$k] == 0) then "Matrix is singular." | error
else .iMax as $iMax
| .a |= swap($k; $iMax)
| reduce range($k + 1; $m) as $i (.;
reduce range($k + 1; $m + 1 ) as $j (.;
.a[$i][$j] = .a[$i][$j] - (.a[$k][$j] * .a[$i][$k] / .a[$k][$k]) )
| .a[$i][$k] = 0 )
end
)
| .x = [range(0;$m)|0]
| reduce range($m - 1; -1; -1) as $i (.;
.x[$i] = .a[$i][$m]
| reduce range($i + 1; $m) as $j (.;
.x[$i] = .x[$i] - .a[$i][$j] * .x[$j] )
| .x[$i] = .x[$i] / .a[$i][$i] )
| .x ;
def x: gaussPartial(ta; tb);
# Input: the array of values to be compared againt $target
def pointwise_check($target; $EPSILON):
. as $x
| range(0; $x|length) as $i
| select( ($target[$i] - $x[$i])|length > $EPSILON )
| "\($x[$i]) vs expected value \($target[$i])" ;
def task:
x
| ., pointwise_check(tx; 1E-14) ;
task
|
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.
|
#PL.2FI
|
PL/I
|
/* Gauss-Jordan matrix inversion */
G_J: procedure options (main); /* 4 November 2020 */
declare t float;
declare (i, j, k, n) fixed binary;
open file (sysin) title ('/GAUSSJOR.DAT');
get (n); /* Read in the order of the matrix. */
put skip data (n);
begin;
declare a(n,n)float, aux(n,n) float;
aux = 0;
do i = 1 to n; aux(i,i) = 1; end;
get (a); /* Read in the matrix. */
put skip list ('The matrix to be inverted is:');
put edit (a) ( skip, (n) F(10,4)); /* Print the matrix. */
do k = 1 to n;
/* Divide row k by a(k,k) */
t = a(k,k); a(k,*) = a(k,*) / t; aux(k,*) = aux(k,*) / t;
do i = 1 to k-1, k+1 to n; /* Work down the rows. */
t = a(i,k);
a(i,*) = a(i,*) - t*a(k,*); aux(i,*) = aux(i,*) - t*aux(k,*);
end;
end;
put skip (2) list ('The inverse is:');
put edit (aux) ( skip, (n) F(10,4));
end; /* of BEGIN block */
end G_J;
|
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.
|
#PowerShell
|
PowerShell
|
function gauss-jordan-inv([double[][]]$a) {
$n = $a.count
[double[][]]$b = 0..($n-1) | foreach{[double[]]$row = @(0) * $n; $row[$_] = 1; ,$row}
for ($k = 0; $k -lt $n; $k++) {
$lmax, $max = $k, [Math]::Abs($a[$k][$k])
for ($l = $k+1; $l -lt $n; $l++) {
$tmp = [Math]::Abs($a[$l][$k])
if($max -lt $tmp) {
$max, $lmax = $tmp, $l
}
}
if ($k -ne $lmax) {
$a[$k], $a[$lmax] = $a[$lmax], $a[$k]
$b[$k], $b[$lmax] = $b[$lmax], $b[$k]
}
$akk = $a[$k][$k]
if (0 -eq $akk) {throw "Irregular matrix"}
for ($j = 0; $j -lt $n; $j++) {
$a[$k][$j] /= $akk
$b[$k][$j] /= $akk
}
for ($i = 0; $i -lt $n; $i++){
if ($i -ne $k) {
$aik = $a[$i][$k]
for ($j = 0; $j -lt $n; $j++) {
$a[$i][$j] -= $a[$k][$j]*$aik
$b[$i][$j] -= $b[$k][$j]*$aik
}
}
}
}
$b
}
function show($a) { $a | foreach{ "$_"} }
$a = @(@(@(1, 2, 3), @(4, 1, 6), @(7, 8, 9)))
$inva = gauss-jordan-inv $a
"a ="
show $a
""
"inv(a) ="
show $inva
""
$b = @(@(2, -1, 0), @(-1, 2, -1), @(0, -1, 2))
"b ="
show $b
""
$invb = gauss-jordan-inv $b
"inv(b) ="
show $invb
|
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
|
#OCaml
|
OCaml
|
(* Task : General_FizzBuzz *)
(*
The FizzBuzz problem, but
generalized to have any strings, at any steps,
up to any number of iterations.
*)
let gen_fizz_buzz (n : int) (l : (int * string) list) : unit =
let fold_f i (acc : bool) (k, s) =
if i mod k = 0
then (print_string s; true)
else acc
in
let rec helper i =
if i > n
then ()
else
let any_printed = List.fold_left (fold_f i) false l in
begin
(if not any_printed
then print_int i);
print_newline ();
helper (succ i)
end
in
helper 1
;;
(*** Output ***)
gen_fizz_buzz 20 [(3, "Fizz"); (5, "Buzz"); (7, "Baxx")] ;;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.