code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
package main
import (
"fmt"
"math"
)
func main() {
fmt.Println(" x math.Gamma Lanczos7")
for _, x := range []float64{-.5, .1, .5, 1, 1.5, 2, 3, 10, 140, 170} {
fmt.Printf("%5.1f%24.16g%24.16g\n", x, math.Gamma(x), lanczos7(x))
}
}
func lanczos7(z float64) float64 {
t := z + 6.5
x := .99999999999980993 +
676.5203681218851/z -
1259.1392167224028/(z+1) +
771.32342877765313/(z+2) -
176.61502916214059/(z+3) +
12.507343278686905/(z+4) -
.13857109526572012/(z+5) +
9.9843695780195716e-6/(z+6) +
1.5056327351493116e-7/(z+7)
return math.Sqrt2 * math.SqrtPi * math.Pow(t, z-.5) * math.Exp(-t) * x
} | 802Gamma function
| 0go
| 7sjr2 |
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
public class FractalTree extends JFrame {
public FractalTree() {
super("Fractal Tree");
setBounds(100, 100, 800, 600);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private void drawTree(Graphics g, int x1, int y1, double angle, int depth) {
if (depth == 0) return;
int x2 = x1 + (int) (Math.cos(Math.toRadians(angle)) * depth * 10.0);
int y2 = y1 + (int) (Math.sin(Math.toRadians(angle)) * depth * 10.0);
g.drawLine(x1, y1, x2, y2);
drawTree(g, x2, y2, angle - 20, depth - 1);
drawTree(g, x2, y2, angle + 20, depth - 1);
}
@Override
public void paint(Graphics g) {
g.setColor(Color.BLACK);
drawTree(g, 400, 500, -90, 9);
}
public static void main(String[] args) {
new FractalTree().setVisible(true);
}
} | 804Fractal tree
| 9java
| 7qgrj |
(() => {
"use strict"; | 803Fusc sequence
| 10javascript
| kokhq |
a = [ 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].reverse()
def gamma = { 1.0 / a.inject(0) { sm, a_i -> sm * (it - 1) + a_i } }
(1..10).each{ printf("% 1.9e\n", gamma(it / 3.0)) } | 802Gamma function
| 7groovy
| ua5v9 |
$rows_of_pins = 12
$width = $rows_of_pins * 10 + ($rows_of_pins+1)*14
Shoes.app(
:width => $width + 14,
:title =>
) do
@bins = Array.new($rows_of_pins+1, 0)
@x_coords = Array.new($rows_of_pins) {Array.new}
@y_coords = Array.new($rows_of_pins)
stack(:width => $width) do
stroke gray
fill gray
1.upto($rows_of_pins) do |row|
y = 14 + 24*row
@y_coords[row-1] = y
row.times do |i|
x = $width / 2 + (i - 0.5*row)*24 + 14
@x_coords[row-1] << x
oval x+2, y, 6
end
end
end
@y_coords << @y_coords[-1] + 24
@x_coords << @x_coords[-1].map {|x| x-12} + [@x_coords[-1][-1]+12]
@balls = stack(:width => $width) do
stroke red
fill red
end.move(0,0)
@histogram = stack(:width => $width) do
nostroke
fill black
end.move(0, @y_coords[-1] + 10)
@paused = false
keypress do |key|
case key
when , :control_q
exit
when , :control_p
@paused =!@paused
end
end
@ball_row = 0
@ball_col = 0
animate(2*$rows_of_pins) do
if not @paused
y = @y_coords[@ball_row] - 12
x = @x_coords[@ball_row][@ball_col]
@balls.clear {oval x, y, 10}
@ball_row += 1
if @ball_row <= $rows_of_pins
@ball_col += 1 if rand >= 0.5
else
@bins[@ball_col] += 1
@ball_row = @ball_col = 0
update_histogram
end
end
end
def update_histogram
y = @y_coords[-1] + 10
@histogram.clear do
@bins.each_with_index do |num, i|
if num > 0
x = @x_coords[-1][i]
rect x-6, 0, 24, num
end
end
end
end
end | 798Galton box animation
| 14ruby
| rqbgs |
def general_fizzbuzz(text)
num, *nword = text.split
num = num.to_i
dict = nword.each_slice(2).map{|n,word| [n.to_i,word]}
(1..num).each do |i|
str = dict.map{|n,word| word if i%n==0}.join
puts str.empty?? i: str
end
end
text = <<EOS
20
3 Fizz
5 Buzz
7 Baxx
EOS
general_fizzbuzz(text) | 791General FizzBuzz
| 14ruby
| 7ssri |
<html>
<body>
<canvas id="canvas" width="600" height="500"></canvas>
<script type="text/javascript">
var elem = document.getElementById('canvas');
var context = elem.getContext('2d');
context.fillStyle = '#C0C0C0';
context.lineWidth = 1;
var deg_to_rad = Math.PI / 180.0;
var depth = 9;
function drawLine(x1, y1, x2, y2, brightness){
context.moveTo(x1, y1);
context.lineTo(x2, y2);
}
function drawTree(x1, y1, angle, depth){
if (depth !== 0){
var x2 = x1 + (Math.cos(angle * deg_to_rad) * depth * 10.0);
var y2 = y1 + (Math.sin(angle * deg_to_rad) * depth * 10.0);
drawLine(x1, y1, x2, y2, depth);
drawTree(x2, y2, angle - 20, depth - 1);
drawTree(x2, y2, angle + 20, depth - 1);
}
}
context.beginPath();
drawTree(300, 500, -90, depth);
context.closePath();
context.stroke();
</script>
</body>
</html> | 804Fractal tree
| 10javascript
| pikb7 |
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class FractionReduction {
public static void main(String[] args) {
for ( int size = 2 ; size <= 5 ; size++ ) {
reduce(size);
}
}
private static void reduce(int numDigits) {
System.out.printf("Fractions with digits of length%d where cancellation is valid. Examples:%n", numDigits); | 807Fraction reduction
| 9java
| z5itq |
cof :: [Double]
cof =
[ 76.18009172947146
, -86.50532032941677
, 24.01409824083091
, -1.231739572450155
, 0.001208650973866179
, -0.000005395239384953
]
ser :: Double
ser = 1.000000000190015
gammaln :: Double -> Double
gammaln xx =
let tmp_ = (xx + 5.5) - (xx + 0.5) * log (xx + 5.5)
ser_ = ser + sum (zipWith (/) cof [xx + 1 ..])
in -tmp_ + log (2.5066282746310005 * ser_ / xx)
main :: IO ()
main = mapM_ print $ gammaln <$> [0.1,0.2 .. 1.0] | 802Gamma function
| 8haskell
| 89o0z |
use std::io;
use std::io::BufRead;
fn parse_entry(l: &str) -> (i32, String) {
let params: Vec<&str> = l.split(' ').collect();
let divisor = params[0].parse::<i32>().unwrap();
let word = params[1].to_string();
(divisor, word)
}
fn main() {
let stdin = io::stdin();
let mut lines = stdin.lock().lines().map(|l| l.unwrap());
let l = lines.next().unwrap();
let high = l.parse::<i32>().unwrap();
let mut entries = Vec::new();
for l in lines {
if &l == "" { break }
let entry = parse_entry(&l);
entries.push(entry);
}
for i in 1..(high + 1) {
let mut line = String::new();
for &(divisor, ref word) in &entries {
if i% divisor == 0 {
line = line + &word;
}
}
if line == "" {
println!("{}", i);
} else {
println!("{}", line);
}
}
} | 791General FizzBuzz
| 15rust
| j0072 |
$ scala GeneralFizzBuzz.scala
20
3 Fizz
5 Buzz
7 Baxx
^D
1
2
Fizz
4
Buzz
Fizz
Baxx
8
Fizz
Buzz
11
Fizz
13
Baxx
FizzBuzz
16
17
Fizz
19
Buzz | 791General FizzBuzz
| 16scala
| biik6 |
function getAlphabet ()
local letters = {}
for ascii = 97, 122 do table.insert(letters, string.char(ascii)) end
return letters
end
local alpha = getAlphabet()
print(alpha[25] .. alpha[1] .. alpha[25]) | 796Generate lower case ASCII alphabet
| 1lua
| af81v |
<?php
echo ;
?> | 755Hello world/Text
| 12php
| i22ov |
def powers(m)
return enum_for(__method__, m) unless block_given?
0.step{|n| yield n**m}
end
def squares_without_cubes
return enum_for(__method__) unless block_given?
cubes = powers(3)
c = cubes.next
powers(2) do |s|
c = cubes.next while c < s
yield s unless c == s
end
end
p squares_without_cubes.take(30).drop(20) | 788Generator/Exponential
| 14ruby
| 3gjz7 |
null | 803Fusc sequence
| 11kotlin
| 2p2li |
use Math::Matrix;
my $a = Math::Matrix->new([0,1,0],
[0,0,1],
[2,0,1]);
my $b = Math::Matrix->new([1],
[2],
[4]);
my $x = $a->concat($b)->solve;
print $x; | 794Gaussian elimination
| 2perl
| uabvr |
use std::cmp::Ordering;
use std::iter::Peekable;
fn powers(m: u32) -> impl Iterator<Item = u64> {
(0u64..).map(move |x| x.pow(m))
}
fn noncubic_squares() -> impl Iterator<Item = u64> {
NoncubicSquares {
squares: powers(2).peekable(),
cubes: powers(3).peekable(),
}
}
struct NoncubicSquares<T: Iterator<Item = u64>, U: Iterator<Item = u64>> {
squares: Peekable<T>,
cubes: Peekable<U>,
}
impl<T: Iterator<Item = u64>, U: Iterator<Item = u64>> Iterator for NoncubicSquares<T, U> {
type Item = u64;
fn next(&mut self) -> Option<u64> {
loop {
match self.squares.peek()?.cmp(self.cubes.peek()?) {
Ordering::Equal => self.squares.next(),
Ordering::Greater => self.cubes.next(),
Ordering::Less => return self.squares.next(),
};
}
}
}
fn main() {
noncubic_squares()
.skip(20)
.take(10)
.for_each(|x| print!("{} ", x));
println!();
} | 788Generator/Exponential
| 15rust
| 6rh3l |
null | 804Fractal tree
| 11kotlin
| u12vc |
fun indexOf(n: Int, s: IntArray): Int {
for (i_j in s.withIndex()) {
if (n == i_j.value) {
return i_j.index
}
}
return -1
}
fun getDigits(n: Int, le: Int, digits: IntArray): Boolean {
var mn = n
var mle = le
while (mn > 0) {
val r = mn % 10
if (r == 0 || indexOf(r, digits) >= 0) {
return false
}
mle--
digits[mle] = r
mn /= 10
}
return true
}
val pows = intArrayOf(1, 10, 100, 1_000, 10_000)
fun removeDigit(digits: IntArray, le: Int, idx: Int): Int {
var sum = 0
var pow = pows[le - 2]
for (i in 0 until le) {
if (i == idx) {
continue
}
sum += digits[i] * pow
pow /= 10
}
return sum
}
fun main() {
val lims = listOf(
Pair(12, 97),
Pair(123, 986),
Pair(1234, 9875),
Pair(12345, 98764)
)
val count = IntArray(5)
var omitted = arrayOf<Array<Int>>()
for (i in 0 until 5) {
var array = arrayOf<Int>()
for (j in 0 until 10) {
array += 0
}
omitted += array
}
for (i_lim in lims.withIndex()) {
val i = i_lim.index
val lim = i_lim.value
val nDigits = IntArray(i + 2)
val dDigits = IntArray(i + 2)
val blank = IntArray(i + 2) { 0 }
for (n in lim.first..lim.second) {
blank.copyInto(nDigits)
val nOk = getDigits(n, i + 2, nDigits)
if (!nOk) {
continue
}
for (d in n + 1..lim.second + 1) {
blank.copyInto(dDigits)
val dOk = getDigits(d, i + 2, dDigits)
if (!dOk) {
continue
}
for (nix_digit in nDigits.withIndex()) {
val dix = indexOf(nix_digit.value, dDigits)
if (dix >= 0) {
val rn = removeDigit(nDigits, i + 2, nix_digit.index)
val rd = removeDigit(dDigits, i + 2, dix)
if (n.toDouble() / d.toDouble() == rn.toDouble() / rd.toDouble()) {
count[i]++
omitted[i][nix_digit.value]++
if (count[i] <= 12) {
println("$n/$d = $rn/$rd by omitting ${nix_digit.value}'s")
}
}
}
}
}
}
println()
}
for (i in 2..5) {
println("There are ${count[i - 2]} $i-digit fractions of which:")
for (j in 1..9) {
if (omitted[i - 2][j] == 0) {
continue
}
println("%6d have%d's omitted".format(omitted[i - 2][j], j))
}
println()
}
} | 807Fraction reduction
| 11kotlin
| icqo4 |
function fusc(n)
n = math.floor(n)
if n == 0 or n == 1 then
return n
elseif n % 2 == 0 then
return fusc(n / 2)
else
return fusc((n - 1) / 2) + fusc((n + 1) / 2)
end
end
function numLen(n)
local sum = 1
while n > 9 do
n = math.floor(n / 10)
sum = sum + 1
end
return sum
end
function printLargeFuscs(limit)
print("Printing all largest Fusc numbers up to " .. limit)
print("Index | 803Fusc sequence
| 1lua
| v1v2x |
import Foundation
print("Input max number: ", terminator: "")
guard let maxN = Int(readLine()?? "0"), maxN > 0 else {
fatalError("Please input a number greater than 0")
}
func getFactor() -> (Int, String) {
print("Enter a factor and phrase: ", terminator: "")
guard let factor1Input = readLine() else {
fatalError("Please enter a factor")
}
let sep1 = factor1Input.components(separatedBy: " ")
let phrase = sep1.dropFirst().joined(separator: " ")
guard let factor = Int(sep1[0]), factor!= 0,!phrase.isEmpty else {
fatalError("Please enter a factor and phrase")
}
return (factor, phrase)
}
let (factor1, phrase1) = getFactor()
let (factor2, phrase2) = getFactor()
let (factor3, phrase3) = getFactor()
for i in 1...maxN {
let factors = [
(i.isMultiple(of: factor1), phrase1),
(i.isMultiple(of: factor2), phrase2),
(i.isMultiple(of: factor3), phrase3)
].filter({ $0.0 }).map({ $0.1 }).joined()
print("\(factors.isEmpty? String(i): factors)")
} | 791General FizzBuzz
| 17swift
| rqqgg |
object Generators {
def main(args: Array[String]): Unit = {
def squares(n:Int=0):Stream[Int]=(n*n) #:: squares(n+1)
def cubes(n:Int=0):Stream[Int]=(n*n*n) #:: cubes(n+1)
def filtered(s:Stream[Int], c:Stream[Int]):Stream[Int]={
if(s.head>c.head) filtered(s, c.tail)
else if(s.head<c.head) Stream.cons(s.head, filtered(s.tail, c))
else filtered(s.tail, c)
}
filtered(squares(), cubes()) drop 20 take 10 print
}
} | 788Generator/Exponential
| 16scala
| 9hpm5 |
function indexOf(haystack, needle)
for idx,straw in pairs(haystack) do
if straw == needle then
return idx
end
end
return -1
end
function getDigits(n, le, digits)
while n > 0 do
local r = n % 10
if r == 0 or indexOf(digits, r) > 0 then
return false
end
le = le - 1
digits[le + 1] = r
n = math.floor(n / 10)
end
return true
end
function removeDigit(digits, le, idx)
local pows = { 1, 10, 100, 1000, 10000 }
local sum = 0
local pow = pows[le - 2 + 1]
for i = 1, le do
if i ~= idx then
sum = sum + digits[i] * pow
pow = math.floor(pow / 10)
end
end
return sum
end
function main()
local lims = { {12, 97}, {123, 986}, {1234, 9875}, {12345, 98764} }
local count = { 0, 0, 0, 0, 0 }
local omitted = {
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
}
for i,_ in pairs(lims) do
local nDigits = {}
local dDigits = {}
for j = 1, i + 2 - 1 do
nDigits[j] = -1
dDigits[j] = -1
end
for n = lims[i][1], lims[i][2] do
for j,_ in pairs(nDigits) do
nDigits[j] = 0
end
local nOk = getDigits(n, i + 2 - 1, nDigits)
if nOk then
for d = n + 1, lims[i][2] + 1 do
for j,_ in pairs(dDigits) do
dDigits[j] = 0
end
local dOk = getDigits(d, i + 2 - 1, dDigits)
if dOk then
for nix,_ in pairs(nDigits) do
local digit = nDigits[nix]
local dix = indexOf(dDigits, digit)
if dix >= 0 then
local rn = removeDigit(nDigits, i + 2 - 1, nix)
local rd = removeDigit(dDigits, i + 2 - 1, dix)
if (n / d) == (rn / rd) then
count[i] = count[i] + 1
omitted[i][digit + 1] = omitted[i][digit + 1] + 1
if count[i] <= 12 then
print(string.format("%d/%d =%d/%d by omitting%d's", n, d, rn, rd, digit))
end
end
end
end
end
end
end
end
print()
end
for i = 2, 5 do
print("There are "..count[i - 2 + 1].." "..i.."-digit fractions of which:")
for j = 1, 9 do
if omitted[i - 2 + 1][j + 1] > 0 then
print(string.format("%6d have%d's omitted", omitted[i - 2 + 1][j + 1], j))
end
end
print()
end
end
main() | 807Fraction reduction
| 1lua
| nlsi8 |
public class GammaFunction {
public double st_gamma(double x){
return Math.sqrt(2*Math.PI/x)*Math.pow((x/Math.E), x);
}
public double la_gamma(double x){
double[] p = {0.99999999999980993, 676.5203681218851, -1259.1392167224028,
771.32342877765313, -176.61502916214059, 12.507343278686905,
-0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7};
int g = 7;
if(x < 0.5) return Math.PI / (Math.sin(Math.PI * x)*la_gamma(1-x));
x -= 1;
double a = p[0];
double t = x+g+0.5;
for(int i = 1; i < p.length; i++){
a += p[i]/(x+i);
}
return Math.sqrt(2*Math.PI)*Math.pow(t, x+0.5)*Math.exp(-t)*a;
}
public static void main(String[] args) {
GammaFunction test = new GammaFunction();
System.out.println("Gamma \t\tStirling \t\tLanczos");
for(double i = 1; i <= 20; i += 1){
System.out.println("" + i/10.0 + "\t\t" + test.st_gamma(i/10.0) + "\t" + test.la_gamma(i/10.0));
}
}
} | 802Gamma function
| 9java
| etwa5 |
from itertools import islice, count
for start, n in [(100, 30), (1_000_000, 15), (1_000_000_000, 10)]:
print(f)
print(list(islice(( x for x in count(start)
if (x% (int(str(x)[0]) * 10 + (x% 10)) == 0) )
, n))) | 793Gapful numbers
| 3python
| 89y0o |
function swap_rows(&$a, &$b, $r1, $r2)
{
if ($r1 == $r2) return;
$tmp = $a[$r1];
$a[$r1] = $a[$r2];
$a[$r2] = $tmp;
$tmp = $b[$r1];
$b[$r1] = $b[$r2];
$b[$r2] = $tmp;
}
function gauss_eliminate($A, $b, $N)
{
for ($col = 0; $col < $N; $col++)
{
$j = $col;
$max = $A[$j][$j];
for ($i = $col + 1; $i < $N; $i++)
{
$tmp = abs($A[$i][$col]);
if ($tmp > $max)
{
$j = $i;
$max = $tmp;
}
}
swap_rows($A, $b, $col, $j);
for ($i = $col + 1; $i < $N; $i++)
{
$tmp = $A[$i][$col] / $A[$col][$col];
for ($j = $col + 1; $j < $N; $j++)
{
$A[$i][$j] -= $tmp * $A[$col][$j];
}
$A[$i][$col] = 0;
$b[$i] -= $tmp * $b[$col];
}
}
$x = array();
for ($col = $N - 1; $col >= 0; $col--)
{
$tmp = $b[$col];
for ($j = $N - 1; $j > $col; $j--)
{
$tmp -= $x[$j] * $A[$col][$j];
}
$x[$col] = $tmp / $A[$col][$col];
}
return $x;
}
function test_gauss()
{
$a = array(
array(1.00, 0.00, 0.00, 0.00, 0.00, 0.00),
array(1.00, 0.63, 0.39, 0.25, 0.16, 0.10),
array(1.00, 1.26, 1.58, 1.98, 2.49, 3.13),
array(1.00, 1.88, 3.55, 6.70, 12.62, 23.80),
array(1.00, 2.51, 6.32, 15.88, 39.90, 100.28),
array(1.00, 3.14, 9.87, 31.01, 97.41, 306.02)
);
$b = array( -0.01, 0.61, 0.91, 0.99, 0.60, 0.02 );
$x = gauss_eliminate($a, $b, 6);
ksort($x);
print_r($x);
}
test_gauss(); | 794Gaussian elimination
| 12php
| 8960m |
function gamma(x) {
var p = [0.99999999999980993, 676.5203681218851, -1259.1392167224028,
771.32342877765313, -176.61502916214059, 12.507343278686905,
-0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7
];
var g = 7;
if (x < 0.5) {
return Math.PI / (Math.sin(Math.PI * x) * gamma(1 - x));
}
x -= 1;
var a = p[0];
var t = x + g + 0.5;
for (var i = 1; i < p.length; i++) {
a += p[i] / (x + i);
}
return Math.sqrt(2 * Math.PI) * Math.pow(t, x + 0.5) * Math.exp(-t) * a;
} | 802Gamma function
| 10javascript
| 0m8sz |
use strict;
use warnings;
use feature 'say';
sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }
sub stern_diatomic {
my ($p,$q,$i) = (0,1,shift);
while ($i) {
if ($i & 1) { $p += $q; } else { $q += $p; }
$i >>= 1;
}
$p;
}
say "First 61 terms of the Fusc sequence:\n" . join ' ', map { stern_diatomic($_) } 0..60;
say "\nIndex and value for first term longer than any previous:";
my $i = 0;
my $l = -1;
while ($l < 5) {
my $v = stern_diatomic($i);
printf("%15s:%s\n", comma($i), comma($v)) and $l = length $v if length $v > $l;
$i++;
} | 803Fusc sequence
| 2perl
| sysq3 |
null | 806Function composition
| 0go
| s6eqa |
g, angle = love.graphics, 26 * math.pi / 180
wid, hei = g.getWidth(), g.getHeight()
function rotate( x, y, a )
local s, c = math.sin( a ), math.cos( a )
local a, b = x * c - y * s, x * s + y * c
return a, b
end
function branches( a, b, len, ang, dir )
len = len * .76
if len < 5 then return end
g.setColor( len * 16, 255 - 2 * len , 0 )
if dir > 0 then ang = ang - angle
else ang = ang + angle
end
local vx, vy = rotate( 0, len, ang )
vx = a + vx; vy = b - vy
g.line( a, b, vx, vy )
branches( vx, vy, len, ang, 1 )
branches( vx, vy, len, ang, 0 )
end
function createTree()
local lineLen = 127
local a, b = wid / 2, hei - lineLen
g.setColor( 160, 40 , 0 )
g.line( wid / 2, hei, a, b )
branches( a, b, lineLen, 0, 1 )
branches( a, b, lineLen, 0, 0 )
end
function love.load()
canvas = g.newCanvas( wid, hei )
g.setCanvas( canvas )
createTree()
g.setCanvas()
end
function love.draw()
g.draw( canvas )
end | 804Fractal tree
| 1lua
| 5avu6 |
package main
import (
"fmt"
"log"
"math/big"
"os"
"strconv"
"strings"
)
func compile(src string) ([]big.Rat, bool) {
s := strings.Fields(src)
r := make([]big.Rat, len(s))
for i, s1 := range s {
if _, ok := r[i].SetString(s1); !ok {
return nil, false
}
}
return r, true
}
func exec(p []big.Rat, n *big.Int, limit int) {
var q, r big.Int
rule:
for i := 0; i < limit; i++ {
fmt.Printf("%d ", n)
for j := range p {
q.QuoRem(n, p[j].Denom(), &r)
if r.BitLen() == 0 {
n.Mul(&q, p[j].Num())
continue rule
}
}
break
}
fmt.Println()
}
func usage() {
log.Fatal("usage: ft <limit> <n> <prog>")
}
func main() {
if len(os.Args) != 4 {
usage()
}
limit, err := strconv.Atoi(os.Args[1])
if err != nil {
usage()
}
var n big.Int
_, ok := n.SetString(os.Args[2], 10)
if !ok {
usage()
}
p, ok := compile(os.Args[3])
if !ok {
usage()
}
exec(p, &n, limit)
} | 805Fractran
| 0go
| 1nkp5 |
class Integer
def gapful?
a = digits
self % (a.last*10 + a.first) == 0
end
end
specs = {100 => 30, 1_000_000 => 15, 1_000_000_000 => 10, 7123 => 25}
specs.each do |start, num|
puts
p (start..).lazy.select(&:gapful?).take(num).to_a
end | 793Gapful numbers
| 14ruby
| il9oh |
import copy
from fractions import Fraction
def gauss(a, b):
a = copy.deepcopy(a)
b = copy.deepcopy(b)
n = len(a)
p = len(b[0])
det = 1
for i in range(n - 1):
k = i
for j in range(i + 1, n):
if abs(a[j][i]) > abs(a[k][i]):
k = j
if k != i:
a[i], a[k] = a[k], a[i]
b[i], b[k] = b[k], b[i]
det = -det
for j in range(i + 1, n):
t = a[j][i]/a[i][i]
for k in range(i + 1, n):
a[j][k] -= t*a[i][k]
for k in range(p):
b[j][k] -= t*b[i][k]
for i in range(n - 1, -1, -1):
for j in range(i + 1, n):
t = a[i][j]
for k in range(p):
b[i][k] -= t*b[j][k]
t = 1/a[i][i]
det *= a[i][i]
for j in range(p):
b[i][j] *= t
return det, b
def zeromat(p, q):
return [[0]*q for i in range(p)]
def matmul(a, b):
n, p = len(a), len(a[0])
p1, q = len(b), len(b[0])
if p != p1:
raise ValueError()
c = zeromat(n, q)
for i in range(n):
for j in range(q):
c[i][j] = sum(a[i][k]*b[k][j] for k in range(p))
return c
def mapmat(f, a):
return [list(map(f, v)) for v in a]
def ratmat(a):
return mapmat(Fraction, a)
a = [[2, 9, 4], [7, 5, 3], [6, 1, 8]]
b = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
det, c = gauss(a, b)
det
-360.0
c
[[-0.10277777777777776, 0.18888888888888888, -0.019444444444444438],
[0.10555555555555554, 0.02222222222222223, -0.061111111111111116],
[0.0638888888888889, -0.14444444444444446, 0.14722222222222223]]
matmul(a, c)
[[1.0, 0.0, 0.0], [5.551115123125783e-17, 1.0, 0.0],
[1.1102230246251565e-16, -2.220446049250313e-16, 1.0]]
det, c = gauss(ratmat(a), ratmat(b))
det
Fraction(-360, 1)
c
[[Fraction(-37, 360), Fraction(17, 90), Fraction(-7, 360)],
[Fraction(19, 180), Fraction(1, 45), Fraction(-11, 180)],
[Fraction(23, 360), Fraction(-13, 90), Fraction(53, 360)]]
matmul(a, c)
[[Fraction(1, 1), Fraction(0, 1), Fraction(0, 1)],
[Fraction(0, 1), Fraction(1, 1), Fraction(0, 1)],
[Fraction(0, 1), Fraction(0, 1), Fraction(1, 1)]] | 794Gaussian elimination
| 3python
| 5epux |
final times2 = { it * 2 }
final plus1 = { it + 1 }
final plus1_then_times2 = times2 << plus1
final times2_then_plus1 = times2 >> plus1
assert plus1_then_times2(3) == 8
assert times2_then_plus1(3) == 7 | 806Function composition
| 7groovy
| adk1p |
Prelude> let sin_asin = sin . asin
Prelude> sin_asin 0.5
0.49999999999999994 | 806Function composition
| 8haskell
| 9j3mo |
import Data.List (find)
import Data.Ratio (Ratio, (%), denominator)
fractran :: (Integral a) => [Ratio a] -> a -> [a]
fractran fracts n = n:
case find (\f -> n `mod` denominator f == 0) fracts of
Nothing -> []
Just f -> fractran fracts $ truncate (fromIntegral n * f) | 805Fractran
| 8haskell
| tunf7 |
gauss <- function(a, b) {
n <- nrow(a)
det <- 1
for (i in seq_len(n - 1)) {
j <- which.max(a[i:n, i]) + i - 1
if (j!= i) {
a[c(i, j), i:n] <- a[c(j, i), i:n]
b[c(i, j), ] <- b[c(j, i), ]
det <- -det
}
k <- seq(i + 1, n)
for (j in k) {
s <- a[[j, i]] / a[[i, i]]
a[j, k] <- a[j, k] - s * a[i, k]
b[j, ] <- b[j, ] - s * b[i, ]
}
}
for (i in seq(n, 1)) {
if (i < n) {
for (j in seq(i + 1, n)) {
b[i, ] <- b[i, ] - a[[i, j]] * b[j, ]
}
}
b[i, ] <- b[i, ] / a[[i, i]]
det <- det * a[[i, i]]
}
list(x=b, det=det)
}
a <- matrix(c(2, 9, 4, 7, 5, 3, 6, 1, 8), 3, 3, byrow=T)
gauss(a, diag(3)) | 794Gaussian elimination
| 13r
| lbjce |
func powGen(m: Int) -> GeneratorOf<Int> {
let power = Double(m)
var cur: Double = 0
return GeneratorOf { Int(pow(cur++, power)) }
}
var squares = powGen(2)
var cubes = powGen(3)
var nCube = cubes.next()
var filteredSqs = GeneratorOf<Int> {
for var nSq = squares.next();; nCube = cubes.next() {
if nCube > nSq {
return nSq
} else if nCube == nSq {
nSq = squares.next()
}
}
}
extension GeneratorOf {
func drop(n: Int) -> GeneratorOf<T> {
var g = self
for _ in 0..<n {g.next()}
return GeneratorOf{g.next()}
}
func take(n: Int) -> GeneratorOf<T> {
var (i, g) = (0, self)
return GeneratorOf{++i > n? nil: g.next()}
}
}
for num in filteredSqs.drop(20).take(10) {
print(num)
} | 788Generator/Exponential
| 17swift
| z47tu |
use strict;
use warnings;
use feature 'say';
use List::Util qw<sum uniq uniqnum head tail>;
for my $exp (map { $_ - 1 } <2 3 4>) {
my %reduced;
my $start = sum map { 10 ** $_ * ($exp - $_ + 1) } 0..$exp;
my $end = 10**($exp+1) - -1 + sum map { 10 ** $_ * ($exp - $_) } 0..$exp-1;
for my $den ($start .. $end-1) {
next if $den =~ /0/ or (uniqnum split '', $den) <= $exp;
for my $num ($start .. $den-1) {
next if $num =~ /0/ or (uniqnum split '', $num) <= $exp;
my %i;
map { $i{$_}++ } (uniq head -1, split '',$den), uniq tail -1, split '',$num;
my @set = grep { $_ if $i{$_} > 1 } keys %i;
next if @set < 1;
for (@set) {
(my $ne = $num) =~ s/$_//;
(my $de = $den) =~ s/$_//;
if ($ne/$de == $num/$den) {
$reduced{"$num/$den:$_"} = "$ne/$de";
}
}
}
}
my $digit = $exp + 1;
say "\n" . +%reduced . " $digit-digit reducible fractions:";
for my $n (1..9) {
my $cnt = scalar grep { /:$n/ } keys %reduced;
say "$cnt with removed $n" if $cnt;
}
say "\n 12 (or all, if less) $digit-digit reducible fractions:";
for my $f (head 12, sort keys %reduced) {
printf " %s =>%s removed%s\n", substr($f,0,$digit*2+1), $reduced{$f}, substr($f,-1)
}
} | 807Fraction reduction
| 2perl
| rxvgd |
null | 802Gamma function
| 11kotlin
| kobh3 |
public class Compose { | 806Function composition
| 9java
| tuif9 |
from collections import deque
from itertools import islice, count
def fusc():
q = deque([1])
yield 0
yield 1
while True:
x = q.popleft()
q.append(x)
yield x
x += q[0]
q.append(x)
yield x
def longest_fusc():
sofar = 0
for i, f in zip(count(), fusc()):
if f >= sofar:
yield(i, f)
sofar = 10 * sofar or 10
print('First 61:')
print(list(islice(fusc(), 61)))
print('\nLength records:')
for i, f in islice(longest_fusc(), 6):
print(f'fusc({i}) = {f}') | 803Fusc sequence
| 3python
| 0m0sq |
WITH
FUNCTION gapful_numbers(p_start IN INTEGER, p_count IN INTEGER) RETURN varchar2 IS
v_start INTEGER:= p_start;
v_count INTEGER:= 0;
v_res varchar2(32767);
BEGIN
v_res:= 'First '||p_count||' gapful numbers starting from '||p_start||': ';
-- main cycle
while TRUE loop
IF MOD(v_start,to_number(substr(v_start,1,1)||substr(v_start,-1))) = 0 THEN
v_res:= v_res || v_start;
v_count:= v_count + 1;
exit WHEN v_count = p_count;
v_res:= v_res || ', ';
END IF;
v_start:= v_start + 1;
END loop;
--
RETURN v_res;
--
END;
--Test
SELECT gapful_numbers(100,30) AS res FROM dual
UNION ALL
SELECT gapful_numbers(1000000,15) AS res FROM dual
UNION ALL
SELECT gapful_numbers(1000000000,10) AS res FROM dual;
/ | 793Gapful numbers
| 19sql
| 6r43m |
function compose(f, g) {
return function(x) {
return f(g(x));
};
} | 806Function composition
| 10javascript
| m7zyv |
use GD::Simple;
my ($width, $height) = (1000,1000);
my $scale = 6/10;
my $length = 400;
my $img = GD::Simple->new($width,$height);
$img->fgcolor('black');
$img->penSize(1,1);
tree($width/2, $height, $length, 270);
print $img->png;
sub tree
{
my ($x, $y, $len, $angle) = @_;
return if $len < 1;
$img->moveTo($x,$y);
$img->angle($angle);
$img->line($len);
($x, $y) = $img->curPos();
tree($x, $y, $len*$scale, $angle+35);
tree($x, $y, $len*$scale, $angle-35);
} | 804Fractal tree
| 2perl
| 8ms0w |
def indexOf(haystack, needle):
idx = 0
for straw in haystack:
if straw == needle:
return idx
else:
idx += 1
return -1
def getDigits(n, le, digits):
while n > 0:
r = n% 10
if r == 0 or indexOf(digits, r) >= 0:
return False
le -= 1
digits[le] = r
n = int(n / 10)
return True
def removeDigit(digits, le, idx):
pows = [1, 10, 100, 1000, 10000]
sum = 0
pow = pows[le - 2]
i = 0
while i < le:
if i == idx:
i += 1
continue
sum = sum + digits[i] * pow
pow = int(pow / 10)
i += 1
return sum
def main():
lims = [ [ 12, 97 ], [ 123, 986 ], [ 1234, 9875 ], [ 12345, 98764 ] ]
count = [0 for i in range(5)]
omitted = [[0 for i in range(10)] for j in range(5)]
i = 0
while i < len(lims):
n = lims[i][0]
while n < lims[i][1]:
nDigits = [0 for k in range(i + 2)]
nOk = getDigits(n, i + 2, nDigits)
if not nOk:
n += 1
continue
d = n + 1
while d <= lims[i][1] + 1:
dDigits = [0 for k in range(i + 2)]
dOk = getDigits(d, i + 2, dDigits)
if not dOk:
d += 1
continue
nix = 0
while nix < len(nDigits):
digit = nDigits[nix]
dix = indexOf(dDigits, digit)
if dix >= 0:
rn = removeDigit(nDigits, i + 2, nix)
rd = removeDigit(dDigits, i + 2, dix)
if (1.0 * n / d) == (1.0 * rn / rd):
count[i] += 1
omitted[i][digit] += 1
if count[i] <= 12:
print % (n, d, rn, rd, digit)
nix += 1
d += 1
n += 1
print
i += 1
i = 2
while i <= 5:
print % (count[i - 2], i)
j = 1
while j <= 9:
if omitted[i - 2][j] == 0:
j += 1
continue
print % (omitted[i - 2][j], j)
j += 1
print
i += 1
return None
main() | 807Fraction reduction
| 3python
| 7qurm |
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Fractran{
public static void main(String []args){
new Fractran("17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1", 2);
}
final int limit = 15;
Vector<Integer> num = new Vector<>();
Vector<Integer> den = new Vector<>();
public Fractran(String prog, Integer val){
compile(prog);
dump();
exec(2);
}
void compile(String prog){
Pattern regexp = Pattern.compile("\\s*(\\d*)\\s*\\/\\s*(\\d*)\\s*(.*)");
Matcher matcher = regexp.matcher(prog);
while(matcher.find()){
num.add(Integer.parseInt(matcher.group(1)));
den.add(Integer.parseInt(matcher.group(2)));
matcher = regexp.matcher(matcher.group(3));
}
}
void exec(Integer val){
int n = 0;
while(val != null && n<limit){
System.out.println(n+": "+val);
val = step(val);
n++;
}
}
Integer step(int val){
int i=0;
while(i<den.size() && val%den.get(i) != 0) i++;
if(i<den.size())
return num.get(i)*val/den.get(i);
return null;
}
void dump(){
for(int i=0; i<den.size(); i++)
System.out.print(num.get(i)+"/"+den.get(i)+" ");
System.out.println();
}
} | 805Fractran
| 9java
| 8mq06 |
firstNFuscNumbers <- function(n)
{
stopifnot(n > 0)
if(n == 1) return(0) else fusc <- c(0, 1)
if(n > 2)
{
for(i in seq(from = 3, to = n, by = 1))
{
fusc[i] <- if(i %% 2) fusc[(i + 1) / 2] else fusc[i / 2] + fusc[(i + 2) / 2]
}
}
fusc
}
first61 <- firstNFuscNumbers(61)
cat("The first 61 Fusc numbers are:", "\n", first61, "\n") | 803Fusc sequence
| 13r
| wzwe5 |
gamma, coeff, quad, qui, set = 0.577215664901, -0.65587807152056, -0.042002635033944, 0.16653861138228, -0.042197734555571
function recigamma(z)
return z + gamma * z^2 + coeff * z^3 + quad * z^4 + qui * z^5 + set * z^6
end
function gammafunc(z)
if z == 1 then return 1
elseif math.abs(z) <= 0.5 then return 1 / recigamma(z)
else return (z - 1) * gammafunc(z-1)
end
end | 802Gamma function
| 1lua
| bipka |
func isGapful(n: Int) -> Bool {
guard n > 100 else {
return true
}
let asString = String(n)
let div = Int("\(asString.first!)\(asString.last!)")!
return n% div == 0
}
let first30 = (100...).lazy.filter(isGapful).prefix(30)
let mil = (1_000_000...).lazy.filter(isGapful).prefix(15)
let bil = (1_000_000_000...).lazy.filter(isGapful).prefix(15)
print("First 30 gapful numbers: \(Array(first30))")
print("First 15 >= 1,000,000: \(Array(mil))")
print("First 15 >= 1,000,000,000: \(Array(bil))") | 793Gapful numbers
| 17swift
| ocm8k |
print 'a'..'z' | 796Generate lower case ASCII alphabet
| 2perl
| mj5yz |
null | 805Fractran
| 10javascript
| fvidg |
require 'bigdecimal/ludcmp'
include LUSolve
BigDecimal::limit(30)
a = [1.00, 0.00, 0.00, 0.00, 0.00, 0.00,
1.00, 0.63, 0.39, 0.25, 0.16, 0.10,
1.00, 1.26, 1.58, 1.98, 2.49, 3.13,
1.00, 1.88, 3.55, 6.70, 12.62, 23.80,
1.00, 2.51, 6.32, 15.88, 39.90, 100.28,
1.00, 3.14, 9.87, 31.01, 97.41, 306.02].map{|i|BigDecimal(i,16)}
b = [-0.01, 0.61, 0.91, 0.99, 0.60, 0.02].map{|i|BigDecimal(i,16)}
n = 6
zero = BigDecimal()
one = BigDecimal()
lusolve(a, b, ludecomp(a, n, zero,one), zero).each{|v| puts v.to_s('F')[0..20]} | 794Gaussian elimination
| 14ruby
| gxa4q |
<?php
$lower = range('a', 'z');
var_dump($lower);
?> | 796Generate lower case ASCII alphabet
| 12php
| etoa9 |
<?php
header();
$width = 512;
$height = 512;
$img = imagecreatetruecolor($width,$height);
$bg = imagecolorallocate($img,255,255,255);
imagefilledrectangle($img, 0, 0, $width, $width, $bg);
$depth = 8;
function drawTree($x1, $y1, $angle, $depth){
global $img;
if ($depth != 0){
$x2 = $x1 + (int)(cos(deg2rad($angle)) * $depth * 10.0);
$y2 = $y1 + (int)(sin(deg2rad($angle)) * $depth * 10.0);
imageline($img, $x1, $y1, $x2, $y2, imagecolorallocate($img,0,0,0));
drawTree($x2, $y2, $angle - 20, $depth - 1);
drawTree($x2, $y2, $angle + 20, $depth - 1);
}
}
drawTree($width/2, $height, -90, $depth);
imagepng($img);
imagedestroy($img);
?> | 804Fractal tree
| 12php
| 4eu5n |
null | 794Gaussian elimination
| 15rust
| rqeg5 |
null | 806Function composition
| 11kotlin
| o9q8z |
null | 805Fractran
| 11kotlin
| wt1ek |
fusc = Enumerator.new do |y|
y << 0
y << 1
arr = [0,1]
2.step do |n|
res = n.even?? arr[n/2]: arr[(n-1)/2] + arr[(n+1)/2]
y << res
arr << res
end
end
fusc_max_digits = Enumerator.new do |y|
cur_max, cur_exp = 0, 0
0.step do |i|
f = fusc.next
if f >= cur_max
cur_exp += 1
cur_max = 10**cur_exp
y << [i, f]
end
end
end
puts fusc.take(61).join()
fusc_max_digits.take(6).each{|pair| puts % pair } | 803Fusc sequence
| 14ruby
| oco8v |
def indexOf(haystack, needle)
idx = 0
for straw in haystack
if straw == needle then
return idx
else
idx = idx + 1
end
end
return -1
end
def getDigits(n, le, digits)
while n > 0
r = n % 10
if r == 0 or indexOf(digits, r) >= 0 then
return false
end
le = le - 1
digits[le] = r
n = (n / 10).floor
end
return true
end
POWS = [1, 10, 100, 1000, 10000]
def removeDigit(digits, le, idx)
sum = 0
pow = POWS[le - 2]
i = 0
while i < le
if i == idx then
i = i + 1
next
end
sum = sum + digits[i] * pow
pow = (pow / 10).floor
i = i + 1
end
return sum
end
def main
lims = [ [ 12, 97 ], [ 123, 986 ], [ 1234, 9875 ], [ 12345, 98764 ] ]
count = Array.new(5, 0)
omitted = Array.new(5) { Array.new(10, 0) }
i = 0
for lim in lims
n = lim[0]
while n < lim[1]
nDigits = [0] * (i + 2)
nOk = getDigits(n, i + 2, nDigits)
if not nOk then
n = n + 1
next
end
d = n + 1
while d <= lim[1] + 1
dDigits = [0] * (i + 2)
dOk = getDigits(d, i + 2, dDigits)
if not dOk then
d = d + 1
next
end
nix = 0
while nix < nDigits.length
digit = nDigits[nix]
dix = indexOf(dDigits, digit)
if dix >= 0 then
rn = removeDigit(nDigits, i + 2, nix)
rd = removeDigit(dDigits, i + 2, dix)
if (1.0 * n / d) == (1.0 * rn / rd) then
count[i] = count[i] + 1
omitted[i][digit] = omitted[i][digit] + 1
if count[i] <= 12 then
print % [n, d, rn, rd, digit]
end
end
end
nix = nix + 1
end
d = d + 1
end
n = n + 1
end
print
i = i + 1
end
i = 2
while i <= 5
print % [count[i - 2], i]
j = 1
while j <= 9
if omitted[i - 2][j] == 0 then
j = j + 1
next
end
print % [omitted[i - 2][j], j]
j = j + 1
end
print
i = i + 1
end
end
main() | 807Fraction reduction
| 14ruby
| h04jx |
fn fusc_sequence() -> impl std::iter::Iterator<Item = u32> {
let mut sequence = vec![0, 1];
let mut n = 0;
std::iter::from_fn(move || {
if n > 1 {
sequence.push(match n% 2 {
0 => sequence[n / 2],
_ => sequence[(n - 1) / 2] + sequence[(n + 1) / 2],
});
}
let result = sequence[n];
n += 1;
Some(result)
})
}
fn main() {
println!("First 61 fusc numbers:");
for n in fusc_sequence().take(61) {
print!("{} ", n)
}
println!();
let limit = 1000000000;
println!(
"Fusc numbers up to {} that are longer than any previous one:",
limit
);
let mut max = 0;
for (index, n) in fusc_sequence().take(limit).enumerate() {
if n >= max {
max = std::cmp::max(10, max * 10);
println!("index = {}, fusc number = {}", index, n);
}
}
} | 803Fusc sequence
| 15rust
| iliod |
function compose(f, g) return function(...) return f(g(...)) end end | 806Function composition
| 1lua
| icsot |
struct FuscSeq: Sequence, IteratorProtocol {
private var arr = [0, 1]
private var i = 0
mutating func next() -> Int? {
defer {
i += 1
}
guard i > 1 else {
return arr[i]
}
switch i & 1 {
case 0:
arr.append(arr[i / 2])
case 1:
arr.append(arr[(i - 1) / 2] + arr[(i + 1) / 2])
case _:
fatalError()
}
return arr.last!
}
}
let first = FuscSeq().prefix(61)
print("First 61: \(Array(first))")
var max = -1
for (i, n) in FuscSeq().prefix(20_000_000).enumerated() {
let f = String(n).count
if f > max {
max = f
print("New max: \(i): \(n)")
}
} | 803Fusc sequence
| 17swift
| 8980v |
func gaussEliminate(_ sys: [[Double]]) -> [Double]? {
var system = sys
let size = system.count
for i in 0..<size-1 where system[i][i]!= 0 {
for j in i..<size-1 {
let factor = system[j + 1][i] / system[i][i]
for k in i..<size+1 {
system[j + 1][k] -= factor * system[i][k]
}
}
}
for i in (1..<size).reversed() where system[i][i]!= 0 {
for j in (1..<i+1).reversed() {
let factor = system[j - 1][i] / system[i][i]
for k in (0..<size+1).reversed() {
system[j - 1][k] -= factor * system[i][k]
}
}
}
var solutions = [Double]()
for i in 0..<size {
guard system[i][i]!= 0 else {
return nil
}
system[i][size] /= system[i][i]
system[i][i] = 1
solutions.append(system[i][size])
}
return solutions
}
let sys = [
[1.00, 0.00, 0.00, 0.00, 0.00, 0.00, -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.90, 100.28, 0.60],
[1.00, 3.14, 9.87, 31.01, 97.41, 306.02, 0.02]
]
guard let sols = gaussEliminate(sys) else {
fatalError("No solutions")
}
for (i, f) in sols.enumerated() {
print("X\(i + 1) = \(f)")
} | 794Gaussian elimination
| 17swift
| 4w15g |
from string import ascii_lowercase
lower = [chr(i) for i in range(ord('a'), ord('z') + 1)] | 796Generate lower case ASCII alphabet
| 3python
| 9h4mf |
letters
sapply(97:122, intToUtf8) | 796Generate lower case ASCII alphabet
| 13r
| 3g2zt |
import pygame, math
pygame.init()
window = pygame.display.set_mode((600, 600))
pygame.display.set_caption()
screen = pygame.display.get_surface()
def drawTree(x1, y1, angle, depth):
fork_angle = 20
base_len = 10.0
if depth > 0:
x2 = x1 + int(math.cos(math.radians(angle)) * depth * base_len)
y2 = y1 + int(math.sin(math.radians(angle)) * depth * base_len)
pygame.draw.line(screen, (255,255,255), (x1, y1), (x2, y2), 2)
drawTree(x2, y2, angle - fork_angle, depth - 1)
drawTree(x2, y2, angle + fork_angle, depth - 1)
def input(event):
if event.type == pygame.QUIT:
exit(0)
drawTree(300, 550, -90, 9)
pygame.display.flip()
while True:
input(pygame.event.wait()) | 804Fractal tree
| 3python
| o9081 |
use strict;
use warnings;
use Math::BigRat;
my ($n, @P) = map Math::BigRat->new($_), qw{
2 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
};
$|=1;
MAIN: for( 1 .. 5000 ) {
print " " if $_ > 1;
my ($pow, $rest) = (0, $n->copy);
until( $rest->is_odd ) {
++$pow;
$rest->bdiv(2);
}
if( $rest->is_one ) {
print "2**$pow";
} else {
}
for my $f_i (@P) {
my $nf_i = $n * $f_i;
next unless $nf_i->is_int;
$n = $nf_i;
next MAIN;
}
last;
}
print "\n"; | 805Fractran
| 2perl
| lkmc5 |
double multiply(double a, double b)
{
return a * b;
} | 808Function definition
| 5c
| gwl45 |
plotftree <- function(x, y, a, d, c) {
x2=y2=0; d2r=pi/180.0; a1 <- a*d2r; d1=0;
if(d<=0) {return()}
if(d>0)
{ d1=d*10.0;
x2=x+cos(a1)*d1;
y2=y+sin(a1)*d1;
segments(x*c, y*c, x2*c, y2*c, col='darkgreen');
plotftree(x2,y2,a-20,d-1,c);
plotftree(x2,y2,a+20,d-1,c);
}
}
pFractalTree <- function(ord, c=1, xsh=0, fn="", ttl="") {
cat(" *** START FRT:", date(), "\n");
m=640;
if(fn=="") {pf=paste0("FRTR", ord, ".png")} else {pf=paste0(fn, ".png")};
if(ttl=="") {ttl=paste0("Fractal tree, order - ", ord)};
cat(" *** Plot file -", pf, "title:", ttl, "\n");
plot(NA, xlim=c(0,m), ylim=c(0,m), xlab="", ylab="", main=ttl);
plotftree(m/2+xsh,100,90,ord,c);
dev.copy(png, filename=pf, width=m, height=m);
dev.off(); graphics.off();
cat(" *** END FRT:",date(),"\n");
}
pFractalTree(9);
pFractalTree(12,0.6,210);
pFractalTree(15,0.35,600); | 804Fractal tree
| 13r
| q3wxs |
use strict;
use warnings;
use constant pi => 4*atan2(1, 1);
use constant e => exp(1);
my $have_MPFR = eval { require Math::MPFR; Math::MPFR->import(); 1; };
sub Gamma {
my $z = shift;
my $method = shift // 'lanczos';
if ($method eq 'lanczos') {
use constant g => 9;
$z < .5 ? pi / sin(pi * $z) / Gamma(1 - $z, $method) :
sqrt(2* pi) *
($z + g - .5)**($z - .5) *
exp(-($z + g - .5)) *
do {
my @coeff = qw{
1.000000000000000174663
5716.400188274341379136
-14815.30426768413909044
14291.49277657478554025
-6348.160217641458813289
1301.608286058321874105
-108.1767053514369634679
2.605696505611755827729
-0.7423452510201416151527e-2
0.5384136432509564062961e-7
-0.4023533141268236372067e-8
};
my ($sum, $i) = (shift(@coeff), 0);
$sum += $_ / ($z + $i++) for @coeff;
$sum;
}
} elsif ($method eq 'taylor') {
$z < .5 ? Gamma($z+1, $method)/$z :
$z > 1.5 ? ($z-1)*Gamma($z-1, $method) :
do {
my $s = 0; ($s *= $z-1) += $_ for qw{
0.00000000000000000002 -0.00000000000000000023 0.00000000000000000141
0.00000000000000000119 -0.00000000000000011813 0.00000000000000122678
-0.00000000000000534812 -0.00000000000002058326 0.00000000000051003703
-0.00000000000369680562 0.00000000000778226344 0.00000000010434267117
-0.00000000118127457049 0.00000000500200764447 0.00000000611609510448
-0.00000020563384169776 0.00000113302723198170 -0.00000125049348214267
-0.00002013485478078824 0.00012805028238811619 -0.00021524167411495097
-0.00116516759185906511 0.00721894324666309954 -0.00962197152787697356
-0.04219773455554433675 0.16653861138229148950 -0.04200263503409523553
-0.65587807152025388108 0.57721566490153286061 1.00000000000000000000
}; 1/$s;
}
} elsif ($method eq 'stirling') {
no warnings qw(recursion);
$z < 100 ? Gamma($z + 1, $method)/$z :
sqrt(2*pi*$z)*($z/e + 1/(12*e*$z))**$z / $z;
} elsif ($method eq 'MPFR') {
my $result = Math::MPFR->new();
Math::MPFR::Rmpfr_gamma($result, Math::MPFR->new($z), 0);
$result;
} else { die "unknown method '$method'" }
}
for my $method (qw(MPFR lanczos taylor stirling)) {
next if $method eq 'MPFR' && !$have_MPFR;
printf "%10s: ", $method;
print join(' ', map { sprintf "%.12f", Gamma($_/3, $method) } 1 .. 10);
print "\n";
} | 802Gamma function
| 2perl
| 3g6zs |
p ('a' .. 'z').to_a
p [*'a' .. 'z'] | 796Generate lower case ASCII alphabet
| 14ruby
| lbrcl |
fn main() { | 796Generate lower case ASCII alphabet
| 15rust
| 2p7lt |
from fractions import Fraction
def fractran(n, fstring='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'):
flist = [Fraction(f) for f in fstring.replace(' ', '').split(',')]
n = Fraction(n)
while True:
yield n.numerator
for f in flist:
if (n * f).denominator == 1:
break
else:
break
n *= f
if __name__ == '__main__':
n, m = 2, 15
print('First%i members of fractran(%i):\n '% (m, n) +
', '.join(str(f) for f,i in zip(fractran(n), range(m)))) | 805Fractran
| 3python
| 2b9lz |
object Abc extends App {
val lowAlpha = 'a' to 'z' | 796Generate lower case ASCII alphabet
| 16scala
| 5ekut |
Shoes.app(:title => , :width => 600, :height => 600) do
background
stroke
@deg_to_rad = Math::PI / 180.0
def drawTree(x1, y1, angle, depth)
if depth!= 0
x2 = x1 + (Math.cos(angle * @deg_to_rad) * depth * 10.0).to_i
y2 = y1 + (Math.sin(angle * @deg_to_rad) * depth * 10.0).to_i
line x1, y1, x2, y2
drawTree(x2, y2, angle - 20, depth - 1)
drawTree(x2, y2, angle + 20, depth - 1)
end
end
drawTree(300,550,-90,9)
end | 804Fractal tree
| 14ruby
| nloit |
null | 804Fractal tree
| 15rust
| d2iny |
import swing._
import java.awt.{RenderingHints, BasicStroke, Color}
object FractalTree extends SimpleSwingApplication {
val DEPTH = 9
def top = new MainFrame {
contents = new Panel {
preferredSize = new Dimension(600, 500)
override def paintComponent(g: Graphics2D) {
draw(300, 460, -90, DEPTH)
def draw(x1: Int, y1: Int, angle: Double, depth: Int) {
if (depth > 0) {
val x2 = x1 + (math.cos(angle.toRadians) * depth * 10).toInt
val y2 = y1 + (math.sin(angle.toRadians) * depth * 10).toInt
g.setColor(Color.getHSBColor(0.25f - depth * 0.125f / DEPTH, 0.9f, 0.6f))
g.setStroke(new BasicStroke(depth))
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
g.drawLine(x1, y1, x2, y2)
draw(x2, y2, angle - 20, depth - 1)
draw(x2, y2, angle + 20, depth - 1)
}
}
}
}
}
} | 804Fractal tree
| 16scala
| z5ftr |
(defn multiply [x y]
(* x y))
(multiply 4 5) | 808Function definition
| 6clojure
| k84hs |
_a = ( 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
)
def gamma (x):
y = float(x) - 1.0;
sm = _a[-1];
for an in _a[-2::-1]:
sm = sm * y + an;
return 1.0 / sm;
if __name__ == '__main__':
for i in range(1,11):
print % gamma(i/3.0) | 802Gamma function
| 3python
| 6ry3w |
stirling <- function(z) sqrt(2*pi/z) * (exp(-1)*z)^z
nemes <- function(z) sqrt(2*pi/z) * (exp(-1)*(z + (12*z - (10*z)^-1)^-1))^z
lanczos <- function(z)
{
if(length(z) > 1)
{
sapply(z, lanczos)
} else
{
g <- 7
p <- c(0.99999999999980993, 676.5203681218851, -1259.1392167224028,
771.32342877765313, -176.61502916214059, 12.507343278686905,
-0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7)
z <- as.complex(z)
if(Re(z) < 0.5)
{
pi / (sin(pi*z) * lanczos(1-z))
} else
{
z <- z - 1
x <- p[1] + sum(p[-1]/seq.int(z+1, z+g+1))
tt <- z + g + 0.5
sqrt(2*pi) * tt^(z+0.5) * exp(-tt) * x
}
}
}
spouge <- function(z, a=49)
{
if(length(z) > 1)
{
sapply(z, spouge)
} else
{
z <- z-1
k <- seq.int(1, a-1)
ck <- rep(c(1, -1), len=a-1) / factorial(k-1) * (a-k)^(k-0.5) * exp(a-k)
(z + a)^(z+0.5) * exp(-z - a) * (sqrt(2*pi) + sum(ck/(z+k)))
}
}
z <- (1:10)/3
all.equal(gamma(z), stirling(z))
all.equal(gamma(z), nemes(z))
all.equal(as.complex(gamma(z)), lanczos(z))
all.equal(gamma(z), spouge(z))
data.frame(z=z, stirling=stirling(z), nemes=nemes(z), lanczos=lanczos(z), spouge=spouge(z), builtin=gamma(z)) | 802Gamma function
| 13r
| futdc |
var letters = [Character]()
for i in 97...122 {
let char = Character(UnicodeScalar(i))
letters.append(char)
} | 796Generate lower case ASCII alphabet
| 17swift
| ckg9t |
sub compose {
my ($f, $g) = @_;
sub {
$f -> ($g -> (@_))
};
}
use Math::Trig;
print compose(sub {sin $_[0]}, \&asin)->(0.5), "\n"; | 806Function composition
| 2perl
| gwv4e |
ar = %w[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]
FractalProgram = ar.map(&:to_r)
Runner = Enumerator.new do |y|
num = 2
loop{ y << num *= FractalProgram.detect{|f| (num*f).denominator == 1} }
end
prime_generator = Enumerator.new do |y|
Runner.each do |num|
l = Math.log2(num)
y << l.to_i if l.floor == l
end
end
p Runner.take(20).map(&:numerator)
p prime_generator.take(20) | 805Fractran
| 14ruby
| u1lvz |
<?php
function compose($f, $g) {
return function($x) use ($f, $g) { return $f($g($x)); };
}
$trim_strlen = compose('strlen', 'trim');
echo $result = $trim_strlen(' Test '), ;
?> | 806Function composition
| 12php
| nl0ig |
class TestFractran extends FunSuite {
val program = Fractran("17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1")
val expect = List(2, 15, 825, 725, 1925, 2275, 425, 390, 330, 290, 770, 910, 170, 156, 132)
test("find first fifteen fractran figures") {
assert((program .execute(2) take 15 toList) === expect)
}
}
object Fractran {
val pattern = """\s*(\d+)\s*/\s*(\d+)\s*""".r
def parse(m: Match) = ((m group 1).toInt, (m group 2).toInt)
def apply(program: String) = new Fractran(
pattern.findAllMatchIn(program).map(parse).toList)
}
class Fractran(val numDem: List[(Int,Int)]) {
def execute(value: Int) = unfold(value) { v =>
numDem indexWhere(v % _._2 == 0) match {
case i if i > -1 => Some(v, numDem(i)._1 * v / numDem(i)._2)
case _ => None
}
}
} | 805Fractran
| 16scala
| rx5gn |
extension CGFloat {
func degrees_to_radians() -> CGFloat {
return CGFloat(M_PI) * self / 180.0
}
}
extension Double {
func degrees_to_radians() -> Double {
return Double(M_PI) * self / 180.0
}
}
class Tree: UIView {
func drawTree(x1: CGFloat, y1: CGFloat, angle: CGFloat, depth:Int){
if depth == 0 {
return
}
let ang = angle.degrees_to_radians()
let x2:CGFloat = x1 + ( cos(ang) as CGFloat) * CGFloat(depth) * (self.frame.width / 60)
let y2:CGFloat = y1 + ( sin(ang) as CGFloat) * CGFloat(depth) * (self.frame.width / 60)
let line = drawLine(x1, y1: y1, x2: x2, y2: y2)
line.stroke()
drawTree(x2, y1: y2, angle: angle - 20, depth: depth - 1)
drawTree(x2, y1: y2, angle: angle + 20, depth: depth - 1)
}
func drawLine(x1:CGFloat, y1:CGFloat, x2:CGFloat, y2:CGFloat) -> UIBezierPath
{
let path = UIBezierPath()
path.moveToPoint(CGPoint(x: x1,y: y1))
path.addLineToPoint(CGPoint(x: x2,y: y2))
path.lineWidth = 1
return path
}
override func drawRect(rect: CGRect) {
let color = UIColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0)
color.set()
drawTree(self.frame.width / 2 , y1: self.frame.height * 0.8, angle: -90 , depth: 9 )
}
}
let tree = Tree(frame: CGRectMake(0, 0, 300, 300))
tree | 804Fractal tree
| 17swift
| ic8o0 |
print | 755Hello world/Text
| 3python
| gqq4h |
$a = [ 1.00000_00000_00000_00000, 0.57721_56649_01532_86061, -0.65587_80715_20253_88108,
-0.04200_26350_34095_23553, 0.16653_86113_82291_48950, -0.04219_77345_55544_33675,
-0.00962_19715_27876_97356, 0.00721_89432_46663_09954, -0.00116_51675_91859_06511,
-0.00021_52416_74114_95097, 0.00012_80502_82388_11619, -0.00002_01348_54780_78824,
-0.00000_12504_93482_14267, 0.00000_11330_27231_98170, -0.00000_02056_33841_69776,
0.00000_00061_16095_10448, 0.00000_00050_02007_64447, -0.00000_00011_81274_57049,
0.00000_00001_04342_67117, 0.00000_00000_07782_26344, -0.00000_00000_03696_80562,
0.00000_00000_00510_03703, -0.00000_00000_00020_58326, -0.00000_00000_00005_34812,
0.00000_00000_00001_22678, -0.00000_00000_00000_11813, 0.00000_00000_00000_00119,
0.00000_00000_00000_00141, -0.00000_00000_00000_00023, 0.00000_00000_00000_00002 ]
def gamma(x)
y = Float(x) - 1
1.0 / $a.reverse.inject {|sum, an| sum * y + an}
end
(1..10).each {|i| puts format(, gamma(i/3.0))} | 802Gamma function
| 14ruby
| mj9yj |
null | 804Fractal tree
| 20typescript
| vpl23 |
import java.util.Locale._
object Gamma {
def stGamma(x:Double):Double=math.sqrt(2*math.Pi/x)*math.pow((x/math.E), x)
def laGamma(x:Double):Double={
val p=Seq(676.5203681218851, -1259.1392167224028, 771.32342877765313,
-176.61502916214059, 12.507343278686905, -0.13857109526572012,
9.9843695780195716e-6, 1.5056327351493116e-7)
if(x < 0.5) {
math.Pi/(math.sin(math.Pi*x)*laGamma(1-x))
} else {
val x2=x-1
val t=x2+7+0.5
val a=p.zipWithIndex.foldLeft(0.99999999999980993)((r,v) => r+v._1/(x2+v._2+1))
math.sqrt(2*math.Pi)*math.pow(t, x2+0.5)*math.exp(-t)*a
}
}
def main(args: Array[String]): Unit = {
println("Gamma Stirling Lanczos")
for(x <- 0.1 to 2.0 by 0.1)
println("%.1f -> %.16f %.16f".formatLocal(ENGLISH, x, stGamma(x), laGamma(x)))
}
} | 802Gamma function
| 16scala
| 2pvlb |
compose = lambda f, g: lambda x: f( g(x) ) | 806Function composition
| 3python
| rxugq |
compose <- function(f,g) function(x) { f(g(x)) }
r <- compose(sin, cos)
print(r(.5)) | 806Function composition
| 13r
| u1cvx |
main(){
print(multiply(1,2));
print(multiply2(1,2));
print(multiply3(1,2));
} | 808Function definition
| 18dart
| lk3ct |
cat("Hello world!\n") | 755Hello world/Text
| 13r
| vaa27 |
def compose(f,g)
lambda {|x| f[g[x]]}
end
s = compose(Math.method(:sin), Math.method(:cos))
p s[0.5]
p Math.sin(Math.cos(0.5)) | 806Function composition
| 14ruby
| js47x |
fn compose<'a,F,G,T,U,V>(f: F, g: G) -> Box<Fn(T) -> V + 'a>
where F: Fn(U) -> V + 'a,
G: Fn(T) -> U + 'a,
{
Box::new(move |x| f(g(x)))
} | 806Function composition
| 15rust
| h0gj2 |
def compose[A](f: A => A, g: A => A) = { x: A => f(g(x)) }
def add1(x: Int) = x+1
val add2 = compose(add1, add1) | 806Function composition
| 16scala
| pijbj |
func compose<A,B,C>(f: (B) -> C, g: (A) -> B) -> (A) -> C {
return { f(g($0)) }
}
let sin_asin = compose(sin, asin)
println(sin_asin(0.5)) | 806Function composition
| 17swift
| 7q5rq |
function compose<T, U, V> (fn1: (input: T) => U, fn2: (input: U) => V){
return function(value: T) {
return fn2(fn1(value))
}
}
function size (s: string): number { return s.length; }
function isEven(x: number): boolean { return x% 2 === 0; }
const evenSize = compose(size, isEven);
console.log(evenSize("ABCD")) | 806Function composition
| 20typescript
| 8mx0i |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.