code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
package main import ( "fmt" "math" "rcu" ) func contains(a []int, n int) bool { for _, e := range a { if e == n { return true } } return false }
506Numbers which are not the sum of distinct squares
0go
w29eg
null
494Optional parameters
11kotlin
njxij
class CList extends ArrayList implements Comparable { CList() { } CList(Collection c) { super(c) } int compareTo(Object that) { assert that instanceof List def n = [this.size(), that.size()].min() def comp = [this[0..<n], that[0..<n]].transpose().find { it[0] != it[1] } comp ? comp[0] <=> comp[1]: this.size() <=> that.size() } }
500Order two numerical lists
7groovy
lsoc1
def isOrdered = { word -> def letters = word as List; letters == ([] + letters).sort() } assert isOrdered('abbey') assert !isOrdered('cat') def dictUrl = new URL('http:
491Ordered words
7groovy
k6rh7
<?php function is_palindrome($string) { return $string == strrev($string); } ?>
483Palindrome detection
12php
dk6n8
typedef struct{ double value; double delta; }imprecise; imprecise imprecise_add(imprecise a, imprecise b) { imprecise ret; ret.value = a.value + b.value; ret.delta = sqrt(SQR(a.delta) + SQR(b.delta)); return ret; } imprecise imprecise_mul(imprecise a, imprecise b) { imprecise ret; ret.value = a.value * b.value; ret.delta = sqrt(SQR(a.value * b.delta) + SQR(b.value * a.delta)); return ret; } imprecise imprecise_div(imprecise a, imprecise b) { imprecise ret; ret.value = a.value / b.value; ret.delta = sqrt(SQR(a.value * b.delta) + SQR(b.value * a.delta)) / SQR(b.value); return ret; } imprecise imprecise_pow(imprecise a, double c) { imprecise ret; ret.value = pow(a.value, c); ret.delta = fabs(ret.value * c * a.delta / a.value); return ret; } char* printImprecise(imprecise val) { char principal[30],error[30],*string,sign[2]; sign[0] = 241; sign[1] = 00; sprintf(principal,,val.value); sprintf(error,,val.delta); string = (char*)malloc((strlen(principal)+1+strlen(error)+1)*sizeof(char)); strcpy(string,principal); strcat(string,sign); strcat(string,error); return string; } int main(void) { imprecise x1 = {100, 1.1}; imprecise y1 = {50, 1.2}; imprecise x2 = {-200, 2.2}; imprecise y2 = {-100, 2.3}; imprecise d; d = imprecise_pow(imprecise_add(imprecise_pow(imprecise_add(x1, x2), 2),imprecise_pow(imprecise_add(y1, y2), 2)), 0.5); printf(); printf(,printImprecise(x1),printImprecise(y1)); printf(,printImprecise(x2),printImprecise(y2)); printf(, printImprecise(d)); return 0; }
507Numeric error propagation
5c
lsecy
(defn next-char [] (char (.read *in*))) (defn forward [] (let [ch (next-char)] (print ch) (if (Character/isLetter ch) (forward) (not= ch \.)))) (defn backward [] (let [ch (next-char)] (if (Character/isLetter ch) (let [result (backward)] (print ch) result) (fn [] (print ch) (not= ch \.)))) ) (defn odd-word [s] (with-in-str s (loop [forward? true] (when (if forward? (forward) ((backward))) (recur (not forward?)))) ) (println))
504Odd word problem
6clojure
xv2wk
package main import ( "bufio" "fmt" "os" "strconv" "strings" ) func main() { units := []string{ "tochka", "liniya", "dyuim", "vershok", "piad", "fut", "arshin", "sazhen", "versta", "milia", "centimeter", "meter", "kilometer", } convs := []float32{ 0.0254, 0.254, 2.54, 4.445, 17.78, 30.48, 71.12, 213.36, 10668, 74676, 1, 100, 10000, } scanner := bufio.NewScanner(os.Stdin) for { for i, u := range units { fmt.Printf("%2d%s\n", i+1, u) } fmt.Println() var unit int var err error for { fmt.Print("Please choose a unit 1 to 13: ") scanner.Scan() unit, err = strconv.Atoi(scanner.Text()) if err == nil && unit >= 1 && unit <= 13 { break } } unit-- var value float64 for { fmt.Print("Now enter a value in that unit: ") scanner.Scan() value, err = strconv.ParseFloat(scanner.Text(), 32) if err == nil && value >= 0 { break } } fmt.Println("\nThe equivalent in the remaining units is:\n") for i, u := range units { if i == unit { continue } fmt.Printf("%10s:%g\n", u, float32(value)*convs[unit]/convs[i]) } fmt.Println() yn := "" for yn != "y" && yn != "n" { fmt.Print("Do another one y/n: ") scanner.Scan() yn = strings.ToLower(scanner.Text()) } if yn == "n" { return } } }
501Old Russian measure of length
0go
yex64
import org.lwjgl.LWJGLException; import org.lwjgl.opengl.Display; import org.lwjgl.opengl.DisplayMode; import static org.lwjgl.opengl.GL11.*; public class OpenGlExample { public void run() throws LWJGLException { Display.setDisplayMode(new DisplayMode(640, 480)); Display.create(); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-30, 30, -30, 30, -30, 30); glMatrixMode(GL_MODELVIEW); while(!Display.isCloseRequested()) { render(); Display.update(); } Display.destroy(); } public void render() { glClearColor(0.3f, 0.3f, 0.3f, 0.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glShadeModel(GL_SMOOTH); glLoadIdentity(); glTranslatef(-15.0f, -15.0f, 0.0f); glBegin(GL_TRIANGLES); glColor3f(1.0f, 0.0f, 0.0f); glVertex2f(0.0f, 0.0f); glColor3f(0.0f, 1.0f, 0.0f); glVertex2f(30f, 0.0f); glColor3f(0.0f, 0.0f, 1.0f); glVertex2f(0.0f, 30.0f); glEnd(); } public static void main(String[] args) { OpenGlExample openGlExmpl = new OpenGlExample(); try { openGlExmpl.run(); } catch(LWJGLException e) { System.err.println(e); } } }
499OpenGL
9java
h39jm
def order_disjoint(m,n) print m, n = m.split, n.split from = 0 n.each_slice(2) do |x,y| next unless y sd = m[from..-1] if x > y && (sd.include? x) && (sd.include? y) && (sd.index(x) > sd.index(y)) new_from = m.index(x)+1 m[m.index(x)+from], m[m.index(y)+from] = m[m.index(y)+from], m[m.index(x)+from] from = new_from end end puts m.join(' ') end [ ['the cat sat on the mat', 'mat cat'], ['the cat sat on the mat', 'cat mat'], ['A B C A B C A B C' , 'C A C A'], ['A B C A B D A B E' , 'E A D A'], ['A B' , 'B' ], ['A B' , 'B A' ], ['A B B A' , 'B A' ] ].each {|m,n| order_disjoint(m,n)}
498Order disjoint list items
14ruby
zpxtw
Prelude> [1,2,1,3,2] < [1,2,0,4,4,0,0,0] False
500Order two numerical lists
8haskell
qugx9
$ syntax expr: .(). + .() is -> 7;
493Operator precedence
14ruby
bygkq
$ syntax expr: .(). + .() is -> 7;
493Operator precedence
16scala
elhab
isOrdered wws@(_:ws) = and $ zipWith (<=) wws ws longestOrderedWords = reverse . snd . foldl f (0,[]) . filter isOrdered where f (max, acc) w = let len = length w in case compare len max of LT -> (max, acc) EQ -> (max, w:acc) GT -> (len, [w]) main = do str <- getContents let ws = longestOrderedWords $ words str mapM_ putStrLn ws
491Ordered words
8haskell
31dzj
package main import ( "encoding/gob" "fmt" "os" ) type printable interface { print() } func main() {
508Object serialization
0go
k6dhz
module Main where import Text.Printf (printf) import System.Environment (getArgs, getProgName) tochka = ("tochka" , 0.000254) liniya = ("liniya" , 0.00254) centimeter = ("centimeter", 0.01) diuym = ("diuym" , 0.0254) vershok = ("vershok" , 0.04445) piad = ("piad" , 0.1778) fut = ("fut" , 0.3048) arshin = ("arshin" , 0.7112) meter = ("meter" , 1.0) sazhen = ("sazhen" , 2.1336) kilometer = ("kilometer" , 1000.0) versta = ("versta" , 1066.8) milia = ("milia" , 7467.6) units :: [(String, Double)] units = [tochka, liniya, centimeter, diuym, vershok, piad, fut, arshin, meter, sazhen, kilometer, versta, milia] convert :: Double -> Double -> IO () convert num factor = mapM_ (\(unit, fac) -> printf "|%-10s |%-22f|\n" unit (num * factor / fac)) units main :: IO () main = do args <- getArgs case args of [x,y] | [(num, "")] <- reads x :: [(Double, String)] , (Just factor) <- lookup y units -> convert num factor (_) -> do name <- getProgName printf "Arguments were wrong - please use ./%s <number> <unit>\n" name
501Old Russian measure of length
8haskell
h3yju
<html style="margin: 0;"> <head> <title>Minimal WebGL Example</title> <!-- This use of <script> elements is so that we can have multiline text without quoting it inside of JavaScript; the web browser doesn't actually do anything besides store the text of these. --> <script id="shader-fs" type="x-shader/x-fragment"> precision highp float; varying vec4 v_color; void main(void) {
499OpenGL
10javascript
el5ao
def order[T](input: Seq[T], using: Seq[T], used: Seq[T] = Seq()): Seq[T] = if (input.isEmpty || used.size >= using.size) input else if (using diff used contains input.head) using(used.size) +: order(input.tail, using, used :+ input.head) else input.head +: order(input.tail, using, used)
498Order disjoint list items
16scala
mw8yc
function showTable(tbl) if type(tbl)=='table' then local result = {} for _, val in pairs(tbl) do table.insert(result, showTable(val)) end return '{' .. table.concat(result, ', ') .. '}' else return (tostring(tbl)) end end function sortTable(op) local tbl = op.table or {} local column = op.column or 1 local reverse = op.reverse or false local cmp = op.cmp or (function (a, b) return a < b end) local compareTables = function (a, b) local result = cmp(a[column], b[column]) if reverse then return not result else return result end end table.sort(tbl, compareTables) end A = {{"quail", "deer", "snake"}, {"dalmation", "bear", "fox"}, {"ant", "cougar", "coyote"}} print('original', showTable(A)) sortTable{table=A} print('defaults', showTable(A)) sortTable{table=A, column=2} print('col 2 ', showTable(A)) sortTable{table=A, column=3} print('col 3 ', showTable(A)) sortTable{table=A, column=3, reverse=true} print('col 3 rev', showTable(A)) sortTable{table=A, cmp=(function (a, b) return #a < #b end)} print('by length', showTable(A))
494Optional parameters
1lua
dhqnq
class Entity implements Serializable { static final serialVersionUID = 3504465751164822571L String name = 'Thingamabob' public String toString() { return name } } class Person extends Entity implements Serializable { static final serialVersionUID = -9170445713373959735L Person() { name = 'Clement' } Person(name) { this.name = name } }
508Object serialization
7groovy
gd046
module Main (main) where import qualified Data.ByteString.Lazy as ByteString (readFile, writeFile) import Data.Binary (Binary) import qualified Data.Binary as Binary (decode, encode) import GHC.Generics (Generic) data Employee = Manager String String | IndividualContributor String String deriving (Generic, Show) instance Binary Employee main :: IO () main = do ByteString.writeFile "objects.dat" $ Binary.encode [ IndividualContributor "John Doe" "Sales" , Manager "Jane Doe" "Engineering" ] bytes <- ByteString.readFile "objects.dat" let employees = Binary.decode bytes print (employees :: [Employee])
508Object serialization
8haskell
nj5ie
static char const *animals[] = { , , , , , , , }; static char const *verses[] = { , , , , , , , }; int main(void) { for (size_t i = 0; i < LEN(animals); i++) { printf(, animals[i], verses[i]); for (size_t j = i; j > 0 && i < LEN(animals) - 1; j--) { printf(, animals[j], animals[j-1]); if (j == 1) { printf(, verses[0]); } } } }
509Old lady swallowed a fly
5c
6aj32
public class OldRussianMeasures { final static String[] keys = {"tochka", "liniya", "centimeter", "diuym", "vershok", "piad", "fut", "arshin", "meter", "sazhen", "kilometer", "versta", "milia"}; final static double[] values = {0.000254, 0.00254, 0.01,0.0254, 0.04445, 0.1778, 0.3048, 0.7112, 1.0, 2.1336, 1000.0, 1066.8, 7467.6}; public static void main(String[] a) { if (a.length == 2 && a[0].matches("[+-]?\\d*(\\.\\d+)?")) { double inputVal = lookup(a[1]); if (!Double.isNaN(inputVal)) { double magnitude = Double.parseDouble(a[0]); double meters = magnitude * inputVal; System.out.printf("%s%s to:%n%n", a[0], a[1]); for (String k: keys) System.out.printf("%10s:%g%n", k, meters / lookup(k)); return; } } System.out.println("Please provide a number and unit"); } public static double lookup(String key) { for (int i = 0; i < keys.length; i++) if (keys[i].equals(key)) return values[i]; return Double.NaN; } }
501Old Russian measure of length
9java
5iduf
null
499OpenGL
11kotlin
4nz57
func disjointOrder<T: Hashable>(m: [T], n: [T]) -> [T] { let replaceCounts = n.reduce(into: [T: Int](), { $0[$1, default: 0] += 1 }) let reduced = m.reduce(into: ([T](), n, replaceCounts), {cur, el in cur.0.append(cur.2[el, default: 0] > 0? cur.1.removeFirst(): el) cur.2[el]? -= 1 }) return reduced.0 } print(disjointOrder(m: ["the", "cat", "sat", "on", "the", "mat"], n: ["mat", "cat"])) print(disjointOrder(m: ["the", "cat", "sat", "on", "the", "mat"], n: ["cat", "mat"])) print(disjointOrder(m: ["A", "B", "C", "A", "B", "C", "A", "B", "C"], n: ["C", "A", "C", "A"])) print(disjointOrder(m: ["A", "B", "C", "A", "B", "D", "A", "B", "E"], n: ["E", "A", "D", "A"])) print(disjointOrder(m: ["A", "B"], n: ["B"])) print(disjointOrder(m: ["A", "B"], n: ["B", "A"])) print(disjointOrder(m: ["A", "B", "B", "A"], n: ["B", "A"]))
498Order disjoint list items
17swift
tbwfl
import java.util.Arrays; import java.util.List; public class ListOrder{ public static boolean ordered(double[] first, double[] second){ if(first.length == 0) return true; if(second.length == 0) return false; if(first[0] == second[0]) return ordered(Arrays.copyOfRange(first, 1, first.length), Arrays.copyOfRange(second, 1, second.length)); return first[0] < second[0]; } public static <T extends Comparable<? super T>> boolean ordered(List<T> first, List<T> second){ int i = 0; for(; i < first.size() && i < second.size();i++){ int cmp = first.get(i).compareTo(second.get(i)); if(cmp == 0) continue; if(cmp < 0) return true; return false; } return i == first.size(); } public static boolean ordered2(double[] first, double[] second){ int i = 0; for(; i < first.length && i < second.length;i++){ if(first[i] == second[i]) continue; if(first[i] < second[i]) return true; return false; } return i == first.length; } }
500Order two numerical lists
9java
pmlb3
int riseEqFall(int num) { int rdigit = num % 10; int netHeight = 0; while (num /= 10) { netHeight += ((num % 10) > rdigit) - ((num % 10) < rdigit); rdigit = num % 10; } return netHeight == 0; } int nextNum() { static int num = 0; do {num++;} while (!riseEqFall(num)); return num; } int main(void) { int total, num; printf(); for (total = 0; total < 200; total++) printf(, nextNum()); printf(); for (; total < 10000000; total++) num = nextNum(); printf(, num); return 0; }
510Numbers with equal rises and falls
5c
lspcy
import java.io.*;
508Object serialization
9java
qu9xa
null
501Old Russian measure of length
11kotlin
cq098
(() => { 'use strict';
500Order two numerical lists
10javascript
xv4w9
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.LinkedList; import java.util.List; public class Ordered { private static boolean isOrderedWord(String word){ char[] sortedWord = word.toCharArray(); Arrays.sort(sortedWord); return word.equals(new String(sortedWord)); } public static void main(String[] args) throws IOException{ List<String> orderedWords = new LinkedList<String>(); BufferedReader in = new BufferedReader(new FileReader(args[0])); while(in.ready()){ String word = in.readLine(); if(isOrderedWord(word)) orderedWords.add(word); } in.close(); Collections.<String>sort(orderedWords, new Comparator<String>() { @Override public int compare(String o1, String o2) { return new Integer(o2.length()).compareTo(o1.length()); } }); int maxLen = orderedWords.get(0).length(); for(String word: orderedWords){ if(word.length() == maxLen){ System.out.println(word); }else{ break; } } } }
491Ordered words
9java
i7sos
null
508Object serialization
11kotlin
19zpd
local gl = require "luagl" local iup = require "iuplua" require "iupluagl" local function paint() gl.ClearColor(0.3,0.3,0.3,0.0) gl.Clear"COLOR_BUFFER_BIT,DEPTH_BUFFER_BIT" gl.ShadeModel"SMOOTH" gl.LoadIdentity() gl.Translate(-15.0, -15.0, 0.0) gl.Begin"TRIANGLES" gl.Color(1.0, 0.0, 0.0) gl.Vertex(0.0, 0.0) gl.Color(0.0, 1.0, 0.0) gl.Vertex(30.0, 0.0) gl.Color(0.0, 0.0, 1.0) gl.Vertex(0.0, 30.0) gl.End() gl.Flush() end local function reshape(width, height) gl.Viewport(0, 0, width, height) gl.MatrixMode"PROJECTION" gl.LoadIdentity() gl.Ortho(-30.0, 30.0, -30.0, 30.0, -30.0, 30.0) gl.MatrixMode"MODELVIEW" end local glc = iup.glcanvas{rastersize="640x480"} function glc:action() paint() end function glc:resize_cb(w,h) reshape(w,h) end function glc:map_cb() iup.GLMakeCurrent(self) end local dlg = iup.dialog{title="Triangle", shrink="yes"; glc} dlg:show() iup.MainLoop()
499OpenGL
1lua
gd34j
var fs = require('fs'), print = require('sys').print; fs.readFile('./unixdict.txt', 'ascii', function (err, data) { var is_ordered = function(word){return word.split('').sort().join('') === word;}, ordered_words = data.split('\n').filter(is_ordered).sort(function(a, b){return a.length - b.length}).reverse(), longest = [], curr = len = ordered_words[0].length, lcv = 0; while (curr === len){ longest.push(ordered_words[lcv]); curr = ordered_words[++lcv].length; }; print(longest.sort().join(', ') + '\n'); });
491Ordered words
10javascript
zpnt2
package main import ( "fmt" "math" )
505Numerical integration/Gauss-Legendre Quadrature
0go
cqw9g
sub convert { my($magnitude, $unit) = @_; my %factor = ( tochka => 0.000254, liniya => 0.00254, diuym => 0.0254, vershok => 0.04445, piad => 0.1778, fut => 0.3048, arshin => 0.7112, sazhen => 2.1336, versta => 1066.8, milia => 7467.6, centimeter => 0.01, meter => 1.0, kilometer => 1000.0, ); my $base= $magnitude * $factor{$unit}; my $result .= "$magnitude $unit to:\n"; for (sort { $factor{$a} <=> $factor{$b} } keys %factor) { $result .= sprintf "%10s:%s\n", $_, sigdig($base / $factor{$_}, 5) unless $_ eq $unit } return $result; } sub sigdig { my($num,$sig) = @_; return $num unless $num =~ /\./; $num =~ /([1-9]\d*\.?\d*)/; my $prefix = $`; my $match = $&; $sig++ if $match =~ /\./; my $digits = substr $match, 0, $sig; my $nextd = substr $match, $sig, 1; $digits =~ s/(.)$/{1+$1}/e if $nextd > 5; return $prefix . $digits; } print convert(1,'meter'), "\n\n"; print convert(1,'milia'), "\n";
501Old Russian measure of length
2perl
xv5w8
gaussLegendre n f a b = d*sum [ w x*f(m + d*x) | x <- roots ] where d = (b - a)/2 m = (b + a)/2 w x = 2/(1-x^2)/(legendreP' n x)^2 roots = map (findRoot (legendreP n) (legendreP' n) . x0) [1..n] x0 i = cos (pi*(i-1/4)/(n+1/2))
505Numerical integration/Gauss-Legendre Quadrature
8haskell
pm6bt
package main import ( "bufio" "fmt" "io" "math/rand" "time" )
502One of n lines in a file
0go
h36jq
null
500Order two numerical lists
11kotlin
7t6r4
package main import ( "fmt" "math" )
507Numeric error propagation
0go
xv9wf
double int_leftrect(double from, double to, double n, double (*func)()) { double h = (to-from)/n; double sum = 0.0, x; for(x=from; x <= (to-h); x += h) sum += func(x); return h*sum; } double int_rightrect(double from, double to, double n, double (*func)()) { double h = (to-from)/n; double sum = 0.0, x; for(x=from; x <= (to-h); x += h) sum += func(x+h); return h*sum; } double int_midrect(double from, double to, double n, double (*func)()) { double h = (to-from)/n; double sum = 0.0, x; for(x=from; x <= (to-h); x += h) sum += func(x+h/2.0); return h*sum; } double int_trapezium(double from, double to, double n, double (*func)()) { double h = (to - from) / n; double sum = func(from) + func(to); int i; for(i = 1;i < n;i++) sum += 2.0*func(from + i * h); return h * sum / 2.0; } double int_simpson(double from, double to, double n, double (*func)()) { double h = (to - from) / n; double sum1 = 0.0; double sum2 = 0.0; int i; double x; for(i = 0;i < n;i++) sum1 += func(from + h * i + h / 2.0); for(i = 1;i < n;i++) sum2 += func(from + h * i); return h / 6.0 * (func(from) + func(to) + 4.0 * sum1 + 2.0 * sum2); }
511Numerical integration
5c
7tsrg
package main import "fmt" func risesEqualsFalls(n int) bool { if n < 10 { return true } rises := 0 falls := 0 prev := -1 for n > 0 { d := n % 10 if prev >= 0 { if d < prev { rises = rises + 1 } else if d > prev { falls = falls + 1 } } prev = d n /= 10 } return rises == falls } func main() { fmt.Println("The first 200 numbers in the sequence are:") count := 0 n := 1 for { if risesEqualsFalls(n) { count++ if count <= 200 { fmt.Printf("%3d ", n) if count%20 == 0 { fmt.Println() } } if count == 1e7 { fmt.Println("\nThe 10 millionth number in the sequence is ", n) break } } n++ } }
510Numbers with equal rises and falls
0go
xv6wf
from sys import argv unit2mult = {: 0.7112, : 0.01, : 0.0254, : 0.3048, : 1000.0, : 0.00254, : 1.0, : 7467.6, : 0.1778, : 2.1336, : 0.000254, : 0.04445, : 1066.8} if __name__ == '__main__': assert len(argv) == 3, 'ERROR. Need two arguments - number then units' try: value = float(argv[1]) except: print('ERROR. First argument must be a (float) number') raise unit = argv[2] assert unit in unit2mult, ( 'ERROR. Only know the following units: ' + ' '.join(unit2mult.keys()) ) print(% (value, unit)) for unt, mlt in sorted(unit2mult.items()): print(' %10s:%g'% (unt, value * unit2mult[unit] / mlt))
501Old Russian measure of length
3python
qu4xi
import qualified Data.Map as M import System.Random import Data.List import Control.Monad import System.Environment testFile = [1..10] selItem g xs = foldl' f (head xs, 1, 2, g) $ tail xs where f:: RandomGen a => (b, Int, Int, a) -> b -> (b, Int, Int, a) f (c, cn, n, gen) l | v == 1 = (l, n, n+1, ngen) | otherwise = (c, cn, n+1, ngen) where (v, ngen) = randomR (1, n) gen oneOfN a = do g <- newStdGen let (r, _, _, _) = selItem g a return r test = do x <- replicateM 1000000 (oneOfN testFile) let f m l = M.insertWith (+) l 1 m let results = foldl' f M.empty x forM_ (M.toList results) $ \(x, y) -> putStrLn $ "Line number " ++ show x ++ " had count:" ++ show y main = do a <- getArgs g <- newStdGen if null a then test else putStrLn.(\(l, n, _, _) -> "Line " ++ show n ++ ": " ++ l) .selItem g.lines =<< (readFile $ head a)
502One of n lines in a file
8haskell
i7jor
sub sorttable {my @table = @{shift()}; my %opt = (ordering => sub {$_[0] cmp $_[1]}, column => 0, reverse => 0, @_); my $col = $opt{column}; my $func = $opt{ordering}; my @result = sort {$func->($a->[$col], $b->[$col])} @table; return ($opt{reverse} ? [reverse @result] : \@result);}
494Optional parameters
2perl
7t2rh
import java.io.File fun main(args: Array<String>) { val file = File("unixdict.txt") val result = mutableListOf<String>() file.forEachLine { if (it.toCharArray().sorted().joinToString(separator = "") == it) { result += it } } result.sortByDescending { it.length } val max = result[0].length for (word in result) { if (word.length == max) { println(word) } } }
491Ordered words
11kotlin
quax1
data Error a = Error {value :: a, uncertainty :: a} deriving (Eq, Show) instance (Floating a) => Num (Error a) where Error a ua + Error b ub = Error (a + b) (sqrt (ua ^ 2 + ub ^ 2)) negate (Error a ua) = Error (negate a) ua Error a ua * Error b ub = Error (a * b) (abs (a * b * sqrt ((ua / a) ^ 2 + (ub / b) ^ 2))) fromInteger a = Error (fromInteger a) 0 instance (Floating a) => Fractional (Error a) where fromRational a = Error (fromRational a) 0 Error a ua / Error b ub = Error (a / b) (abs (a / b * sqrt ((ua / a) ^ 2 + (ub / b) ^ 2))) instance (Floating a) => Floating (Error a) where Error a ua ** Error c 0 = Error (a ** c) (abs (ua * c * a**c / a)) main = print (sqrt ((x1 - x2) ** 2 + (y1 - y2) ** 2)) where x1 = Error 100 1.1 y1 = Error 50 1.2 x2 = Error 200 2.2 y2 = Error 100 2.3
507Numeric error propagation
8haskell
yeb66
package main import ( "bytes" "fmt" "io" "os" "unicode" ) func main() { owp(os.Stdout, bytes.NewBufferString("what,is,the;meaning,of:life.")) fmt.Println() owp(os.Stdout, bytes.NewBufferString("we,are;not,in,kansas;any,more.")) fmt.Println() } func owp(dst io.Writer, src io.Reader) { byte_in := func () byte { bs := make([]byte, 1) src.Read(bs) return bs[0] } byte_out := func (b byte) { dst.Write([]byte{b}) } var odd func() byte odd = func() byte { s := byte_in() if unicode.IsPunct(rune(s)) { return s } b := odd() byte_out(s) return b } for { for { b := byte_in() byte_out(b) if b == '.' { return } if unicode.IsPunct(rune(b)) { break } } b := odd() byte_out(b) if b == '.' { return } } }
504Odd word problem
0go
6a13p
import Data.Char pairs :: [a] -> [(a,a)] pairs (a:b:as) = (a,b):pairs (b:as) pairs _ = [] riseEqFall :: Int -> Bool riseEqFall n = rel (>) digitPairs == rel (<) digitPairs where rel r = sum . map (fromEnum . uncurry r) digitPairs = pairs $ map digitToInt $ show n a296712 :: [Int] a296712 = [n | n <- [1..], riseEqFall n] main :: IO () main = do putStrLn "The first 200 numbers are: " putStrLn $ unwords $ map show $ take 200 a296712 putStrLn "" putStr "The 10,000,000th number is: " putStrLn $ show $ a296712 !! 9999999
510Numbers with equal rises and falls
8haskell
yej66
public class EqualRisesFalls { public static void main(String[] args) { final int limit1 = 200; final int limit2 = 10000000; System.out.printf("The first%d numbers in the sequence are:\n", limit1); int n = 0; for (int count = 0; count < limit2; ) { if (equalRisesAndFalls(++n)) { ++count; if (count <= limit1) System.out.printf("%3d%c", n, count % 20 == 0 ? '\n' : ' '); } } System.out.printf("\nThe%dth number in the sequence is%d.\n", limit2, n); } private static boolean equalRisesAndFalls(int n) { int total = 0; for (int previousDigit = -1; n > 0; n /= 10) { int digit = n % 10; if (previousDigit > digit) ++total; else if (previousDigit >= 0 && previousDigit < digit) --total; previousDigit = digit; } return total == 0; } }
510Numbers with equal rises and falls
9java
dhun9
import static java.lang.Math.*; import java.util.function.Function; public class Test { final static int N = 5; static double[] lroots = new double[N]; static double[] weight = new double[N]; static double[][] lcoef = new double[N + 1][N + 1]; static void legeCoef() { lcoef[0][0] = lcoef[1][1] = 1; for (int n = 2; n <= N; n++) { lcoef[n][0] = -(n - 1) * lcoef[n - 2][0] / n; for (int i = 1; i <= n; i++) { lcoef[n][i] = ((2 * n - 1) * lcoef[n - 1][i - 1] - (n - 1) * lcoef[n - 2][i]) / n; } } } static double legeEval(int n, double x) { double s = lcoef[n][n]; for (int i = n; i > 0; i--) s = s * x + lcoef[n][i - 1]; return s; } static double legeDiff(int n, double x) { return n * (x * legeEval(n, x) - legeEval(n - 1, x)) / (x * x - 1); } static void legeRoots() { double x, x1; for (int i = 1; i <= N; i++) { x = cos(PI * (i - 0.25) / (N + 0.5)); do { x1 = x; x -= legeEval(N, x) / legeDiff(N, x); } while (x != x1); lroots[i - 1] = x; x1 = legeDiff(N, x); weight[i - 1] = 2 / ((1 - x * x) * x1 * x1); } } static double legeInte(Function<Double, Double> f, double a, double b) { double c1 = (b - a) / 2, c2 = (b + a) / 2, sum = 0; for (int i = 0; i < N; i++) sum += weight[i] * f.apply(c1 * lroots[i] + c2); return c1 * sum; } public static void main(String[] args) { legeCoef(); legeRoots(); System.out.print("Roots: "); for (int i = 0; i < N; i++) System.out.printf("%f", lroots[i]); System.out.print("\nWeight:"); for (int i = 0; i < N; i++) System.out.printf("%f", weight[i]); System.out.printf("%nintegrating Exp(x) over [-3, 3]:%n\t%10.8f,%n" + "compared to actual%n\t%10.8f%n", legeInte(x -> exp(x), -3, 3), exp(3) - exp(-3)); } }
505Numerical integration/Gauss-Legendre Quadrature
9java
rfng0
import java.util.Arrays; import java.util.Random; public class OneOfNLines { static Random rand; public static int oneOfN(int n) { int choice = 0; for(int i = 1; i < n; i++) { if(rand.nextInt(i+1) == 0) choice = i; } return choice; } public static void main(String[] args) { int n = 10; int trials = 1000000; int[] bins = new int[n]; rand = new Random(); for(int i = 0; i < trials; i++) bins[oneOfN(n)]++; System.out.println(Arrays.toString(bins)); } }
502One of n lines in a file
9java
xvuwy
function arraycompare(a, b) for i = 1, #a do if b[i] == nil then return true end if a[i] ~= b[i] then return a[i] < b[1] end end return true end
500Order two numerical lists
1lua
jzy71
import System.IO (BufferMode(..), getContents, hSetBuffering, stdin, stdout) import Data.Char (isAlpha) split :: String -> (String, String) split = span isAlpha parse :: String -> String parse [] = [] parse l = let (a, w) = split l (b, x) = splitAt 1 w (c, y) = split x (d, z) = splitAt 1 y in a <> b <> reverse c <> d <> parse z main :: IO () main = hSetBuffering stdin NoBuffering >> hSetBuffering stdout NoBuffering >> getContents >>= putStr . takeWhile (/= '.') . parse >> putStrLn "."
504Odd word problem
8haskell
jzt7g
char trans[] = ; int evolve(char cell[], char backup[], int len) { int i, diff = 0; for (i = 0; i < len; i++) { backup[i] = trans[ v(i-1) * 4 + v(i) * 2 + v(i + 1) ]; diff += (backup[i] != cell[i]); } strcpy(cell, backup); return diff; } int main() { char c[] = , b[] = ; do { printf(c + 1); } while (evolve(c + 1, b + 1, sizeof(c) - 3)); return 0; }
512One-dimensional cellular automata
5c
fkvd3
const factorial = n => n <= 1 ? 1 : n * factorial(n - 1); const M = n => (n - (n % 2 !== 0)) / 2; const gaussLegendre = (fn, a, b, n) => {
505Numerical integration/Gauss-Legendre Quadrature
10javascript
by3ki
{ package Greeting; sub new { my $v = "Hello world!\n"; bless \$v, shift; }; sub stringify { ${shift()}; }; }; { package Son::of::Greeting; use base qw(Greeting); sub new { my $v = "Hello world from Junior!\n"; bless \$v, shift; }; }; { use Storable qw(store retrieve); package main; my $g1 = Greeting->new; my $s1 = Son::of::Greeting->new; print $g1->stringify; print $s1->stringify; store $g1, 'objects.dat'; my $g2 = retrieve 'objects.dat'; store $s1, 'objects.dat'; my $s2 = retrieve 'objects.dat'; print $g2->stringify; print $s2->stringify; };
508Object serialization
2perl
mwbyz
module Distances RATIOS = {arshin: 0.7112, centimeter: 0.01, diuym: 0.0254, fut: 0.3048, kilometer: 1000.0, liniya: 0.00254, meter: 1.0, milia: 7467.6, piad: 0.1778, sazhen: 2.1336, tochka: 0.000254, vershok: 0.04445, versta: 1066.8} def self.method_missing(meth, arg) from, to = meth.to_s.split().map(&:to_sym) raise NoMethodError, meth if ([from,to]-RATIOS.keys).size > 0 RATIOS[from] * arg / RATIOS[to] end def self.print_others(name, num) puts RATIOS.except(name.to_sym).each {|k,v| puts } end end Distances.print_others(, 2) puts p Distances.meter2centimeter(3) p Distances.arshin2meter(1) p Distances.versta2kilometer(20) p Distances.mile2piad(1)
501Old Russian measure of length
14ruby
04rsu
>>> def printtable(data): for row in data: print ' '.join('%-5s'% (''% cell) for cell in row) >>> import operator >>> def sorttable(table, ordering=None, column=0, reverse=False): return sorted(table, cmp=ordering, key=operator.itemgetter(column), reverse=reverse) >>> data = [[, , ], [, , ], [, , ]] >>> printtable(data) >>> printtable( sorttable(data) ) >>> printtable( sorttable(data, column=2) ) >>> printtable( sorttable(data, column=1) ) >>> printtable( sorttable(data, column=1, reverse=True) ) >>> printtable( sorttable(data, ordering=lambda a,b: cmp(len(b),len(a))) ) >>>
494Optional parameters
3python
jzv7p
public class Approx { private double value; private double error; public Approx(){this.value = this.error = 0;} public Approx(Approx b){ this.value = b.value; this.error = b.error; } public Approx(double value, double error){ this.value = value; this.error = error; } public Approx add(Approx b){ value+= b.value; error = Math.sqrt(error * error + b.error * b.error); return this; } public Approx add(double b){ value+= b; return this; } public Approx sub(Approx b){ value-= b.value; error = Math.sqrt(error * error + b.error * b.error); return this; } public Approx sub(double b){ value-= b; return this; } public Approx mult(Approx b){ double oldVal = value; value*= b.value; error = Math.sqrt(value * value * (error*error) / (oldVal*oldVal) + (b.error*b.error) / (b.value*b.value)); return this; } public Approx mult(double b){ value*= b; error = Math.abs(b * error); return this; } public Approx div(Approx b){ double oldVal = value; value/= b.value; error = Math.sqrt(value * value * (error*error) / (oldVal*oldVal) + (b.error*b.error) / (b.value*b.value)); return this; } public Approx div(double b){ value/= b; error = Math.abs(b * error); return this; } public Approx pow(double b){ double oldVal = value; value = Math.pow(value, b); error = Math.abs(value * b * (error / oldVal)); return this; } @Override public String toString(){return value+""+error;} public static void main(String[] args){ Approx x1 = new Approx(100, 1.1); Approx y1 = new Approx(50, 1.2); Approx x2 = new Approx(200, 2.2); Approx y2 = new Approx(100, 2.3); x1.sub(x2).pow(2).add(y1.sub(y2).pow(2)).pow(0.5); System.out.println(x1); } }
507Numeric error propagation
9java
dhgn9
use strict; use warnings; sub rf { local $_ = shift; my $sum = 0; $sum += $1 <=> $2 while /(.)(?=(.))/g; $sum } my $count = 0; my $n = 0; my @numbers; while( $count < 200 ) { rf(++$n) or $count++, push @numbers, $n; } print "first 200: @numbers\n" =~ s/.{1,70}\K\s/\n/gr; $count = 0; $n = 0; while( $count < 10e6 ) { rf(++$n) or $count++; } print "\n10,000,000th number: $n\n";
510Numbers with equal rises and falls
2perl
5iwu2
use std::env; use std::process; use std::collections::HashMap; fn main() { let units: HashMap<&str, f32> = [("arshin",0.7112),("centimeter",0.01),("diuym",0.0254),("fut",0.3048),("kilometer",1000.0),("liniya",0.00254),("meter",1.0),("milia",7467.6),("piad",0.1778),("sazhen",2.1336),("tochka",0.000254),("vershok",0.04445),("versta",1066.8)].iter().cloned().collect(); let args: Vec<String> = env::args().collect(); if args.len() < 3 { eprintln!("A correct use is oldrus [amount] [unit]."); process::exit(1); }; let length_float; length_float = match args[1].parse::<f32>() { Ok(length_float) => length_float, Err(..) => 1 as f32, }; let unit: &str = &args[2]; if! units.contains_key(unit) { let mut keys: Vec<&str> = Vec::new(); for i in units.keys() { keys.push(i) }; eprintln!("The correct units are: {}.", keys.join(", ")); process::exit(1); }; println!("{} {} to:", length_float, unit); for (lunit, length) in &units { println!(" {}: {:?}", lunit, length_float * units.get(unit).unwrap() / length); }; }
501Old Russian measure of length
15rust
8g707
import scala.collection.immutable.HashMap object OldRussianLengths extends App { private def measures = HashMap("tochka" -> 0.000254, "liniya"-> 0.000254, "centimeter"-> 0.01, "diuym"-> 0.0254, "vershok"-> 0.04445, "piad" -> 0.1778, "fut" -> 0.3048, "arshin"-> 0.7112, "meter" -> 1.0, "sazhen"-> 2.1336, "kilometer" -> 1000.0, "versta"-> 1066.8, "milia" -> 7467.6 ).withDefaultValue(Double.NaN) if (args.length == 2 && args(0).matches("[+-]?\\d*(\\.\\d+)?")) { val inputVal = measures(args(1)) def meters = args(0).toDouble * inputVal if (!java.lang.Double.isNaN(inputVal)) { printf("%s%s to:%n%n", args(0), args(1)) for (k <- measures) println(f"${k._1}%10s: ${meters / k._2}%g") } } else println("Please provide a number and unit on the command line.") }
501Old Russian measure of length
16scala
njkic
use OpenGL; sub triangle { glBegin GL_TRIANGLES; glColor3f 1.0, 0.0, 0.0; glVertex2f 5.0, 5.0; glColor3f 0.0, 1.0, 0.0; glVertex2f 25.0, 5.0; glColor3f 0.0, 0.0, 1.0; glVertex2f 5.0, 25.0; glEnd; }; glpOpenWindow; glMatrixMode GL_PROJECTION; glLoadIdentity; gluOrtho2D 0.0, 30.0, 0.0, 30.0; glMatrixMode GL_MODELVIEW; glClear GL_COLOR_BUFFER_BIT; triangle; glpFlush; glpMainLoop;
499OpenGL
2perl
i7bo3
null
502One of n lines in a file
11kotlin
pm9b6
tablesort <- function(x, ordering="lexicographic", column=1, reverse=false) { } tablesort(mytable, column=3)
494Optional parameters
13r
4n95y
import java.lang.Math.* data class Approx(val : Double, val : Double = 0.0) { constructor(a: Approx) : this(a., a.) constructor(n: Number) : this(n.toDouble(), 0.0) override fun toString() = "$ $" operator infix fun plus(a: Approx) = Approx( + a., sqrt( * + a. * a.)) operator infix fun plus(d: Double) = Approx( + d, ) operator infix fun minus(a: Approx) = Approx( - a., sqrt( * + a. * a.)) operator infix fun minus(d: Double) = Approx( - d, ) operator infix fun times(a: Approx): Approx { val v = * a. return Approx(v, sqrt(v * v * * / ( * ) + a. * a. / (a. * a.))) } operator infix fun times(d: Double) = Approx( * d, abs(d * )) operator infix fun div(a: Approx): Approx { val v = / a. return Approx(v, sqrt(v * v * * / ( * ) + a. * a. / (a. * a.))) } operator infix fun div(d: Double) = Approx( / d, abs(d * )) fun pow(d: Double): Approx { val v = pow(, d) return Approx(v, abs(v * d * / )) } } fun main(args: Array<String>) { val x1 = Approx(100.0, 1.1) val y1 = Approx(50.0, 1.2) val x2 = Approx(200.0, 2.2) val y2 = Approx(100.0, 2.3) println(((x1 - x2).pow(2.0) + (y1 - y2).pow(2.0)).pow(0.5)) }
507Numeric error propagation
11kotlin
042sf
import itertools def riseEqFall(num): height = 0 d1 = num% 10 num while num: d2 = num% 10 height += (d1<d2) - (d1>d2) d1 = d2 num return height == 0 def sequence(start, fn): num=start-1 while True: num += 1 while not fn(num): num += 1 yield num a296712 = sequence(1, riseEqFall) print() print(*itertools.islice(a296712, 200)) print() print(*itertools.islice(a296712, 10000000-200-1, 10000000-200))
510Numbers with equal rises and falls
3python
4nx5k
import java.lang.Math.* class Legendre(val N: Int) { fun evaluate(n: Int, x: Double) = (n downTo 1).fold(c[n][n]) { s, i -> s * x + c[n][i - 1] } fun diff(n: Int, x: Double) = n * (x * evaluate(n, x) - evaluate(n - 1, x)) / (x * x - 1) fun integrate(f: (Double) -> Double, a: Double, b: Double): Double { val c1 = (b - a) / 2 val c2 = (b + a) / 2 return c1 * (0 until N).fold(0.0) { s, i -> s + weights[i] * f(c1 * roots[i] + c2) } } private val roots = DoubleArray(N) private val weights = DoubleArray(N) private val c = Array(N + 1) { DoubleArray(N + 1) }
505Numerical integration/Gauss-Legendre Quadrature
11kotlin
v8s21
$myObj = new Object(); $serializedObj = serialize($myObj);
508Object serialization
12php
el6a9
math.randomseed(os.time()) local n = 10 local trials = 1000000 function one(n) local chosen = 1 for i = 1, n do if math.random() < 1/i then chosen = i end end return chosen end
502One of n lines in a file
1lua
19cpo
fp = io.open( "dictionary.txt" ) maxlen = 0 list = {} for w in fp:lines() do ordered = true for l = 2, string.len(w) do if string.byte( w, l-1 ) > string.byte( w, l ) then ordered = false break end end if ordered then if string.len(w) > maxlen then list = {} list[1] = w maxlen = string.len(w) elseif string.len(w) == maxlen then list[#list+1] = w end end end for _, w in pairs(list) do print( w ) end fp:close()
491Ordered words
1lua
s5eq8
public class OddWord { interface CharHandler { CharHandler handle(char c) throws Exception; } final CharHandler fwd = new CharHandler() { public CharHandler handle(char c) { System.out.print(c); return (Character.isLetter(c) ? fwd : rev); } }; class Reverser extends Thread implements CharHandler { Reverser() { setDaemon(true); start(); } private Character ch;
504Odd word problem
9java
uo8vv
local order = 0 local legendreRoots = {} local legendreWeights = {} local function legendre(term, z) if (term == 0) then return 1 elseif (term == 1) then return z else return ((2 * term - 1) * z * legendre(term - 1, z) - (term - 1) * legendre(term - 2, z)) / term end end local function legendreDerivative(term, z) if (term == 0) then return 0 elseif (term == 1) then return 1 else return ( term * ((z * legendre(term, z)) - legendre(term - 1, z))) / (z * z - 1) end end local function getLegendreRoots() local y, y1 for index = 1, order do y = math.cos(math.pi * (index - 0.25) / (order + 0.5)) repeat y1 = y y = y - (legendre(order, y) / legendreDerivative(order, y)) until y == y1 table.insert(legendreRoots, y) end end local function getLegendreWeights() for index = 1, order do local weight = 2 / ((1 - (legendreRoots[index]) ^ 2) * (legendreDerivative(order, legendreRoots[index])) ^ 2) table.insert(legendreWeights, weight) end end function gaussLegendreQuadrature(f, lowerLimit, upperLimit, n) order = n do getLegendreRoots() getLegendreWeights() end local c1 = (upperLimit - lowerLimit) / 2 local c2 = (upperLimit + lowerLimit) / 2 local sum = 0 for i = 1, order do sum = sum + legendreWeights[i] * f(c1 * legendreRoots[i] + c2) end return c1 * sum end do print(gaussLegendreQuadrature(function(x) return math.exp(x) end, -3, 3, 5)) end
505Numerical integration/Gauss-Legendre Quadrature
1lua
uo0vl
import pickle class Entity: def __init__(self): self.name = def printName(self): print self.name class Person(Entity): def __init__(self): self.name = instance1 = Person() instance1.printName() instance2 = Entity() instance2.printName() target = file(, ) pickle.dump((instance1, instance2), target) target.close() print target = file() i1, i2 = pickle.load(target) print i1.printName() i2.printName()
508Object serialization
3python
9xpmf
null
504Odd word problem
11kotlin
9xwmh
(ns one-dimensional-cellular-automata (:require (clojure.contrib (string:as s)))) (defn next-gen [cells] (loop [cs cells ncs (s/take 1 cells)] (let [f3 (s/take 3 cs)] (if (= 3 (count f3)) (recur (s/drop 1 cs) (str ncs (if (= 2 (count (filter #(= \# %) f3))) "#" "_"))) (str ncs (s/drop 1 cs)))))) (defn generate [n cells] (if (= n 0) '() (cons cells (generate (dec n) (next-gen cells)))))
512One-dimensional cellular automata
6clojure
yer6b
class Being def initialize(specialty=nil) @specialty=specialty end def to_s +.ljust(12)+to_s4Being+(@specialty? +*12+@specialty: ) end def to_s4Being end end class Earthling < Being def to_s4Being +*12+to_s4Earthling end end class Mammal < Earthling def initialize(type) @type=type end def to_s4Earthling end end class Fish < Earthling def initialize(iq) @iq=(iq>1? :instrustableValue: iq) end def to_s4Earthling end end class Moonling < Being def to_s4Being end end diverseCollection=[] diverseCollection << (marsian=Being.new()) diverseCollection << (me=Mammal.new(:human)) diverseCollection << (nemo=Fish.new(0.99)) diverseCollection << (jannakeMaan=Moonling.new) puts diverseCollection.each do |being| puts ,being.to_s end puts puts +*50+ File.open('diverseCollection.bin','w') do |fo| fo << Marshal.dump(diverseCollection) end sameDiverseCollection=Marshal.load(File.read('diverseCollection.bin')) puts puts( sameDiverseCollection.collect do |being| being.to_s end.join() ) puts
508Object serialization
14ruby
lsacl
def table_sort(table, ordering=:<=>, column=0, reverse=false)
494Optional parameters
14ruby
k65hg
use std::cmp::Ordering; struct Table { rows: Vec<Vec<String>>, ordering_function: fn(&str, &str) -> Ordering, ordering_column: usize, reverse: bool, } impl Table { fn new(rows: Vec<Vec<String>>) -> Table { Table { rows: rows, ordering_column: 0, reverse: false, ordering_function: |str1, str2| str1.cmp(str2), } } } impl Table { fn with_ordering_column(&mut self, ordering_column: usize) -> &mut Table { self.ordering_column = ordering_column; self } fn with_reverse(&mut self, reverse: bool) -> &mut Table { self.reverse = reverse; self } fn with_ordering_fun(&mut self, compare: fn(&str, &str) -> Ordering) -> &mut Table { self.ordering_function = compare; self } fn sort(&mut self) { let fun = &mut self.ordering_function; let idx = self.ordering_column; if self.reverse { self.rows .sort_unstable_by(|vec1, vec2| (fun)(&vec1[idx], &vec2[idx]).reverse()); } else { self.rows .sort_unstable_by(|vec1, vec2| (fun)(&vec1[idx], &vec2[idx])); } } } #[cfg(test)] mod test { use super::Table; fn generate_test_table() -> Table { Table::new(vec![ vec!["0".to_string(), "fff".to_string()], vec!["2".to_string(), "aab".to_string()], vec!["1".to_string(), "ccc".to_string()], ]) } #[test] fn test_simple_sort() { let mut table = generate_test_table(); table.sort(); assert_eq!( table.rows, vec![ vec!["0".to_string(), "fff".to_string()], vec!["1".to_string(), "ccc".to_string()], vec!["2".to_string(), "aab".to_string()], ], ) } #[test] fn test_ordering_column() { let mut table = generate_test_table(); table.with_ordering_column(1).sort(); assert_eq!( table.rows, vec![ vec!["2".to_string(), "aab".to_string()], vec!["1".to_string(), "ccc".to_string()], vec!["0".to_string(), "fff".to_string()], ], ) } #[test] fn test_with_reverse() { let mut table = generate_test_table(); table.with_reverse(true).sort(); assert_eq!( table.rows, vec![ vec!["2".to_string(), "aab".to_string()], vec!["1".to_string(), "ccc".to_string()], vec!["0".to_string(), "fff".to_string()], ], ) } #[test] fn test_custom_ordering_fun() { let mut table = generate_test_table();
494Optional parameters
15rust
by4kx
use strict; use warnings; sub orderlists { my ($firstlist, $secondlist) = @_; my ($first, $second); while (@{$firstlist}) { $first = shift @{$firstlist}; if (@{$secondlist}) { $second = shift @{$secondlist}; if ($first < $second) { return 1; } if ($first > $second) { return 0; } } else { return 0; } } @{$secondlist} ? 1 : 0; } foreach my $pair ( [[1, 2, 4], [1, 2, 4]], [[1, 2, 4], [1, 2, ]], [[1, 2, ], [1, 2, 4]], [[55,53,1], [55,62,83]], [[20,40,51],[20,17,78,34]], ) { my $first = $pair->[0]; my $second = $pair->[1]; my $before = orderlists([@$first], [@$second]) ? 'true' : 'false'; print "(@$first) comes before (@$second): $before\n"; }
500Order two numerical lists
2perl
fk1d7
def is_palindrome(s): return s == s[::-1]
483Palindrome detection
3python
7zprm
use utf8; package ErrVar; use strict; sub zip(&$$) { my ($f, $x, $y) = @_; my $l = $ if ($l < $ my @out; for (0 .. $l) { local $a = $x->[$_]; local $b = $y->[$_]; push @out, $f->(); } \@out } use overload '""' => \&_str, '+' => \&_add, '-' => \&_sub, '*' => \&_mul, '/' => \&_div, 'bool' => \&_bool, '<=>' => \&_ncmp, 'neg' => \&_neg, 'sqrt' => \&_sqrt, 'log' => \&_log, 'exp' => \&_exp, '**' => \&_pow, ; sub make { my $x = shift; bless [$x, [@{+shift}]] } sub _str { sprintf "%g%.3g", $_[0][0], sigma($_[0]) } sub mean { my $x = shift; ref($x) && $x->isa(__PACKAGE__) ? $x->[0] : $x } sub vlist { my $x = shift; ref($x) && $x->isa(__PACKAGE__) ? $x->[1] : []; } sub variance { my $x = shift; return 0 unless ref($x) and $x->isa(__PACKAGE__); my $s; $s += $_ * $_ for (@{$x->[1]}); $s } sub covariance { my ($x, $y) = @_; return 0 unless ref($x) && $x->isa(__PACKAGE__); return 0 unless ref($y) && $y->isa(__PACKAGE__); my $s; zip { $s += $a * $b } vlist($x), vlist($y); $s } sub sigma { sqrt variance(shift) } sub _bool { my $x = shift; return abs(mean($x)) > sigma($x); } sub _ncmp { my $x = shift() - shift() or return 0; return mean($x) > 0 ? 1 : -1; } sub _neg { my $x = shift; bless [ -mean($x), [map(-$_, @{vlist($x)}) ] ]; } sub _add { my ($x, $y) = @_; my ($x0, $y0) = (mean($x), mean($y)); my ($xv, $yv) = (vlist($x), vlist($y)); bless [$x0 + $y0, zip {$a + $b} $xv, $yv]; } sub _sub { my ($x, $y, $swap) = @_; if ($swap) { ($x, $y) = ($y, $x) } my ($x0, $y0) = (mean($x), mean($y)); my ($xv, $yv) = (vlist($x), vlist($y)); bless [$x0 - $y0, zip {$a - $b} $xv, $yv]; } sub _mul { my ($x, $y) = @_; my ($x0, $y0) = (mean($x), mean($y)); my ($xv, $yv) = (vlist($x), vlist($y)); $xv = [ map($y0 * $_, @$xv) ]; $yv = [ map($x0 * $_, @$yv) ]; bless [$x0 * $y0, zip {$a + $b} $xv, $yv]; } sub _div { my ($x, $y, $swap) = @_; if ($swap) { ($x, $y) = ($y, $x) } my ($x0, $y0) = (mean($x), mean($y)); my ($xv, $yv) = (vlist($x), vlist($y)); $xv = [ map($_/$y0, @$xv) ]; $yv = [ map($x0 * $_/$y0/$y0, @$yv) ]; bless [$x0 / $y0, zip {$a + $b} $xv, $yv]; } sub _sqrt { my $x = shift; my $x0 = mean($x); my $xv = vlist($x); $x0 = sqrt($x0); $xv = [ map($_ / 2 / $x0, @$xv) ]; bless [$x0, $xv] } sub _pow { my ($x, $y, $swap) = @_; if ($swap) { ($x, $y) = ($y, $x) } if ($x < 0) { if (int($y) != $y || ($y & 1)) { die "Can't take pow of negative number $x"; } $x = -$x; } exp($y * log $x) } sub _exp { my $x = shift; my $x0 = exp(mean($x)); my $xv = vlist($x); bless [ $x0, [map($x0 * $_, @$xv) ] ] } sub _log { my $x = shift; my $x0 = mean($x); my $xv = vlist($x); bless [ log($x0), [ map($_ / $x0, @$xv) ] ] } "If this package were to be in its own file, you need some truth value to end it like this."; package main; sub e { ErrVar::make @_ }; my $x1 = e 100, [1.1, 0, 0, 0 ]; my $x2 = e 200, [0, 2.2, 0, 0 ]; my $y1 = e 50, [0, 0, 1.2, 0 ]; my $y2 = e 100, [0, 0, 0, 2.3]; my $z1 = sqrt(($x1 - $x2) ** 2 + ($y1 - $y2) ** 2); print "distance: $z1\n\n"; my $a = $x1 + $x2; my $b = $y1 - 2 * $x2; print "covariance between $a and $b: ", $a->covariance($b), "\n";
507Numeric error propagation
2perl
5isu2
function reverse() local ch = io.read(1) if ch:find("%w") then local rc = reverse() io.write(ch) return rc end return ch end function forward() ch = io.read(1) io.write(ch) if ch == "." then return false end if not ch:find("%w") then ch = reverse() if ch then io.write(ch) end if ch == "." then return false end end return true end while forward() do end
504Odd word problem
1lua
cqx92
int main() { char *object = 0; if (object == NULL) { puts(); } return 0; }
513Null object
5c
046st
import Foundation func equalRisesAndFalls(_ n: Int) -> Bool { var total = 0 var previousDigit = -1 var m = n while m > 0 { let digit = m% 10 m /= 10 if previousDigit > digit { total += 1 } else if previousDigit >= 0 && previousDigit < digit { total -= 1 } previousDigit = digit } return total == 0 } var count = 0 var n = 0 let limit1 = 200 let limit2 = 10000000 print("The first \(limit1) numbers in the sequence are:") while count < limit2 { n += 1 if equalRisesAndFalls(n) { count += 1 if count <= limit1 { print(String(format: "%3d", n), terminator: count% 20 == 0? "\n": " ") } } } print("\nThe \(limit2)th number in the sequence is \(n).")
510Numbers with equal rises and falls
17swift
gdq49
serde = { version = "1.0.89", features = ["derive"] } bincode = "1.1.2"
508Object serialization
15rust
20elt
package main import "fmt" var name, lyric, animals = 0, 1, [][]string{ {"fly", "I don't know why she swallowed a fly. Perhaps she'll die."}, {"spider", "That wiggled and jiggled and tickled inside her."}, {"bird", "How absurd, to swallow a bird."}, {"cat", "Imagine that, she swallowed a cat."}, {"dog", "What a hog, to swallow a dog."}, {"goat", "She just opened her throat and swallowed that goat."}, {"cow", "I don't know how she swallowed that cow."}, {"horse", "She's dead, of course."}, } func main() { for i, animal := range animals { fmt.Printf("There was an old lady who swallowed a%s,\n", animal[name]) if i > 0 { fmt.Println(animal[lyric]) }
509Old lady swallowed a fly
0go
pmfbg
from OpenGL.GL import * from OpenGL.GLUT import * def paint(): glClearColor(0.3,0.3,0.3,0.0) glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT) glShadeModel(GL_SMOOTH) glLoadIdentity() glTranslatef(-15.0, -15.0, 0.0) glBegin(GL_TRIANGLES) glColor3f(1.0, 0.0, 0.0) glVertex2f(0.0, 0.0) glColor3f(0.0, 1.0, 0.0) glVertex2f(30.0, 0.0) glColor3f(0.0, 0.0, 1.0) glVertex2f(0.0, 30.0) glEnd() glFlush() def reshape(width, height): glViewport(0, 0, width, height) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(-30.0, 30.0, -30.0, 30.0, -30.0, 30.0) glMatrixMode(GL_MODELVIEW) if __name__ == '__main__': glutInit(1, 1) glutInitWindowSize(640, 480) glutCreateWindow() glutDisplayFunc(paint) glutReshapeFunc(reshape) glutMainLoop()
499OpenGL
3python
njpiz
def sortTable(data: List[List[String]], ordering: (String, String) => Boolean = (_ < _), column: Int = 0, reverse: Boolean = false) = { val result = data.sortWith((a, b) => ordering(a(column), b(column))) if (reverse) result.reverse else result }
494Optional parameters
16scala
ac71n
import Data.List (tails) animals :: [String] animals = [ "fly.\nI don't know why she swallowed a fly.\nPerhaps she'll die.\n" , "spider.\nThat wiggled and jiggled and tickled inside her." , "bird.\t\nHow absurd, to swallow a bird." , "cat.\t\nImagine that. She swallowed a cat." , "dog.\t\nWhat a hog to swallow a dog." , "goat.\t\nShe just opened her throat and swallowed a goat." , "cow.\nI don't know how she swallowed a cow." , "horse.\nShe's dead, of course." ] beginnings :: [String] beginnings = ("There was an old lady who swallowed a " ++) <$> animals lastVerse :: [String] lastVerse = reverse [ "She swallowed the " ++ takeWhile (/= '.') y ++ " to catch the " ++ takeWhile (/= '\t') x | (x:y:_:_) <- tails animals ] main :: IO () main = putStr $ concatMap unlines $ zipWith (:) beginnings $ reverse $ ([]:) (tails lastVerse)
509Old lady swallowed a fly
8haskell
fk4d1
palindro <- function(p) { if ( nchar(p) == 1 ) { return(TRUE) } else if ( nchar(p) == 2 ) { return(substr(p,1,1) == substr(p,2,2)) } else { if ( substr(p,1,1) == substr(p, nchar(p), nchar(p)) ) { return(palindro(substr(p, 2, nchar(p)-1))) } else { return(FALSE) } } }
483Palindrome detection
13r
5njuy
from collections import namedtuple import math class I(namedtuple('Imprecise', 'value, delta')): 'Imprecise type: I(value=0.0, delta=0.0)' __slots__ = () def __new__(_cls, value=0.0, delta=0.0): 'Defaults to 0.0 delta' return super().__new__(_cls, float(value), abs(float(delta))) def reciprocal(self): return I(1. / self.value, self.delta / (self.value**2)) def __str__(self): 'Shorter form of Imprecise as string' return 'I(%g,%g)'% self def __neg__(self): return I(-self.value, self.delta) def __add__(self, other): if type(other) == I: return I( self.value + other.value, (self.delta**2 + other.delta**2)**0.5 ) try: c = float(other) except: return NotImplemented return I(self.value + c, self.delta) def __sub__(self, other): return self + (-other) def __radd__(self, other): return I.__add__(self, other) def __mul__(self, other): if type(other) == I: a1,b1 = self a2,b2 = other f = a1 * a2 return I( f, f * ( (b1 / a1)**2 + (b2 / a2)**2 )**0.5 ) try: c = float(other) except: return NotImplemented return I(self.value * c, self.delta * c) def __pow__(self, other): if type(other) == I: return NotImplemented try: c = float(other) except: return NotImplemented f = self.value ** c return I(f, f * c * (self.delta / self.value)) def __rmul__(self, other): return I.__mul__(self, other) def __truediv__(self, other): if type(other) == I: return self.__mul__(other.reciprocal()) try: c = float(other) except: return NotImplemented return I(self.value / c, self.delta / c) def __rtruediv__(self, other): return other * self.reciprocal() __div__, __rdiv__ = __truediv__, __rtruediv__ Imprecise = I def distance(p1, p2): x1, y1 = p1 x2, y2 = p2 return ((x1 - x2)**2 + (y1 - y2)**2)**0.5 x1 = I(100, 1.1) x2 = I(200, 2.2) y1 = I( 50, 1.2) y2 = I(100, 2.3) p1, p2 = (x1, y1), (x2, y2) print(% ( p1, p2, distance(p1, p2)))
507Numeric error propagation
3python
4n05k
(let [x nil] (println "Object is" (if (nil? x) "nil" "not nil")))
513Null object
6clojure
dhlnb
library(rgl) x <- c(-1, -1, 1) y <- c(0, -1, -1) z <- c(0, 0, 0) M <- cbind(x,y,z) rgl.bg(color="gray15") triangles3d(M, col=rainbow(8))
499OpenGL
13r
04jsg
use warnings; use strict; sub one_of_n { my $n = shift; my $return = 1; for my $line (2 .. $n) { $return = $line if 1 > rand $line; } return $return; } my $repeat = 1_000_000; my $size = 10; my @freq; ++$freq[ one_of_n($size) - 1 ] for 1 .. $repeat; print "@freq\n";
502One of n lines in a file
2perl
yew6u
enum SortOrder { case kOrdNone, kOrdLex, kOrdByAddress, kOrdNumeric } func sortTable(table: [[String]], less: (String,String)->Bool = (<), column: Int = 0, reversed: Bool = false) {
494Optional parameters
17swift
h3uj0
what,is,the;meaning,of:life.
504Odd word problem
2perl
w2le6
void number_reversal_game() { printf(); printf(); printf(); printf(); int list[9] = {1,2,3,4,5,6,7,8,9}; shuffle_list(list,9); int tries=0; unsigned int i; int input; while(!check_array(list, 9)) { ((tries<10) ? printf(, tries) : printf(, tries)); for(i=0;i<9;i++)printf(,list[i]); printf(); while(1) { scanf(, &input); if(input>1&&input<10) break; printf(, (int)input); } tries++; do_flip(list, 9, input); } printf(, tries); }
514Number reversal game
5c
dhcnv
public class OldLadySwallowedAFly { final static String[] data = { "_ha _c _e _p,/Quite absurd_f_p;_`cat,/Fancy that_fcat;_j`dog,/What a hog" + "_fdog;_l`pig,/Her mouth_qso big_fpig;_d_r,/She just opened her throat_f_" + "r;_icow,/_mhow she_ga cow;_k_o,/It_qrather wonky_f_o;_a_o_bcow,_khorse.." + "./She's dead, of course!/", "_a_p_b_e ", "/S_t ", " to catch the ", "fly,/Bu" + "t _mwhy s_t fly,/Perhaps she'll die!
509Old lady swallowed a fly
9java
04cse