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++) { w = (w + days[m]) % 7; printf(, y, m + 1,days[m] - w); } return 0; }
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 n = n - 1 end end return test end def runTest(l, n) print % [l, n, p(l, n)] end runTest(12, 1) runTest(12, 2) runTest(123, 45) runTest(123, 12345) runTest(123, 678910)
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 = 0; $j < 10; ++$j) { if ($graph[$i][$j] > $graph[$i][$k] + $graph[$k][$j]) $graph[$i][$j] = $graph[$i][$k] + $graph[$k][$j]; } } } print_r($graph); ?>
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, -32] >>> from pprint import pprint >>> pprint( [difn(s, i) for i in xrange(10)] ) [[90, 47, 58, 29, 22, 32, 55, 5, 55, 73], [-43, 11, -29, -7, 10, 23, -50, 50, 18], [54, -40, 22, 17, 13, -73, 100, -32], [-94, 62, -5, -4, -86, 173, -132], [156, -67, 1, -82, 259, -305], [-223, 68, -83, 341, -564], [291, -151, 424, -905], [-442, 575, -1329], [1017, -1904], [-2921]]
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 = floor($d[$e]-1); my $ceil = ceil($d[$e]-1); push @sum_array, (0.5 * ($x[$floor] + $x[$ceil])); } return @sum_array; } my @x = (15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43); my @tukey = fivenum(\@x); say join (',', @tukey); @x = (36, 40, 7, 39, 41, 15), @tukey = fivenum(\@x); say join (',', @tukey); @x = (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); @tukey = fivenum(\@x); say join (',', @tukey);
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) (:offset line1))}))
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[32m'; const CONSOLE_COLOR_CLOSE = '\x1b[91m'; const CONSOLE_CLEAR = '\u001B[2J\u001B[0;0f'; const NEIGHBOURS = [ [-1, -1], [-1, 0], [-1, 1], [ 0, -1], [ 0, 1], [ 1, -1], [ 1, 0], [ 1, 1] ]; const PRINT_DECODE = { ' ': ' ', 'T': `${CONSOLE_GREEN}T${CONSOLE_COLOR_CLOSE}`, 'B': `${CONSOLE_RED}T${CONSOLE_COLOR_CLOSE}`, }; const CONDITIONS = { 'T': (forest, y, x) => Math.random() < BURN_PROBABILITY || burningNeighbour(forest, y, x) ? 'B' : 'T', ' ': () => Math.random() < NEW_TREE_PROBABILITY ? 'T' : ' ', 'B': () => ' ' }; const WIDTH = process.argv[WIDTH_ARGUMENT_POSITION] || 20; const HEIGHT = process.argv[HEIGHT_ARGUMENT_POSITION] || 10; const update = forest => { return _.map(forest, (c, ci) => { return _.map(c, (r, ri) => { return CONDITIONS[r](forest, ci, ri); }); }); } const printForest = forest => { process.stdout.write(CONSOLE_CLEAR); _.each(forest, c => { _.each(c, r => { process.stdout.write(PRINT_DECODE[r]); }); process.stdout.write('\n'); }) } const burningNeighbour = (forest, y, x) => { return _(NEIGHBOURS) .map(n => _.isUndefined(forest[y + n[0]]) ? null : forest[y + n[0]][x + n[1]]) .any(_.partial(_.isEqual, 'B')); }; let forest = _.times(HEIGHT, () => _.times(WIDTH, () => Math.random() < TREE_PROBABILITY ? 'T' : ' ')); setInterval(() => { forest = update(forest); printForest(forest) }, 20);
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; let val: isize = (factor as f64 * 10.0_f64.powf(test as f64 * log% 1.0)) as isize; if val == l { nn = nn - 1; } } test } fn run_test(l: isize, n: isize) { println!("p({}, {}) = {}", l, n, power_of_two(l, n)); } fn main() { run_test(12, 1); run_test(12, 2); run_test(123, 45); run_test(123, 12345); run_test(123, 678910); }
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 * log % 1)).asInstanceOf[Int] if (value == l) { n2 -= 1 } } test } def runTest(l: Int, n: Int): Unit = { printf("p(%d,%d) =%,d%n", l, n, p(l, n)) } def main(args: Array[String]): Unit = { runTest(12, 1) runTest(12, 2) runTest(123, 45) runTest(123, 12345) runTest(123, 678910) } }
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 < lastInRow { fmt.Printf("%*d ", w, i) lastInColumn++ } else { fmt.Printf("%*d\n", w, i) row++ lastInRow += row lastInColumn = lowerLeftCorner } } }
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(v, 9)) print(fdiff(v, 9))
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) { my $sq = $r * $r; my $cnt = 0; my $s = todigitstring($sq, $n); my $i = scalar @digits; for (@digits) { $r++ and redo TRY if (-1 == index($s, $_)) || ($i-- + $cnt < $n); last if $cnt++ == $n; } return sprintf "Base%2d:%10s ==%s", $n, todigitstring($r, $n), todigitstring($sq, $n); } } say "First perfect square with N unique digits in base N: "; say first_square($_) for 2..16;
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) end def play moves = 0 puts , target until solved? puts , , self print ans = $stdin.gets.strip if @columns.include? ans flip_column @columns.index(ans) moves += 1 elsif @rows.include? ans flip_row @rows.index(ans) moves += 1 else puts + ans end end puts , , self end def target format_array @target end def to_s format_array @board end private def solved? @board == @target end def randomize_board (@size + rand(@size)).times do flip_bit rand(@size), rand(@size) end end def generate_target orig_board = @board.clone (@size + rand(@size)).times do rand(2).zero?? flip_row( rand(@size) ): flip_column( rand(@size) ) end target, @board = @board, orig_board target end def flip_row(row) @size.times {|col| flip_bit(row, col)} end def flip_column(col) @size.times {|row| flip_bit(row, col)} end def flip_bit(row, col) @board[@size * row + col] ^= 1 end def format_array(ary) str = + @columns.join() + @size.times do |row| str << % @rows[row] + ary[@size*row, @size].join() + end str end end begin FlipBoard.new(ARGV.shift.to_i).play rescue => e puts e.message end
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)| multiplier(*x,*y)(0.5)) .collect::<Vec<_>>(); println!("{:?}", result); } fn multiplier(x: f64, y: f64) -> impl Fn(f64) -> f64 { move |m| x*y*m }
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) private def executeFrom(label: Label): Unit = { val nextLabel = try { label.k(label) None } catch { case g: GotoThunk => Some(g.label) } if (nextLabel.isDefined) executeFrom(nextLabel.get) } }
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 = (int) Math.ceil(Math.log10(n * (n - 1) / 2 + numsPrinted + 2)) printf("%" + cols + "d ", printMe) if (++numsPrinted == rowNum) { println() rowNum++ numsPrinted = 0 } } } }
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, repeat=3): sum_ik_kj = dist[i][k] + dist[k][j] if dist[i][j] > sum_ik_kj: dist[i][j] = sum_ik_kj nxt[i][j] = nxt[i][k] print() for i, j in product(rn, repeat=2): if i != j: path = [i] while path[-1] != j: path.append(nxt[path[-1]][j]) print( % (i + 1, j + 1, dist[i][j], ' '.join(str(p + 1) for p in path))) if __name__ == '__main__': floyd_warshall(4, [[1, 3, -2], [2, 1, 4], [2, 3, 3], [3, 4, 2], [4, 2, -1]])
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([s0, s1, s2, s3]), c3.to_s] end def full_adder(a, b, c0) s, c = half_adder(c0, a) s, c1 = half_adder(s, b) [s, _or(c,c1)] end def half_adder(a, b) [xor(a, b), _and(a,b)] end def xor(a, b) _or(_and(a, _not(b)), _and(_not(a), b)) end def _and(a, b) a & b end def _or(a, b) a | b end def _not(a) ~a & 1 end def int_to_binary_string(n, length) % n end def binary_string_to_bits(s, length) ( % s).reverse.chars.map(&:to_i) end def bits_to_binary_string(bits) bits.map(&:to_s).reverse.join end puts 0.upto(15) do |a| 0.upto(15) do |b| bin_a = int_to_binary_string(a, 4) bin_b = int_to_binary_string(b, 4) sum, carry = four_bit_adder(bin_a, bin_b) puts % [a, b, bin_a, bin_b, carry, sum, (carry + sum).to_i(2)] end end
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] - 1)) ceil = int(math.ceil(d[e] - 1)) sum_array.append(0.5 * (x[floor] + x[ceil])) return sum_array x = [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] y = fivenum(x) print(y)
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-while #(= (time/year %) year) (filter sunday? (periodic-seq (time/date-time year 1 1) (time/days 1))))) (defn last-sundays-of-months [year] (->> (sundays year) (group-by time/month) (vals) (map (comp first #(sort-by time/day > %))) (map #(fmt/unparse (fmt/formatters:year-month-day) %)) (interpose "\n") (apply str))) (defn -main [& args] (println (last-sundays-of-months (Integer. (first args)))))
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(digits)) == L { count += 1 } i += 1 } return i - 1 } let cases = [ (12, 1), (12, 2), (123, 45), (123, 12345), (123, 678910) ] for (l, n) in cases { print("p(\(l), \(n)) = \(p(L: l, n: n))") }
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.0, 4.0, 6.0) scala> val inverses = List(xi, yi, zi) inverses: List[Double] = List(0.5, 0.25, 0.16666666666666666) scala> def multiplier = (n1: Double, n2: Double) => (m: Double) => n1 * n2 * m multiplier: (Double, Double) => (Double) => Double scala> def comp = numbers zip inverses map multiplier.tupled comp: List[(Double) => Double] scala> comp.foreach(f=>println(f(0.5))) 0.5 0.5 0.5
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 = take n floydTriangle ws = length . show <$> last t alignR :: Int -> Int -> String alignR n = ( (<>) =<< flip replicate ' ' . (-) n . length ) . show
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) *Vector3D { return &Vector3D{s * v.x, s * v.y, s * v.z} } func (v *Vector3D) Dot(w *Vector3D) float64 { return v.x*w.x + v.y*w.y + v.z*w.z } func (v *Vector3D) String() string { return fmt.Sprintf("(%v,%v,%v)", v.x, v.y, v.z) } func intersectPoint(rayVector, rayPoint, planeNormal, planePoint *Vector3D) *Vector3D { diff := rayPoint.Sub(planePoint) prod1 := diff.Dot(planeNormal) prod2 := rayVector.Dot(planeNormal) prod3 := prod1 / prod2 return rayPoint.Sub(rayVector.Mul(prod3)) } func main() { rv := &Vector3D{0.0, -1.0, -1.0} rp := &Vector3D{0.0, 0.0, 10.0} pn := &Vector3D{0.0, 0.0, 1.0} pp := &Vector3D{0.0, 0.0, 5.0} ip := intersectPoint(rv, rp, pn, pp) fmt.Println("The ray intersects the plane at", ip) }
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'); print('Year with none: $empty'); }
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)) return next( dropwhile( missingDigitsAtBase(base, bools), count( max( above, ceil(sqrt(int( '10' + '0123456789abcdef'[2:base], base ))) ) ) ) ) def missingDigitsAtBase(base, bools): '''Fusion of representing the square of integer N at a given base with checking whether all digits of that base contribute to N^2. Clears the bool at a digit position to False when used. True if any positions remain uncleared (unused). ''' def go(x): xs = bools.copy() while x: xs[x% base] = False x return any(xs) return lambda n: go(n * n) def digit(n): '''Digit character for given integer.''' return '0123456789abcdef'[n] def main(): '''Smallest perfect squares using all digits in bases 2-16''' start = time() print(main.__doc__ + ':\n\nBase Root Square') q = 0 for b in enumFromTo(2)(16): q = allDigitSquare(b, q) print( str(b).rjust(2, ' ') + ' -> ' + showIntAtBase(b)(digit)(q)('').rjust(8, ' ') + ' -> ' + showIntAtBase(b)(digit)(q * q)('') ) print( '\nc. ' + str(ceil(time() - start)) + ' seconds.' ) def enumFromTo(m): '''Integer enumeration from m to n.''' return lambda n: list(range(m, 1 + n)) def showIntAtBase(base): '''String representation of an integer in a given base, using a supplied function for the string representation of digits. ''' def wrap(toChr, n, rs): def go(nd, r): n, d = nd r_ = toChr(d) + r return go(divmod(n, base), r_) if 0 != n else r_ return 'unsupported base' if 1 >= base else ( 'negative number' if 0 > n else ( go(divmod(n, base), rs)) ) return lambda toChr: lambda n: lambda rs: ( wrap(toChr, n, rs) ) if __name__ == '__main__': main()
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 val box: Rectangle = new Rectangle(120, 90, 400, 400) private var n: Int = maxLevel private var grid: Array[Array[Boolean]] = _ private var target: Array[Array[Boolean]] = _ private var solved: Boolean = true override def paintComponent(gg: Graphics): Unit = { def drawGrid(g: Graphics2D): Unit = { if (solved) g.drawString("Solved! Click here to play again.", 180, 600) else g.drawString("Click next to a row or a column to flip.", 170, 600) val size: Int = box.width / n for {r <- 0 until n c <- 0 until n} { g.setColor(if (grid(r)(c)) Color.blue else Color.orange) g.fillRect(box.x + c * size, box.y + r * size, size, size) g.setColor(getBackground) g.drawRect(box.x + c * size, box.y + r * size, size, size) g.setColor(if (target(r)(c)) Color.blue else Color.orange) g.fillRect(7 + box.x + c * size, 7 + box.y + r * size, 10, 10) } } super.paintComponent(gg) val g: Graphics2D = gg.asInstanceOf[Graphics2D] g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) drawGrid(g) } private def printGrid(msg: String, g: Array[Array[Boolean]]): Unit = { println(msg) for (row <- g) println(row.mkString(", ")) println() } private def startNewGame(): Unit = { val rand = scala.util.Random if (solved) { val minLevel: Int = 3 n = if (n == maxLevel) minLevel else n + 1 grid = Array.ofDim[Boolean](n, n) target = Array.ofDim[Boolean](n, n) do { def shuffle(): Unit = for (i <- 0 until n * n) if (rand.nextBoolean()) flipRow(rand.nextInt(n)) else flipCol(rand.nextInt(n)) shuffle() for (i <- grid.indices) grid(i).copyToArray(target(i))
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']++; for (j = 0; j < N && cnt[j] == n; j++); miss[i] = j + 'A'; } printf(, N, miss); return 0; }
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) } Vector3D minus(Vector3D v) { return new Vector3D(x - v.x, y - v.y, z - v.z) } Vector3D multiply(double s) { return new Vector3D(s * x, s * y, s * z) } double dot(Vector3D v) { return x * v.x + y * v.y + z * v.z } @Override String toString() { return "($x, $y, $z)" } } private static Vector3D intersectPoint(Vector3D rayVector, Vector3D rayPoint, Vector3D planeNormal, Vector3D planePoint) { Vector3D diff = rayPoint - planePoint double prod1 = diff.dot(planeNormal) double prod2 = rayVector.dot(planeNormal) double prod3 = prod1 / prod2 return rayPoint - rayVector * prod3 } static void main(String[] args) { Vector3D rv = new Vector3D(0.0, -1.0, -1.0) Vector3D rp = new Vector3D(0.0, 0.0, 10.0) Vector3D pn = new Vector3D(0.0, 0.0, 1.0) Vector3D pp = new Vector3D(0.0, 0.0, 5.0) Vector3D ip = intersectPoint(rv, rp, pn, pp) println("The ray intersects the plane at $ip") } }
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 * size + x] } set { tiles[y * size + x] = newValue } } mutating func randomize() { for i in 0..<tiles.count { tiles[i] = Bool(random()% 2) } } mutating func flipRow(row: Int) { for i in 0..<size { self[row, i] =!self[row, i] } } mutating func flipColumn(column: Int) { for i in 0..<size { self[i, column] =!self[i, column] } } var description: String { var desc = "\n\ta\tb\tc\n" for i in 0..<size { desc += "\(i+1):\t" for j in 0..<size { desc += "\(Int(self[i, j]))\t" } desc += "\n" } return desc } } func ==(lhs: Board, rhs: Board) -> Bool { return lhs.tiles == rhs.tiles } class FlippingGame: CustomStringConvertible { var board: Board var target: Board var solved: Bool { return board == target } init(boardSize: Int) { target = Board(size: 3) board = Board(size: 3) generateTarget() } func generateTarget() { target.randomize() board = target let size = board.size while solved { for _ in 0..<size + (random()% size + 1) { if random()% 2 == 0 { board.flipColumn(random()% size) } else { board.flipRow(random()% size) } } } } func getMove() -> Bool { print(self) print("Flip what? ", terminator: "") guard let move = readLine(stripNewline: true) where move.characters.count == 1 else { return false } var moveValid = true if let row = Int(move) { board.flipRow(row - 1) } else if let column = move.lowercaseString.utf8.first where column < 100 && column > 96 { board.flipColumn(numericCast(column) - 97) } else { moveValid = false } return moveValid } var description: String { var str = "" print("Target: \n \(target)", toStream: &str) print("Board: \n \(board)", toStream: &str) return str } } func playGame(game: FlippingGame) -> String { game.generateTarget() var numMoves = 0 while!game.solved { numMoves++ print("Move #\(numMoves)") while!game.getMove() {} } print("You win!") print("Number of moves: \(numMoves)") print("\n\nPlay Again? ", terminator: "") return readLine(stripNewline: true)!.lowercaseString } let game = FlippingGame(boardSize: 3) repeat { } while playGame(game) == "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 + numsPrinted + 2)); System.out.printf("%"+cols+"d ", printMe); if(++numsPrinted == rowNum){ System.out.println(); rowNum++; numsPrinted = 0; } } } }
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) val (s, c2)=halfAdder(s1, b) val cOut=c1 || c2 (s, cOut) } def fourBitAdder(a:Nibble, b:Nibble)={ val (s0, c0)=fullAdder(a._4, b._4, false) val (s1, c1)=fullAdder(a._3, b._3, c0) val (s2, c2)=fullAdder(a._2, b._2, c1) val (s3, cOut)=fullAdder(a._1, b._1, c2) ((s3, s2, s1, s0), cOut) } }
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 + l.yint } func Intersection (l1, l2 Line) (Point, error) { if l1.slope == l2.slope { return Point{}, errors.New("The lines do not intersect") } x := (l2.yint-l1.yint) / (l1.slope-l2.slope) y := EvalX(l1, x) return Point{x, y}, nil } func main() { l1 := CreateLine(Point{4, 0}, Point{6, 10}) l2 := CreateLine(Point{0, 3}, Point{10, 7}) if result, err := Intersection(l1, l2); err == nil { fmt.Println(result) } else { fmt.Println("The lines do not intersect") } }
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 (+) = liftA2 (+) (-) = liftA2 (-) (*) = liftA2 (*) negate = fmap negate abs = fmap abs signum = fmap signum fromInteger = pure . fromInteger dot ::Num a => V3 a -> V3 a -> a dot a b = x + y + z where V3 x y z = a * b intersect :: Fractional a => V3 a -> V3 a -> V3 a -> V3 a -> V3 a intersect rayVector rayPoint planeNormal planePoint = rayPoint - rayVector * pure prod3 where diff = rayPoint - planePoint prod1 = diff `dot` planeNormal prod2 = rayVector `dot` planeNormal prod3 = prod1 / prod2 main = printf "The ray intersects the plane at (%f,%f,%f)\n" x y z where V3 x y z = intersect rv rp pn pp :: V3 Double rv = V3 0 (-1) (-1) rp = V3 0 0 10 pn = V3 0 0 1 pp = V3 0 0 5
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[index_floor] + sorted_arr[index_ceil])) end sum_array end test_array = [15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43] tukey_array = fivenum(test_array) p tukey_array test_array = [36, 40, 7, 39, 41, 15] tukey_array = fivenum(test_array) p tukey_array test_array = [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] tukey_array = fivenum(test_array) p tukey_array
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 Line(Point s, Point e) { this.s = s this.e = e } } private static Point findIntersection(Line l1, Line l2) { double a1 = l1.e.y - l1.s.y double b1 = l1.s.x - l1.e.x double c1 = a1 * l1.s.x + b1 * l1.s.y double a2 = l2.e.y - l2.s.y double b2 = l2.s.x - l2.e.x double c2 = a2 * l2.s.x + b2 * l2.s.y double delta = a1 * b2 - a2 * b1 return new Point((b2 * c1 - b1 * c2) / delta, (a1 * c2 - a2 * c1) / delta) } static void main(String[] args) { Line l1 = new Line(new Point(4, 0), new Point(6, 10)) Line l2 = new Line(new Point(0, 3), new Point(10, 7)) println(findIntersection(l1, l2)) l1 = new Line(new Point(0, 0), new Point(1, 1)) l2 = new Line(new Point(1, 2), new Point(4, 5)) println(findIntersection(l1, l2)) } }
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.y, z + v.z); } Vector3D minus(Vector3D v) { return new Vector3D(x - v.x, y - v.y, z - v.z); } Vector3D times(double s) { return new Vector3D(s * x, s * y, s * z); } double dot(Vector3D v) { return x * v.x + y * v.y + z * v.z; } @Override public String toString() { return String.format("(%f,%f,%f)", x, y, z); } } private static Vector3D intersectPoint(Vector3D rayVector, Vector3D rayPoint, Vector3D planeNormal, Vector3D planePoint) { Vector3D diff = rayPoint.minus(planePoint); double prod1 = diff.dot(planeNormal); double prod2 = rayVector.dot(planeNormal); double prod3 = prod1 / prod2; return rayPoint.minus(rayVector.times(prod3)); } public static void main(String[] args) { Vector3D rv = new Vector3D(0.0, -1.0, -1.0); Vector3D rp = new Vector3D(0.0, 0.0, 10.0); Vector3D pn = new Vector3D(0.0, 0.0, 1.0); Vector3D pp = new Vector3D(0.0, 0.0, 5.0); Vector3D ip = intersectPoint(rv, rp, pn, pp); System.out.println("The ray intersects the plane at " + ip); } }
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] dist[i][j] = dist[i][k] + dist[k][j] nxt[i][j] = nxt[i][k] end end end end puts n.times do |i| n.times do |j| next if i==j u = i path = [u] path << (u = nxt[u][j]) while u!= j path = path.map{|u| u+1}.join() puts % [i+1, j+1, dist[i][j], path] end end end n = 4 edge = [[1, 3, -2], [2, 1, 4], [2, 3, 3], [3, 4, 2], [4, 2, -1]] floyd_warshall(n, edge)
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] = [\(ab, pq) -> diff [abD, ab, pqD, pq] / determinant] <*> [(abDX, pqDX), (abDY, pqDY)] in Right (ix, iy) where delta f x = f (fst x) - f (snd x) diff [a, b, c, d] = a * d - b * c [abDX, pqDX, abDY, pqDY] = [delta fst, delta snd] <*> [ab, pq] determinant = diff [abDX, abDY, pqDX, pqDY] ab :: Line ab = ((4.0, 0.0), (6.0, 10.0)) pq :: Line pq = ((0.0, 3.0), (10.0, 7.0)) interSection :: Either String Point interSection = intersection ab pq main :: IO () main = putStrLn $ case interSection of Left x -> x Right x -> show x
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)).toInt() print("%${cols}d ".format(printMe)) if (++printed == row) { println(); row++; printed = 0 } printMe++ } } }
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(), } } pub fn new_with(size: usize, f: impl FnMut(Edge) -> Option<T>) -> Self { let edges = (0..size) .flat_map(|i| (0..size).map(move |j| (i, j))) .map(f) .collect(); Self { size, edges } } pub fn with_diagonal(mut self, mut f: impl FnMut(usize) -> Option<T>) -> Self { self.edges .iter_mut() .step_by(self.size + 1) .enumerate() .for_each(move |(vertex, edge)| *edge = f(vertex)); self } pub fn size(&self) -> usize { self.size } pub fn edge(&self, edge: Edge) -> &Option<T> { let index = self.edge_index(edge); &self.edges[index] } pub fn edge_mut(&mut self, edge: Edge) -> &mut Option<T> { let index = self.edge_index(edge); &mut self.edges[index] } fn edge_index(&self, (row, col): Edge) -> usize { assert!(row < self.size && col < self.size); row * self.size() + col } } impl<T> std::ops::Index<Edge> for Graph<T> { type Output = Option<T>; fn index(&self, index: Edge) -> &Self::Output { self.edge(index) } } impl<T> std::ops::IndexMut<Edge> for Graph<T> { fn index_mut(&mut self, index: Edge) -> &mut Self::Output { self.edge_mut(index) } } #[derive(Clone, Debug, PartialEq, Eq)] pub struct Paths(Graph<usize>); impl Paths { pub fn new<T>(graph: &Graph<T>) -> Self { Self(Graph::new_with(graph.size(), |(i, j)| { graph[(i, j)].as_ref().map(|_| j) })) } pub fn vertices(&self, from: usize, to: usize) -> Path<'_> { assert!(from < self.0.size() && to < self.0.size()); Path { graph: &self.0, from: Some(from), to, } } fn update(&mut self, from: usize, to: usize, via: usize) { self.0[(from, to)] = self.0[(from, via)]; } } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Path<'a> { graph: &'a Graph<usize>, from: Option<usize>, to: usize, } impl<'a> Iterator for Path<'a> { type Item = usize; fn next(&mut self) -> Option<Self::Item> { self.from.map(|from| { let result = from; self.from = if result!= self.to { self.graph[(result, self.to)] } else { None }; result }) } } pub fn floyd_warshall<W>(mut result: Graph<W>) -> (Graph<W>, Option<Paths>) where W: Copy + std::ops::Add<W, Output = W> + std::cmp::Ord + Default, { let mut without_negative_cycles = true; let mut paths = Paths::new(&result); let n = result.size(); for k in 0..n { for i in 0..n { for j in 0..n {
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.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578) ) for (x <- xl) println(f"${util.Arrays.toString(fivenum(x))}%s\n\n") def fivenum(x: Array[Double]): Array[Double] = { require(x.forall(!_.isNaN), "Unable to deal with arrays containing NaN") def median(x: Array[Double], start: Int, endInclusive: Int): Double = { val size = endInclusive - start + 1 require(size > 0, "Array slice cannot be empty") val m = start + size / 2 if (size % 2 == 1) x(m) else (x(m - 1) + x(m)) / 2.0 } val result = new Array[Double](5) util.Arrays.sort(x) result(0) = x(0) result(2) = median(x, 0, x.length - 1) result(4) = x(x.length - 1) val m = x.length / 2 val lowerEnd = if (x.length % 2 == 1) m else m - 1 result(1) = median(x, 0, lowerEnd) result(3) = median(x, m, x.length - 1) result } }
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 class Line { Point s, e; Line(Point s, Point e) { this.s = s; this.e = e; } } private static Point findIntersection(Line l1, Line l2) { double a1 = l1.e.y - l1.s.y; double b1 = l1.s.x - l1.e.x; double c1 = a1 * l1.s.x + b1 * l1.s.y; double a2 = l2.e.y - l2.s.y; double b2 = l2.s.x - l2.e.x; double c2 = a2 * l2.s.x + b2 * l2.s.y; double delta = a1 * b2 - a2 * b1; return new Point((b2 * c1 - b1 * c2) / delta, (a1 * c2 - a2 * c1) / delta); } public static void main(String[] args) { Line l1 = new Line(new Point(4, 0), new Point(6, 10)); Line l2 = new Line(new Point(0, 3), new Point(10, 7)); System.out.println(findIntersection(l1, l2)); l1 = new Line(new Point(0, 0), new Point(1, 1)); l2 = new Line(new Point(1, 2), new Point(4, 5)); System.out.println(findIntersection(l1, l2)); } }
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, CASE WHEN SUBSTR(LIST, INSTR(LIST, ',') + 1, LENGTH(LIST)) <> '' THEN SUBSTR(LIST, 1, INSTR(LIST, ',') - 1) ELSE NULL END, CASE WHEN SUBSTR(LIST, INSTR(LIST, ',') + 1, LENGTH(LIST)) = '' THEN IFNULL(NEW_LIST || (SUBSTR(LIST, 1, INSTR(LIST, ',') - 1) - ITEM) || ',', '') ELSE SUBSTR(LIST, INSTR(LIST, ',') + 1, LENGTH(LIST)) END, CASE WHEN SUBSTR(LIST, INSTR(LIST, ',') + 1, LENGTH(LIST)) <> '' THEN IFNULL(NEW_LIST, '') || IFNULL((SUBSTR(LIST, 1, INSTR(LIST, ',') - 1) - ITEM) || ',', '') ELSE NULL END FROM T0 WHERE INSTR(LIST, ',') > 0 ) SELECT N, TRIM(LIST, ',') LIST FROM T0 WHERE NEW_LIST IS NULL AND LIST <> '' ORDER BY N;
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: FourBit) -> (FourBit, carry: Int) { let (sum1, carry1) = halfAdder(a.3, b.3) let (sum2, carry2) = fullAdder(a.2, b.2, carry: carry1) let (sum3, carry3) = fullAdder(a.1, b.1, carry: carry2) let (sum4, carryOut) = fullAdder(a.0, b.0, carry: carry3) return ((sum4, sum3, sum2, sum1), carryOut) } let a = (0, 1, 1, 0) let b = (0, 1, 1, 0) print("\(a) + \(b) = \(fourBitAdder(a, b))")
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 * lhs.y, scale * lhs.z) end function dot(lhs, rhs) return lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z end function tostr(val) return "(" .. val.x .. ", " .. val.y .. ", " .. val.z .. ")" end function intersectPoint(rayVector, rayPoint, planeNormal, planePoint) diff = minus(rayPoint, planePoint) prod1 = dot(diff, planeNormal) prod2 = dot(rayVector, planeNormal) prod3 = prod1 / prod2 return minus(rayPoint, times(rayVector, prod3)) end rv = make(0.0, -1.0, -1.0) rp = make(0.0, 0.0, 10.0) pn = make(0.0, 0.0, 1.0) pp = make(0.0, 0.0, 5.0) ip = intersectPoint(rv, rp, pn, pp) print("The ray intersects the plane at " .. tostr(ip))
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([ map(0, 1 .. $w) ], 1 .. $h); for my $i (0 .. $h - 1) { for my $j (0 .. $w - 1) { $new[$i][$j] = $forest[$i][$j]; if ($forest[$i][$j] == 2) { $new[$i][$j] = 3; next; } elsif ($forest[$i][$j] == 1) { if (rand() < $burn_prob) { $new[$i][$j] = 2; next; } for ( [-1, -1], [-1, 0], [-1, 1], [ 0, -1], [ 0, 1], [ 1, -1], [ 1, 0], [ 1, 1] ) { my $y = $_->[0] + $i; next if $y < 0 || $y >= $h; my $x = $_->[1] + $j; next if $x < 0 || $x >= $w; if ($forest[$y][$x] == 2) { $new[$i][$j] = 2; last; } } } elsif (rand() < $tree_prob) { $new[$i][$j] = 1; } elsif ($forest[$i][$j] == 3) { $new[$i][$j] = 0; } }} @forest = @new; } sub forest { print $r; for (@forest) { for (@$_) { when(0) { print " "; } when(1) { print "${green}*"} when(2) { print "${red}&" } when(3) { print "${yellow}&" } } print "\033[E\033[1G"; } iterate; } forest while (1);
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): return nthForwardsDifference(of: forwardsDifference(of: arr), n: i - 1) } } for diff in (0...9).map({ nthForwardsDifference(of: [90, 47, 58, 29, 22, 32, 55, 5, 55, 73], n: $0) }) { print(diff) }
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)); } }; } public static void main(String[] args){ ArrayList<Function<Double, Double>> functions = new ArrayList<Function<Double,Double>>(); functions.add( new Function<Double, Double>(){ @Override public Double apply(Double x){ return Math.cos(x); } }); functions.add( new Function<Double, Double>(){ @Override public Double apply(Double x){ return Math.tan(x); } }); functions.add( new Function<Double, Double>(){ @Override public Double apply(Double x){ return x * x; } }); ArrayList<Function<Double, Double>> inverse = new ArrayList<Function<Double,Double>>(); inverse.add( new Function<Double, Double>(){ @Override public Double apply(Double x){ return Math.acos(x); } }); inverse.add( new Function<Double, Double>(){ @Override public Double apply(Double x){ return Math.atan(x); } }); inverse.add( new Function<Double, Double>(){ @Override public Double apply(Double x){ return Math.sqrt(x); } }); System.out.println("Compositions:"); for(int i = 0; i < functions.size(); i++){ System.out.println(compose(functions.get(i), inverse.get(i)).apply(0.5)); } System.out.println("Hard-coded compositions:"); System.out.println(Math.cos(Math.acos(0.5))); System.out.println(Math.tan(Math.atan(0.5))); System.out.println(Math.pow(Math.sqrt(0.5), 2)); } }
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 < GEN_CNT; $i++) { displayForest($forest, $i); $forest = getNextForest($forest); } displayForest($forest, 'done'); exit; function makeNewForest() { return mapForest([ 'func' => function(){ return isProb(TREE_PROB)? TREE : BARE; } ]); } function displayForest($forest, $generationNum) { system(); echo PHP_EOL . . PHP_EOL; mapForest(['forest' => $forest, 'func' => function($f, $x, $y){ echo $f[$y][$x] . ($x == WIDTH - 1? PHP_EOL : ''); } ]); echo PHP_EOL; usleep(PAUSE); } function getNextForest($oldForest) { return mapForest(['forest' => $oldForest, 'func' => function($f, $x, $y){ switch ($f[$y][$x]) { case BURN: return BARE; case BARE: return isProb(GROW_PROB)? TREE : BARE; case TREE: $caughtFire = isProb(FIRE_PROB); $ablaze = $caughtFire? true : getNumBurningNeighbors($f, $x, $y) > 0; return $ablaze? BURN : TREE; } } ]); } function getNumBurningNeighbors($forest, $x, $y) { $burningNeighbors = mapForest([ 'forest' => $forest, 'x1' => $x - 1, 'x2' => $x + 2, 'y1' => $y - 1, 'y2' => $y + 2, 'default' => 0, 'func' => function($f, $x, $y){ return $f[$y][$x] == BURN? 1 : 0; } ]); $numOnFire = 0; foreach ($burningNeighbors as $row) { $numOnFire += array_sum($row); } return $numOnFire; } function mapForest($params) { $p = array_merge([ 'forest' => [], 'func' => function(){echo ;}, 'x1' => 0, 'x2' => WIDTH, 'y1' => 0, 'y2' => HEIGHT, 'default' => BARE ], $params); $newForest = []; for ($y = $p['y1']; $y < $p['y2']; $y++) { $newRow = []; for ($x = $p['x1']; $x < $p['x2']; $x++) { $inBounds = ($x >= 0 && $x < WIDTH && $y >= 0 && $y < HEIGHT); $newRow[] = ($inBounds? $p['func']($p['forest'], $x, $y) : $p['default']); } $newForest[] = $newRow; } return $newForest; } function isProb($prob) { return rand(0, 100) < $prob; }
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 local line1start, line1end = {x = 4, y = 0}, {x = 6, y = 10} local line2start, line2end = {x = 0, y = 3}, {x = 10, y = 7} print(intersection(line1start, line1end, line2start, line2end))
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 0..@{$_[0]}-1; @v } sub va { my @v; $v[$_] = $_[0][$_] + $_[1][$_] for 0..@{$_[0]}-1; @v } sub vp { my @v; $v[$_] = $_[0][$_] * $_[1][$_] for 0..@{$_[0]}-1; @v } sub line_plane_intersection { my($L, $P) = @_; my $cos = dot($L->{u}, $P->{n}); return 'Vectors are orthogonol; no intersection or line within plane' if $cos == 0; my @W = vd($L->{P0},$P->{V0}); my $SI = -dot($P->{n}, \@W) / $cos; my @a = vp($L->{u},[($SI)x3]); my @b = va($P->{V0},\@a); va(\@W,\@b); } my $L = Line->new({ P0=>[0,0,10], u=>[0,-1,-1]}); my $P = Plane->new({ V0=>[0,0,5 ], n=>[0, 0, 1]}); print 'Intersection at point: ', join(' ', line_plane_intersection($L, $P)) . "\n";
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 -> date("${year}-${month}-01") }.findAll { firstDay -> isLongMonth(firstDay) && Day.valueOf(firstDay) == Day.Fri } }.flatten() }
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 | March | April | May | June | July | August | September | October | November | December deriving (Show) type Year = Int type YearCalendar = (Year, [DayOfWeek]) type MonthlyCalendar = (Year, [(Month, [DayOfWeek])]) yearsFrom :: [DayOfWeek] -> Year -> [YearCalendar] yearsFrom s i = (i, yeardays): yearsFrom rest (i + 1) where yeardays = take (leapOrNot i) s yearlen = length yeardays rest = drop yearlen s leapOrNot n = if isLeapYear n then 366 else 365 yearsFrom1900 :: [YearCalendar] yearsFrom1900 = yearsFrom daysFrom1_1_1900 1900 months :: YearCalendar -> MonthlyCalendar months (y, d) = (y, [(January, january), (February, february), (March, march), (April, april), (May, may), (June, june), (July, july), (August, august), (September, september), (October, october), (November, november), (December, december)]) where leapOrNot = if isLeapYear y then 29 else 28 january = take 31 d february = take leapOrNot $ drop 31 d march = take 31 $ drop (31 + leapOrNot) d april = take 30 $ drop (62 + leapOrNot) d may = take 31 $ drop (92 + leapOrNot) d june = take 30 $ drop (123 + leapOrNot) d july = take 31 $ drop (153 + leapOrNot) d august = take 31 $ drop (184 + leapOrNot) d september = take 30 $ drop (215 + leapOrNot) d october = take 31 $ drop (245 + leapOrNot) d november = take 30 $ drop (276 + leapOrNot) d december = take 31 $ drop (306 + leapOrNot) d isLeapYear n | n `mod` 100 == 0 = n `mod` 400 == 0 | otherwise = n `mod` 4 == 0 whichFiveWeekends :: MonthlyCalendar -> (Year, [Month]) whichFiveWeekends (y, ms) = (y, map (\(m, _) -> m) found) where found = filter (\(m, a@(d:ds)) -> and [length a == 31, d == Friday]) ms calendar :: [MonthlyCalendar] calendar = map months $ yearsFrom1900 fiveWeekends1900To2100 :: [(Year, [Month])] fiveWeekends1900To2100 = takeWhile (\(y, _) -> y <= 2100) $ map whichFiveWeekends calendar main = do let answer1 = foldl (\c (_, m) -> c + length m) 0 fiveWeekends1900To2100 answer2 = filter (\(_, m) -> not $ null m) fiveWeekends1900To2100 answer30 = filter (\(_, m) -> null m) fiveWeekends1900To2100 answer31 = length answer30 answer32 = intercalate ", " $ map (\(y, m) -> show y) answer30 putStrLn $ "There are " ++ show answer1 ++ " months with 5 weekends between 1900 and 2100." putStrLn "\nThe first ones are:" mapM_ (putStrLn . formatMonth) $ take 5 $ answer2 putStrLn "\nThe last ones are:" mapM_ (putStrLn . formatMonth) $ reverse $ take 5 $ reverse answer2 putStrLn $ "\n" ++ show answer31 ++ " years don't have at least one five-weekened month" putStrLn "\nThose are:" putStrLn answer32 formatMonth :: (Year, [Month]) -> String formatMonth (y, m) = show y ++ ": " ++ intercalate ", " [ show x | x <- m ]
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(): grid = {(x,y): (tree if random.random()<= initial_trees else space) for x in range(L) for y in range(L) } return grid def gprint(grid): txt = '\n'.join(''.join(grid[(x,y)] for x in range(L)) for y in range(L)) print(txt) def quickprint(grid): t = b = 0 ll = L * L for x in range(L): for y in range(L): if grid[(x,y)] in (tree, burning): t += 1 if grid[(x,y)] == burning: b += 1 print(('Of%6i cells,%6i are trees of which%6i are currently burning.' + ' (%6.3f%%,%6.3f%%)') % (ll, t, b, 100. * t / ll, 100. * b / ll)) def gnew(grid): newgrid = {} for x in range(L): for y in range(L): if grid[(x,y)] == burning: newgrid[(x,y)] = space elif grid[(x,y)] == space: newgrid[(x,y)] = tree if random.random()<= p else space elif grid[(x,y)] == tree: newgrid[(x,y)] = (burning if any(grid.get((x+dx,y+dy),space) == burning for dx,dy in hood) or random.random()<= f else tree) return newgrid if __name__ == '__main__': grid = initialise() iter = 0 while True: quickprint(grid) inp = raw_input('Print/Quit/<int>/<return>%6i: '% iter).lower().strip() if inp: if inp[0] == 'p': gprint(grid) elif inp.isdigit(): for i in range(int(inp)): iter +=1 grid = gnew(grid) quickprint(grid) elif inp[0] == 'q': break grid = gnew(grid) iter +=1
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 flatten(s []interface{}) (r []int) { for _, e := range s { switch i := e.(type) { case int: r = append(r, i) case []interface{}: r = append(r, flatten(i)...) } } return }
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.Println("Last Sundays of each month of", year) fmt.Println("==================================") for i := 1;i < 13; i++ { j := lastDay[i-1] if i == 2 { if time.Date(int(year), time.Month(i), j, 0, 0, 0, 0, time.UTC).Month() == time.Date(int(year), time.Month(i), j-1, 0, 0, 0, 0, time.UTC).Month() { j = 29 } else { j = 28 } } for { t = time.Date(int(year), time.Month(i), j, 0, 0, 0, 0, time.UTC) if t.Weekday() == 0 { fmt.Printf("%s:%d\n", time.Month(i), j) break } j = j - 1 } } }
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 * rayDirection + planePoint return Psi if __name__==: planeNormal = np.array([0, 0, 1]) planePoint = np.array([0, 0, 5]) rayDirection = np.array([0, -1, -1]) rayPoint = np.array([0, 0, 10]) Psi = LinePlaneCollision(planeNormal, planePoint, rayDirection, rayPoint) print (, Psi)
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 { Day.valueOf(it) == dayOfWeek } } def lastWeekDays = { dayOfWeek, year -> weekDays(dayOfWeek, year).reverse().inject([:]) { months, sunday -> def monthStr = month(sunday) !months[monthStr] ? months + [(monthStr):sunday] : months }.values().sort() }
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 * $c1 - $b1 * $c2) / $delta; my $iy = ($a1 * $c2 - $a2 * $c1) / $delta; return ($ix, $iy); } my ($ix, $iy) = intersect(4, 0, 6, 10, 0, 3, 10, 7); print "$ix $iy\n"; ($ix, $iy) = intersect(0, 0, 1, 1, 1, 2, 4, 5); print "$ix $iy\n";
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 [] [] ] flattenList :: Tree [a] -> [a] flattenList = concat . flatten main :: IO () main = print $ flattenList list
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_ putStrLn ( intercalate " " <$> transpose (lastSundayOfEachMonth <$> [2013 .. 2017]) ) lastWeekDayDates :: Int -> Integer -> [String] lastWeekDayDates dayOfWeek year = (showGregorian . mostRecentWeekday dayOfWeek) . (fromGregorian year <*> gregorianMonthLength year) <$> [1 .. 12] mostRecentWeekday :: Int -> Day -> Day mostRecentWeekday dayOfWeek date = fromJust (find p ((`addDays` date) <$> [-6 .. 0])) where p x = let (_, _, day) = toWeekDate x in dayOfWeek == day
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 static void main(String[] args) { StringBuilder months = new StringBuilder(); int numMonths = 0; for (int year = 1900; year <= 2100; year++) { for (int month : month31) { Calendar date = new GregorianCalendar(year, month, 1); if (date.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) { years[year - 1900] = true; numMonths++;
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) { ++$digit; ++$col; my $colMaxDigit = $maxVal - $numRows + $col; $output .= sprintf "%*d", length($colMaxDigit), $digit; } print "$output\n"; } return; } my @counts; @counts = @ARGV; @counts = (5, 14) unless @ARGV; foreach my $count (@counts) { displayFloydTriangle($count); } 0; __END__
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 <= uA <= 1 and 0 <= uB <= 1): return x = Ax1 + uA * (Ax2 - Ax1) y = Ay1 + uA * (Ay2 - Ay1) return x, y if __name__ == '__main__': (a, b), (c, d) = (4, 0), (6, 10) (e, f), (g, h) = (0, 3), (10, 7) pt = line_intersect(a, b, c, d, e, f, g, h) print(pt)
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.0] pn = Vector[0.0, 0.0, 1.0] pp = Vector[0.0, 0.0, 5.0] ip = intersectPoint(rv, rp, pn, pp) puts % [ip] end main()
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 @generation += 1 work = @field.map{|row| row.map{|cell| cell}} for i in 0...@xsize for j in 0...@ysize case cell=@field[i][j] when :empty cell = :tree if rand < @p when :tree cell = :fire if fire?(i,j) else cell = :empty end work[i][j] = cell end end @field = work end def fire?(i,j) rand < @f or Neighborhood.any? {|di,dj| @field[i+di][j+dj] == :fire} end def display puts puts @xsize.times.map{|i| @ysize.times.map{|j| States[@field[i][j]]}.join} end end forest = Forest_Fire.new(10,30) 10.times do |i| forest.evolve forest.display end
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 _, p := range given { m[p[i]]++ } for char, count := range m { if count&1 == 1 { b[i] = char break } } } fmt.Println(string(b)) }
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,31,30,31,31,30,31,30,31}; int[] lastDay=new int[12]; for(int m=0;i<12;i++) { int d; for(d=days[m]; getWeekDay(year,m,d)!=0; d--) ; lastDay[m]=d; } return lastDay; } private static boolean isLeapYear(int year) { if(year%4==0) { if(year%100!=0) return true; else if (year%400==0) return true; } return false; } private static int getWeekDay(int y, int m, int d) { int f=y+d+3*m-1; m++; if(m<3) y--; else f-=(int)(0.4*m+2.3); f+=(int)(y/4)-(int)((y/100+1)*0.75); f%=7; return f; } private static void display(int year, int[] lastDay) { System.out.println("\nYEAR: "+year); for(int m=0;i<12;i++) System.out.println(months[m]+": "+lastDay[m]); } public static void main(String[] args) throws Exception { System.out.print("Enter year: "); Scanner s=new Scanner(System.in); int y=Integer.parseInt(s.next()); int[] lastDay = findLastSunday(y); display(y, lastDay); s.close(); } }
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(a.x, b.x), y: f(a.y, b.y), z: f(a.z, b.z), } } impl<T> Add for V3<T> where T: Add<Output = T>, { type Output = Self; fn add(self, other: Self) -> Self { zip_with(<T>::add, self, other) } } impl<T> Sub for V3<T> where T: Sub<Output = T>, { type Output = Self; fn sub(self, other: Self) -> Self { zip_with(<T>::sub, self, other) } } impl<T> Mul for V3<T> where T: Mul<Output = T>, { type Output = Self; fn mul(self, other: Self) -> Self { zip_with(<T>::mul, self, other) } } impl<T> V3<T> where T: Mul<Output = T> + Add<Output = T>, { fn dot(self, other: Self) -> T { let V3 { x, y, z } = self * other; x + y + z } } impl<T> V3<T> where T: Mul<Output = T> + Copy, { fn scale(self, scalar: T) -> Self { self * V3 { x: scalar, y: scalar, z: scalar, } } } fn intersect<T>( ray_vector: V3<T>, ray_point: V3<T>, plane_normal: V3<T>, plane_point: V3<T>, ) -> V3<T> where T: Add<Output = T> + Sub<Output = T> + Mul<Output = T> + Div<Output = T> + Copy, { let diff = ray_point - plane_point; let prod1 = diff.dot(plane_normal); let prod2 = ray_vector.dot(plane_normal); let prod3 = prod1 / prod2; ray_point - ray_vector.scale(prod3) } fn main() { let rv = V3::new(0.0, -1.0, -1.0); let rp = V3::new(0.0, 0.0, 10.0); let pn = V3::new(0.0, 0.0, 1.0); let pp = V3::new(0.0, 0.0, 5.0); println!("{:?}", intersect(rv, rp, pn, pp)); }
832Find the intersection of a line with a plane
15rust
2brlt