code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
$odd = function ($prev) use ( &$odd ) {
$a = fgetc(STDIN);
if (!ctype_alpha($a)) {
$prev();
fwrite(STDOUT, $a);
return $a != '.';
}
$clos = function () use ($a , $prev) {
fwrite(STDOUT, $a);
$prev();
};
return $odd($clos);
};
$even = function () {
while (true) {
$c = fgetc(STDIN);
fwrite(STDOUT, $c);
if (!ctype_alpha($c)) {
return $c != ;
}
}
};
$prev = function(){};
$e = false;
while ($e? $odd($prev) : $even()) {
$e = !$e;
} | 504Odd word problem
| 12php
| lsqcj |
null | 509Old lady swallowed a fly
| 11kotlin
| el3a4 |
require 'rubygems'
require 'gl'
require 'glut'
include Gl
include Glut
paint = lambda do
glClearColor(0.3,0.3,0.3,0.0)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glShadeModel(GL_SMOOTH)
glLoadIdentity
glTranslatef(-15.0, -15.0, 0.0)
glBegin(GL_TRIANGLES)
glColor3f(1.0, 0.0, 0.0)
glVertex2f(0.0, 0.0)
glColor3f(0.0, 1.0, 0.0)
glVertex2f(30.0, 0.0)
glColor3f(0.0, 0.0, 1.0)
glVertex2f(0.0, 30.0)
glEnd
glFlush
end
reshape = lambda do |width, height|
glViewport(0, 0, width, height)
glMatrixMode(GL_PROJECTION)
glLoadIdentity
glOrtho(-30.0, 30.0, -30.0, 30.0, -30.0, 30.0)
glMatrixMode(GL_MODELVIEW)
end
glutInit
glutInitWindowSize(640, 480)
glutCreateWindow()
glutDisplayFunc(paint)
glutReshapeFunc(reshape)
glutMainLoop | 499OpenGL
| 14ruby
| fkadr |
class NumberWithUncertainty
def initialize(number, error)
@num = number
@err = error.abs
end
attr_reader :num, :err
def +(other)
if other.kind_of?(self.class)
self.class.new(num + other.num, Math::hypot(err, other.err))
else
self.class.new(num + other, err)
end
end
def -(other)
if other.kind_of?(self.class)
self.class.new(num - other.num, Math::hypot(err, other.err))
else
self.class.new(num - other, err)
end
end
def *(other)
if other.kind_of?(self.class)
prod = num * other.num
e = Math::hypot((prod * err / num), (prod * other.err / other.num))
self.class.new(prod, e)
else
self.class.new(num * other, (err * other).abs)
end
end
def /(other)
if other.kind_of?(self.class)
quo = num / other.num
e = Math::hypot((quo * err / num), (quo * other.err / other.num))
self.class.new(quo, e)
else
self.class.new(num / other, (err * other).abs)
end
end
def **(exponent)
Float(exponent) rescue raise ArgumentError,
prod = num ** exponent
self.class.new(prod, (prod * exponent * err / num).abs)
end
def sqrt
self ** 0.5
end
def to_s
end
end
x1 = NumberWithUncertainty.new(100, 1.1)
y1 = NumberWithUncertainty.new( 50, 1.2)
x2 = NumberWithUncertainty.new(200, 2.2)
y2 = NumberWithUncertainty.new(100, 2.3)
puts ((x1 - x2) ** 2 + (y1 - y2) ** 2).sqrt | 507Numeric error propagation
| 14ruby
| rfogs |
use glow::*;
use glutin::event::*;
use glutin::event_loop::{ControlFlow, EventLoop};
use std::os::raw::c_uint;
const VERTEX: &str = "#version 410
const vec2 verts[3] = vec2[3](
vec2(0.5f, 1.0f),
vec2(0.0f, 0.0f),
vec2(1.0f, 0.0f)
);
out vec2 vert;
void main() {
vert = verts[gl_VertexID];
gl_Position = vec4(vert - 0.5, 0.0, 1.0);
}";
const FRAGMENT: &str = "#version 410
precision mediump float;
in vec2 vert;
out vec4 color;
void main() {
color = vec4(vert, 0.5, 1.0);
}";
unsafe fn create_program(gl: &Context, vert: &str, frag: &str) -> c_uint {
let program = gl.create_program().expect("Cannot create program");
let shader_sources = [(glow::VERTEX_SHADER, vert), (glow::FRAGMENT_SHADER, frag)];
let mut shaders = Vec::new();
for (shader_type, shader_source) in shader_sources.iter() {
let shader = gl
.create_shader(*shader_type)
.expect("Cannot create shader");
gl.shader_source(shader, shader_source);
gl.compile_shader(shader);
if!gl.get_shader_compile_status(shader) {
panic!(gl.get_shader_info_log(shader));
}
gl.attach_shader(program, shader);
shaders.push(shader);
}
gl.link_program(program);
if!gl.get_program_link_status(program) {
panic!(gl.get_program_info_log(program));
}
for shader in shaders {
gl.detach_shader(program, shader);
gl.delete_shader(shader);
}
program
}
fn main() {
let (gl, event_loop, window) = unsafe {
let el = EventLoop::new();
let wb = glutin::window::WindowBuilder::new()
.with_title("Hello triangle!")
.with_inner_size(glutin::dpi::LogicalSize::new(1024.0, 768.0));
let windowed_context = glutin::ContextBuilder::new()
.with_vsync(true)
.build_windowed(wb, &el)
.unwrap();
let windowed_context = windowed_context.make_current().unwrap();
let context = glow::Context::from_loader_function(|s| {
windowed_context.get_proc_address(s) as *const _
});
(context, el, windowed_context)
};
let (program, vab) = unsafe {
let vertex_array = gl
.create_vertex_array()
.expect("Cannot create vertex array");
gl.bind_vertex_array(Some(vertex_array));
let program = create_program(&gl, VERTEX, FRAGMENT);
gl.use_program(Some(program));
(program, vertex_array)
};
event_loop.run(move |ev, _, flow| match ev {
Event::WindowEvent {
event: WindowEvent::CloseRequested, ..
} => {
unsafe {
gl.delete_program(program);
gl.delete_vertex_array(vab);
}
*flow = ControlFlow::Exit;
}
Event::WindowEvent {
event: WindowEvent::Resized(size), ..
} => {
unsafe {
gl.viewport(0, 0, size.width as i32, size.height as i32);
}
window.resize(size);
}
Event::RedrawRequested(_) => unsafe {
gl.clear_color(0.1, 0.2, 0.3, 1.0);
gl.clear(glow::COLOR_BUFFER_BIT);
gl.draw_arrays(glow::TRIANGLES, 0, 3);
window.swap_buffers().unwrap();
},
_ => {}
});
} | 499OpenGL
| 15rust
| tbefd |
from random import randrange
try:
range = xrange
except: pass
def one_of_n(lines):
choice = None
for i, line in enumerate(lines):
if randrange(i+1) == 0:
choice = line
return choice
def one_of_n_test(n=10, trials=1000000):
bins = [0] * n
if n:
for i in range(trials):
bins[one_of_n(range(n))] += 1
return bins
print(one_of_n_test()) | 502One of n lines in a file
| 3python
| mwxyh |
one_of_n <- function(n)
{
choice <- 1L
for (i in 2:n)
{
if (i*runif(1) < 1)
choice <- i
}
return(choice)
}
table(sapply(1:1000000, function(i) one_of_n(10))) | 502One of n lines in a file
| 13r
| zp1th |
>>> [1,2,1,3,2] < [1,2,0,4,4,0,0,0]
False | 500Order two numerical lists
| 3python
| tbafw |
use strict;
use warnings;
open(FH, "<", "unixdict.txt") or die "Can't open file!\n";
my @words;
while (<FH>) {
chomp;
push @{$words[length]}, $_ if $_ eq join("", sort split(//));
}
close FH;
print "@{$words[-1]}\n"; | 491Ordered words
| 2perl
| v8920 |
import java.lang.Math._
class Approx(val : Double, val : Double = 0.0) {
def this(a: Approx) = this(a., a.)
def this(n: Number) = this(n.doubleValue(), 0.0)
override def toString = s"$ $"
def +(a: Approx) = Approx( + a., sqrt( * + a. * a.))
def +(d: Double) = Approx( + d, )
def -(a: Approx) = Approx( - a., sqrt( * + a. * a.))
def -(d: Double) = Approx( - d, )
def *(a: Approx) = {
val v = * a.
Approx(v, sqrt(v * v * * / ( * ) + a. * a. / (a. * a.)))
}
def *(d: Double) = Approx( * d, abs(d * ))
def /(a: Approx) = {
val t = / a.
Approx(t, sqrt(t * t * * / ( * ) + a. * a. / (a. * a.)))
}
def /(d: Double) = Approx( / d, abs(d * ))
def ^(d: Double) = {
val t = pow(, d)
Approx(t, abs(t * d * / ))
}
}
object Approx { def apply(: Double, : Double = 0.0) = new Approx(, ) }
object NumericError extends App {
def (a: Approx) = a^0.5
val x1 = Approx(100.0, 1.1)
val x2 = Approx(50.0, 1.2)
val y1 = Approx(200.0, 2.2)
val y2 = Approx(100.0, 2.3)
println((((x1 - x2)^2.0) + ((y1 - y2)^2.0))) | 507Numeric error propagation
| 16scala
| k6fhk |
(defn flip-at [n coll]
(let [[x y] (split-at n coll)]
(concat (reverse x) y )))
(def sorted '(1 2 3 4 5 6 7 8 9))
(def unsorted? #(not= % sorted))
(loop [unsorted (first (filter unsorted? (iterate shuffle sorted))), steps 0]
(if (= unsorted sorted)
(printf "Done! That took you%d steps%n" steps)
(do
(println unsorted)
(printf "Reverse how many? ")
(flush)
(let [flipcount (read)]
(recur (flip-at flipcount unsorted), (inc steps)))))) | 514Number reversal game
| 6clojure
| 6a53q |
import org.lwjgl.opengl.{ Display, DisplayMode }
import org.lwjgl.opengl.GL11._
object OpenGlExample extends App {
def render() {
glClearColor(0.3f, 0.3f, 0.3f, 0.0f)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glShadeModel(GL_SMOOTH)
glLoadIdentity()
glTranslatef(-15.0f, -15.0f, 0.0f)
glBegin(GL_TRIANGLES)
glColor3f(1.0f, 0.0f, 0.0f)
glVertex2f(0.0f, 0.0f)
glColor3f(0.0f, 1.0f, 0.0f)
glVertex2f(30f, 0.0f)
glColor3f(0.0f, 0.0f, 1.0f)
glVertex2f(0.0f, 30.0f)
glEnd()
}
Display.setDisplayMode(new DisplayMode(640, 480))
Display.create()
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(-30, 30, -30, 30, -30, 30)
glMatrixMode(GL_MODELVIEW)
while (!Display.isCloseRequested()) {
render()
Display.update()
Thread.sleep(1000)
}
} | 499OpenGL
| 16scala
| 6aq31 |
import Foundation
precedencegroup ExponentiationGroup {
higherThan: MultiplicationPrecedence
}
infix operator **: ExponentiationGroup
infix operator
func (_ lhs: Double, _ rhs: Double) -> UncertainDouble { UncertainDouble(value: lhs, error: rhs) }
struct UncertainDouble {
var value: Double
var error: Double
static func +(_ lhs: UncertainDouble, _ rhs: UncertainDouble) -> UncertainDouble {
return UncertainDouble(value: lhs.value + rhs.value, error: pow(pow(lhs.error, 2) + pow(rhs.error, 2), 0.5))
}
static func +(_ lhs: UncertainDouble, _ rhs: Double) -> UncertainDouble {
return UncertainDouble(value: lhs.value + rhs, error: lhs.error)
}
static func -(_ lhs: UncertainDouble, _ rhs: UncertainDouble) -> UncertainDouble {
return UncertainDouble(value: lhs.value - rhs.value, error: pow(pow(lhs.error, 2) + pow(rhs.error, 2), 0.5))
}
static func -(_ lhs: UncertainDouble, _ rhs: Double) -> UncertainDouble {
return UncertainDouble(value: lhs.value - rhs, error: lhs.error)
}
static func *(_ lhs: UncertainDouble, _ rhs: UncertainDouble) -> UncertainDouble {
let val = lhs.value * rhs.value
return UncertainDouble(
value: val,
error: pow(pow(val, 2) * (pow(lhs.error / lhs.value, 2) + pow(rhs.error / rhs.value, 2)), 0.5)
)
}
static func *(_ lhs: UncertainDouble, _ rhs: Double) -> UncertainDouble {
return UncertainDouble(value: lhs.value * rhs, error: abs(lhs.error * rhs))
}
static func /(_ lhs: UncertainDouble, _ rhs: UncertainDouble) -> UncertainDouble {
let val = lhs.value / rhs.value
return UncertainDouble(
value: val,
error: pow(val, 2) * (pow(lhs.error / lhs.value, 2) + pow(rhs.error / rhs.value, 2))
)
}
static func /(_ lhs: UncertainDouble, _ rhs: Double) -> UncertainDouble {
return UncertainDouble(value: lhs.value / rhs, error: abs(lhs.error * rhs))
}
static func **(_ lhs: UncertainDouble, _ power: Double) -> UncertainDouble {
let val = pow(lhs.value, power)
return UncertainDouble(value: val, error: abs((val * power) * (lhs.error / lhs.value)))
}
}
extension UncertainDouble: CustomStringConvertible {
public var description: String { "\(value) \(error)" }
}
let (x1, y1) = (100 1.1, 50 1.2)
let (x2, y2) = (200 2.2, 100 2.3)
let d = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
print(d) | 507Numeric error propagation
| 17swift
| gd849 |
const char *ones[] = { 0, , , , ,
, , , , ,
, , , , ,
, , , , };
const char *tens[] = { 0, , , , ,
, , , , };
const char *llions[] = { 0, , , , ,
};
const int maxillion = sizeof(llions) / sizeof(llions[0]) * 3 - 3;
int say_hundred(const char *s, int len, int depth, int has_lead)
{
int c[3], i;
for (i = -3; i < 0; i++) {
if (len + i >= 0) c[i + 3] = s[len + i] - '0';
else c[i + 3] = 0;
}
if (!(c[0] + c[1] + c[2])) return 0;
if (c[0]) {
printf(, ones[c[0]]);
has_lead = 1;
}
if (has_lead && (c[1] || c[2]))
printf((!depth || c[0]) && (!c[0] || !c[1]) ? :
c[0] ? : );
if (c[1] < 2) {
if (c[1] || c[2]) printf(, ones[c[1] * 10 + c[2]]);
} else {
if (c[1]) {
printf(, tens[c[1]]);
if (c[2]) putchar('-');
}
if (c[2]) printf(, ones[c[2]]);
}
return 1;
}
int say_maxillion(const char *s, int len, int depth, int has_lead)
{
int n = len / 3, r = len % 3;
if (!r) {
n--;
r = 3;
}
const char *e = s + r;
do {
if (say_hundred(s, r, n, has_lead) && n) {
has_lead = 1;
printf(, llions[n]);
if (!depth) printf();
else printf();
}
s = e; e += 3;
} while (r = 3, n--);
return 1;
}
void say_number(const char *s)
{
int len, i, got_sign = 0;
while (*s == ' ') s++;
if (*s < '0' || *s > '9') {
if (*s == '-') got_sign = -1;
else if (*s == '+') got_sign = 1;
else goto nan;
s++;
} else
got_sign = 1;
while (*s == '0') {
s++;
if (*s == '\0') {
printf();
return;
}
}
len = strlen(s);
if (!len) goto nan;
for (i = 0; i < len; i++) {
if (s[i] < '0' || s[i] > '9') {
printf();
return;
}
}
if (got_sign == -1) printf();
int n = len / maxillion;
int r = len % maxillion;
if (!r) {
r = maxillion;
n--;
}
const char *end = s + len - n * maxillion;
int has_lead = 0;
do {
if ((has_lead = say_maxillion(s, r, n, has_lead))) {
for (i = 0; i < n; i++)
printf(, llions[maxillion / 3]);
if (n) printf();
}
n--;
r = maxillion;
s = end;
end += r;
} while (n >= 0);
printf();
return;
nan: printf();
return;
}
int main()
{
say_number();
say_number();
say_number();
say_number();
say_number();
say_number();
return 0;
} | 515Number names
| 5c
| eliav |
use List::Util qw(sum);
use constant pi => 3.14159265;
sub legendre_pair {
my($n, $x) = @_;
if ($n == 1) { return $x, 1 }
my ($m1, $m2) = legendre_pair($n - 1, $x);
my $u = 1 - 1 / $n;
(1 + $u) * $x * $m1 - $u * $m2, $m1;
}
sub legendre {
my($n, $x) = @_;
(legendre_pair($n, $x))[0]
}
sub legendre_prime {
my($n, $x) = @_;
if ($n == 0) { return 0 }
if ($n == 1) { return 1 }
my ($m0, $m1) = legendre_pair($n, $x);
($m1 - $x * $m0) * $n / (1 - $x**2);
}
sub approximate_legendre_root {
my($n, $k) = @_;
my $t = (4*$k - 1) / (4*$n + 2);
(1 - ($n - 1) / (8 * $n**3)) * cos(pi * $t);
}
sub newton_raphson {
my($n, $r) = @_;
while (abs(my $dr = - legendre($n,$r) / legendre_prime($n,$r)) >= 2e-16) {
$r += $dr;
}
$r;
}
sub legendre_root {
my($n, $k) = @_;
newton_raphson($n, approximate_legendre_root($n, $k));
}
sub weight {
my($n, $r) = @_;
2 / ((1 - $r**2) * legendre_prime($n, $r)**2)
}
sub nodes {
my($n) = @_;
my %node;
$node{'0'} = weight($n, 0) if 0 != $n%2;
for (1 .. int $n/2) {
my $r = legendre_root($n, $_);
my $w = weight($n, $r);
$node{$r} = $w; $node{-$r} = $w;
}
return %node
}
sub quadrature {
our($n, $a, $b) = @_;
sub scale { ($_[0] * ($b - $a) + $a + $b) / 2 }
%nodes = nodes($n);
($b - $a) / 2 * sum map { $nodes{$_} * exp(scale($_)) } keys %nodes;
}
printf("Gauss-Legendre%2d-point quadrature exp(x) dx %.13f\n", $_, quadrature($_, -3, +3) )
for 5 .. 10, 20; | 505Numerical integration/Gauss-Legendre Quadrature
| 2perl
| 04us4 |
animals = {"fly", "spider", "bird", "cat","dog", "goat", "cow", "horse"}
phrases = {
"",
"That wriggled and jiggled and tickled inside her",
"How absurd to swallow a bird",
"Fancy that to swallow a cat",
"What a hog, to swallow a dog",
"She just opened her throat and swallowed a goat",
"I don't know how she swallowed a cow",
" ...She's dead of course"
}
for i=0,7 do
io.write(string.format("There was an old lady who swallowed a%s\n", animals[i+1]))
if i>0 then io.write(phrases[i+1]) end
if i==7 then break end
if i>0 then
io.write("\n")
for j=i,1,-1 do
io.write(string.format("She swallowed the%s to catch the%s", animals[j+1], animals[j])) | 509Old lady swallowed a fly
| 1lua
| w26ea |
from sys import stdin, stdout
def char_in(): return stdin.read(1)
def char_out(c): stdout.write(c)
def odd(prev = lambda: None):
a = char_in()
if not a.isalpha():
prev()
char_out(a)
return a != '.'
def clos():
char_out(a)
prev()
return odd(clos)
def even():
while True:
c = char_in()
char_out(c)
if not c.isalpha(): return c != '.'
e = False
while odd() if e else even():
e = not e | 504Odd word problem
| 3python
| xv2wr |
def random_line(io)
choice = io.gets; count = 1
while line = io.gets
rand(count += 1).zero? and choice = line
end
choice
end
def one_of_n(n)
(mock_io = Object.new).instance_eval do
@count = 0
@last = n
def self.gets
(@count < @last)? (@count += 1): nil
end
end
random_line(mock_io)
end
chosen = Hash.new(0)
1_000_000.times { chosen[one_of_n(10)] += 1 }
chosen.keys.sort.each do |key|
puts
end | 502One of n lines in a file
| 14ruby
| cqs9k |
>> ([1,2,1,3,2] <=> [1,2,0,4,4,0,0,0]) < 0
=> false | 500Order two numerical lists
| 14ruby
| 31wz7 |
extern crate rand;
use rand::{Rng, thread_rng};
fn one_of_n<R: Rng>(rng: &mut R, n: usize) -> usize {
(1..n).fold(0, |keep, cand| { | 502One of n lines in a file
| 15rust
| ls0cc |
def one_of_n(n: Int, i: Int = 1, j: Int = 1): Int =
if (n < 1) i else one_of_n(n - 1, if (scala.util.Random.nextInt(j) == 0) n else i, j + 1)
def simulate(lines: Int, iterations: Int) = {
val counts = new Array[Int](lines)
for (_ <- 1 to iterations; i = one_of_n(lines) - 1) counts(i) = counts(i) + 1
counts
}
println(simulate(10, 1000000) mkString "\n") | 502One of n lines in a file
| 16scala
| uoiv8 |
vec![1, 2, 1, 3, 2] < vec![1, 2, 0, 4, 4, 0, 0, 0] | 500Order two numerical lists
| 15rust
| 6ax3l |
def lessThan1(a: List[Int], b: List[Int]): Boolean =
if (b.isEmpty) false
else if (a.isEmpty) true
else if (a.head != b.head) a.head < b.head
else lessThan1(a.tail, b.tail) | 500Order two numerical lists
| 16scala
| 9x0m5 |
def palindrome?(s)
s == s.reverse
end | 483Palindrome detection
| 14ruby
| h6ajx |
(clojure.pprint/cl-format nil "~R" 1234)
=> "one thousand, two hundred thirty-four" | 515Number names
| 6clojure
| 04zsj |
package main
import (
"fmt"
"math"
) | 511Numerical integration
| 0go
| dhvne |
from numpy import *
def Legendre(n,x):
x=array(x)
if (n==0):
return x*0+1.0
elif (n==1):
return x
else:
return ((2.0*n-1.0)*x*Legendre(n-1,x)-(n-1)*Legendre(n-2,x))/n
def DLegendre(n,x):
x=array(x)
if (n==0):
return x*0
elif (n==1):
return x*0+1.0
else:
return (n/(x**2-1.0))*(x*Legendre(n,x)-Legendre(n-1,x))
def LegendreRoots(polyorder,tolerance=1e-20):
if polyorder<2:
err=1
else:
roots=[]
for i in range(1,int(polyorder)/2 +1):
x=cos(pi*(i-0.25)/(polyorder+0.5))
error=10*tolerance
iters=0
while (error>tolerance) and (iters<1000):
dx=-Legendre(polyorder,x)/DLegendre(polyorder,x)
x=x+dx
iters=iters+1
error=abs(dx)
roots.append(x)
roots=array(roots)
if polyorder%2==0:
roots=concatenate( (-1.0*roots, roots[::-1]) )
else:
roots=concatenate( (-1.0*roots, [0.0], roots[::-1]) )
err=0
return [roots, err]
def GaussLegendreWeights(polyorder):
W=[]
[xis,err]=LegendreRoots(polyorder)
if err==0:
W=2.0/( (1.0-xis**2)*(DLegendre(polyorder,xis)**2) )
err=0
else:
err=1
return [W, xis, err]
def GaussLegendreQuadrature(func, polyorder, a, b):
[Ws,xs, err]= GaussLegendreWeights(polyorder)
if err==0:
ans=(b-a)*0.5*sum( Ws*func( (b-a)*0.5*xs+ (b+a)*0.5 ) )
else:
err=1
ans=None
return [ans,err]
def func(x):
return exp(x)
order=5
[Ws,xs,err]=GaussLegendreWeights(order)
if err==0:
print , order
print , xs
print , Ws
else:
print
[ans,err]=GaussLegendreQuadrature(func , order, -3,3)
if err==0:
print , ans
else:
print | 505Numerical integration/Gauss-Legendre Quadrature
| 3python
| 8g50o |
f, r = nil
fwd = proc {|c|
c =~ /[[:alpha:]]/? [(print c), fwd[Fiber.yield f]][1]: c }
rev = proc {|c|
c =~ /[[:alpha:]]/? [rev[Fiber.yield r], (print c)][0]: c }
(f = Fiber.new { loop { print fwd[Fiber.yield r] }}).resume
(r = Fiber.new { loop { print rev[Fiber.yield f] }}).resume
coro = f
until $stdin.eof?
coro = coro.resume($stdin.getc)
end | 504Odd word problem
| 14ruby
| s5uqw |
def assertBounds = { List bounds, int nRect ->
assert (bounds.size() == 2) && (bounds[0] instanceof Double) && (bounds[1] instanceof Double) && (nRect > 0)
}
def integral = { List bounds, int nRectangles, Closure f, List pointGuide, Closure integralCalculator->
double a = bounds[0], b = bounds[1], h = (b - a)/nRectangles
def xPoints = pointGuide.collect { double it -> a + it*h }
def fPoints = xPoints.collect { x -> f(x) }
integralCalculator(h, fPoints)
}
def leftRectIntegral = { List bounds, int nRect, Closure f ->
assertBounds(bounds, nRect)
integral(bounds, nRect, f, (0..<nRect)) { h, fPoints -> h*fPoints.sum() }
}
def rightRectIntegral = { List bounds, int nRect, Closure f ->
assertBounds(bounds, nRect)
integral(bounds, nRect, f, (1..nRect)) { h, fPoints -> h*fPoints.sum() }
}
def midRectIntegral = { List bounds, int nRect, Closure f ->
assertBounds(bounds, nRect)
integral(bounds, nRect, f, ((0.5d)..nRect)) { h, fPoints -> h*fPoints.sum() }
}
def trapezoidIntegral = { List bounds, int nRect, Closure f ->
assertBounds(bounds, nRect)
integral(bounds, nRect, f, (0..nRect)) { h, fPoints ->
def fLeft = fPoints[0..<nRect]
def fRight = fPoints[1..nRect]
h/2*(fLeft + fRight).sum()
}
}
def simpsonsIntegral = { List bounds, int nSimpRect, Closure f ->
assertBounds(bounds, nSimpRect)
integral(bounds, nSimpRect*2, f, (0..(nSimpRect*2))) { h, fPoints ->
def fLeft = fPoints[(0..<nSimpRect*2).step(2)]
def fMid = fPoints[(1..<nSimpRect*2).step(2)]
def fRight = fPoints[(2..nSimpRect*2).step(2)]
h/3*((fLeft + fRight).sum() + 4*(fMid.sum()))
}
} | 511Numerical integration
| 7groovy
| 04msh |
func one_of_n(n: Int) -> Int {
var result = 1
for i in 2...n {
if arc4random_uniform(UInt32(i)) < 1 {
result = i
}
}
return result
}
var counts = [0,0,0,0,0,0,0,0,0,0]
for _ in 1..1_000_000 {
counts[one_of_n(10)-1]++
}
println(counts) | 502One of n lines in a file
| 17swift
| 9xqmj |
fn is_palindrome(string: &str) -> bool {
let half_len = string.len() / 2;
string
.chars()
.take(half_len)
.eq(string.chars().rev().take(half_len))
}
macro_rules! test {
( $( $x:tt ),* ) => { $( println!("'{}': {}", $x, is_palindrome($x)); )* };
}
fn main() {
test!(
"",
"a",
"ada",
"adad",
"ingirumimusnocteetconsumimurigni",
",",
" , ",
"",
"The quick brown fox"
);
} | 483Palindrome detection
| 15rust
| kyeh5 |
import scala.io.Source
import java.io.PrintStream
def process(s: Source, p: PrintStream, w: Int = 0): Unit = if (s.hasNext) s.next match {
case '.' => p append '.'
case c if !Character.isAlphabetic(c) => p append c; reverse(s, p, w + 1)
case c => p append c; process(s, p, w)
}
def reverse(s: Source, p: PrintStream, w: Int = 0, x: Char = '.'): Char = s.next match {
case c if !Character.isAlphabetic(c) => p append x; c
case c => val n = reverse(s, p, w, c);
if (x == '.') {p append n; process(s, p, w + 1)} else p append x; n
}
process(Source.fromString("what,is,the;meaning,of:life."), System.out); println
process(Source.fromString("we,are;not,in,kansas;any,more."), System.out); println | 504Odd word problem
| 16scala
| i7rox |
package main
import "fmt"
var (
s []int | 513Null object
| 0go
| uopvt |
undefined
error "oops"
head [] | 513Null object
| 8haskell
| w2fed |
approx f xs ws = sum [w * f x | (x,w) <- zip xs ws] | 511Numerical integration
| 8haskell
| 5ieug |
let a = [1,2,1,3,2]
let b = [1,2,0,4,4,0,0,0]
println(lexicographicalCompare(a, b)) | 500Order two numerical lists
| 17swift
| zpetu |
my @animals = (
"fly",
"spider/That wriggled and jiggled and tickled inside her.\n",
"bird//Quite absurd!",
"cat//Fancy that!",
"dog//What a hog!",
"pig//Her mouth was so big!",
"goat//She just opened her throat!",
"cow//I don't know how;",
"donkey//It was rather wonkey!",
"horse:",
);
my $s = "swallow";
my $e = $s."ed";
my $t = "There was an old lady who $e a ";
my $_ = $t."But I don't know why she $e the fly;\nPerhaps she'll die!\n\n";
my ($a, $b, $c, $d);
while (my $x = shift @animals) {
s/$c//;
($a, $b, $c) = split('/', $x);
$d = " the $a";
$c =~ s/;/ she $e$d;\n/;
$c =~ s/!/, to $s$d;\n/;
s/$t/"$t$a,\n$c".(($b||$c) && "${b}She $e$d to catch the ")/e;
s/:.*/--\nShe's dead, of course!\n/s;
print;
} | 509Old lady swallowed a fly
| 2perl
| cqp9a |
import urllib.request
url = 'http:
words = urllib.request.urlopen(url).read().decode().split()
ordered = [word for word in words if word==''.join(sorted(word))]
maxlen = len(max(ordered, key=len))
maxorderedwords = [word for word in ordered if len(word) == maxlen]
print(' '.join(maxorderedwords)) | 491Ordered words
| 3python
| uocvd |
def isPalindrome(s: String): Boolean = (s.size >= 2) && s == s.reverse | 483Palindrome detection
| 16scala
| 1cqpf |
null | 513Null object
| 9java
| k60hm |
package main
import "fmt"
const (
start = "_###_##_#_#_#_#__#__"
offLeft = '_'
offRight = '_'
dead = '_'
)
func main() {
fmt.Println(start)
g := newGenerator(start, offLeft, offRight, dead)
for i := 0; i < 10; i++ {
fmt.Println(g())
}
}
func newGenerator(start string, offLeft, offRight, dead byte) func() string {
g0 := string(offLeft) + start + string(offRight)
g1 := []byte(g0)
last := len(g0) - 1
return func() string {
for i := 1; i < last; i++ {
switch l := g0[i-1]; {
case l != g0[i+1]:
g1[i] = g0[i]
case g0[i] == dead:
g1[i] = l
default:
g1[i] = dead
}
}
g0 = string(g1)
return g0[1:last]
}
} | 512One-dimensional cellular automata
| 0go
| jzs7d |
class NumericalIntegration
{
interface FPFunction
{
double eval(double n);
}
public static double rectangularLeft(double a, double b, int n, FPFunction f)
{
return rectangular(a, b, n, f, 0);
}
public static double rectangularMidpoint(double a, double b, int n, FPFunction f)
{
return rectangular(a, b, n, f, 1);
}
public static double rectangularRight(double a, double b, int n, FPFunction f)
{
return rectangular(a, b, n, f, 2);
}
public static double trapezium(double a, double b, int n, FPFunction f)
{
double range = checkParamsGetRange(a, b, n);
double nFloat = (double)n;
double sum = 0.0;
for (int i = 1; i < n; i++)
{
double x = a + range * (double)i / nFloat;
sum += f.eval(x);
}
sum += (f.eval(a) + f.eval(b)) / 2.0;
return sum * range / nFloat;
}
public static double simpsons(double a, double b, int n, FPFunction f)
{
double range = checkParamsGetRange(a, b, n);
double nFloat = (double)n;
double sum1 = f.eval(a + range / (nFloat * 2.0));
double sum2 = 0.0;
for (int i = 1; i < n; i++)
{
double x1 = a + range * ((double)i + 0.5) / nFloat;
sum1 += f.eval(x1);
double x2 = a + range * (double)i / nFloat;
sum2 += f.eval(x2);
}
return (f.eval(a) + f.eval(b) + sum1 * 4.0 + sum2 * 2.0) * range / (nFloat * 6.0);
}
private static double rectangular(double a, double b, int n, FPFunction f, int mode)
{
double range = checkParamsGetRange(a, b, n);
double modeOffset = (double)mode / 2.0;
double nFloat = (double)n;
double sum = 0.0;
for (int i = 0; i < n; i++)
{
double x = a + range * ((double)i + modeOffset) / nFloat;
sum += f.eval(x);
}
return sum * range / nFloat;
}
private static double checkParamsGetRange(double a, double b, int n)
{
if (n <= 0)
throw new IllegalArgumentException("Invalid value of n");
double range = b - a;
if (range <= 0)
throw new IllegalArgumentException("Invalid range");
return range;
}
private static void testFunction(String fname, double a, double b, int n, FPFunction f)
{
System.out.println("Testing function \"" + fname + "\", a=" + a + ", b=" + b + ", n=" + n);
System.out.println("rectangularLeft: " + rectangularLeft(a, b, n, f));
System.out.println("rectangularMidpoint: " + rectangularMidpoint(a, b, n, f));
System.out.println("rectangularRight: " + rectangularRight(a, b, n, f));
System.out.println("trapezium: " + trapezium(a, b, n, f));
System.out.println("simpsons: " + simpsons(a, b, n, f));
System.out.println();
return;
}
public static void main(String[] args)
{
testFunction("x^3", 0.0, 1.0, 100, new FPFunction() {
public double eval(double n) {
return n * n * n;
}
}
);
testFunction("1/x", 1.0, 100.0, 1000, new FPFunction() {
public double eval(double n) {
return 1.0 / n;
}
}
);
testFunction("x", 0.0, 5000.0, 5000000, new FPFunction() {
public double eval(double n) {
return n;
}
}
);
testFunction("x", 0.0, 6000.0, 6000000, new FPFunction() {
public double eval(double n) {
return n;
}
}
);
return;
}
} | 511Numerical integration
| 9java
| 9xhmu |
import scala.math.{Pi, cos, exp}
object GaussLegendreQuadrature extends App {
private val N = 5
private def legeInte(a: Double, b: Double): Double = {
val (c1, c2) = ((b - a) / 2, (b + a) / 2)
val tuples: IndexedSeq[(Double, Double)] = {
val lcoef = {
val lcoef = Array.ofDim[Double](N + 1, N + 1)
lcoef(0)(0) = 1
lcoef(1)(1) = 1
for (i <- 2 to N) {
lcoef(i)(0) = -(i - 1) * lcoef(i - 2)(0) / i
for (j <- 1 to i) lcoef(i)(j) =
((2 * i - 1) * lcoef(i - 1)(j - 1) - (i - 1) * lcoef(i - 2)(j)) / i
}
lcoef
}
def legeEval(n: Int, x: Double): Double =
lcoef(n).take(n).foldRight(lcoef(n)(n))((o, s) => s * x + o)
def legeDiff(n: Int, x: Double): Double =
n * (x * legeEval(n, x) - legeEval(n - 1, x)) / (x * x - 1)
@scala.annotation.tailrec
def convergention(x0: Double, x1: Double): Double = {
if (x0 == x1) x1
else convergention(x1, x1 - legeEval(N, x1) / legeDiff(N, x1))
}
for {i <- 0 until 5
x = convergention(0.0, cos(Pi * (i + 1 - 0.25) / (N + 0.5)))
x1 = legeDiff(N, x)
} yield (x, 2 / ((1 - x * x) * x1 * x1))
}
println(s"Roots: ${tuples.map(el => f" ${el._1}%10.6f").mkString}")
println(s"Weight:${tuples.map(el => f" ${el._2}%10.6f").mkString}")
c1 * tuples.map { case (lroot, weight) => weight * exp(c1 * lroot + c2) }.sum
}
println(f"Integrating exp(x) over [-3, 3]:\n\t${legeInte(-3, 3)}%10.8f,")
println(f"compared to actual%n\t${exp(3) - exp(-3)}%10.8f")
} | 505Numerical integration/Gauss-Legendre Quadrature
| 16scala
| tbhfb |
if (object === null) {
alert("object is null"); | 513Null object
| 10javascript
| eldao |
def life1D = { self ->
def right = self[1..-1] + [false]
def left = [false] + self[0..-2]
[left, self, right].transpose().collect { hood -> hood.count { it } == 2 }
} | 512One-dimensional cellular automata
| 7groovy
| 5iauv |
<?php
$swallowed = array(
array('swallowed' => 'fly.',
'reason' => ),
array('swallowed' => 'spider,',
'aside' => ,
'reason' => ),
array('swallowed' => 'bird.',
'aside' => ,
'reason' => ),
array('swallowed' => 'cat.',
'aside' => ,
'reason' => ),
array('swallowed' => 'dog.',
'aside' => ,
'reason' => ),
array('swallowed' => 'horse',
'aside' => ,
'reason' => ));
foreach($swallowed as $creature)
{
print . $creature['swallowed'] . ;
if(array_key_exists('aside', $creature))
print $creature['aside'] . ;
$reversed = array_reverse($swallowed);
$history = array_slice($reversed, array_search($creature, $reversed));
foreach($history as $note)
{
print $note['reason'] . ;
}
if($swallowed[count($swallowed) - 1] == $creature)
print ;
else
print . ;
} | 509Old lady swallowed a fly
| 12php
| xvyw5 |
words = scan("https://web.archive.org/web/20180611003215/http://www.puzzlers.org/pub/wordlists/unixdict.txt",what = "character")
ordered = logical()
for(i in 1:length(words)){
first = strsplit(words[i],"")[[1]][1:nchar(words[i])-1]
second = strsplit(words[i],"")[[1]][2:nchar(words[i])]
ordered[i] = all(first<=second)
}
cat(words[ordered][which(nchar(words[ordered])==max(nchar(words[ordered])))],sep="\n") | 491Ordered words
| 13r
| cq695 |
import Data.List (unfoldr)
import System.Random (newStdGen, randomRs)
bnd :: String -> Char
bnd "_##" = '#'
bnd "#_#" = '#'
bnd "##_" = '#'
bnd _ = '_'
nxt :: String -> String
nxt = unfoldr go . ('_':) . (<> "_")
where
go [_, _] = Nothing
go xs = Just (bnd $ take 3 xs, drop 1 xs)
lahmahgaan :: String -> [String]
lahmahgaan xs =
init
. until
((==) . last <*> last . init)
((<>) <*> pure . nxt . last)
$ [xs, nxt xs]
main :: IO ()
main =
newStdGen
>>= ( mapM_ putStrLn . lahmahgaan
. map ("_#" !!)
. take 36
. randomRs (0, 1)
) | 512One-dimensional cellular automata
| 8haskell
| or98p |
null | 511Numerical integration
| 11kotlin
| zp4ts |
null | 513Null object
| 11kotlin
| gde4d |
import zlib, base64
b64 = b'''
eNrtVE1rwzAMvedXaKdeRn7ENrb21rHCzmrs1m49K9gOJv9+cko/HBcGg0LHcpOfnq2np0QL
2FuKgBbICDAoeoiKwEc0hqIUgLAxfV0tQJCdhQM7qh68kheswKeBt5ROYetTemYMCC3rii
WMS3WkhXVyuFAaLT261JuBWwu4iDbvYp1tYzHVS68VEIObwFgaDB0KizuFs38aSdqKv3TgcJ
uPYdn2B1opwIpeKE53qPftxRd88Y6uoVbdPzWxznrQ3ZUi3DudQ/bcELbevqM32iCIrj3IIh
W6plOJf6L6xaajZjzqW/qAsKIvITBGs9Nm3glboZzkVP5l6Y+0bHLnedD0CttIyrpEU5Kv7N
Mz3XkPBc/TSN3yxGiqMiipHRekycK0ZwMhM8jerGC9zuZaoTho3kMKSfJjLaF8v8wLzmXMqM
zJvGew/jnZPzclA08yAkikegDTTUMfzwDXBcwoE='''
print(zlib.decompress(base64.b64decode(b64)).decode(, )) | 509Old lady swallowed a fly
| 3python
| ls1cv |
animals = list(
c("fly", "I don't know why she swallowed a fly, perhaps she'll die."),
c("spider", "It wiggled and jiggled and tickled inside her."),
c("bird", "How absurd, to swallow a bird."),
c("cat", "Imagine that, she swallowed a cat."),
c("dog", "What a hog, to swallow a dog."),
c("goat", "She just opened her throat and swallowed a goat."),
c("cow", "I don't know how she swallowed a cow."),
c("horse", "She's dead, of course.")
)
oldladyalive <- TRUE
oldladysnack <- 1
while(oldladyalive == TRUE) {
nextmeal <- animals[[oldladysnack]][1]
nextcomment <- animals[[oldladysnack]][2]
print(sprintf("There was an old lady who swallowed a%s.%s",nextmeal,nextcomment))
if(oldladysnack == 8){
oldladyalive <- FALSE
} else if(oldladysnack > 1) {
for(i in oldladysnack:2) {
print(sprintf(" She swallowed the%s to catch the%s",
animals[[i]][1],
animals[[i-1]][1]))
}
print(animals[[1]][2])
}
oldladysnack <- oldladysnack + 1
} | 509Old lady swallowed a fly
| 13r
| yeh6h |
require 'open-uri'
ordered_words = open('http:
word.strip!
word.chars.sort.join == word
end
grouped = ordered_words.group_by &:size
puts grouped[grouped.keys.max] | 491Ordered words
| 14ruby
| 4n25p |
public class Life{
public static void main(String[] args) throws Exception{
String start= "_###_##_#_#_#_#__#__";
int numGens = 10;
for(int i= 0; i < numGens; i++){
System.out.println("Generation " + i + ": " + start);
start= life(start);
}
}
public static String life(String lastGen){
String newGen= "";
for(int i= 0; i < lastGen.length(); i++){
int neighbors= 0;
if (i == 0){ | 512One-dimensional cellular automata
| 9java
| w2tej |
function caStep(old) {
var old = [0].concat(old, [0]); | 512One-dimensional cellular automata
| 10javascript
| 8gm0l |
function leftRect( f, a, b, n )
local h = (b - a) / n
local x = a
local sum = 0
for i = 1, 100 do
sum = sum + a + f(x)
x = x + h
end
return sum * h
end
function rightRect( f, a, b, n )
local h = (b - a) / n
local x = b
local sum = 0
for i = 1, 100 do
sum = sum + a + f(x)
x = x - h
end
return sum * h
end
function midRect( f, a, b, n )
local h = (b - a) / n
local x = a + h/2
local sum = 0
for i = 1, 100 do
sum = sum + a + f(x)
x = x + h
end
return sum * h
end
function trapezium( f, a, b, n )
local h = (b - a) / n
local x = a
local sum = 0
for i = 1, 100 do
sum = sum + f(x)*2
x = x + h
end
return (b - a) * sum / (2 * n)
end
function simpson( f, a, b, n )
local h = (b - a) / n
local sum1 = f(a + h/2)
local sum2 = 0
for i = 1, n-1 do
sum1 = sum1 + f(a + h * i + h/2)
sum2 = sum2 + f(a + h * i)
end
return (h/6) * (f(a) + f(b) + 4*sum1 + 2*sum2)
end
int_methods = { leftRect, rightRect, midRect, trapezium, simpson }
for i = 1, 5 do
print( int_methods[i]( function(x) return x^3 end, 0, 1, 100 ) )
print( int_methods[i]( function(x) return 1/x end, 1, 100, 1000 ) )
print( int_methods[i]( function(x) return x end, 0, 5000, 5000000 ) )
print( int_methods[i]( function(x) return x end, 0, 6000, 6000000 ) )
end | 511Numerical integration
| 1lua
| 31gzo |
const FILE: &'static str = include_str!("./unixdict.txt");
fn is_ordered(s: &str) -> bool {
let mut prev = '\x00';
for c in s.to_lowercase().chars() {
if c < prev {
return false;
}
prev = c;
}
return true;
}
fn find_longest_ordered_words(dict: Vec<&str>) -> Vec<&str> {
let mut result = Vec::new();
let mut longest_length = 0;
for s in dict.into_iter() {
if is_ordered(&s) {
let n = s.len();
if n > longest_length {
longest_length = n;
result.truncate(0);
}
if n == longest_length {
result.push(s);
}
}
}
return result;
}
fn main() {
let lines = FILE.lines().collect();
let longest_ordered = find_longest_ordered_words(lines);
for s in longest_ordered.iter() {
println!("{}", s.to_string());
}
} | 491Ordered words
| 15rust
| gdv4o |
isnil = (object == nil)
print(isnil) | 513Null object
| 1lua
| rfwga |
descriptions = {
:fly => ,
:spider => ,
:bird => ,
:cat => ,
:dog => ,
:goat => ,
:cow => ,
:horse => ,
}
animals = descriptions.keys
animals.each_with_index do |animal, idx|
puts
d = descriptions[animal]
case d[-1]
when then d[-1] =
when then d[-1] =
end
puts d
break if animal == :horse
idx.downto(1) do |i|
puts
case animals[i-1]
when :spider, :fly then puts descriptions[animals[i-1]]
end
end
print
end | 509Old lady swallowed a fly
| 14ruby
| v8e2n |
val wordsAll = scala.io.Source.fromURL("http: | 491Ordered words
| 16scala
| jz47i |
enum Action {Once, Every, Die}
use Action::*;
fn main() {
let animals = [ ("horse" , Die , "She's dead, of course!")
, ("donkey", Once , "It was rather wonky. To swallow a donkey.")
, ("cow" , Once , "I don't know how. To swallow a cow.")
, ("goat" , Once , "She just opened her throat. To swallow a goat.")
, ("pig" , Once , "Her mouth was so big. To swallow a pig.")
, ("dog" , Once , "What a hog. To swallow a dog.")
, ("cat" , Once , "Fancy that. To swallow a cat.")
, ("bird" , Once , "Quite absurd. To swallow a bird.")
, ("spider", Once , "That wriggled and jiggled and tickled inside her.")
, ("fly" , Every, "I don't know why she swallowed the fly.")
];
for (i, a) in animals.iter().enumerate().rev() {
println!("There was an old lady who swallowed a {}\n{}", a.0, a.2);
if let Die = a.1 {break}
for (swallowed, to_catch) in animals[i..].iter().zip(&animals[i+1..]) {
println!("She swallowed the {} to catch the {}.", swallowed.0, to_catch.0);
if let Every = to_catch.1 {
println!("{}", to_catch.2);
}
}
println!("Perhaps she'll die.\n");
}
} | 509Old lady swallowed a fly
| 15rust
| uowvj |
case class Verse(animal: String, remark: String, die: Boolean = false, always: Boolean = false)
val verses = List(
Verse("horse", "Shes dead, of course!", die = true),
Verse("donkey", "It was rather wonky. To swallow a donkey."),
Verse("cow", "I dont know how. To swallow a cow."),
Verse("goat", "She just opened her throat. To swallow a goat."),
Verse("pig", "Her mouth was so big. To swallow a pig."),
Verse("dog", "What a hog. To swallow a dog."),
Verse("cat", "Fancy that. To swallow a cat."),
Verse("bird", "Quite absurd. To swallow a bird."),
Verse("spider", "That wriggled and jiggled and tickled inside her."),
Verse("fly", "I dont know why she swallowed the fly.", always = true)
)
for (i <- 1 to verses.size; verse = verses takeRight i; starting = verse.head) {
println(s"There was an old lady who swallowed a ${starting.animal},")
println(starting.remark)
if (!starting.die) {
for (List(it, next) <- verse.sliding(2,1)) {
println(s"She swallowed the ${it.animal} to catch the ${next.animal},")
if (next.always) println(next.remark)
}
println("Perhaps shell die!")
println
}
} | 509Old lady swallowed a fly
| 16scala
| gds4i |
SET @txt = REPLACE('In girum imus nocte et consumimur igni', ' ', '');
SELECT REVERSE(@txt) = @txt; | 483Palindrome detection
| 19sql
| wv8ex |
package main
import "fmt"
func main() {
for _, n := range []int64{12, 1048576, 9e18, -2, 0} {
fmt.Println(say(n))
}
}
var small = [...]string{"zero", "one", "two", "three", "four", "five", "six",
"seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen",
"fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"}
var tens = [...]string{"", "", "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"}
var illions = [...]string{"", " thousand", " million", " billion",
" trillion", " quadrillion", " quintillion"}
func say(n int64) string {
var t string
if n < 0 {
t = "negative " | 515Number names
| 0go
| 9xgmt |
null | 512One-dimensional cellular automata
| 11kotlin
| byokb |
import Foundation | 483Palindrome detection
| 17swift
| j3174 |
def divMod(BigInteger number, BigInteger divisor) {
def qr = number.divideAndRemainder(divisor)
[div:qr[0], remainder:qr[1]]
}
def toText(value) {
value = value as BigInteger
def units = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten',
'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
def tens = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
def big = ['', 'thousand'] + ['m', 'b', 'tr', 'quadr', 'quint', 'sext', 'sept', 'oct', 'non', 'dec'].collect { "${it}illion"}
if (value < 0) {
"negative ${toText(-value)}"
} else if (value < 20) {
units[value]
} else if (value < 100) {
divMod(value, 10).with { "${tens[div]} ${units[remainder]}".replace(' zero', '') }
} else if (value < 1000) {
divMod(value, 100).with { "${toText(div)} hundred and ${toText(remainder)}".replace(' and zero', '') }
} else {
def chunks = []
while (value != 0) {
divMod(value, 1000).with {
chunks << remainder
value = div
}
}
if (chunks.size() > big.size()) {
throw new IllegalArgumentException("Number overflow")
}
def text = []
(0..<chunks.size()).each { index ->
if (chunks[index] > 0) {
text << "${toText(chunks[index])}${index == 0? '': ' ' + big[index]}"
if (index == 0 && chunks[index] < 100) {
text << "and"
}
}
}
text.reverse().join(', ').replace(', and,', ' and')
}
} | 515Number names
| 7groovy
| zp2t5 |
package main
import (
"fmt"
"math/rand"
"sort"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
var k []int
for {
k = rand.Perm(9)
for i, r := range k {
if r == 0 {
k[i] = 9
}
}
if !sort.IntsAreSorted(k) {
break
}
}
fmt.Println("Sort digits by reversing a number of digits on the left.")
var n, score int
for {
fmt.Print("Digits: ", k, ". How many to reverse? ")
i, _ := fmt.Scanln(&n)
score++
if i == 0 || n < 2 || n > 9 {
fmt.Println("\n(Enter a number from 2 to 9)")
continue
}
for l, r := 0, n-1; l < r; l, r = l+1, r-1 {
k[l], k[r] = k[r], k[l]
}
if sort.IntsAreSorted(k) {
fmt.Print("Digits: ", k, ".\n")
fmt.Print("Your score: ", score, ". Good job.\n")
return
}
}
} | 514Number reversal game
| 0go
| 7twr2 |
import Data.List (intercalate, unfoldr)
spellInteger :: Integer -> String
spellInteger n
| n < 0 = "negative " ++ spellInteger (-n)
| n < 20 = small n
| n < 100 = let (a, b) = n `divMod` 10
in tens a ++ nonzero '-' b
| n < 1000 = let (a, b) = n `divMod` 100
in small a ++ " hundred" ++ nonzero ' ' b
| otherwise = intercalate ", " $ map big $ reverse $
filter ((/= 0) . snd) $ zip [0..] $ unfoldr uff n
where nonzero :: Char -> Integer -> String
nonzero _ 0 = ""
nonzero c n = c: spellInteger n
uff :: Integer -> Maybe (Integer, Integer)
uff 0 = Nothing
uff n = Just $ uncurry (flip (,)) $ n `divMod` 1000
small, tens :: Integer -> String
small = (["zero", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine", "ten", "eleven",
"twelve", "thirteen", "fourteen", "fifteen", "sixteen",
"seventeen", "eighteen", "nineteen"] !!) . fromEnum
tens = ([undefined, undefined, "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"] !!) .
fromEnum
big :: (Int, Integer) -> String
big (0, n) = spellInteger n
big (1, n) = spellInteger n ++ " thousand"
big (e, n) = spellInteger n ++ ' ': (l !! e) ++ "illion"
where l = [undefined, undefined, "m", "b", "tr", "quadr",
"quint", "sext", "sept", "oct", "non", "dec"] | 515Number names
| 8haskell
| bysk2 |
sorted = [*(1..9)]
arr = sorted.clone()
void flipstart(n) { arr[0..<n] = arr[0..<n].reverse() }
int steps = 0
while (arr==sorted) Collections.shuffle(arr)
while (arr!=sorted) {
println arr.join(' ')
print 'Reverse how many? '
def flipcount = System.in.readLine()
flipstart( flipcount.toInteger() )
steps += 1
}
println "Done! That took you ${steps} steps" | 514Number reversal game
| 7groovy
| uobv9 |
import Data.List
import Control.Arrow
import Rosetta.Knuthshuffle
numberRevGame = do
let goal = [1..9]
shuffle xs =
if xs /= goal then return xs
else shuffle =<< knuthShuffle xs
prefixFlipAt k = uncurry (++). first reverse. splitAt k
prompt r ry = do
putStr $ show r ++ ". " ++ concatMap (flip (++) " ". show) ry
++ " How many to flip? "
answ <- getLine
let n = read answ
if n<10 && 0<n then return n
else do
putStrLn "Error. The number should be between 0 and 10. Try again"
prompt r ry
playNRG r nrs =
if nrs == goal then do
putStrLn $ "The answer is: " ++ concatMap (flip (++) " ". show) nrs
putStrLn $ "It took you " ++ show r ++ " attempts to sort the numbers."
putStrLn ""
else do
answ <- prompt r nrs
playNRG (succ r) (prefixFlipAt answ nrs)
start <- shuffle goal
playNRG 1 start | 514Number reversal game
| 8haskell
| 8g60z |
num_iterations = 9
f = { 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0 }
function Output( f, l )
io.write( l, ": " )
for i = 1, #f do
local c
if f[i] == 1 then c = '#' else c = '_' end
io.write( c )
end
print ""
end
Output( f, 0 )
for l = 1, num_iterations do
local g = {}
for i = 2, #f-1 do
if f[i-1] + f[i+1] == 1 then
g[i] = f[i]
elseif f[i] == 0 and f[i-1] + f[i+1] == 2 then
g[i] = 1
else
g[i] = 0
end
end
if f[1] == 1 and f[2] == 1 then g[1] = 1 else g[1] = 0 end
if f[#f] == 1 and f[#f-1] == 1 then g[#f] = 1 else g[#f] = 0 end
f, g = g, f
Output( f, l )
end | 512One-dimensional cellular automata
| 1lua
| pmibw |
import Foundation
guard
let url = NSURL(string: "http: | 491Ordered words
| 17swift
| 5ilu8 |
const detectNonLetterRegexp=/[^A-Z--]/g;
function stripDiacritics(phrase:string){
return phrase.normalize('NFD').replace(/[\u0300-\u036f]/g, "")
}
function isPalindrome(phrase:string){
const TheLetters = stripDiacritics(phrase.toLocaleUpperCase().replace(detectNonLetterRegexp, ''));
const middlePosition = TheLetters.length/2;
const leftHalf = TheLetters.substr(0, middlePosition);
const rightReverseHalf = TheLetters.substr(-middlePosition).split('').reverse().join('');
return leftHalf == rightReverseHalf;
}
console.log(isPalindrome('Sueo que esto no es un palndromo'))
console.log(isPalindrome('Dbale arroz a la zorra el abad!'))
console.log(isPalindrome(' ')) | 483Palindrome detection
| 20typescript
| o7t8l |
use feature 'say';
sub leftrect {
my($func, $a, $b, $n) = @_;
my $h = ($b - $a) / $n;
my $sum = 0;
for ($_ = $a; $_ < $b; $_ += $h) { $sum += $func->($_) }
$h * $sum
}
sub rightrect {
my($func, $a, $b, $n) = @_;
my $h = ($b - $a) / $n;
my $sum = 0;
for ($_ = $a+$h; $_ < $b+$h; $_ += $h) { $sum += $func->($_) }
$h * $sum
}
sub midrect {
my($func, $a, $b, $n) = @_;
my $h = ($b - $a) / $n;
my $sum = 0;
for ($_ = $a + $h/2; $_ < $b; $_ += $h) { $sum += $func->($_) }
$h * $sum
}
sub trapez {
my($func, $a, $b, $n) = @_;
my $h = ($b - $a) / $n;
my $sum = $func->($a) + $func->($b);
for ($_ = $a+$h; $_ < $b; $_ += $h) { $sum += 2 * $func->($_) }
$h/2 * $sum
}
sub simpsons {
my($func, $a, $b, $n) = @_;
my $h = ($b - $a) / $n;
my $h2 = $h/2;
my $sum1 = $func->($a + $h2);
my $sum2 = 0;
for ($_ = $a+$h; $_ < $b; $_ += $h) {
$sum1 += $func->($_ + $h2);
$sum2 += $func->($_);
}
$h/6 * ($func->($a) + $func->($b) + 4*$sum1 + 2*$sum2)
}
sub sig {
my($value) = @_;
my $rounded;
if ($value < 10) {
$rounded = sprintf '%.6f', $value;
$rounded =~ s/(\.\d*[1-9])0+$/$1/;
$rounded =~ s/\.0+$//;
} else {
$rounded = sprintf "%.1f", $value;
$rounded =~ s/\.0+$//;
}
return $rounded;
}
sub integrate {
my($func, $a, $b, $n, $exact) = @_;
my $f = sub { local $_ = shift; eval $func };
my @res;
push @res, "$func\n in [$a..$b] / $n";
push @res, ' exact result: ' . rnd($exact);
push @res, ' rectangle method left: ' . rnd( leftrect($f, $a, $b, $n));
push @res, ' rectangle method right: ' . rnd(rightrect($f, $a, $b, $n));
push @res, ' rectangle method mid: ' . rnd( midrect($f, $a, $b, $n));
push @res, 'composite trapezoidal rule: ' . rnd( trapez($f, $a, $b, $n));
push @res, ' quadratic simpsons rule: ' . rnd( simpsons($f, $a, $b, $n));
@res;
}
say for integrate('$_ ** 3', 0, 1, 100, 0.25); say '';
say for integrate('1 / $_', 1, 100, 1000, log(100)); say '';
say for integrate('$_', 0, 5_000, 5_000_000, 12_500_000); say '';
say for integrate('$_', 0, 6_000, 6_000_000, 18_000_000); | 511Numerical integration
| 2perl
| byik4 |
public enum IntToWords {
;
private static final String[] small = {
"", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine",
"ten", "eleven", "twelve", "thirteen", "fourteen",
"fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
private static final String[] tens = {
"", "", "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"};
private static final String[] big = {
"", "thousand", "million", "billion", "trillion",
"quadrillion", "quintillion"};
public static void main(String[] args) {
System.out.println(int2Text(0));
System.out.println(int2Text(10));
System.out.println(int2Text(30));
System.out.println(int2Text(47));
System.out.println(int2Text(100));
System.out.println(int2Text(999));
System.out.println(int2Text(1000));
System.out.println(int2Text(9999));
System.out.println(int2Text(123_456));
System.out.println(int2Text(900_000_001));
System.out.println(int2Text(1_234_567_890));
System.out.println(int2Text(-987_654_321));
System.out.println(int2Text(Long.MAX_VALUE));
System.out.println(int2Text(Long.MIN_VALUE));
}
public static String int2Text(long number) {
StringBuilder sb = new StringBuilder();
if (number == 0) {
return "zero";
}
long num = -Math.abs(number);
int unit = 1;
while (true) {
int rem100 = (int) -(num % 100);
if (rem100 >= 20) {
if (rem100 % 10 == 0) {
sb.insert(0, tens[rem100 / 10] + " ");
} else {
sb.insert(0, tens[rem100 / 10] + "-" + small[rem100 % 10] + " ");
}
} else if (rem100 != 0) {
sb.insert(0, small[rem100] + " ");
}
int hundreds = (int) -(num % 1000) / 100;
if (hundreds != 0) {
sb.insert(0, small[hundreds] + " hundred ");
}
num /= 1000;
if (num == 0) {
break;
}
int rem1000 = (int) -(num % 1000);
if (rem1000 != 0) {
sb.insert(0, big[unit] + " ");
}
unit++;
}
if (number < 0) {
sb.insert(0, "negative ");
}
return sb.toString().trim();
}
} | 515Number names
| 9java
| gd14m |
const divMod = y => x => [Math.floor(y/x), y % x];
const sayNumber = value => {
let name = '';
let quotient, remainder;
const dm = divMod(value);
const units = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven',
'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen',
'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'];
const tens = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty',
'seventy', 'eighty', 'ninety'];
const big = [...['', 'thousand'], ...['m', 'b', 'tr', 'quadr', 'quint',
'sext', 'sept', 'oct', 'non', 'dec'].map(e => `${e}illion`)];
if (value < 0) {
name = `negative ${sayNumber(-value)}`
} else if (value < 20) {
name = units[value]
} else if (value < 100) {
[quotient, remainder] = dm(10);
name = `${tens[quotient]} ${units[remainder]}`.replace(' zero', '');
} else if (value < 1000) {
[quotient, remainder] = dm(100);
name = `${sayNumber(quotient)} hundred and ${sayNumber(remainder)}`
.replace(' and zero', '')
} else {
const chunks = [];
const text = [];
while (value !== 0) {
[value, remainder] = divMod(value)(1000);
chunks.push(remainder);
}
chunks.forEach((e,i) => {
if (e > 0) {
text.push(`${sayNumber(e)}${i === 0 ? '' : ' ' + big[i]}`);
if (i === 0 && e < 100) {
text.push('and');
}
}
});
name = text.reverse().join(', ').replace(', and,', ' and');
}
return name;
}; | 515Number names
| 10javascript
| k6qhq |
print defined($x) ? 'Defined' : 'Undefined', ".\n"; | 513Null object
| 2perl
| njciw |
import java.util.List;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Collections;
public class ReversalGame {
private List<Integer> gameList;
public ReversalGame() {
initialize();
}
public void play() throws Exception {
int i = 0;
int moveCount = 0;
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println(gameList);
System.out.println("Please enter a index to reverse from 2 to 9. Enter 99 to quit");
i = scanner.nextInt();
if (i == 99) {
break;
}
if (i < 2 || i > 9) {
System.out.println("Invalid input");
} else {
moveCount++;
reverse(i);
if (isSorted()) {
System.out.println("Congratulations you solved this in " + moveCount + " moves!");
break;
}
}
}
scanner.close();
}
private void reverse(int position) {
Collections.reverse(gameList.subList(0, position));
}
private boolean isSorted() {
for (int i=0; i < gameList.size() - 1; ++i) {
if (gameList.get(i).compareTo(gameList.get(i + 1)) > 0) {
return false;
}
}
return true;
}
private void initialize() {
this.gameList = new ArrayList<Integer>(9);
for (int i=1; i < 10; ++i) {
gameList.add(i);
}
while (isSorted()) {
Collections.shuffle(gameList);
}
}
public static void main(String[] args) {
try {
ReversalGame game = new ReversalGame();
game.play();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
} | 514Number reversal game
| 9java
| elna5 |
from fractions import Fraction
def left_rect(f,x,h):
return f(x)
def mid_rect(f,x,h):
return f(x + h/2)
def right_rect(f,x,h):
return f(x+h)
def trapezium(f,x,h):
return (f(x) + f(x+h))/2.0
def simpson(f,x,h):
return (f(x) + 4*f(x + h/2) + f(x+h))/6.0
def cube(x):
return x*x*x
def reciprocal(x):
return 1/x
def identity(x):
return x
def integrate( f, a, b, steps, meth):
h = (b-a)/steps
ival = h * sum(meth(f, a+i*h, h) for i in range(steps))
return ival
for a, b, steps, func in ((0., 1., 100, cube), (1., 100., 1000, reciprocal)):
for rule in (left_rect, mid_rect, right_rect, trapezium, simpson):
print('%s integrated using%s\n from%r to%r (%i steps) =%r'%
(func.__name__, rule.__name__, a, b, steps,
integrate( func, a, b, steps, rule)))
a, b = Fraction.from_float(a), Fraction.from_float(b)
for rule in (left_rect, mid_rect, right_rect, trapezium, simpson):
print('%s integrated using%s\n from%r to%r (%i steps and fractions) =%r'%
(func.__name__, rule.__name__, a, b, steps,
float(integrate( func, a, b, steps, rule))))
for a, b, steps, func in ((0., 5000., 5000000, identity),
(0., 6000., 6000000, identity)):
for rule in (left_rect, mid_rect, right_rect, trapezium, simpson):
print('%s integrated using%s\n from%r to%r (%i steps) =%r'%
(func.__name__, rule.__name__, a, b, steps,
integrate( func, a, b, steps, rule)))
a, b = Fraction.from_float(a), Fraction.from_float(b)
for rule in (left_rect, mid_rect, right_rect, trapezium, simpson):
print('%s integrated using%s\n from%r to%r (%i steps and fractions) =%r'%
(func.__name__, rule.__name__, a, b, steps,
float(integrate( func, a, b, steps, rule)))) | 511Numerical integration
| 3python
| pmnbm |
<html>
<head>
<title>Number Reversal Game</title>
</head>
<body>
<div id="start"></div>
<div id="progress"></div>
<div id="score"></div>
<script type="text/javascript"> | 514Number reversal game
| 10javascript
| 043sz |
$x = NULL;
if (is_null($x))
echo ; | 513Null object
| 12php
| 7txrp |
integ <- function(f, a, b, n, u, v) {
h <- (b - a) / n
s <- 0
for (i in seq(0, n - 1)) {
s <- s + sum(v * f(a + i * h + u * h))
}
s * h
}
test <- function(f, a, b, n) {
c(rect.left = integ(f, a, b, n, 0, 1),
rect.right = integ(f, a, b, n, 1, 1),
rect.mid = integ(f, a, b, n, 0.5, 1),
trapezoidal = integ(f, a, b, n, c(0, 1), c(0.5, 0.5)),
simpson = integ(f, a, b, n, c(0, 0.5, 1), c(1, 4, 1) / 6))
}
test(\(x) x^3, 0, 1, 100)
test(\(x) 1 / x, 1, 100, 1000)
test(\(x) x, 0, 5000, 5e6)
test(\(x) x, 0, 6000, 6e6) | 511Numerical integration
| 13r
| jz078 |
null | 515Number names
| 11kotlin
| 20jli |
x = None
if x is None:
print
else:
print | 513Null object
| 3python
| dhln1 |
is.null(NULL)
is.null(123)
is.null(NA)
123==NULL
foo <- function(){}
foo() | 513Null object
| 13r
| 8gy0x |
null | 514Number reversal game
| 11kotlin
| k6sh3 |
$_="_
do {
y/01/_
print;
y/_
s/(?<=(.))(.)(?=(.))/$1 == $3? $1? 1-$2: 0: $2/eg;
} while ($x ne $_ and $x=$_); | 512One-dimensional cellular automata
| 2perl
| 6ag36 |
words = {"one ", "two ", "three ", "four ", "five ", "six ", "seven ", "eight ", "nine "}
levels = {"thousand ", "million ", "billion ", "trillion ", "quadrillion ", "quintillion ", "sextillion ", "septillion ", "octillion ", [0] = ""}
iwords = {"ten ", "twenty ", "thirty ", "forty ", "fifty ", "sixty ", "seventy ", "eighty ", "ninety "}
twords = {"eleven ", "twelve ", "thirteen ", "fourteen ", "fifteen ", "sixteen ", "seventeen ", "eighteen ", "nineteen "}
function digits(n)
local i, ret = -1
return function()
i, ret = i + 1, n % 10
if n > 0 then
n = math.floor(n / 10)
return i, ret
end
end
end
level = false
function getname(pos, dig) | 515Number names
| 1lua
| v8h2x |
null | 514Number reversal game
| 1lua
| by0ka |
def leftrect(f, left, right)
f.call(left)
end
def midrect(f, left, right)
f.call((left+right)/2.0)
end
def rightrect(f, left, right)
f.call(right)
end
def trapezium(f, left, right)
(f.call(left) + f.call(right)) / 2.0
end
def simpson(f, left, right)
(f.call(left) + 4*f.call((left+right)/2.0) + f.call(right)) / 6.0
end
def integrate(f, a, b, steps, method)
delta = 1.0 * (b - a) / steps
total = 0.0
steps.times do |i|
left = a + i*delta
right = left + delta
total += delta * send(method, f, left, right)
end
total
end
def square(x)
x**2
end
def def_int(f, a, b)
l = case f.to_s
when /sin>/
lambda {|x| -Math.cos(x)}
when /square>/
lambda {|x| (x**3)/3.0}
end
l.call(b) - l.call(a)
end
a = 0
b = Math::PI
steps = 10
for func in [method(:square), Math.method(:sin)]
puts
actual = def_int(func, a, b)
for method in [:leftrect, :midrect, :rightrect, :trapezium, :simpson]
int = integrate(func, a, b, steps, method)
diff = (int - actual) * 100.0 / actual
printf , method, int, diff
end
end | 511Numerical integration
| 14ruby
| acf1s |
puts if @object.nil?
puts if $object.nil?
object = 1 if false
puts if object.nil?
puts nil.class | 513Null object
| 14ruby
| tbvf2 |
null | 513Null object
| 15rust
| zputo |
fn integral<F>(f: F, range: std::ops::Range<f64>, n_steps: u32) -> f64
where F: Fn(f64) -> f64
{
let step_size = (range.end - range.start)/n_steps as f64;
let mut integral = (f(range.start) + f(range.end))/2.;
let mut pos = range.start + step_size;
while pos < range.end {
integral += f(pos);
pos += step_size;
}
integral * step_size
}
fn main() {
println!("{}", integral(|x| x.powi(3), 0.0..1.0, 100));
println!("{}", integral(|x| 1.0/x, 1.0..100.0, 1000));
println!("{}", integral(|x| x, 0.0..5000.0, 5_000_000));
println!("{}", integral(|x| x, 0.0..6000.0, 6_000_000));
} | 511Numerical integration
| 15rust
| eltaj |
scala> Nil
res0: scala.collection.immutable.Nil.type = List()
scala> Nil == List()
res1: Boolean = true
scala> Null
<console>:8: error: not found: value Null
Null
^
scala> null
res3: Null = null
scala> None
res4: None.type = None
scala> Unit
res5: Unit.type = object scala.Unit
scala> val a = println()
a: Unit = () | 513Null object
| 16scala
| yeg63 |
object NumericalIntegration {
def leftRect(f:Double=>Double, a:Double, b:Double)=f(a)
def midRect(f:Double=>Double, a:Double, b:Double)=f((a+b)/2)
def rightRect(f:Double=>Double, a:Double, b:Double)=f(b)
def trapezoid(f:Double=>Double, a:Double, b:Double)=(f(a)+f(b))/2
def simpson(f:Double=>Double, a:Double, b:Double)=(f(a)+4*f((a+b)/2)+f(b))/6;
def fn1(x:Double)=x*x*x
def fn2(x:Double)=1/x
def fn3(x:Double)=x
type Method = (Double=>Double, Double, Double) => Double
def integrate(f:Double=>Double, a:Double, b:Double, steps:Double, m:Method)={
val delta:Double=(b-a)/steps
delta*(a until b by delta).foldLeft(0.0)((s,x) => s+m(f, x, x+delta))
}
def print(f:Double=>Double, a:Double, b:Double, steps:Double)={
println("rectangular left :%f".format(integrate(f, a, b, steps, leftRect)))
println("rectangular middle:%f".format(integrate(f, a, b, steps, midRect)))
println("rectangular right :%f".format(integrate(f, a, b, steps, rightRect)))
println("trapezoid :%f".format(integrate(f, a, b, steps, trapezoid)))
println("simpson :%f".format(integrate(f, a, b, steps, simpson)))
}
def main(args: Array[String]): Unit = {
print(fn1, 0, 1, 100)
println("------")
print(fn2, 1, 100, 1000)
println("------")
print(fn3, 0, 5000, 5000000)
println("------")
print(fn3, 0, 6000, 6000000)
}
} | 511Numerical integration
| 16scala
| qu6xw |
import random
printdead, printlive = '_
maxgenerations = 10
cellcount = 20
offendvalue = '0'
universe = ''.join(random.choice('01') for i in range(cellcount))
neighbours2newstate = {
'000': '0',
'001': '0',
'010': '0',
'011': '1',
'100': '0',
'101': '1',
'110': '1',
'111': '0',
}
for i in range(maxgenerations):
print % ( i,
universe.replace('0', printdead).replace('1', printlive) )
universe = offendvalue + universe + offendvalue
universe = ''.join(neighbours2newstate[universe[i:i+3]] for i in range(cellcount)) | 512One-dimensional cellular automata
| 3python
| yer6q |
set.seed(15797, kind="Mersenne-Twister")
maxgenerations = 10
cellcount = 20
offendvalue = FALSE
universe <- c(offendvalue,
sample( c(TRUE, FALSE), cellcount, replace=TRUE),
offendvalue)
stayingAlive <- lapply(list(c(1,1,0),
c(1,0,1),
c(0,1,0)), as.logical)
deadOrAlive <- function(x, map) list(x)%in% map
cellularAutomata <- function(x, map) {
c(x[1], apply(embed(x, 3), 1, deadOrAlive, map=map), x[length(x)])
}
deadOrAlive2string <- function(x) {
paste(ifelse(x, '
}
for (i in 1:maxgenerations) {
universe <- cellularAutomata(universe, stayingAlive)
cat(format(i, width=3), deadOrAlive2string(universe), "\n")
} | 512One-dimensional cellular automata
| 13r
| tbufz |
let maybeInt: Int? = nil | 513Null object
| 17swift
| fk2dk |
public enum IntegrationType: CaseIterable {
case rectangularLeft
case rectangularRight
case rectangularMidpoint
case trapezium
case simpson
}
public func integrate(
from: Double,
to: Double,
n: Int,
using: IntegrationType = .simpson,
f: (Double) -> Double
) -> Double {
let integrationFunc: (Double, Double, Int, (Double) -> Double) -> Double
switch using {
case .rectangularLeft:
integrationFunc = integrateRectL
case .rectangularRight:
integrationFunc = integrateRectR
case .rectangularMidpoint:
integrationFunc = integrateRectMid
case .trapezium:
integrationFunc = integrateTrapezium
case .simpson:
integrationFunc = integrateSimpson
}
return integrationFunc(from, to, n, f)
}
private func integrateRectL(from: Double, to: Double, n: Int, f: (Double) -> Double) -> Double {
let h = (to - from) / Double(n)
var x = from
var sum = 0.0
while x <= to - h {
sum += f(x)
x += h
}
return h * sum
}
private func integrateRectR(from: Double, to: Double, n: Int, f: (Double) -> Double) -> Double {
let h = (to - from) / Double(n)
var x = from
var sum = 0.0
while x <= to - h {
sum += f(x + h)
x += h
}
return h * sum
}
private func integrateRectMid(from: Double, to: Double, n: Int, f: (Double) -> Double) -> Double {
let h = (to - from) / Double(n)
var x = from
var sum = 0.0
while x <= to - h {
sum += f(x + h / 2.0)
x += h
}
return h * sum
}
private func integrateTrapezium(from: Double, to: Double, n: Int, f: (Double) -> Double) -> Double {
let h = (to - from) / Double(n)
var sum = f(from) + f(to)
for i in 1..<n {
sum += 2 * f(from + Double(i) * h)
}
return h * sum / 2
}
private func integrateSimpson(from: Double, to: Double, n: Int, f: (Double) -> Double) -> Double {
let h = (to - from) / Double(n)
var sum1 = 0.0
var sum2 = 0.0
for i in 0..<n {
sum1 += f(from + h * Double(i) + h / 2.0)
}
for i in 1..<n {
sum2 += f(from + h * Double(i))
}
return h / 6.0 * (f(from) + f(to) + 4.0 * sum1 + 2.0 * sum2)
}
let types = IntegrationType.allCases
print("f(x) = x^3:", types.map({ integrate(from: 0, to: 1, n: 100, using: $0, f: { pow($0, 3) }) }))
print("f(x) = 1 / x:", types.map({ integrate(from: 1, to: 100, n: 1000, using: $0, f: { 1 / $0 }) }))
print("f(x) = x, 0 -> 5_000:", types.map({ integrate(from: 0, to: 5_000, n: 5_000_000, using: $0, f: { $0 }) }))
print("f(x) = x, 0 -> 6_000:", types.map({ integrate(from: 0, to: 6_000, n: 6_000_000, using: $0, f: { $0 }) })) | 511Numerical integration
| 17swift
| 19dpt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.