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 ... | 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... | 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 ... | 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.025... | 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)... | 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.i... | 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 ... | 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 ... | 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"... | 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... | 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' ... | 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
... | 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 ... | 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.... | 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
}... | 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.copy... | 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));
re... | 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 =... | 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... | 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()... | 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,
ve... | 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 =... | 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 {
f... | 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 a... | 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, nge... | 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 }
va... | 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)))
... | 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... | 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 |... | 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 (equalRisesA... | 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[... | 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 ... | 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
... | 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); } whil... | 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;
};
};
{
... | 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)... | 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 = [[, , ], [, , ], [, , ]]
... | 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 = er... | 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( ... | 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.0... | 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,
"sazhe... | 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, 3... | 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: D... | 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 ... | 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 {
... | 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
m... | 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 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... | 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)... | 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 ... | 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=ty... | 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:... | 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;
... | 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' => \&_boo... | 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... | 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 {
tota... | 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 h... | 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)
... | 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 swall... | 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)))
... | 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<... | 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,_khors... | 509Old lady swallowed a fly | 9java | 04cse |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.