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" ) type xy struct { x, y float64 } type seg struct { p1, p2 xy } type poly struct { name string sides []seg } func inside(pt xy, pg poly) (i bool) { for _, side := range pg.sides { if rayIntersectsSegment(pt, side) { i = !i ...
370Ray-casting algorithm
0go
7y0r2
use strict; use warnings; my $book = do { local (@ARGV, $/) = 'waroftheworlds.txt'; <> }; my (%one, %two); s/^.*?START OF THIS\N*\n//s, s/END OF THIS.*//s, tr/a-zA-Z.!?/ /c, tr/ / /s for $book; my $qr = qr/(\b\w+\b|[.!?])/; $one{$1}{$2}++, $two{$1}{$2}{$3}++ while $book =~ /$qr(?= *$qr *$qr)/g; sub weightedpick ...
373Random sentence from book
2perl
lihc5
import Data.Ratio type Point = (Rational, Rational) type Polygon = [Point] data Line = Sloped {lineSlope, lineYIntercept :: Rational} | Vert {lineXIntercept :: Rational} polygonSides :: Polygon -> [(Point, Point)] polygonSides poly@(p1: ps) = zip poly $ ps ++ [p1] intersects :: Point -> Line -> Bool int...
370Ray-casting algorithm
8haskell
8hc0z
function fileLine (lineNum, fileName) local count = 0 for line in io.lines(fileName) do count = count + 1 if count == lineNum then return line end end error(fileName .. " has fewer than " .. lineNum .. " lines.") end print(fileLine(7, "test.txt"))
369Read a specific line from a file
1lua
r60ga
from urllib.request import urlopen import re from string import punctuation from collections import Counter, defaultdict import random text_url = 'http: text_start = 'No one would have believed' sentence_ending = '.!?' sentence_pausing = ',;:' def read_book(text_url, text_start) -> str: with urlopen(text_url) ...
373Random sentence from book
3python
2nklz
struct configs { char *fullname; char *favouritefruit; rosetta_uint8_t needspeeling; rosetta_uint8_t seedsremoved; char **otherfamily; size_t otherfamily_len; size_t _configs_left_; }; static char ** make_array (size_t * arrlen, const char * src, const size_t buffsize, IniFormat ini_format) { *arrlen = ini_...
374Read a configuration file
5c
vdk2o
package main import ( "fmt" "math" "sort" ) type Range struct{ Lower, Upper float64 } func (r Range) Norm() Range { if r.Lower > r.Upper { return Range{r.Upper, r.Lower} } return r } func (r Range) String() string { return fmt.Sprintf("[%g,%g]", r.Lower, r.Upper) } func (r1 Rang...
372Range consolidation
0go
likcw
import static java.lang.Math.*; public class RayCasting { static boolean intersects(int[] A, int[] B, double[] P) { if (A[1] > B[1]) return intersects(B, A, P); if (P[1] == A[1] || P[1] == B[1]) P[1] += 0.0001; if (P[1] > B[1] || P[1] < A[1] || P[0] >= max(A[0], B...
370Ray-casting algorithm
9java
e5za5
package main import ( "fmt" "sort" ) type rankable interface { Len() int RankEqual(int, int) bool } func StandardRank(d rankable) []float64 { r := make([]float64, d.Len()) var k int for i := range r { if i == 0 || !d.RankEqual(i, i-1) { k = i + 1 } r[i] = float64(k) } return r } func ModifiedRank(...
371Ranking methods
0go
98hmt
import Data.List (intercalate, maximumBy, sort) import Data.Ord (comparing) consolidated :: [(Float, Float)] -> [(Float, Float)] consolidated = foldr go [] . sort . fmap ab where go xy [] = [xy] go xy@(x, y) abetc@((a, b): etc) | y >= b = xy: etc | y >= a = (x, b): etc | otherwise = xy: a...
372Range consolidation
8haskell
1vnps
function contains(bounds, lat, lng) {
370Ray-casting algorithm
10javascript
0j9sz
(ns read-conf-file.core (:require [clojure.java.io:as io] [clojure.string:as str]) (:gen-class)) (def conf-keys ["fullname" "favouritefruit" "needspeeling" "seedsremoved" "otherfamily"]) (defn get-lines "Read file returning vec of lines...
374Read a configuration file
6clojure
r6eg2
package main import ( "fmt" "math" "sort" "time" ) type term struct { coeff uint64 ix1, ix2 int8 } const maxDigits = 19 func toUint64(digits []int8, reverse bool) uint64 { sum := uint64(0) if !reverse { for i := 0; i < len(digits); i++ { sum = sum*10 + uint64(d...
375Rare numbers
0go
0jzsk
import Data.List (groupBy, sortBy, intercalate) type Item = (Int, String) type ItemList = [Item] type ItemGroups = [ItemList] type RankItem a = (a, Int, String) type RankItemList a = [RankItem a] prepare :: ItemList -> ItemGroups prepare = groupBy gf . sortBy (flip compare) where gf (a, _) (b, _) = a == b ...
371Ranking methods
8haskell
blik2
int main(void) { unsigned char buf[4]; unsigned long v; FILE *fin; if ((fin = fopen(RANDOM_PATH, )) == NULL) { fprintf(stderr, , RANDOM_PATH); return EXIT_FAILURE; } if (fread(buf, 1, sizeof buf, fin) != sizeof buf) { fprin...
376Random number generator (device)
5c
g3p45
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; public class RangeConsolidation { public static void main(String[] args) { displayRanges( Arrays.asList(new Range(1.1, 2.2))); displayRanges( Arrays.asList(new Ran...
372Range consolidation
9java
7yqrj
import java.lang.Double.MAX_VALUE import java.lang.Double.MIN_VALUE import java.lang.Math.abs data class Point(val x: Double, val y: Double) data class Edge(val s: Point, val e: Point) { operator fun invoke(p: Point) : Boolean = when { s.y > e.y -> Edge(e, s).invoke(p) p.y == s.y || p.y == e.y -> ...
370Ray-casting algorithm
11kotlin
kcih3
typedef struct point_tag { double x; double y; } point_t; double perpendicular_distance(point_t p, point_t p1, point_t p2) { double dx = p2.x - p1.x; double dy = p2.y - p1.y; double d = sqrt(dx * dx + dy * dy); return fabs(p.x * dy - p.y * dx + p2.x * p1.y - p2.y * p1.x)/d; } size_t douglas...
377Ramer-Douglas-Peucker line simplification
5c
2nrlo
package main import ( "fmt" "math" "rcu" "time" ) var count []int func primeCounter(limit int) { count = make([]int, limit) for i := 0; i < limit; i++ { count[i] = 1 } if limit > 0 { count[0] = 0 } if limit > 1 { count[1] = 0 } for i := 4; i < l...
378Ramanujan primes/twins
0go
r6bgm
double drand() { return (rand()+1.0)/(RAND_MAX+1.0); } double random_normal() { return sqrt(-2*log(drand())) * cos(2*M_PI*drand()); } int main() { int i; double rands[1000]; for (i=0; i<1000; i++) rands[i] = 1.0 + 0.5*random_normal(); return 0; }
379Random numbers
5c
jmp70
import java.time.Duration; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; public class RareNumbers { ...
375Rare numbers
9java
zw2tq
import java.util.*; public class RankingMethods { final static String[] input = {"44 Solomon", "42 Jason", "42 Errol", "41 Garry", "41 Bernard", "41 Barry", "39 Stephen"}; public static void main(String[] args) { int len = input.length; Map<String, int[]> map = new TreeMap<>((a, b) -...
371Ranking methods
9java
g3x4m
(() => { 'use strict'; const main = () => {
372Range consolidation
10javascript
p2ib7
package main import ( "fmt" "github.com/ALTree/bigfloat" "math/big" ) const ( prec = 256
380Ramanujan's constant
0go
m0lyi
use strict; use warnings; use ntheory <ramanujan_primes nth_ramanujan_prime>; sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r } my $rp = ramanujan_primes nth_ramanujan_prime 1_000_000; for my $limit (1e5, 1e6) { printf "The%sth Ramanujan prime is%s\n", comma($limit), comma $rp->[$limit-1]; ...
378Ramanujan primes/twins
2perl
zw9tb
int main() { int i; srand(time(NULL)); for (i = 0; i < 10; i++) puts((rand() % 2) ? : ); return 0; }
381Random number generator (included)
5c
ibdo2
(function () { var xs = 'Solomon Jason Errol Garry Bernard Barry Stephen'.split(' '), ns = [44, 42, 42, 41, 41, 41, 39], sorted = xs.map(function (x, i) { return { name: x, score: ns[i] }; }).sort(function (a, b) { var c = b.score - a.score; return c ? c...
371Ranking methods
10javascript
kcohq
int randInt(int low, int high) { return (rand() % (high - low)) + low; } void shuffle(int *const array, const int n) { if (n > 1) { int i; for (i = 0; i < n - 1; i++) { int j = randInt(i, n); int t = array[i]; array[i] = array[j]; array[j] = t; ...
382Random Latin squares
5c
vdu2o
function Point(x,y) return {x=x, y=y} end function Polygon(name, points) local function contains(self, p) local odd, eps = false, 1e-9 local function rayseg(p, a, b) if a.y > b.y then a, b = b, a end if p.y == a.y or p.y == b.y then p.y = p.y + eps end if p.y < a.y or p.y > b.y or p.x > mat...
370Ray-casting algorithm
1lua
blnka
import Control.Monad (forM_) import Data.Number.CReal (CReal, showCReal) import Text.Printf (printf) ramfun :: CReal -> CReal ramfun x = exp (pi * sqrt x) ramanujan :: CReal ramanujan = ramfun 163 heegners :: [Int] heegners = [19, 43, 67, 163] intDist :: CReal -> CReal intDist x = abs (x - fromIntegral (round x)...
380Ramanujan's constant
8haskell
kc1h0
(import '(java.util Random)) (def normals (let [r (Random.)] (take 1000 (repeatedly #(-> r .nextGaussian (* 0.5) (+ 1.0))))))
379Random numbers
6clojure
1vxpy
# Show random integer from 0 to 9999. string(RANDOM LENGTH 4 ALPHABET 0123456789 number) math(EXPR number "${number} + 0") # Remove extra leading 0s. message(STATUS ${number})
381Random number generator (included)
6clojure
zw6tj
import java.time.Duration import java.time.LocalDateTime import kotlin.math.sqrt class Term(var coeff: Long, var ix1: Byte, var ix2: Byte) const val maxDigits = 16 fun toLong(digits: List<Byte>, reverse: Boolean): Long { var sum: Long = 0 if (reverse) { var i = digits.size - 1 while (i >= 0) ...
375Rare numbers
11kotlin
ibyo4
int main() { int n1, n2, n3; printf( , 163 ); scanf( , &n1 ); printf( , 163 ); scanf( , &n2 ); printf( , 163 ); scanf( , &n3 ); if ( n1 >= n2 && n1 >= n3 ) printf( , n1 ); else if ( n2 > n3 ) printf( , n2 ); else printf( , n3 ); ...
383Read a file line by line
5c
989m1
fun <T> consolidate(ranges: Iterable<ClosedRange<T>>): List<ClosedRange<T>> where T: Comparable<T> { return ranges .sortedWith(compareBy({ it.start }, { it.endInclusive })) .asReversed() .fold(mutableListOf<ClosedRange<T>>()) { consolidatedRanges, range -> if (consoli...
372Range consolidation
11kotlin
uf1vc
while (<>) { $. == $n and print, exit } die "file too short\n";
369Read a specific line from a file
2perl
npuiw
package main import ( "fmt" "os" "regexp" "strconv" )
384Quoting constructs
0go
avp1f
import java.math.BigDecimal; import java.math.MathContext; import java.util.Arrays; import java.util.List; public class RamanujanConstant { public static void main(String[] args) { System.out.printf("Ramanujan's Constant to 100 digits =%s%n%n", ramanujanConstant(163, 100)); System.out.printf("Heeg...
380Ramanujan's constant
9java
4z758
int get_list(const char *, char **); int get_rnge(const char *, char **); void add_number(int x); int add_range(int x, int y); int get_list(const char *s, char **e) { int x; while (1) { skip_space; if (!get_rnge(s, e) && !get_number(x, s, e)) break; s = *e; skip_space; if ((*s) == '\0') { putchar('\n'...
385Range expansion
5c
4tv5t
use strict; use warnings; use List::Util qw(min max); sub consolidate { our @arr; local *arr = shift; my @sorted = sort { @$a[0] <=> @$b[0] } map { [sort { $a <=> $b } @$_] } @arr; my @merge = shift @sorted; for my $i (@sorted) { if ($merge[-1][1] >= @$i[0]) { $merge[-1][0] = min($...
372Range consolidation
2perl
8hm0w
package main import ( "crypto/rand" "encoding/binary" "fmt" "io" "os" ) func main() { testRandom("crypto/rand", rand.Reader) testRandom("dev/random", newDevRandom()) } func newDevRandom() (f *os.File) { var err error if f, err = os.Open("/dev/random"); err != nil { panic(e...
376Random number generator (device)
0go
ib6og
<?php $DOCROOT = $_SERVER['DOCUMENT_ROOT']; function fileLine ($lineNum, $file) { $count = 0; while (!feof($file)) { $count++; $line = fgets($file); if ($count == $lineNum) return $line; } die(.$lineNum.); } @ $fp = fopen(, 'r'); if (!$fp) die(); echo fileLine(7, $fp); ...
369Read a specific line from a file
12php
7y8rp
s1 = "This is a double-quoted 'string' with embedded single-quotes." s2 = 'This is a single-quoted "string" with embedded double-quotes.' s3 = "this is a double-quoted \"string\" with escaped double-quotes." s4 = 'this is a single-quoted \'string\' with escaped single-quotes.' s5 = [[This is a long-bracket "'string'" w...
384Quoting constructs
1lua
qgwx0
null
371Ranking methods
11kotlin
2npli
def rng = new java.security.SecureRandom()
376Random number generator (device)
7groovy
qrdxp
#!/usr/bin/env runhaskell import System.Entropy import Data.Binary.Get import qualified Data.ByteString.Lazy as B main = do bytes <- getEntropy 4 print (runGet getWord32be $ B.fromChunks [bytes])
376Random number generator (device)
8haskell
vdj2k
use strict; use List::Util qw(max min); sub point_in_polygon { my ( $point, $polygon ) = @_; my $count = 0; foreach my $side ( @$polygon ) { $count++ if ray_intersect_segment($point, $side); } return ($count % 2 == 0) ? 0 : 1; } my $eps = 0.0001; my $inf = 1e600; sub ray_intersect_segment { ...
370Ray-casting algorithm
2perl
3xrzs
package main import ( "fmt" "math" ) type point struct{ x, y float64 } func RDP(l []point, float64) []point { x := 0 dMax := -1. last := len(l) - 1 p1 := l[0] p2 := l[last] x21 := p2.x - p1.x y21 := p2.y - p1.y for i, p := range l[1:last] { if d := math.Abs(y21*p.x - ...
377Ramer-Douglas-Peucker line simplification
0go
qrnxz
use strict; use warnings; use Math::AnyNum; sub ramanujan_const { my ($x, $decimals) = @_; $x = Math::AnyNum->new($x); my $prec = (Math::AnyNum->pi * $x->sqrt)/log(10) + $decimals + 1; local $Math::AnyNum::PREC = 4*$prec->round->numify; exp(Math::AnyNum->pi * $x->sqrt)->round(-$decimals)->stringi...
380Ramanujan's constant
2perl
qr8x6
(with-open [r (clojure.java.io/reader "some-file.txt")] (doseq [l (line-seq r)] (println l)))
383Read a file line by line
6clojure
ufuvi
import java.security.SecureRandom; public class RandomExample { public static void main(String[] args) { SecureRandom rng = new SecureRandom(); System.out.println(rng.nextInt()); } }
376Random number generator (device)
9java
ysu6g
size_t rprint(char *s, int *x, int len) { int i, j; char *a = s; for (i = j = 0; i < len; i = ++j) { for (; j < len - 1 && x[j + 1] == x[j] + 1; j++); if (i + 1 < j) a += snprintf(s?a:s, ol, , sep, x[i], x[j]); else while (i <= j) a += snprintf(s?a:s, ol, , sep, x[i++]); } return a - s; } int...
386Range extraction
5c
5fluk
use strict; use warnings; use integer; my $count = 0; my @squares; for my $large ( 0 .. 1e5 ) { my $largesquared = $squares[$large] = $large * $large; for my $small ( 0 .. $large - 1 ) { my $n = $largesquared + $squares[$small]; 2 * $large * $small == reverse $n or next; printf "%12s%s\n", $n, ...
375Rare numbers
2perl
r6agd
(defn split [s sep] (defn skipFirst [[x & xs:as s]] (cond (empty? s) [nil nil] (= x sep) [x xs] true [nil s])) (loop [lst '(), s s] (if (empty? s) (reverse lst) (let [[hd trunc] (skipFirst s) [word news] (split-with #(not= % sep) trunc) cWord (cons hd word)] ...
385Range expansion
6clojure
hmrjr
def normalize(s): return sorted(sorted(bounds) for bounds in s if bounds) def consolidate(ranges): norm = normalize(ranges) for i, r1 in enumerate(norm): if r1: for r2 in norm[i+1:]: if r2 and r1[-1] >= r2[0]: r1[:] = [r1[0], max(r1[-1], r2[-1])]...
372Range consolidation
3python
ok981
null
376Random number generator (device)
11kotlin
fa9do
package main import ( "fmt" "math/rand" "time" ) type matrix [][]int func shuffle(row []int, n int) { rand.Shuffle(n, func(i, j int) { row[i], row[j] = row[j], row[i] }) } func latinSquare(n int) { if n <= 0 { fmt.Println("[]\n") return } latin := make(matrix,...
382Random Latin squares
0go
s70qa
<?php function contains($bounds, $lat, $lng) { $count = 0; $bounds_count = count($bounds); for ($b = 0; $b < $bounds_count; $b++) { $vertex1 = $bounds[$b]; $vertex2 = $bounds[($b + 1) % $bounds_count]; if (west($vertex1, $vertex2, $lng, $lat)) $count++; } return...
370Ray-casting algorithm
12php
p2dba
import javafx.util.Pair; import java.util.ArrayList; import java.util.List; public class LineSimplification { private static class Point extends Pair<Double, Double> { Point(Double key, Double value) { super(key, value); } @Override public String toString() { ...
377Ramer-Douglas-Peucker line simplification
9java
famdv
from mpmath import mp heegner = [19,43,67,163] mp.dps = 50 x = mp.exp(mp.pi*mp.sqrt(163)) print(.format(x)) print() for i in heegner: print(.format(str(i),mp.exp(mp.pi*mp.sqrt(i)),round(mp.exp(mp.pi*mp.sqrt(i))),(mp.pi*mp.sqrt(i)) - round(mp.pi*mp.sqrt(i))))
380Ramanujan's constant
3python
s7oq9
import Data.List (permutations, (\\)) latinSquare :: Eq a => [a] -> [a] -> [[a]] latinSquare [] [] = [] latinSquare c r | head r /= head c = [] | otherwise = reverse <$> foldl addRow firstRow perms where perms = tail $ fmap (fmap . (:) <*> (permutations . (r \\) . return)) ...
382Random Latin squares
8haskell
98cmo
with open('xxx.txt') as f: for i, line in enumerate(f): if i == 6: break else: print('Not 7 lines in file') line = None
369Read a specific line from a file
3python
d15n1
> seven <- scan('hw.txt', '', skip = 6, nlines = 1, sep = '\n') Read 0 items > seven <- scan('Incoming/quotes.txt', '', skip = 6, nlines = 1, sep = '\n') Read 1 item
369Read a specific line from a file
13r
8hl0x
let pointType; const RDP = (l, eps) => { const last = l.length - 1; const p1 = l[0]; const p2 = l[last]; const x21 = p2.x - p1.x; const y21 = p2.y - p1.y; const [dMax, x] = l.slice(1, last) .map(p => Math.abs(y21 * p.x - x21 * p.y + p2.x * p1.y - p2.y * p1.x)) .reduce((p, c, i) => { c...
377Ramer-Douglas-Peucker line simplification
10javascript
ysv6r
setrand(3) random(6)+1 \\ chosen by fair dice roll. \\ guaranteed to the random.
381Random number generator (included)
0go
g374n
from math import floor, sqrt from datetime import datetime def main(): start = datetime.now() for i in xrange(1, 10 ** 11): if rare(i): print , i end = datetime.now() print , end - start def is_square(n): s = floor(sqrt(n + 0.5)) return s * s == n def reverse(n): return int(str(n)[::-1]) def is_palindro...
375Rare numbers
3python
7yerm
import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Objects; public class RandomLatinSquares { private static void printSquare(List<List<Integer>> latin) { for (List<Integer> row : latin) { Iterator<Integer> it = row.itera...
382Random Latin squares
9java
tezf9
require include BigMath e, pi = E(200), PI(200) [19, 43, 67, 163].each do |x| puts F end
380Ramanujan's constant
14ruby
8hn01
setrand(3) random(6)+1 \\ chosen by fair dice roll. \\ guaranteed to the random.
381Random number generator (included)
7groovy
2nulv
setrand(3) random(6)+1 \\ chosen by fair dice roll. \\ guaranteed to the random.
381Random number generator (included)
8haskell
s78qk
use std::fmt::{Display, Formatter};
372Range consolidation
15rust
d12ny
class Latin { constructor(size = 3) { this.size = size; this.mst = [...Array(this.size)].map((v, i) => i + 1); this.square = Array(this.size).fill(0).map(() => Array(this.size).fill(0)); if (this.create(0, 0)) { console.table(this.square); } } create(c, r) { const d = [...this.mst]...
382Random Latin squares
10javascript
m09yv
from collections import namedtuple from pprint import pprint as pp import sys Pt = namedtuple('Pt', 'x, y') Edge = namedtuple('Edge', 'a, b') Poly = namedtuple('Poly', 'name, edges') _eps = 0.00001 _huge = sys.float_info.max _tiny = sys.float_info.min def rayintersectseg(p, edge): '...
370Ray-casting algorithm
3python
6q73w
int qselect(int *v, int len, int k) { int i, st, tmp; for (st = i = 0; i < len - 1; i++) { if (v[i] > v[len-1]) continue; SWAP(i, st); st++; } SWAP(len-1, st); return k == st ?v[st] :st > k ? qselect(v, st, k) : qselect(v + st, len - st, k - st); } int main(void) { int x[] = {9, 8, 7, 6, 5, 0, ...
387Quickselect algorithm
5c
qg1xc
null
377Ramer-Douglas-Peucker line simplification
11kotlin
8ht0q
(use '[flatland.useful.seq:only (partition-between)]) (defn nonconsecutive? [[x y]] (not= (inc x) y)) (defn string-ranges [coll] (let [left (first coll) size (count coll)] (cond (> size 2) (str left "-" (last coll)) (= size 2) (str left "," (last coll)) :else (str left)))) (defn form...
386Range extraction
6clojure
jy47m
setrand(3) random(6)+1 \\ chosen by fair dice roll. \\ guaranteed to the random.
381Random number generator (included)
9java
1vep2
setrand(3) random(6)+1 \\ chosen by fair dice roll. \\ guaranteed to the random.
381Random number generator (included)
10javascript
qr0x8
use Crypt::Random::Seed; my $source = Crypt::Random::Seed->new( NonBlocking => 1 ); print "$_\n" for $source->random_values(10);
376Random number generator (device)
2perl
h9wjl
typealias matrix = MutableList<MutableList<Int>> fun printSquare(latin: matrix) { for (row in latin) { println(row) } println() } fun latinSquare(n: Int) { if (n <= 0) { println("[]") return } val latin = MutableList(n) { MutableList(n) { it } }
382Random Latin squares
11kotlin
oki8z
point_in_polygon <- function(polygon, p) { count <- 0 for(side in polygon) { if ( ray_intersect_segment(p, side) ) { count <- count + 1 } } if ( count%% 2 == 1 ) "INSIDE" else "OUTSIDE" } ray_intersect_segment <- function(p, side) { eps <- 0.0001 a <- side$A b <- side$B if ( a$y...
370Ray-casting algorithm
13r
fa5dc
setrand(3) random(6)+1 \\ chosen by fair dice roll. \\ guaranteed to the random.
381Random number generator (included)
11kotlin
jmk7r
my %scores = ( 'Solomon' => 44, 'Jason' => 42, 'Errol' => 42, 'Garry' => 41, 'Bernard' => 41, 'Barry' => 41, 'Stephen' => 39 ); sub tiers { my(%s) = @_; my(%h); push @{$h{$s{$_}}}, $_ for keys %s; @{\%h}{reverse sort keys %h}; } sub standard { my(%s) = @_; my($resul...
371Ranking methods
2perl
s7yq3
int main() { int i; FIFOList head; TAILQ_INIT(&head); for(i=0; i < 20; i++) { m_enqueue(i, &head); } while( m_dequeue(&i, &head) ) printf(, i); fprintf(stderr, , ( m_dequeue(&i, &head) ) ? : ); exit(0); }
388Queue/Usage
5c
3wiza
use strict; use warnings; use feature 'say'; use List::MoreUtils qw(firstidx minmax); my $epsilon = 1; sub norm { my(@list) = @_; my $sum; $sum += $_**2 for @list; sqrt($sum) } sub perpendicular_distance { our(@start,@end,@point); local(*start,*end,*point) = (shift, shift, shift); return ...
377Ramer-Douglas-Peucker line simplification
2perl
4zk5d
setrand(3) random(6)+1 \\ chosen by fair dice roll. \\ guaranteed to the random.
381Random number generator (included)
1lua
h9bj8
package config import ( "errors" "io" "fmt" "bytes" "strings" "io/ioutil" ) var ( ENONE = errors.New("Requested value does not exist") EBADTYPE = errors.New("Requested type and actual type do not match") EBADVAL = errors.New("Value and type do not match") ) type varError struct { err error n string ...
374Read a configuration file
0go
s7zqa
import random rand = random.SystemRandom() rand.randint(1,10)
376Random number generator (device)
3python
kcxhf
seventh_line = open().each_line.take(7).last
369Read a specific line from a file
14ruby
tegf2
def config = [:] def loadConfig = { File file -> String regex = /^(;{0,1})\s*(\S+)\s*(.*)$/ file.eachLine { line -> (line =~ regex).each { matcher, invert, key, value -> if (key == '' || key.startsWith("#")) return parts = value ? value.split(/\s*,\s*/): (invert ? [false]: [true]...
374Read a configuration file
7groovy
aui1p
Term = Struct.new(:coeff, :ix1, :ix2) do end MAX_DIGITS = 16 def toLong(digits, reverse) sum = 0 if reverse then i = digits.length - 1 while i >=0 sum = sum *10 + digits[i] i = i - 1 end else i = 0 while i < digits.length sum = s...
375Rare numbers
14ruby
h9xjx
use strict; use warnings; use feature 'say'; use List::Util 'shuffle'; sub random_ls { my($n) = @_; my(@cols,@symbols,@ls_sym); my @ls = [0,]; for my $i (1..$n-1) { @{$ls[$i]} = @{$ls[0]}; splice(@{$ls[$_]}, $_, 0, $i) for 0..$i; } @cols = shuffle 0..$n-1; @ls = ...
382Random Latin squares
2perl
g3r4e
use std::fs::File; use std::io::BufRead; use std::io::BufReader; use std::io::Error; use std::path::Path; fn main() { let path = Path::new("file.txt"); let line_num = 7usize; let line = get_line_at(&path, line_num - 1); println!("{}", line.unwrap()); } fn get_line_at(path: &Path, line_num: usize) -> R...
369Read a specific line from a file
15rust
zwrto
val lines = io.Source.fromFile("input.txt").getLines val seventhLine = lines drop(6) next
369Read a specific line from a file
16scala
ysh63
function perpendicular_distance(array $pt, array $line) { $dx = $line[1][0] - $line[0][0]; $dy = $line[1][1] - $line[0][1]; $mag = sqrt($dx * $dx + $dy * $dy); if ($mag > 0) { $dx /= $mag; $dy /= $mag; } $pvx = $pt[0] - $line[0][0]; $pvy = $pt[1] - $line[0][1]; $pvdot = $dx * $pvx + $dy *...
377Ramer-Douglas-Peucker line simplification
12php
ib3ov
import Data.Char import Data.List import Data.List.Split main :: IO () main = readFile "config" >>= (print . parseConfig) parseConfig :: String -> Config parseConfig = foldr addConfigValue defaultConfig . clean . lines where clean = filter (not . flip any ["#", ";", "", " "] . (==) . take 1) addConfigValue :: St...
374Read a configuration file
8haskell
98rmo
use itertools::Itertools; use std::collections::HashMap; use std::convert::TryInto; use std::fmt; use std::time::Instant; #[derive(Debug)] struct RareResults { digits: u8, time_to_find: u128, counter: u32, number: u64, } impl fmt::Display for RareResults { fn fmt(&self, f: &mut fmt::Formatter) -> ...
375Rare numbers
15rust
kcqh5
def mc_rank(iterable, start=1): lastresult, fifo = None, [] for n, item in enumerate(iterable, start-1): if item[0] == lastresult: fifo += [item] else: while fifo: yield n, fifo.pop(0) lastresult, fifo = item[0], fifo + [item] while fi...
371Ranking methods
3python
0jmsq
use utf8; binmode STDOUT, ":utf8"; print reverse('visor'), "\n"; print join("", reverse "Jos" =~ /\X/g), "\n"; $string = ' '; print join("", reverse $string =~ /\X/g), "\n";
366Reverse a string
2perl
5t0u2
require 'securerandom' SecureRandom.random_number(1 << 32) p (1..10).to_a.sample(3, random: SecureRandom)
376Random number generator (device)
14ruby
p2sbh