code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
IDLE 2.6.1 >>> >>> x,xi, y,yi = 2.0,0.5, 4.0,0.25 >>> >>> z = x + y >>> zi = 1.0 / (x + y) >>> >>> multiplier = lambda n1, n2: (lambda m: n1 * n2 * m) >>> >>> numlist = [x, y, z] >>> numlisti = [xi, yi, zi] >>> >>> [multiplier(inversen, n)(.5) for n, inversen in zip(numlist, numlisti)] [0.5, 0.5, 0.5] >>>
823First-class functions/Use numbers analogously
3python
nl5iz
int main(int argc, char *argv[]) { int days[] = {31,29,31,30,31,30,31,31,30,31,30,31}; int m, y, w; if (argc < 2 || (y = atoi(argv[1])) <= 1752) return 1; days[1] -= (y % 4) || (!(y % 100) && (y % 400)); w = y * 365 + 97 * (y - 1) / 400 + 4; for(m = 0; m < 12; m++) { ...
833Find the last Sunday of each month
5c
6gl32
import java.util.Arrays; import java.util.LinkedList; import java.util.List; public class Fire { private static final char BURNING = 'w';
821Forest fire
9java
m71ym
def p(l, n) test = 0 logv = Math.log(2.0) / Math.log(10.0) factor = 1 loopv = l while loopv > 10 do factor = factor * 10 loopv = loopv / 10 end while n > 0 do test = test + 1 val = (factor * (10.0 ** ((test * logv).modulo(1.0)))).floor if val == l then...
822First power of 2 that has leading decimal digits of 12
14ruby
z5jtw
multiplier <- function(n1,n2) { (function(m){n1*n2*m}) } x = 2.0 xi = 0.5 y = 4.0 yi = 0.25 z = x + y zi = 1.0 / ( x + y ) num = c(x,y,z) inv = c(xi,yi,zi) multiplier(num,inv)(0.5) Output [1] 0.5 0.5 0.5
823First-class functions/Use numbers analogously
13r
0ylsg
<?php $graph = array(); for ($i = 0; $i < 10; ++$i) { $graph[] = array(); for ($j = 0; $j < 10; ++$j) $graph[$i][] = $i == $j? 0 : 9999999; } for ($i = 1; $i < 10; ++$i) { $graph[0][$i] = $graph[$i][0] = rand(1, 9); } for ($k = 0; $k < 10; ++$k) { for ($i = 0; $i < 10; ++$i) { for ($j ...
817Floyd-Warshall algorithm
12php
tupf1
>>> dif = lambda s: [x-s[i] for i,x in enumerate(s[1:])] >>> >>> difn = lambda s, n: difn(dif(s), n-1) if n else s >>> s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73] >>> difn(s, 0) [90, 47, 58, 29, 22, 32, 55, 5, 55, 73] >>> difn(s, 1) [-43, 11, -29, -7, 10, 23, -50, 50, 18] >>> difn(s, 2) [54, -40, 22, 17, 13, -73, 100...
815Forward difference
3python
u1dvd
use POSIX qw(ceil floor); sub fivenum { my(@array) = @_; my $n = scalar @array; die "No values were entered into fivenum!" if $n == 0; my @x = sort {$a <=> $b} @array; my $n4 = floor(($n+3)/2)/2; my @d = (1, $n4, ($n +1)/2, $n+1-$n4, $n); my @sum_array; for my $e (0..4) { my $floor = floo...
825Fivenum
2perl
xz6w8
(defn compute-line [pt1 pt2] (let [[x1 y1] pt1 [x2 y2] pt2 m (/ (- y2 y1) (- x2 x1))] {:slope m :offset (- y1 (* m x1))})) (defn intercept [line1 line2] (let [x (/ (- (:offset line1) (:offset line2)) (- (:slope line2) (:slope line1)))] {:x x :y (+ (* (:slope line1) x...
831Find the intersection of two lines
6clojure
4eb5o
"use strict" const _ = require('lodash'); const WIDTH_ARGUMENT_POSITION = 2; const HEIGHT_ARGUMENT_POSITION = 3; const TREE_PROBABILITY = 0.5; const NEW_TREE_PROBABILITY = 0.01; const BURN_PROBABILITY = 0.0001; const CONSOLE_RED = '\x1b[31m'; const CONSOLE_GREEN = '\x1b[32...
821Forest fire
10javascript
vpq25
fn power_of_two(l: isize, n: isize) -> isize { let mut test: isize = 0; let log: f64 = 2.0_f64.ln() / 10.0_f64.ln(); let mut factor: isize = 1; let mut looop = l; let mut nn = n; while looop > 10 { factor *= 10; looop /= 10; } while nn > 0 { test = test + 1; ...
822First power of 2 that has leading decimal digits of 12
15rust
34hz8
object FirstPowerOfTwo { def p(l: Int, n: Int): Int = { var n2 = n var test = 0 val log = math.log(2) / math.log(10) var factor = 1 var loop = l while (loop > 10) { factor *= 10 loop /= 10 } while (n2 > 0) { test += 1 val value = (factor * math.pow(10, test * lo...
822First power of 2 that has leading decimal digits of 12
16scala
m7pyc
begin rescue ExceptionClassA => a rescue ExceptionClassB, ExceptionClassC => b_or_c rescue else ensure end
819Flow-control structures
14ruby
d2jns
package main import "fmt" func main() { floyd(5) floyd(14) } func floyd(n int) { fmt.Printf("Floyd%d:\n", n) lowerLeftCorner := n*(n-1)/2 + 1 lastInColumn := lowerLeftCorner lastInRow := 1 for i, row := 1, 1; row <= n; i++ { w := len(fmt.Sprint(lastInColumn)) if i < lastIn...
824Floyd's triangle
0go
4eq52
forwarddif <- function(a, n) { if ( n == 1 ) a[2:length(a)] - a[1:length(a)-1] else { r <- forwarddif(a, 1) forwarddif(r, n-1) } } fdiff <- function(a, n) { r <- a for(i in 1:n) { r <- r[2:length(r)] - r[1:length(r)-1] } r } v <- c(90, 47, 58, 29, 22, 32, 55, 5, 55, 73) print(forwarddif...
815Forward difference
13r
ch895
use strict; use warnings; use feature 'say'; use ntheory qw/fromdigits todigitstring/; use utf8; binmode('STDOUT', 'utf8'); sub first_square { my $n = shift; my $sr = substr('1023456789abcdef',0,$n); my $r = int fromdigits($sr, $n) ** .5; my @digits = reverse split '', $sr; TRY: while (1) { ...
828First perfect square in base n with n unique digits
2perl
wtfe6
class FlipBoard def initialize(size) raise ArgumentError.new() if size < 2 @size = size @board = Array.new(size**2, 0) randomize_board loop do @target = generate_target break unless solved? end @columns = [*'a'...('a'.ord+@size).chr] @rows = (1..@size).map(&:to_s) ...
820Flipping bits game
14ruby
2bqlw
multiplier = proc {|n1, n2| proc {|m| n1 * n2 * m}} numlist = [x=2, y=4, x+y] invlist = [0.5, 0.25, 1.0/(x+y)] p numlist.zip(invlist).map {|n, invn| multiplier[invn, n][0.5]}
823First-class functions/Use numbers analogously
14ruby
fvgdr
#![feature(conservative_impl_trait)] fn main() { let (x, xi) = (2.0, 0.5); let (y, yi) = (4.0, 0.25); let z = x + y; let zi = 1.0/z; let numlist = [x,y,z]; let invlist = [xi,yi,zi]; let result = numlist.iter() .zip(&invlist) .map(|(x,y)| mult...
823First-class functions/Use numbers analogously
15rust
turfd
import Goto._ import scala.util.continuations._ object Goto { case class Label(k: Label => Unit) private case class GotoThunk(label: Label) extends Throwable def label: Label @suspendable = shift((k: Label => Unit) => executeFrom(Label(k))) def goto(l: Label): Nothing = throw new GotoThunk(l) pr...
819Flow-control structures
16scala
34pzy
class Floyd { static void main(String[] args) { printTriangle(5) printTriangle(14) } private static void printTriangle(int n) { println(n + " rows:") int printMe = 1 int numsPrinted = 0 for (int rowNum = 1; rowNum <= n; printMe++) { int cols = (in...
824Floyd's triangle
7groovy
lk1c1
from math import inf from itertools import product def floyd_warshall(n, edge): rn = range(n) dist = [[inf] * n for i in rn] nxt = [[0] * n for i in rn] for i in rn: dist[i][i] = 0 for u, v, w in edge: dist[u-1][v-1] = w nxt[u-1][v-1] = v-1 for k, i, j in product(rn, ...
817Floyd-Warshall algorithm
3python
h06jw
def four_bit_adder(a, b) a_bits = binary_string_to_bits(a,4) b_bits = binary_string_to_bits(b,4) s0, c0 = full_adder(a_bits[0], b_bits[0], 0) s1, c1 = full_adder(a_bits[1], b_bits[1], c0) s2, c2 = full_adder(a_bits[2], b_bits[2], c1) s3, c3 = full_adder(a_bits[3], b_bits[3], c2) [bits_to_binary_string(...
814Four bit adder
14ruby
jsm7x
from __future__ import division import math import sys def fivenum(array): n = len(array) if n == 0: print() sys.exit() x = sorted(array) n4 = math.floor((n+3.0)/2.0)/2.0 d = [1, n4, (n+1)/2, n+1-n4, n] sum_array = [] for e in range(5): floor = int(math.floor(d[e] ...
825Fivenum
3python
q3yxi
(ns last-sundays.core (:require [clj-time.core:as time] [clj-time.periodic:refer [periodic-seq]] [clj-time.format:as fmt]) (:import (org.joda.time DateTime DateTimeConstants)) (:gen-class)) (defn sunday? [t] (= (.getDayOfWeek t) (DateTimeConstants/SUNDAY))) (defn sundays [year] (take...
833Find the last Sunday of each month
6clojure
lk4cb
null
821Forest fire
1lua
z5hty
null
820Flipping bits game
15rust
vps2t
let ld10 = log(2.0) / log(10.0) func p(L: Int, n: Int) -> Int { var l = L var digits = 1 while l >= 10 { digits *= 10 l /= 10 } var count = 0 var i = 0 while count < n { let rhs = (Double(i) * ld10).truncatingRemainder(dividingBy: 1) let e = exp(log(10.0) * rhs) if Int(e * Double(...
822First power of 2 that has leading decimal digits of 12
17swift
tu7fl
scala> val x = 2.0 x: Double = 2.0 scala> val xi = 0.5 xi: Double = 0.5 scala> val y = 4.0 y: Double = 4.0 scala> val yi = 0.25 yi: Double = 0.25 scala> val z = x + y z: Double = 6.0 scala> val zi = 1.0 / ( x + y ) zi: Double = 0.16666666666666666 scala> val numbers = List(x, y, z) numbers: List[Double] = List(2....
823First-class functions/Use numbers analogously
16scala
6gh31
floydTriangle :: [[Int]] floydTriangle = ( zipWith (fmap (.) enumFromTo <*> (\a b -> pred (a + b))) <$> scanl (+) 1 <*> id ) [1 ..] main :: IO () main = mapM_ (putStrLn . formatFT) [5, 14] formatFT :: Int -> String formatFT n = unlines $ unwords . zipWith alignR ws <$> t where t = ...
824Floyd's triangle
8haskell
q3mx9
null
814Four bit adder
15rust
h09j2
x <- c(0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555,-0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578) fivenum(x)
825Fivenum
13r
adt1z
package main import "fmt" type Vector3D struct{ x, y, z float64 } func (v *Vector3D) Add(w *Vector3D) *Vector3D { return &Vector3D{v.x + w.x, v.y + w.y, v.z + w.z} } func (v *Vector3D) Sub(w *Vector3D) *Vector3D { return &Vector3D{v.x - w.x, v.y - w.y, v.z - w.z} } func (v *Vector3D) Mul(s float64) *Vector...
832Find the intersection of a line with a plane
0go
k8whz
main() { var total = 0; var empty = <int>[]; for (var year = 1900; year < 2101; year++) { var months = [1, 3, 5, 7, 8, 10, 12].where((m) => DateTime(year, m, 1).weekday == 5); print('$year\t$months'); total += months.length; if (months.isEmpty) empty.add(year); } print('Total: $total')...
830Five weekends
18dart
z52te
'''Perfect squares using every digit in a given base.''' from itertools import count, dropwhile, repeat from math import ceil, sqrt from time import time def allDigitSquare(base, above): '''The lowest perfect square which requires all digits in the given base. ''' bools = list(repeat(True, base))...
828First perfect square in base n with n unique digits
3python
xztwr
import java.awt.{BorderLayout, Color, Dimension, Font, Graphics, Graphics2D, Rectangle, RenderingHints} import java.awt.event.{MouseAdapter, MouseEvent} import javax.swing.{JFrame, JPanel} object FlippingBitsGame extends App { class FlippingBitsGame extends JPanel { private val maxLevel: Int = 7 private va...
820Flipping bits game
16scala
4eo50
def dif(s) s.each_cons(2).collect { |x, y| y - x } end def difn(s, n) n.times.inject(s) { |s, | dif(s) } end
815Forward difference
14ruby
4et5p
const char *perms[] = { , , , , , , , , , , , , , , , , , , , , , , , }; int main() { int i, j, n, cnt[N]; char miss[N]; for (n = i = 1; i < N; i++) n *= i; for (i = 0; i < N; i++) { for (j = 0; j < N; j++) cnt[j] = 0; for (j = 0; j < sizeof(perms)/sizeof(const char*); j++) cnt[perms[j][i] - 'A']+...
834Find the missing permutation
5c
lk5cy
class LinePlaneIntersection { private static class Vector3D { private double x, y, z Vector3D(double x, double y, double z) { this.x = x this.y = y this.z = z } Vector3D plus(Vector3D v) { return new Vector3D(x + v.x, y + v.y, z + v.z...
832Find the intersection of a line with a plane
7groovy
gwb46
import Foundation struct Board: Equatable, CustomStringConvertible { let size: Int private var tiles: [Bool] init(size: Int) { self.size = size tiles = Array(count: size * size, repeatedValue: false) } subscript(x: Int, y: Int) -> Bool { get { return tiles[y * ...
820Flipping bits game
17swift
lkxc2
public class Floyd { public static void main(String[] args){ printTriangle(5); printTriangle(14); } private static void printTriangle(int n){ System.out.println(n + " rows:"); for(int rowNum = 1, printMe = 1, numsPrinted = 0; rowNum <= n; printMe++){ int cols = (int)Math.ceil(Math.log10(n*(n-1)/2 + n...
824Floyd's triangle
9java
pifb3
def fdiff(xs: List[Int]) = (xs.tail, xs).zipped.map(_ - _) def fdiffn(i: Int, xs: List[Int]): List[Int] = if (i == 1) fdiff(xs) else fdiffn(i - 1, fdiff(xs))
815Forward difference
16scala
jsy7i
object FourBitAdder { type Nibble=(Boolean, Boolean, Boolean, Boolean) def xor(a:Boolean, b:Boolean)=(!a)&&b || a&&(!b) def halfAdder(a:Boolean, b:Boolean)={ val s=xor(a,b) val c=a && b (s, c) } def fullAdder(a:Boolean, b:Boolean, cIn:Boolean)={ val (s1, c1)=halfAdder(a, cIn) ...
814Four bit adder
16scala
pi2bj
package main import ( "fmt" "errors" ) type Point struct { x float64 y float64 } type Line struct { slope float64 yint float64 } func CreateLine (a, b Point) Line { slope := (b.y-a.y) / (b.x-a.x) yint := a.y - slope*a.x return Line{slope, yint} } func EvalX (l Line, x float64) float64 { return l.slope*x...
831Find the intersection of two lines
0go
xznwf
import Control.Applicative (liftA2) import Text.Printf (printf) data V3 a = V3 a a a deriving Show instance Functor V3 where fmap f (V3 a b c) = V3 (f a) (f b) (f c) instance Applicative V3 where pure a = V3 a a a V3 a b c <*> V3 d e f = V3 (a d) (b e) (c f) instance Num a => Num (V3 a) where (+...
832Find the intersection of a line with a plane
8haskell
nl6ie
(function () { 'use strict';
824Floyd's triangle
10javascript
xzyw9
def fivenum(array) sorted_arr = array.sort n = array.size n4 = (((n + 3).to_f / 2.to_f) / 2.to_f).floor d = Array.[](1, n4, ((n.to_f + 1) / 2).to_i, n + 1 - n4, n) sum_array = [] (0..4).each do |e| index_floor = (d[e] - 1).floor index_ceil = (d[e] - 1).ceil sum_array.push(0.5 * (sorted_arr[ind...
825Fivenum
14ruby
0y9su
class Intersection { private static class Point { double x, y Point(double x, double y) { this.x = x this.y = y } @Override String toString() { return "($x, $y)" } } private static class Line { Point s, e ...
831Find the intersection of two lines
7groovy
pisbo
public class LinePlaneIntersection { private static class Vector3D { private double x, y, z; Vector3D(double x, double y, double z) { this.x = x; this.y = y; this.z = z; } Vector3D plus(Vector3D v) { return new Vector3D(x + v.x, y + v...
832Find the intersection of a line with a plane
9java
q3nxa
DIGITS = 2.upto(16) do |n| start = Integer.sqrt( DIGITS[0,n].to_i(n) ) res = start.step.detect{|i| (i*i).digits(n).uniq.size == n } puts % [n, res.to_s(n), (res*res).to_s(n)] end
828First perfect square in base n with n unique digits
14ruby
s63qw
def floyd_warshall(n, edge) dist = Array.new(n){|i| Array.new(n){|j| i==j? 0: Float::INFINITY}} nxt = Array.new(n){Array.new(n)} edge.each do |u,v,w| dist[u-1][v-1] = w nxt[u-1][v-1] = v-1 end n.times do |k| n.times do |i| n.times do |j| if dist[i][j] > dist[i][k] + dist[k][j] ...
817Floyd-Warshall algorithm
14ruby
bomkq
#[derive(Debug)] struct FiveNum { minimum: f64, lower_quartile: f64, median: f64, upper_quartile: f64, maximum: f64, } fn median(samples: &[f64]) -> f64 {
825Fivenum
15rust
8mc07
(use 'clojure.math.combinatorics) (use 'clojure.set) (def given (apply hash-set (partition 4 5 "ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB" ))) (def s1 (apply hash-set (permutations "ABCD"))) (def missing (difference s1 given))
834Find the missing permutation
6clojure
4ej5o
type Line = (Point, Point) type Point = (Float, Float) intersection :: Line -> Line -> Either String Point intersection ab pq = case determinant of 0 -> Left "(Parallel lines no intersection)" _ -> let [abD, pqD] = (\(a, b) -> diff ([fst, snd] <*> [a, b])) <$> [ab, pq] [ix, iy] = ...
831Find the intersection of two lines
8haskell
yru66
fun main(args: Array<String>) = args.forEach { Triangle(it.toInt()) } internal class Triangle(n: Int) { init { println("$n rows:") var printMe = 1 var printed = 0 var row = 1 while (row <= n) { val cols = Math.ceil(Math.log10(n * (n - 1) / 2 + printed + 2.0)).toI...
824Floyd's triangle
11kotlin
7q8r4
pub type Edge = (usize, usize); #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct Graph<T> { size: usize, edges: Vec<Option<T>>, } impl<T> Graph<T> { pub fn new(size: usize) -> Self { Self { size, edges: std::iter::repeat_with(|| None).take(size * size).collect(), ...
817Floyd-Warshall algorithm
15rust
pi9bu
import java.util object Fivenum extends App { val xl = Array( Array(15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0), Array(36.0, 40.0, 7.0, 39.0, 41.0, 15.0), Array(0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.725...
825Fivenum
16scala
nlvic
public class Intersection { private static class Point { double x, y; Point(double x, double y) { this.x = x; this.y = y; } @Override public String toString() { return String.format("{%f,%f}", x, y); } } private static cl...
831Find the intersection of two lines
9java
d2mn9
null
832Find the intersection of a line with a plane
11kotlin
1nspd
package main import "math" import "fmt"
829First-class functions
0go
ch79g
WITH RECURSIVE T0 (N, ITEM, LIST, NEW_LIST) AS ( SELECT 1, NULL, '90,47,58,29,22,32,55,5,55,73' || ',', NULL UNION ALL SELECT CASE WHEN SUBSTR(LIST, INSTR(LIST, ',') + 1, LENGTH(LIST)) = '' THEN N + 1 ELSE N END, ...
815Forward difference
19sql
bocks
typealias FourBit = (Int, Int, Int, Int) func halfAdder(_ a: Int, _ b: Int) -> (Int, Int) { return (a ^ b, a & b) } func fullAdder(_ a: Int, _ b: Int, carry: Int) -> (Int, Int) { let (s0, c0) = halfAdder(a, b) let (s1, c1) = halfAdder(s0, carry) return (s1, c0 | c1) } func fourBitAdder(_ a: FourBit, _ b: Fo...
814Four bit adder
17swift
7qyrq
(() => { 'use strict';
831Find the intersection of two lines
10javascript
6gv38
function make(xval, yval, zval) return {x=xval, y=yval, z=zval} end function plus(lhs, rhs) return make(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z) end function minus(lhs, rhs) return make(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z) end function times(lhs, scale) return make(scale * lhs.x, scale * ...
832Find the intersection of a line with a plane
1lua
ad01v
def compose = { f, g -> { x -> f(g(x)) } }
829First-class functions
7groovy
34uzd
cube :: Floating a => a -> a cube x = x ** 3.0 croot :: Floating a => a -> a croot x = x ** (1/3) funclist :: Floating a => [a -> a] funclist = [sin, cos, cube ] invlist :: Floating a => [a -> a] invlist = [asin, acos, croot] main :: IO () main = print $ zipWith (\f i -> f . i $ 0.5) funclist invlist
829First-class functions
8haskell
pi8bt
use 5.10.0; my $w = `tput cols` - 1; my $h = `tput lines` - 1; my $r = "\033[H"; my ($green, $red, $yellow, $norm) = ("\033[32m", "\033[31m", "\033[33m", "\033[m"); my $tree_prob = .05; my $burn_prob = .0002; my @forest = map([ map((rand(1) < $tree_prob) ? 1 : 0, 1 .. $w) ], 1 .. $h); sub iterate { my @new = map(...
821Forest fire
2perl
k8thc
function print_floyd(rows) local c = 1 local h = rows*(rows-1)/2 for i=1,rows do local s = "" for j=1,i do for k=1, #tostring(h+j)-#tostring(c) do s = s .. " " end if j ~= 1 then s = s .. " " end s = s .. tostring(c) c = c + 1 end print(s) end end print_floyd(5) print_floyd(14)
824Floyd's triangle
1lua
jso71
func forwardsDifference<T: SignedNumeric>(of arr: [T]) -> [T] { return zip(arr.dropFirst(), arr).map({ $0.0 - $0.1 }) } func nthForwardsDifference<T: SignedNumeric>(of arr: [T], n: Int) -> [T] { assert(n >= 0) switch (arr, n) { case ([], _): return [] case let (arr, 0): return arr case let (arr, i...
815Forward difference
17swift
5afu8
null
831Find the intersection of two lines
11kotlin
0ytsf
package main import ( "fmt" "time" ) func main() { var n int
830Five weekends
0go
wtneg
import java.util.ArrayList; public class FirstClass{ public interface Function<A,B>{ B apply(A x); } public static <A,B,C> Function<A, C> compose( final Function<B, C> f, final Function<A, B> g) { return new Function<A, C>() { @Override public C apply(A x) { return f.apply(g.apply(x)); } }; } ...
829First-class functions
9java
rxeg0
<?php define('WIDTH', 10); define('HEIGHT', 10); define('GEN_CNT', 10); define('PAUSE', 250000); define('TREE_PROB', 50); define('GROW_PROB', 5); define('FIRE_PROB', 1); define('BARE', ' '); define('TREE', 'A'); define('BURN', '/'); $forest = makeNewForest(); for ($i = 0; $i < GE...
821Forest fire
12php
34kzq
function intersection (s1, e1, s2, e2) local d = (s1.x - e1.x) * (s2.y - e2.y) - (s1.y - e1.y) * (s2.x - e2.x) local a = s1.x * e1.y - s1.y * e1.x local b = s2.x * e2.y - s2.y * e2.x local x = (a * (s2.x - e2.x) - (s1.x - e1.x) * b) / d local y = (a * (s2.y - e2.y) - (s1.y - e1.y) * b) / d return x, y end ...
831Find the intersection of two lines
1lua
8mz0e
package Line; sub new { my ($c, $a) = @_; my $self = { P0 => $a->{P0}, u => $a->{u} } } package Plane; sub new { my ($c, $a) = @_; my $self = { V0 => $a->{V0}, n => $a->{n} } } package main; sub dot { my $p; $p += $_[0][$_] * $_[1][$_] for 0..@{$_[0]}-1; $p } sub vd { my @v; $v[$_] = $_[0][$_] - $_[1][$_] for...
832Find the intersection of a line with a plane
2perl
m7uyz
enum Day { Sun, Mon, Tue, Wed, Thu, Fri, Sat static Day valueOf(Date d) { Day.valueOf(d.format('EEE')) } } def date = Date.&parse.curry('yyyy-M-dd') def isLongMonth = { firstDay -> (firstDay + 31).format('dd') == '01'} def fiveWeekends = { years -> years.collect { year -> (1..12).collect { month -...
830Five weekends
7groovy
bosky
null
829First-class functions
10javascript
bo0ki
null
829First-class functions
11kotlin
vpk21
import Data.List (intercalate) data DayOfWeek = Monday | Tuesday | Wednesday | Thursday | Friday | Saturday | Sunday deriving (Eq, Show) daysFrom1_1_1900 :: [DayOfWeek] daysFrom1_1_1900 = concat $ repeat [Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday] data Month = January | February | ...
830Five weekends
8haskell
6gu3k
''' Forest-Fire Cellular automation See: http: ''' L = 15 initial_trees = 0.55 p = 0.01 f = 0.001 try: raw_input except: raw_input = input import random tree, burning, space = 'TB.' hood = ((-1,-1), (-1,0), (-1,1), (0,-1), (0, 1), (1,-1), (1,0), (1,1)) def initialise(): gr...
821Forest fire
3python
bozkr
package main import "fmt" func list(s ...interface{}) []interface{} { return s } func main() { s := list(list(1), 2, list(list(3, 4), 5), list(list(list())), list(list(list(6))), 7, 8, list(), ) fmt.Println(s) fmt.Println(flatten(s)) } func...
827Flatten a list
0go
q33xz
package main import ( "fmt" "time" ) func main() { var year int var t time.Time var lastDay = [12]int { 31,29,31,30,31,30,31,31,30,31,30,31 } for { fmt.Print("Please select a year: ") _, err := fmt.Scanf("%d", &year) if err != nil { fmt.Println(err) continue } else { break } } fmt.Printl...
833Find the last Sunday of each month
0go
pixbg
from __future__ import print_function import numpy as np def LinePlaneCollision(planeNormal, planePoint, rayDirection, rayPoint, epsilon=1e-6): ndotu = planeNormal.dot(rayDirection) if abs(ndotu) < epsilon: raise RuntimeError() w = rayPoint - planePoint si = -planeNormal.dot(w) / ndotu Psi = w + si * rayDirec...
832Find the intersection of a line with a plane
3python
9j5mf
assert [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []].flatten() == [1, 2, 3, 4, 5, 6, 7, 8]
827Flatten a list
7groovy
1nnp6
enum Day { Sun, Mon, Tue, Wed, Thu, Fri, Sat static Day valueOf(Date d) { Day.valueOf(d.format('EEE')) } } def date = Date.&parse.curry('yyyy-MM-dd') def month = { it.format('MM') } def days = { year -> (date("${year}-01-01")..<date("${year+1}-01-01")) } def weekDays = { dayOfWeek, year -> days(year).findAll {...
833Find the last Sunday of each month
7groovy
7qprz
sub intersect { my ($x1, $y1, $x2, $y2, $x3, $y3, $x4, $y4) = @_; my $a1 = $y2 - $y1; my $b1 = $x1 - $x2; my $c1 = $a1 * $x1 + $b1 * $y1; my $a2 = $y4 - $y3; my $b2 = $x3 - $x4; my $c2 = $a2 * $x3 + $b2 * $y3; my $delta = $a1 * $b2 - $a2 * $b1; return (undef, undef) if $delta == 0; my $ix = ($b2 ...
831Find the intersection of two lines
2perl
5aku2
intersect_point <- function(ray_vec, ray_point, plane_normal, plane_point) { pdiff <- ray_point - plane_point prod1 <- pdiff%*% plane_normal prod2 <- ray_vec%*% plane_normal prod3 <- prod1 / prod2 point <- ray_point - ray_vec * as.numeric(prod3) return(point) }
832Find the intersection of a line with a plane
13r
34lzt
function compose(f,g) return function(...) return f(g(...)) end end fn = {math.sin, math.cos, function(x) return x^3 end} inv = {math.asin, math.acos, function(x) return x^(1/3) end} for i, v in ipairs(fn) do local f = compose(v, inv[i]) print(f(0.5)) end
829First-class functions
1lua
u1bvl
import Data.Tree (Tree(..), flatten) list :: Tree [Int] list = Node [] [ Node [] [Node [1] []] , Node [2] [] , Node [] [Node [] [Node [3] [], Node [4] []], Node [5] []] , Node [] [Node [] [Node [] []]] , Node [] [Node [] [Node [6] []]] , Node [7] [] , Node [8] [] , Node [] []...
827Flatten a list
8haskell
m77yf
import Data.List (find, intercalate, transpose) import Data.Maybe (fromJust) import Data.Time.Calendar ( Day, addDays, fromGregorian, gregorianMonthLength, showGregorian, ) import Data.Time.Calendar.WeekDate (toWeekDate) lastSundayOfEachMonth = lastWeekDayDates 7 main :: IO () main = mapM_ ...
833Find the last Sunday of each month
8haskell
fvyd1
import java.util.Calendar; import java.util.GregorianCalendar; public class FiveFSS { private static boolean[] years = new boolean[201]; private static int[] month31 = {Calendar.JANUARY, Calendar.MARCH, Calendar.MAY, Calendar.JULY, Calendar.AUGUST, Calendar.OCTOBER, Calendar.DECEMBER}; public stat...
830Five weekends
9java
nlmih
use strict; use warnings; sub displayFloydTriangle { my $numRows = shift; print "\ndisplaying a $numRows row Floyd's triangle:\n\n"; my $maxVal = int($numRows * ($numRows + 1) / 2); my $digit = 0; foreach my $row (1 .. $numRows) { my $col = 0; my $output = ''; foreach (1 .. $row) { ++$digi...
824Floyd's triangle
2perl
fv4d7
function startsOnFriday(month, year) {
830Five weekends
10javascript
34vz0
def line_intersect(Ax1, Ay1, Ax2, Ay2, Bx1, By1, Bx2, By2): d = (By2 - By1) * (Ax2 - Ax1) - (Bx2 - Bx1) * (Ay2 - Ay1) if d: uA = ((Bx2 - Bx1) * (Ay1 - By1) - (By2 - By1) * (Ax1 - Bx1)) / d uB = ((Ax2 - Ax1) * (Ay1 - By1) - (Ay2 - Ay1) * (Ax1 - Bx1)) / d else: return if not(0...
831Find the intersection of two lines
3python
4eb5k
require def intersectPoint(rayVector, rayPoint, planeNormal, planePoint) diff = rayPoint - planePoint prod1 = diff.dot planeNormal prod2 = rayVector.dot planeNormal prod3 = prod1 / prod2 return rayPoint - rayVector * prod3 end def main rv = Vector[0.0, -1.0, -1.0] rp = Vector[0.0, 0.0, 10...
832Find the intersection of a line with a plane
14ruby
lkgcl
class Forest_Fire Neighborhood = [-1,0,1].product([-1,0,1]) - [0,0] States = {empty:, tree:, fire:} def initialize(xsize, ysize=xsize, p=0.5, f=0.01) @xsize, @ysize, @p, @f = xsize, ysize, p, f @field = Array.new(xsize+1) {|i| Array.new(ysize+1, :empty)} @generation = 0 end def evolve @gener...
821Forest fire
14ruby
1n6pw
<?php floyds_triangle(5); floyds_triangle(14); function floyds_triangle($n) { echo . $n . ; for($r = 1, $i = 1, $c = 0; $r <= $n; $i++) { $cols = ceil(log10($n*($n-1)/2 + $c + 2)); printf(.$cols., $i); if(++$c == $r) { echo ; $r++; $c = 0; }...
824Floyd's triangle
12php
h0ijf
package main import ( "fmt" "strings" ) var given = strings.Split(`ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB`, "\n") func main() { b := make([]byte, len(given[0])) for i := range b { m := make(map[byte]int) for _...
834Find the missing permutation
0go
xz8wf
import java.util.Scanner; public class LastSunday { static final String[] months={"January","February","March","April","May","June","July","August","September","October","November","December"}; public static int[] findLastSunday(int year) { boolean isLeap = isLeapYear(year); int[] days={31,isLeap?29:28,31,30...
833Find the last Sunday of each month
9java
0ydse
use std::ops::{Add, Div, Mul, Sub}; #[derive(Copy, Clone, Debug, PartialEq)] struct V3<T> { x: T, y: T, z: T, } impl<T> V3<T> { fn new(x: T, y: T, z: T) -> Self { V3 { x, y, z } } } fn zip_with<F, T, U>(f: F, a: V3<T>, b: V3<T>) -> V3<U> where F: Fn(T, T) -> U, { V3 { x: f...
832Find the intersection of a line with a plane
15rust
2brlt