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 } } return } func rayIntersectsSegment(p xy, s seg) bool { var a, b xy if s.p1.y < s.p2.y { a, b = s.p1, s.p2 } else { a, b = s.p2, s.p1 } for p.y == a.y || p.y == b.y { p.y = math.Nextafter(p.y, math.Inf(1)) } if p.y < a.y || p.y > b.y { return false } if a.x > b.x { if p.x > a.x { return false } if p.x < b.x { return true } } else { if p.x > b.x { return false } if p.x < a.x { return true } } return (p.y-a.y)/(p.x-a.x) >= (b.y-a.y)/(b.x-a.x) } var ( p1 = xy{0, 0} p2 = xy{10, 0} p3 = xy{10, 10} p4 = xy{0, 10} p5 = xy{2.5, 2.5} p6 = xy{7.5, 2.5} p7 = xy{7.5, 7.5} p8 = xy{2.5, 7.5} p9 = xy{0, 5} p10 = xy{10, 5} p11 = xy{3, 0} p12 = xy{7, 0} p13 = xy{7, 10} p14 = xy{3, 10} ) var tpg = []poly{ {"square", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1}}}, {"square hole", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1}, {p5, p6}, {p6, p7}, {p7, p8}, {p8, p5}}}, {"strange", []seg{{p1, p5}, {p5, p4}, {p4, p8}, {p8, p7}, {p7, p3}, {p3, p2}, {p2, p5}}}, {"exagon", []seg{{p11, p12}, {p12, p10}, {p10, p13}, {p13, p14}, {p14, p9}, {p9, p11}}}, } var tpt = []xy{
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 { my $href = shift; my @weightedpick = map { ($_) x $href->{$_} } keys %$href; $weightedpick[rand @weightedpick]; } sub sentence { my @sentence = qw( . ! ? )[rand 3]; push @sentence, weightedpick( $one{ $sentence[0] } ); push @sentence, weightedpick( $two{ $sentence[-2] }{ $sentence[-1] } ) while $sentence[-1] =~ /\w/; shift @sentence; "@sentence\n\n" =~ s/\w\K (?=[st]\b)/'/gr =~ s/ (?=[.!?]\n)//r =~ s/.{60,}?\K /\n/gr; } print sentence() for 1 .. 10;
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 intersects (px, _) (Vert xint) = px <= xint intersects (px, py) (Sloped m b) | m < 0 = py <= m * px + b | otherwise = py >= m * px + b onLine :: Point -> Line -> Bool onLine (px, _) (Vert xint) = px == xint onLine (px, py) (Sloped m b) = py == m * px + b carrier :: (Point, Point) -> Line carrier ((ax, ay), (bx, by)) | ax == bx = Vert ax | otherwise = Sloped slope yint where slope = (ay - by) / (ax - bx) yint = ay - slope * ax between :: Ord a => a -> a -> a -> Bool between x a b | a > b = b <= x && x <= a | otherwise = a <= x && x <= b inPolygon :: Point -> Polygon -> Bool inPolygon p@(px, py) = f 0 . polygonSides where f n [] = odd n f n (side: sides) | far = f n sides | onSegment = True | rayIntersects = f (n + 1) sides | otherwise = f n sides where far = not $ between py ay by onSegment | ay == by = between px ax bx | otherwise = p `onLine` line rayIntersects = intersects p line && (py /= ay || by < py) && (py /= by || ay < py) ((ax, ay), (bx, by)) = side line = carrier side
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) as book: text = book.read().decode('utf-8') return text[text.index(text_start):] def remove_punctuation(text: str, keep=sentence_ending+sentence_pausing)-> str: to_remove = ''.join(set(punctuation) - set(keep)) text = text.translate(str.maketrans(to_remove, ' ' * len(to_remove))).strip() text = re.sub(fr, ' ', text) if keep: text = re.sub(f, r, text).strip() if text[-1] not in sentence_ending: text += ' .' return text.lower() def word_follows_words(txt_with_pauses_and_endings): words = ['.'] + txt_with_pauses_and_endings.strip().split() word2next = defaultdict(lambda:defaultdict(int)) word2next2 = defaultdict(lambda:defaultdict(int)) for lh, rh in zip(words, words[1:]): word2next[lh][rh] += 1 for lh, mid, rh in zip(words, words[1:], words[2:]): word2next2[(lh, mid)][rh] += 1 return dict(word2next), dict(word2next2) def gen_sentence(word2next, word2next2) -> str: s = ['.'] s += random.choices(*zip(*word2next[s[-1]].items())) while True: s += random.choices(*zip(*word2next2[(s[-2], s[-1])].items())) if s[-1] in sentence_ending: break s = ' '.join(s[1:]).capitalize() s = re.sub(fr, r'\1', s) s = re.sub(r, , s) s = re.sub(r, , s) s = re.sub(r, , s) return s if __name__ == : txt_with_pauses_and_endings = remove_punctuation(read_book(text_url, text_start)) word2next, word2next2 = word_follows_words(txt_with_pauses_and_endings) sentence = gen_sentence(word2next, word2next2) print(sentence)
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_array_get_length(src, INI_ARRAY_DELIMITER, ini_format); char ** const dest = *arrlen ? (char **) malloc(*arrlen * sizeof(char *) + buffsize) : NULL; if (!dest) { return NULL; } memcpy(dest + *arrlen, src, buffsize); char * iter = (char *) (dest + *arrlen); for (size_t idx = 0; idx < *arrlen; idx++) { dest[idx] = ini_array_release(&iter, INI_ARRAY_DELIMITER, ini_format); ini_string_parse(dest[idx], ini_format); } return dest; } static int configs_member_handler (IniDispatch *this, void *v_confs) { struct configs *confs = (struct configs *) v_confs; if (this->type != INI_KEY) { return 0; } if (ini_string_match_si(, this->data, this->format)) { if (confs->fullname) { return 0; } this->v_len = ini_string_parse(this->value, this->format); confs->fullname = strndup(this->value, this->v_len); confs->_configs_left_--; } else if (ini_string_match_si(, this->data, this->format)) { if (confs->favouritefruit) { return 0; } this->v_len = ini_string_parse(this->value, this->format); confs->favouritefruit = strndup(this->value, this->v_len); confs->_configs_left_--; } else if (ini_string_match_si(, this->data, this->format)) { if (~confs->needspeeling & 0x80) { return 0; } confs->needspeeling = ini_get_bool(this->value, TRUE); confs->_configs_left_--; } else if (ini_string_match_si(, this->data, this->format)) { if (~confs->seedsremoved & 0x80) { return 0; } confs->seedsremoved = ini_get_bool(this->value, TRUE); confs->_configs_left_--; } else if (!confs->otherfamily && ini_string_match_si(, this->data, this->format)) { if (confs->otherfamily) { return 0; } this->v_len = ini_array_collapse(this->value, INI_ARRAY_DELIMITER, this->format); confs->otherfamily = make_array(&confs->otherfamily_len, this->value, this->v_len + 1, this->format); confs->_configs_left_--; } return !confs->_configs_left_; } static int populate_configs (struct configs * confs) { IniFormat config_format = { .delimiter_symbol = INI_ANY_SPACE, .case_sensitive = FALSE, .semicolon_marker = INI_IGNORE, .hash_marker = INI_IGNORE, .multiline_nodes = INI_NO_MULTILINE, .section_paths = INI_NO_SECTIONS, .no_single_quotes = FALSE, .no_double_quotes = FALSE, .no_spaces_in_names = TRUE, .implicit_is_not_empty = TRUE, .do_not_collapse_values = FALSE, .preserve_empty_quotes = FALSE, .disabled_after_space = TRUE, .disabled_can_be_implicit = FALSE }; *confs = (struct configs) { NULL, NULL, 0x80, 0x80, NULL, 0, CONFIGS_TO_READ }; if (load_ini_path(, config_format, NULL, configs_member_handler, confs) & CONFINI_ERROR) { fprintf(stderr, ); return 1; } confs->needspeeling &= 0x7F; confs->seedsremoved &= 0x7F; return 0; } int main () { struct configs confs; ini_global_set_implicit_value(, 0); if (populate_configs(&confs)) { return 1; } printf( , confs.fullname, confs.favouritefruit, confs.needspeeling ? : , confs.seedsremoved ? : ); for (size_t idx = 0; idx < confs.otherfamily_len; idx++) { printf(, idx, confs.otherfamily[idx]); } FREE_NON_NULL(confs.fullname); FREE_NON_NULL(confs.favouritefruit); FREE_NON_NULL(confs.otherfamily); return 0; }
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 Range) Union(r2 Range) []Range { if r1.Upper < r2.Lower { return []Range{r1, r2} } r := Range{r1.Lower, math.Max(r1.Upper, r2.Upper)} return []Range{r} } func consolidate(rs []Range) []Range { for i := range rs { rs[i] = rs[i].Norm() } le := len(rs) if le < 2 { return rs } sort.Slice(rs, func(i, j int) bool { return rs[i].Lower < rs[j].Lower }) if le == 2 { return rs[0].Union(rs[1]) } for i := 0; i < le-1; i++ { for j := i + 1; j < le; j++ { ru := rs[i].Union(rs[j]) if len(ru) == 1 { rs[i] = ru[0] copy(rs[j:], rs[j+1:]) rs = rs[:le-1] le-- i-- break } } } return rs } func main() { rss := [][]Range{ {{1.1, 2.2}}, {{6.1, 7.2}, {7.2, 8.3}}, {{4, 3}, {2, 1}}, {{4, 3}, {2, 1}, {-1, -2}, {3.9, 10}}, {{1, 3}, {-6, -1}, {-4, -5}, {8, 2}, {-6, -6}}, } for _, rs := range rss { s := fmt.Sprintf("%v", rs) fmt.Printf("%40s => ", s[1:len(s)-1]) rs2 := consolidate(rs) s = fmt.Sprintf("%v", rs2) fmt.Println(s[1 : len(s)-1]) } }
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[0])) return false; if (P[0] < min(A[0], B[0])) return true; double red = (P[1] - A[1]) / (double) (P[0] - A[0]); double blue = (B[1] - A[1]) / (double) (B[0] - A[0]); return red >= blue; } static boolean contains(int[][] shape, double[] pnt) { boolean inside = false; int len = shape.length; for (int i = 0; i < len; i++) { if (intersects(shape[i], shape[(i + 1) % len], pnt)) inside = !inside; } return inside; } public static void main(String[] a) { double[][] testPoints = {{10, 10}, {10, 16}, {-20, 10}, {0, 10}, {20, 10}, {16, 10}, {20, 20}}; for (int[][] shape : shapes) { for (double[] pnt : testPoints) System.out.printf("%7s ", contains(shape, pnt)); System.out.println(); } } final static int[][] square = {{0, 0}, {20, 0}, {20, 20}, {0, 20}}; final static int[][] squareHole = {{0, 0}, {20, 0}, {20, 20}, {0, 20}, {5, 5}, {15, 5}, {15, 15}, {5, 15}}; final static int[][] strange = {{0, 0}, {5, 5}, {0, 20}, {5, 15}, {15, 15}, {20, 20}, {20, 0}}; final static int[][] hexagon = {{6, 0}, {14, 0}, {20, 10}, {14, 20}, {6, 20}, {0, 10}}; final static int[][][] shapes = {square, squareHole, strange, hexagon}; }
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(d rankable) []float64 { r := make([]float64, d.Len()) for i := range r { k := i + 1 for j := i + 1; j < len(r) && d.RankEqual(i, j); j++ { k = j + 1 } r[i] = float64(k) } return r } func DenseRank(d rankable) []float64 { r := make([]float64, d.Len()) var k int for i := range r { if i == 0 || !d.RankEqual(i, i-1) { k++ } r[i] = float64(k) } return r } func OrdinalRank(d rankable) []float64 { r := make([]float64, d.Len()) for i := range r { r[i] = float64(i + 1) } return r } func FractionalRank(d rankable) []float64 { r := make([]float64, d.Len()) for i := 0; i < len(r); { var j int f := float64(i + 1) for j = i + 1; j < len(r) && d.RankEqual(i, j); j++ { f += float64(j + 1) } f /= float64(j - i) for ; i < j; i++ { r[i] = f } } return r } type scores []struct { score int name string } func (s scores) Len() int { return len(s) } func (s scores) RankEqual(i, j int) bool { return s[i].score == s[j].score } func (s scores) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s scores) Less(i, j int) bool { if s[i].score != s[j].score { return s[i].score > s[j].score } return s[i].name < s[j].name } var data = scores{ {44, "Solomon"}, {42, "Jason"}, {42, "Errol"}, {41, "Garry"}, {41, "Bernard"}, {41, "Barry"}, {39, "Stephen"}, } func main() { show := func(name string, fn func(rankable) []float64) { fmt.Println(name, "Ranking:") r := fn(data) for i, d := range data { fmt.Printf("%4v -%2d%s\n", r[i], d.score, d.name) } } sort.Sort(data) show("Standard", StandardRank) show("\nModified", ModifiedRank) show("\nDense", DenseRank) show("\nOrdinal", OrdinalRank) show("\nFractional", FractionalRank) }
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: abetc ab (a, b) | a <= b = (a, b) | otherwise = (b, a) tests :: [[(Float, Float)]] tests = [ [], [(1.1, 2.2)], [(6.1, 7.2), (7.2, 8.3)], [(4, 3), (2, 1)], [(4, 3), (2, 1), (-1, -2), (3.9, 10)], [(1, 3), (-6, -1), (-4, -5), (8, 2), (-6, -6)] ] main :: IO () main = putStrLn $ tabulated "Range consolidations:" showPairs showPairs consolidated tests tabulated :: String -> (a -> String) -> (b -> String) -> (a -> b) -> [a] -> String tabulated s xShow fxShow f xs = let w = length $ maximumBy (comparing length) (xShow <$> xs) rjust n c s = drop (length s) (replicate n c <> s) in unlines $ s: fmap ( ((<>) . rjust w ' ' . xShow) <*> ((" -> " <>) . fxShow . f) ) xs showPairs :: [(Float, Float)] -> String showPairs xs | null xs = "[]" | otherwise = '[': intercalate ", " (showPair <$> xs) <> "]" showPair :: (Float, Float) -> String showPair (a, b) = '(': showNum a <> ", " <> showNum b <> ")" showNum :: Float -> String showNum n | 0 == (n - fromIntegral (round n)) = show (round n) | otherwise = show n
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." [file] (try (with-open [rdr (io/reader file)] (into [] (line-seq rdr))) (catch Exception e (.getMessage e)))) (defn parse-line "Parse passed line returning vec: token, vec of values." [line] (if-let [[_ k v] (re-matches #"(?i)^\s*([a-z]+)(?:\s+|=)?(.+)?$" line)] (let [k (str/lower-case k)] (if v [k (str/split v #",\s*")] [k [true]])))) (defn mk-conf "Build configuration map from lines." [lines] (->> (map parse-line lines) (filter (comp not nil?)) (reduce (fn [m [k v]] (assoc m k v)) {}))) (defn output [conf-keys conf] (doseq [k conf-keys] (let [v (get conf k)] (if v (println (format "%s =%s" k (str/join ", " v))) (println (format "%s =%s" k "false")))))) (defn -main [filename] (output conf-keys (mk-conf (get-lines filename))))
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(digits[i]) } } else { for i := len(digits) - 1; i >= 0; i-- { sum = sum*10 + uint64(digits[i]) } } return sum } func isSquare(n uint64) bool { if 0x202021202030213&(1<<(n&63)) != 0 { root := uint64(math.Sqrt(float64(n))) return root*root == n } return false } func seq(from, to, step int8) []int8 { var res []int8 for i := from; i <= to; i += step { res = append(res, i) } return res } func commatize(n uint64) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } return s } func main() { start := time.Now() pow := uint64(1) fmt.Println("Aggregate timings to process all numbers up to:")
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 rank :: Num a => a -> Item -> RankItem a rank n (a, b) = (n, a, b) standard, modified, dense, ordinal :: ItemGroups -> RankItemList Int standard = ms 1 where ms _ [] = [] ms n (x:xs) = (rank n <$> x) ++ ms (n + length x) xs modified = md 1 where md _ [] = [] md n (x:xs) = let l = length x nl = n + l nl1 = nl - 1 in (rank nl1 <$> x) ++ md (n + l) xs dense = md 1 where md _ [] = [] md n (x:xs) = map (rank n) x ++ md (n + 1) xs ordinal = zipWith rank [1 ..] . concat fractional :: ItemGroups -> RankItemList Double fractional = mf 1.0 where mf _ [] = [] mf n (x:xs) = let l = length x o = take l [n ..] ld = fromIntegral l a = sum o / ld in map (rank a) x ++ mf (n + ld) xs test :: ItemGroups test = prepare [ (44, "Solomon") , (42, "Jason") , (42, "Errol") , (41, "Garry") , (41, "Bernard") , (41, "Barry") , (39, "Stephen") ] nicePrint :: Show a => String -> RankItemList a -> IO () nicePrint xs items = do putStrLn xs mapM_ np items putStr "\n" where np (a, b, c) = putStrLn $ intercalate "\t" [show a, show b, c] main :: IO () main = do nicePrint "Standard:" $ standard test nicePrint "Modified:" $ modified test nicePrint "Dense:" $ dense test nicePrint "Ordinal:" $ ordinal test nicePrint "Fractional:" $ fractional test
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) { fprintf(stderr, , RANDOM_PATH, (unsigned) sizeof buf); return EXIT_FAILURE; } fclose(fin); v = buf[0] | buf[1] << 8UL | buf[2] << 16UL | buf[3] << 24UL; printf(, v); return 0; }
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 Range(6.1, 7.2), new Range(7.2, 8.3))); displayRanges( Arrays.asList(new Range(4, 3), new Range(2, 1))); displayRanges( Arrays.asList(new Range(4, 3), new Range(2, 1), new Range(-1, -2), new Range(3.9, 10))); displayRanges( Arrays.asList(new Range(1, 3), new Range(-6, -1), new Range(-4, -5), new Range(8, 2), new Range(-6, -6))); displayRanges( Arrays.asList(new Range(1, 1), new Range(1, 1))); displayRanges( Arrays.asList(new Range(1, 1), new Range(1, 2))); displayRanges( Arrays.asList(new Range(1, 2), new Range(3, 4), new Range(1.5, 3.5), new Range(1.2, 2.5))); } private static final void displayRanges(List<Range> ranges) { System.out.printf("ranges =%-70s, colsolidated =%s%n", ranges, Range.consolidate(ranges)); } private static final class RangeSorter implements Comparator<Range> { @Override public int compare(Range o1, Range o2) { return (int) (o1.left - o2.left); } } private static class Range { double left; double right; public Range(double left, double right) { if ( left <= right ) { this.left = left; this.right = right; } else { this.left = right; this.right = left; } } public Range consolidate(Range range) {
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 -> invoke(Point(p.x, p.y + epsilon)) p.y > e.y || p.y < s.y || p.x > Math.max(s.x, e.x) -> false p.x < Math.min(s.x, e.x) -> true else -> { val blue = if (abs(s.x - p.x) > MIN_VALUE) (p.y - s.y) / (p.x - s.x) else MAX_VALUE val red = if (abs(s.x - e.x) > MIN_VALUE) (e.y - s.y) / (e.x - s.x) else MAX_VALUE blue >= red } } val epsilon = 0.00001 } class Figure(val name: String, val edges: Array<Edge>) { operator fun contains(p: Point) = edges.count({ it(p) }) % 2 != 0 } object Ray_casting { fun check(figures : Array<Figure>, points : List<Point>) { println("points: " + points) figures.forEach { f -> println("figure: " + f.name) f.edges.forEach { println(" " + it) } println("result: " + (points.map { it in f })) } } }
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_peucker(const point_t* points, size_t n, double epsilon, point_t* dest, size_t destlen) { assert(n >= 2); assert(epsilon >= 0); double max_dist = 0; size_t index = 0; for (size_t i = 1; i + 1 < n; ++i) { double dist = perpendicular_distance(points[i], points[0], points[n - 1]); if (dist > max_dist) { max_dist = dist; index = i; } } if (max_dist > epsilon) { size_t n1 = douglas_peucker(points, index + 1, epsilon, dest, destlen); if (destlen >= n1 - 1) { destlen -= n1 - 1; dest += n1 - 1; } else { destlen = 0; } size_t n2 = douglas_peucker(points + index, n - index, epsilon, dest, destlen); return n1 + n2 - 1; } if (destlen >= 2) { dest[0] = points[0]; dest[1] = points[n - 1]; } return 2; } void print_points(const point_t* points, size_t n) { for (size_t i = 0; i < n; ++i) { if (i > 0) printf(); printf(, points[i].x, points[i].y); } printf(); } int main() { point_t points[] = { {0,0}, {1,0.1}, {2,-0.1}, {3,5}, {4,6}, {5,7}, {6,8.1}, {7,9}, {8,9}, {9,9} }; const size_t len = sizeof(points)/sizeof(points[0]); point_t out[len]; size_t n = douglas_peucker(points, len, 1.0, out, len); print_points(out, n); return 0; }
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 < limit; i += 2 { count[i] = 0 } for p, sq := 3, 9; sq < limit; p += 2 { if count[p] != 0 { for q := sq; q < limit; q += p << 1 { count[q] = 0 } } sq += (p + 1) << 2 } sum := 0 for i := 0; i < limit; i++ { sum += count[i] count[i] = sum } } func primeCount(n int) int { if n < 1 { return 0 } return count[n] } func ramanujanMax(n int) int { fn := float64(n) return int(math.Ceil(4 * fn * math.Log(4*fn))) } func ramanujanPrime(n int) int { if n == 1 { return 2 } for i := ramanujanMax(n); i >= 2*n; i-- { if i%2 == 1 { continue } if primeCount(i)-primeCount(i/2) < n { return i + 1 } } return 0 } func rpc(p int) int { return primeCount(p) - primeCount(p/2) } func main() { for _, limit := range []int{1e5, 1e6} { start := time.Now() primeCounter(1 + ramanujanMax(limit)) rplim := ramanujanPrime(limit) climit := rcu.Commatize(limit) fmt.Printf("The%sth Ramanujan prime is%s\n", climit, rcu.Commatize(rplim)) r := rcu.Primes(rplim) c := make([]int, len(r)) for i := 0; i < len(c); i++ { c[i] = rpc(r[i]) } ok := c[len(c)-1] for i := len(c) - 2; i >= 0; i-- { if c[i] < ok { ok = c[i] } else { c[i] = 0 } } var fr []int for i, r := range r { if c[i] != 0 { fr = append(fr, r) } } twins := 0 for i := 0; i < len(fr)-1; i++ { if fr[i]+2 == fr[i+1] { twins++ } } fmt.Printf("There are%s twins in the first%s Ramanujan primes.\n", rcu.Commatize(twins), climit) fmt.Println("Took", time.Since(start)) fmt.Println() } }
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 { public interface Consumer5<A, B, C, D, E> { void apply(A a, B b, C c, D d, E e); } public interface Consumer7<A, B, C, D, E, F, G> { void apply(A a, B b, C c, D d, E e, F f, G g); } public interface Recursable5<A, B, C, D, E> { void apply(A a, B b, C c, D d, E e, Recursable5<A, B, C, D, E> r); } public interface Recursable7<A, B, C, D, E, F, G> { void apply(A a, B b, C c, D d, E e, F f, G g, Recursable7<A, B, C, D, E, F, G> r); } public static <A, B, C, D, E> Consumer5<A, B, C, D, E> recurse(Recursable5<A, B, C, D, E> r) { return (a, b, c, d, e) -> r.apply(a, b, c, d, e, r); } public static <A, B, C, D, E, F, G> Consumer7<A, B, C, D, E, F, G> recurse(Recursable7<A, B, C, D, E, F, G> r) { return (a, b, c, d, e, f, g) -> r.apply(a, b, c, d, e, f, g, r); } private static class Term { long coeff; byte ix1, ix2; public Term(long coeff, byte ix1, byte ix2) { this.coeff = coeff; this.ix1 = ix1; this.ix2 = ix2; } } private static final int MAX_DIGITS = 16; private static long toLong(List<Byte> digits, boolean reverse) { long sum = 0; if (reverse) { for (int i = digits.size() - 1; i >= 0; --i) { sum = sum * 10 + digits.get(i); } } else { for (Byte digit : digits) { sum = sum * 10 + digit; } } return sum; } private static boolean isNotSquare(long n) { long root = (long) Math.sqrt(n); return root * root != n; } private static List<Byte> seq(byte from, byte to, byte step) { List<Byte> res = new ArrayList<>(); for (byte i = from; i <= to; i += step) { res.add(i); } return res; } private static String commatize(long n) { String s = String.valueOf(n); int le = s.length(); int i = le - 3; while (i >= 1) { s = s.substring(0, i) + "," + s.substring(i); i -= 3; } return s; } public static void main(String[] args) { final LocalDateTime startTime = LocalDateTime.now(); long pow = 1L; System.out.println("Aggregate timings to process all numbers up to:");
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) -> b.compareTo(a)); for (int i = 0; i < len; i++) { String key = input[i].split("\\s+")[0]; int[] arr; if ((arr = map.get(key)) == null) arr = new int[]{i, 0}; arr[1]++; map.put(key, arr); } int[][] groups = map.values().toArray(new int[map.size()][]); standardRanking(len, groups); modifiedRanking(len, groups); denseRanking(len, groups); ordinalRanking(len); fractionalRanking(len, groups); } private static void standardRanking(int len, int[][] groups) { System.out.println("\nStandard ranking"); for (int i = 0, rank = 0, group = 0; i < len; i++) { if (group < groups.length && i == groups[group][0]) { rank = i + 1; group++; } System.out.printf("%d%s%n", rank, input[i]); } } private static void modifiedRanking(int len, int[][] groups) { System.out.println("\nModified ranking"); for (int i = 0, rank = 0, group = 0; i < len; i++) { if (group < groups.length && i == groups[group][0]) rank += groups[group++][1]; System.out.printf("%d%s%n", rank, input[i]); } } private static void denseRanking(int len, int[][] groups) { System.out.println("\nDense ranking"); for (int i = 0, rank = 0; i < len; i++) { if (rank < groups.length && i == groups[rank][0]) rank++; System.out.printf("%d%s%n", rank, input[i]); } } private static void ordinalRanking(int len) { System.out.println("\nOrdinal ranking"); for (int i = 0; i < len; i++) System.out.printf("%d%s%n", i + 1, input[i]); } private static void fractionalRanking(int len, int[][] groups) { System.out.println("\nFractional ranking"); float rank = 0; for (int i = 0, tmp = 0, group = 0; i < len; i++) { if (group < groups.length && i == groups[group][0]) { tmp += groups[group++][1]; rank = (i + 1 + tmp) / 2.0F; } System.out.printf("%2.1f%s%n", rank, input[i]); } } }
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]; printf "There are%s twins in the first%s Ramanujan primes.\n\n", comma( scalar grep { $rp->[$_+1] == $rp->[$_]+2 } 0 .. $limit-2 ), comma $limit; }
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 : a.name < b.name ? -1 : a.name > b.name ? 1 : 0; }), names = sorted.map(function (x) { return x.name; }), scores = sorted.map(function (x) { return x.score; }), reversed = scores.slice(0).reverse(), unique = scores.filter(function (x, i) { return scores.indexOf(x) === i; });
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; } } } void printSquare(const int *const latin, const int n) { int i, j; for (i = 0; i < n; i++) { printf(); for (j = 0; j < n; j++) { if (j > 0) { printf(); } printf(, latin[i * n + j]); } printf(); } printf(); } void latinSquare(const int n) { int *latin, *used; int i, j, k; if (n <= 0) { printf(); return; } latin = (int *)malloc(n * n * sizeof(int)); if (!latin) { printf(); return; } for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { latin[i * n + j] = j; } } shuffle(latin, n); for (i = 1; i < n - 1; i++) { bool shuffled = false; while (!shuffled) { shuffle(&latin[i * n], n); for (k = 0; k < i; k++) { for (j = 0; j < n; j++) { if (latin[k * n + j] == latin[i * n + j]) { goto shuffling; } } } shuffled = true; shuffling: {} } } used = (int *)malloc(n * sizeof(int)); for (j = 0; j < n; j++) { memset(used, 0, n * sizeof(int)); for (i = 0; i < n - 1; i++) { used[latin[i * n + j]] = 1; } for (k = 0; k < n; k++) { if (used[k] == 0) { latin[(n - 1) * n + j] = k; break; } } } free(used); printSquare(latin, n); free(latin); } int main() { srand((unsigned int)time((time_t)0)); latinSquare(5); latinSquare(5); latinSquare(10); return 0; }
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 > math.max(a.x, b.x) then return false end if p.x < math.min(a.x, b.x) then return true end local red = a.x == b.x and math.huge or (b.y-a.y)/(b.x-a.x) local blu = a.x == p.x and math.huge or (p.y-a.y)/(p.x-a.x) return blu >= red end for i, a in ipairs(self.points) do local b = self.points[i%#self.points+1] if rayseg(p, a, b) then odd = not odd end end return odd end return {name=name, points=points, contains=contains} end polygons = { Polygon("square", { Point(0,0), Point(10,0), Point(10,10), Point(0,10) }), Polygon("squarehole", { Point(0,0), Point(10,0), Point(10,10), Point(0,10), Point(2.5,2.5), Point(7.5,2.5), Point(7.5,7.5), Point(2.5,7.5) }), Polygon("strange", { Point(0,0), Point(2.5,2.5), Point(0, 10), Point(2.5,7.5), Point(7.5,7.5), Point(10,10), Point(10,0), Point(2.5,2.5) }), Polygon("hexagon", { Point(3,0), Point(7,0), Point(10,5), Point(7,10), Point(3,10), Point(0,5) }) } points = { Point(5,5), Point(5,8), Point(-10,5), Point(0,5), Point(10,5), Point(8,5), Point(10,10) } for _,poly in ipairs(polygons) do print("Does '"..poly.name.."' contain the point..") for _,pt in ipairs(points) do print(string.format(" (%3.f,%2.f)? %s", pt.x, pt.y, tostring(poly:contains(pt)))) end print() end
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)) main :: IO () main = do let n = 35 printf "Ramanujan's constant:%s\n\n" (showCReal n ramanujan) printf "%3s%34s%20s%s\n\n" " h " "e^(pi*sqrt(h))" "" " Dist. to integer" forM_ heegners $ \h -> let r = ramfun (fromIntegral h) d = intDist r in printf "%3d%54s%s\n" h (showCReal n r) (showCReal 15 d)
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) { sum = sum * 10 + digits[i] i-- } } else { var i = 0 while (i < digits.size) { sum = sum * 10 + digits[i] i++ } } return sum } fun isSquare(n: Long): Boolean { val root = sqrt(n.toDouble()).toLong() return root * root == n } fun seq(from: Byte, to: Byte, step: Byte): List<Byte> { val res = mutableListOf<Byte>() var i = from while (i <= to) { res.add(i) i = (i + step).toByte() } return res } fun commatize(n: Long): String { var s = n.toString() val le = s.length var i = le - 3 while (i >= 1) { s = s.slice(0 until i) + "," + s.substring(i) i -= 3 } return s } fun main() { val startTime = LocalDateTime.now() var pow = 1L println("Aggregate timings to process all numbers up to:")
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 ); getch(); return 0; }
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 (consolidatedRanges.isEmpty()) { consolidatedRanges.add(range) }
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("Heegner numbers yielding 'almost' integers:%n"); List<Integer> heegnerNumbers = Arrays.asList(19, 43, 67, 163); List<Integer> heegnerVals = Arrays.asList(96, 960, 5280, 640320); for ( int i = 0 ; i < heegnerNumbers.size() ; i++ ) { int heegnerNumber = heegnerNumbers.get(i); int heegnerVal = heegnerVals.get(i); BigDecimal integer = BigDecimal.valueOf(heegnerVal).pow(3).add(BigDecimal.valueOf(744)); BigDecimal compute = ramanujanConstant(heegnerNumber, 50); System.out.printf("%3d:%50s ~%18s (diff ~%s)%n", heegnerNumber, compute, integer, integer.subtract(compute, new MathContext(30)).toPlainString()); } } public static BigDecimal ramanujanConstant(int sqrt, int digits) {
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'); return 1; } if ((*s) == ',') { s++; continue; } break; } *(const char **)e = s; printf(, s); return 0; } int get_rnge(const char *s, char **e) { int x, y; char *ee; if (!get_number(x, s, &ee)) return 0; s = ee; skip_space; if (*s != '-') { *(const char **)e = s; return 0; } s++; if(!get_number(y, s, e)) return 0; return add_range(x, y); } void add_number(int x) { printf(, x); } int add_range(int x, int y) { if (y <= x) return 0; while (x <= y) printf(, x++); return 1; } int main() { char *end; if (get_list(, &end)) puts(); get_list(, &end); return 0; }
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($merge[-1][0], @$i[0]); $merge[-1][1] = max($merge[-1][1], @$i[1]); } else { push @merge, $i; } } return @merge; } for my $intervals ( [[1.1, 2.2],], [[6.1, 7.2], [7.2, 8.3]], [[4, 3], [2, 1]], [[4, 3], [2, 1], [-1, -2], [3.9, 10]], [[1, 3], [-6, -1], [-4, -5], [8, 2], [-6, -6]]) { my($in,$out); $in = join ', ', map { '[' . join(', ', @$_) . ']' } @$intervals; $out .= join('..', @$_). ' ' for consolidate($intervals); printf "%44s =>%s\n", $in, $out; }
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(err) } return } func testRandom(label string, src io.Reader) { fmt.Printf("%s:\n", label) var r int32 for i := 0; i < 10; i++ { if err := binary.Read(src, binary.LittleEndian, &r); err != nil { panic(err) } fmt.Print(r, " ") } fmt.Println() }
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'" with embedded single- and double-quotes.]] s6 = [=[This is a level 1 long-bracket ]]string[[ with [[embedded]] long-brackets.]=] s7 = [==[This is a level 2 long-bracket ]=]string[=[ with [=[embedded]=] level 1 long-brackets, etc.]==] s8 = [[This is a long-bracket string with embedded line feeds]] s9 = "any \0 form \1 of \2 string \3 may \4 contain \5 raw \6 binary \7 data \xDB" print(s1) print(s2) print(s3) print(s4) print(s5) print(s6) print(s7) print(s8) print(s9)
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 { my ($point, $segment) = @_; my ($A, $B) = @$segment; my @P = @$point; ($A, $B) = ($B, $A) if $A->[1] > $B->[1]; $P[1] += $eps if ($P[1] == $A->[1]) || ($P[1] == $B->[1]); return 0 if ($P[1] < $A->[1]) || ( $P[1] > $B->[1]) || ($P[0] > max($A->[0],$B->[1]) ); return 1 if $P[0] < min($A->[0], $B->[0]); my $m_red = ($A->[0] != $B->[0]) ? ( $B->[1] - $A->[1] )/($B->[0] - $A->[0]) : $inf; my $m_blue = ($A->[0] != $P[0]) ? ( $P[1] - $A->[1] )/($P[0] - $A->[0]) : $inf; return ($m_blue >= $m_red) ? 1 : 0; }
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 - x21*p.y + p2.x*p1.y - p2.y*p1.x); d > dMax { x = i + 1 dMax = d } } if dMax > { return append(RDP(l[:x+1], ), RDP(l[x:], )[1:]...) } return []point{l[0], l[len(l)-1]} } func main() { fmt.Println(RDP([]point{{0, 0}, {1, 0.1}, {2, -0.1}, {3, 5}, {4, 6}, {5, 7}, {6, 8.1}, {7, 9}, {8, 9}, {9, 9}}, 1)) }
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)->stringify; } my $decimals = 100; printf("Ramanujan's constant to $decimals decimals:\n%s\n\n", ramanujan_const(163, $decimals)); print "Heegner numbers yielding 'almost' integers:\n"; my @tests = (19, 96, 43, 960, 67, 5280, 163, 640320); while (@tests) { my ($h, $x) = splice(@tests, 0, 2); my $c = ramanujan_const($h, 32); my $n = Math::AnyNum::ipow($x, 3) + 744; printf("%3s:%51s %18s (diff:%s)\n", $h, $c, $n, ($n - $c)->round(-32)); }
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 main() { int x[] = { 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 }; char *s = malloc(rprint(0, x, sizeof(x) / sizeof(int)) + 1); rprint(s, x, sizeof(x) / sizeof(int)); printf(, s); return 0; }
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, scalar reverse $n; $n == reverse $n and die "oops!"; ++$count >= 5 and exit; } }
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)] (recur (cons (apply str cWord) lst) (apply str (rest news))))))) (defn parseRange [[x & xs:as s]] (if (some #(= % \-) xs) (let [[r0 r1] (split s \-)] (range (read-string r0) (inc (read-string r1)))) (list (read-string (str s)))))) (defn rangeexpand [s] (flatten (map parseRange (split s \,)))) > (rangeexpand "-6,-3--1,3-5,7-11,14,15,17-20") (-6 -3 -2 -1 3 4 5 7 8 9 10 11 14 15 17 18 19 20)
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])] r2.clear() return [rnge for rnge in norm if rnge] if __name__ == '__main__': for s in [ [[1.1, 2.2]], [[6.1, 7.2], [7.2, 8.3]], [[4, 3], [2, 1]], [[4, 3], [2, 1], [-1, -2], [3.9, 10]], [[1, 3], [-6, -1], [-4, -5], [8, 2], [-6, -6]], ]: print(f)
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, n) for i := 0; i < n; i++ { latin[i] = make([]int, n) if i == n-1 { break } for j := 0; j < n; j++ { latin[i][j] = j } }
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 $count % 2; } function west($A, $B, $x, $y) { if ($A['y'] <= $B['y']) { if ($y <= $A['y'] || $y > $B['y'] || $x >= $A['x'] && $x >= $B['x']) { return false; } if ($x < $A['x'] && $x < $B['x']) { return true; } if ($x == $A['x']) { if ($y == $A['y']) { $result1 = NAN; } else { $result1 = INF; } } else { $result1 = ($y - $A['y']) / ($x - $A['x']); } if ($B['x'] == $A['x']) { if ($B['y'] == $A['y']) { $result2 = NAN; } else { $result2 = INF; } } else { $result2 = ($B['y'] - $A['y']) / ($B['x'] - $A['x']); } return $result1 > $result2; } return west($B, $A, $x, $y); } $square = [ 'name' => 'square', 'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20]] ]; $squareHole = [ 'name' => 'squareHole', 'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 5], ['x' => 15, 'y' => 5], ['x' => 15, 'y' => 15], ['x' => 5, 'y' => 15]] ]; $strange = [ 'name' => 'strange', 'bounds' => [['x' => 0, 'y' => 0], ['x' => 5, 'y' => 5], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 15], ['x' => 15, 'y' => 15], ['x' => 20, 'y' => 20], ['x' => 20, 'y' => 0]] ]; $hexagon = [ 'name' => 'hexagon', 'bounds' => [['x' => 6, 'y' => 0], ['x' => 14, 'y' => 0], ['x' => 20, 'y' => 10], ['x' => 14, 'y' => 20], ['x' => 6, 'y' => 20], ['x' => 0, 'y' => 10]] ]; $shapes = [$square, $squareHole, $strange, $hexagon]; $testPoints = [ ['lng' => 10, 'lat' => 10], ['lng' => 10, 'lat' => 16], ['lng' => -20, 'lat' => 10], ['lng' => 0, 'lat' => 10], ['lng' => 20, 'lat' => 10], ['lng' => 16, 'lat' => 10], ['lng' => 20, 'lat' => 20] ]; for ($s = 0; $s < count($shapes); $s++) { $shape = $shapes[$s]; for ($tp = 0; $tp < count($testPoints); $tp++) { $testPoint = $testPoints[$tp]; echo json_encode($testPoint) . . $shape['name'] . . contains($shape['bounds'], $testPoint['lat'], $testPoint['lng']) . PHP_EOL; } }
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() { return String.format("(%f,%f)", getKey(), getValue()); } } private static double perpendicularDistance(Point pt, Point lineStart, Point lineEnd) { double dx = lineEnd.getKey() - lineStart.getKey(); double dy = lineEnd.getValue() - lineStart.getValue();
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)) c firstRow = pure <$> r addRow tbl rows = head [ zipWith (:) row tbl | row <- rows, and $ different (tail row) (tail tbl) ] different = zipWith $ (not .) . elem printTable :: Show a => [[a]] -> IO () printTable tbl = putStrLn $ unlines $ unwords . map show <$> tbl
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) => { const v = Math.max(p[0], c); return [v, v === p[0] ? p[1] : i + 1]; }, [-1, 0]); if (dMax > eps) { return [...RDP(l.slice(0, x + 1), eps), ...RDP(l.slice(x), eps).slice(1)]; } return [l[0], l[last]] }; const points = [ {x: 0, y: 0}, {x: 1, y: 0.1}, {x: 2, y: -0.1}, {x: 3, y: 5}, {x: 4, y: 6}, {x: 5, y: 7}, {x: 6, y: 8.1}, {x: 7, y: 9}, {x: 8, y: 9}, {x: 9, y: 9}]; console.log(RDP(points, 1));
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_palindrome(n): return n == reverse(n) def rare(n): r = reverse(n) return ( not is_palindrome(n) and n > r and is_square(n+r) and is_square(n-r) ) if __name__ == '__main__': main()
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.iterator(); System.out.print("["); if (it.hasNext()) { Integer col = it.next(); System.out.print(col); } while (it.hasNext()) { Integer col = it.next(); System.out.print(", "); System.out.print(col); } System.out.println("]"); } System.out.println(); } private static void latinSquare(int n) { if (n <= 0) { System.out.println("[]"); return; } List<List<Integer>> latin = new ArrayList<>(n); for (int i = 0; i < n; ++i) { List<Integer> inner = new ArrayList<>(n); for (int j = 0; j < n; ++j) { inner.add(j); } latin.add(inner); }
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]; let s; while (true) { do { s = d.splice(Math.floor(Math.random() * d.length), 1)[0]; if (!s) return false; } while (this.check(s, c, r)); this.square[c][r] = s; if (++c >= this.size) { c = 0; if (++r >= this.size) { return true; } } if (this.create(c, r)) return true; if (--c < 0) { c = this.size - 1; if (--r < 0) { return false; } } } } check(d, c, r) { for (let a = 0; a < this.size; a++) { if (c - a > -1) { if (this.square[c - a][r] === d) return true; } if (r - a > -1) { if (this.square[c][r - a] === d) return true; } } return false; } } new Latin(5);
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): ''' takes a point p=Pt() and an edge of two endpoints a,b=Pt() of a line segment returns boolean ''' a,b = edge if a.y > b.y: a,b = b,a if p.y == a.y or p.y == b.y: p = Pt(p.x, p.y + _eps) intersect = False if (p.y > b.y or p.y < a.y) or ( p.x > max(a.x, b.x)): return False if p.x < min(a.x, b.x): intersect = True else: if abs(a.x - b.x) > _tiny: m_red = (b.y - a.y) / float(b.x - a.x) else: m_red = _huge if abs(a.x - p.x) > _tiny: m_blue = (p.y - a.y) / float(p.x - a.x) else: m_blue = _huge intersect = m_blue >= m_red return intersect def _odd(x): return x%2 == 1 def ispointinside(p, poly): ln = len(poly) return _odd(sum(rayintersectseg(p, edge) for edge in poly.edges )) def polypp(poly): print (% poly.name) print (' ', ',\n '.join(str(e) for e in poly.edges) + '\n ))') if __name__ == '__main__': polys = [ Poly(name='square', edges=( Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)), Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)), Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)), Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)) )), Poly(name='square_hole', edges=( Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)), Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)), Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)), Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)), Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=7.5, y=2.5)), Edge(a=Pt(x=7.5, y=2.5), b=Pt(x=7.5, y=7.5)), Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=2.5, y=7.5)), Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=2.5, y=2.5)) )), Poly(name='strange', edges=( Edge(a=Pt(x=0, y=0), b=Pt(x=2.5, y=2.5)), Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=0, y=10)), Edge(a=Pt(x=0, y=10), b=Pt(x=2.5, y=7.5)), Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=7.5, y=7.5)), Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=10, y=10)), Edge(a=Pt(x=10, y=10), b=Pt(x=10, y=0)), Edge(a=Pt(x=10, y=0), b=Pt(x=2.5, y=2.5)) )), Poly(name='exagon', edges=( Edge(a=Pt(x=3, y=0), b=Pt(x=7, y=0)), Edge(a=Pt(x=7, y=0), b=Pt(x=10, y=5)), Edge(a=Pt(x=10, y=5), b=Pt(x=7, y=10)), Edge(a=Pt(x=7, y=10), b=Pt(x=3, y=10)), Edge(a=Pt(x=3, y=10), b=Pt(x=0, y=5)), Edge(a=Pt(x=0, y=5), b=Pt(x=3, y=0)) )), ] testpoints = (Pt(x=5, y=5), Pt(x=5, y=8), Pt(x=-10, y=5), Pt(x=0, y=5), Pt(x=10, y=5), Pt(x=8, y=5), Pt(x=10, y=10)) print () for poly in polys: polypp(poly) print (' ', '\t'.join(% (p, ispointinside(p, poly)) for p in testpoints[:3])) print (' ', '\t'.join(% (p, ispointinside(p, poly)) for p in testpoints[3:6])) print (' ', '\t'.join(% (p, ispointinside(p, poly)) for p in testpoints[6:]))
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, 1, 2, 3, 4}; int y[N]; int i; for (i = 0; i < 10; i++) { memcpy(y, x, sizeof(x)); printf(, i, qselect(y, 10, i)); } return 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 format-with-ranges [coll] (println (clojure.string/join "," (map string-ranges (partition-between nonconsecutive? coll)))))
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 > b$y ) { a <- side$B b <- side$A } if ( (p$y == a$y) || (p$y == b$y) ) { p$y <- p$y + eps } if ( (p$y < a$y) || (p$y > b$y) ) return(FALSE) else if ( p$x > max(a$x, b$x) ) return(FALSE) else { if ( p$x < min(a$x, b$x) ) return(TRUE) else { if ( a$x!= b$x ) m_red <- (b$y - a$y) / (b$x - a$x) else m_red <- Inf if ( a$x!= p$x ) m_blue <- (p$y - a$y) / (p$x - a$x) else m_blue <- Inf return( m_blue >= m_red ) } } }
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($result); my $rank = 1; for my $players (tiers %s) { $result .= "$rank " . join(', ', sort @$players) . "\n"; $rank += @$players; } return $result; } sub modified { my(%s) = @_; my($result); my $rank = 0; for my $players (tiers %s) { $rank += @$players; $result .= "$rank " . join(', ', sort @$players) . "\n"; } return $result; } sub dense { my(%s) = @_; my($n,$result); $result .= sprintf "%d%s\n", ++$n, join(', ', sort @$_) for tiers %s; return $result; } sub ordinal { my(%s) = @_; my($n,$result); for my $players (tiers %s) { $result .= sprintf "%d%s\n", ++$n, $_ for sort @$players; } return $result; } sub fractional { my(%s) = @_; my($result); my $rank = 1; for my $players (tiers %s) { my $beg = $rank; my $end = $rank += @$players; my $avg = 0; $avg += $_/@$players for $beg .. $end-1; $result .= sprintf "%3.1f%s\n", $avg, join ', ', sort @$players; } return $result; } print "Standard:\n" . standard(%scores) . "\n"; print "Modified:\n" . modified(%scores) . "\n"; print "Dense:\n" . dense(%scores) . "\n"; print "Ordinal:\n" . ordinal(%scores) . "\n"; print "Fractional:\n" . fractional(%scores) . "\n";
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 0 if $start[0]==$point[0] && $start[1]==$point[1] or $end[0]==$point[0] && $end[1]==$point[1]; my ( $dx, $dy) = ( $end[0]-$start[0], $end[1]-$start[1]); my ($dpx, $dpy) = ($point[0]-$start[0],$point[1]-$start[1]); my $t = norm($dx, $dy); $dx /= $t; $dy /= $t; norm($dpx - $dx*($dx*$dpx + $dy*$dpy), $dpy - $dy*($dx*$dpx + $dy*$dpy)); } sub Ramer_Douglas_Peucker { my(@points) = @_; return @points if @points == 2; my @d; push @d, perpendicular_distance(@points[0, -1, $_]) for 0..@points-1; my(undef,$dmax) = minmax @d; my $index = firstidx { $_ == $dmax } @d; if ($dmax > $epsilon) { my @lo = Ramer_Douglas_Peucker( @points[0..$index]); my @hi = Ramer_Douglas_Peucker( @points[$index..$ return @lo[0..@lo-2], @hi; } @points[0, -1]; } say '(' . join(' ', @$_) . ') ' for Ramer_Douglas_Peucker( [0,0],[1,0.1],[2,-0.1],[3,5],[4,6],[5,7],[6,8.1],[7,9],[8,9],[9,9] )
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 t VarType } func (err *varError) Error() string { return fmt.Sprintf("%v: (%q,%v)", err.err, err.n, err.t) } type VarType int const ( Bool VarType = 1 + iota Array String ) func (t VarType) String() string { switch t { case Bool: return "Bool" case Array: return "Array" case String: return "String" } panic("Unknown VarType") } type confvar struct { Type VarType Val interface{} } type Config struct { m map[string]confvar } func Parse(r io.Reader) (c *Config, err error) { c = new(Config) c.m = make(map[string]confvar) buf, err := ioutil.ReadAll(r) if err != nil { return } lines := bytes.Split(buf, []byte{'\n'}) for _, line := range lines { line = bytes.TrimSpace(line) if len(line) == 0 { continue } switch line[0] { case '#', ';': continue } parts := bytes.SplitN(line, []byte{' '}, 2) nam := string(bytes.ToLower(parts[0])) if len(parts) == 1 { c.m[nam] = confvar{Bool, true} continue } if strings.Contains(string(parts[1]), ",") { tmpB := bytes.Split(parts[1], []byte{','}) for i := range tmpB { tmpB[i] = bytes.TrimSpace(tmpB[i]) } tmpS := make([]string, 0, len(tmpB)) for i := range tmpB { tmpS = append(tmpS, string(tmpB[i])) } c.m[nam] = confvar{Array, tmpS} continue } c.m[nam] = confvar{String, string(bytes.TrimSpace(parts[1]))} } return } func (c *Config) Bool(name string) (bool, error) { name = strings.ToLower(name) if _, ok := c.m[name]; !ok { return false, nil } if c.m[name].Type != Bool { return false, &varError{EBADTYPE, name, Bool} } v, ok := c.m[name].Val.(bool) if !ok { return false, &varError{EBADVAL, name, Bool} } return v, nil } func (c *Config) Array(name string) ([]string, error) { name = strings.ToLower(name) if _, ok := c.m[name]; !ok { return nil, &varError{ENONE, name, Array} } if c.m[name].Type != Array { return nil, &varError{EBADTYPE, name, Array} } v, ok := c.m[name].Val.([]string) if !ok { return nil, &varError{EBADVAL, name, Array} } return v, nil } func (c *Config) String(name string) (string, error) { name = strings.ToLower(name) if _, ok := c.m[name]; !ok { return "", &varError{ENONE, name, String} } if c.m[name].Type != String { return "", &varError{EBADTYPE, name, String} } v, ok := c.m[name].Val.(string) if !ok { return "", &varError{EBADVAL, name, String} } return v, nil }
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]) if (parts.size() > 1) { parts.eachWithIndex{ part, int i -> config["$key(${i + 1})"] = part} } else { config[key] = parts[0] } } } }
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 = sum * 10 + digits[i] i = i + 1 end end return sum end def isSquare(n) root = Math.sqrt(n).to_i return root * root == n end def seq(from, to, step) res = [] i = from while i <= to res << i i = i + step end return res end def format_number(number) number.to_s.reverse.gsub(/(\d{3})(?=\d)/, '\\1,').reverse end def main pow = 1 allTerms = [] for i in 0 .. MAX_DIGITS - 2 allTerms << [] end for r in 2 .. MAX_DIGITS terms = [] pow = pow * 10 pow1 = pow pow2 = 1 i1 = 0 i2 = r - 1 while i1 < i2 terms << Term.new(pow1 - pow2, i1, i2) pow1 = (pow1 / 10).to_i pow2 = pow2 * 10 i1 = i1 + 1 i2 = i2 - 1 end allTerms[r - 2] = terms end fml = { 0 =>[[2, 2], [8, 8]], 1 =>[[6, 5], [8, 7]], 4 =>[[4, 0]], 6 =>[[6, 0], [8, 2]] } dmd = {} for i in 0 .. 99 a = [(i / 10).to_i, (i % 10)] d = a[0] - a[1] if dmd.include?(d) then dmd[d] << a else dmd[d] = [a] end end fl = [0, 1, 4, 6] dl = seq(-9, 9, 1) zl = [0] el = seq(-8, 8, 2) ol = seq(-9, 9, 2) il = seq(0, 9, 1) rares = [] lists = [] for i in 0 .. 3 lists << [] end fl.each_with_index { |f, i| lists[i] = [[f]] } digits = [] count = 0 fnpr = lambda { |cand, di, dis, indices, nmr, nd, level| if level == dis.length then digits[indices[0][0]] = fml[cand[0]][di[0]][0] digits[indices[0][1]] = fml[cand[0]][di[0]][1] le = di.length if nd % 2 == 1 then le = le - 1 digits[(nd / 2).to_i] = di[le] end di[1 .. le - 1].each_with_index { |d, i| digits[indices[i + 1][0]] = dmd[cand[i + 1]][d][0] digits[indices[i + 1][1]] = dmd[cand[i + 1]][d][1] } r = toLong(digits, true) npr = nmr + 2 * r if not isSquare(npr) then return end count = count + 1 print % [count] n = toLong(digits, false) print % [format_number(n)] rares << n else for num in dis[level] di[level] = num fnpr.call(cand, di, dis, indices, nmr, nd, level + 1) end end } fnmr = lambda { |cand, list, indices, nd, level| if level == list.length then nmr = 0 nmr2 = 0 allTerms[nd - 2].each_with_index { |t, i| if cand[i] >= 0 then nmr = nmr + t.coeff * cand[i] else nmr2 = nmr2 = t.coeff * -cand[i] if nmr >= nmr2 then nmr = nmr - nmr2 nmr2 = 0 else nmr2 = nmr2 - nmr nmr = 0 end end } if nmr2 >= nmr then return end nmr = nmr - nmr2 if not isSquare(nmr) then return end dis = [] dis << seq(0, fml[cand[0]].length - 1, 1) for i in 1 .. cand.length - 1 dis << seq(0, dmd[cand[i]].length - 1, 1) end if nd % 2 == 1 then dis << il.dup end di = [] for i in 0 .. dis.length - 1 di << 0 end fnpr.call(cand, di, dis, indices, nmr, nd, 0) else for num in list[level] cand[level] = num fnmr.call(cand, list, indices, nd, level + 1) end end } for nd in 2 .. 10 digits = [] for i in 0 .. nd - 1 digits << 0 end if nd == 4 then lists[0] << zl.dup lists[1] << ol.dup lists[2] << el.dup lists[3] << ol.dup elsif allTerms[nd - 2].length > lists[0].length then for i in 0 .. 3 lists[i] << dl.dup end end indices = [] for t in allTerms[nd - 2] indices << [t.ix1, t.ix2] end for list in lists cand = [] for i in 0 .. list.length - 1 cand << 0 end fnmr.call(cand, list, indices, nd, 0) end print % [nd] end rares.sort() print % [MAX_DIGITS] rares.each_with_index { |rare, i| print % [i + 1, format_number(rare)] } end main()
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 = map [ @{$_}[@cols] ], @ls[shuffle 0..$n-1]; @symbols = shuffle( ('A'..'Z')[0..$n-1] ); push @ls_sym, [@symbols[@$_]] for @ls; @ls_sym } sub display { my $str; $str .= join(' ', @$_) . "\n" for @_; $str } say display random_ls($_) for 2..5, 5;
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) -> Result<String, Error> { let file = File::open(path).expect("File not found or cannot be opened"); let content = BufReader::new(&file); let mut lines = content.lines(); lines.nth(line_num).expect("No line found at that position") }
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 * $pvy; $dsx = $pvdot * $dx; $dsy = $pvdot * $dy; $ax = $pvx - $dsx; $ay = $pvy - $dsy; return sqrt($ax * $ax + $ay * $ay); } function ramer_douglas_peucker(array $points, $epsilon) { if (count($points) < 2) { throw new InvalidArgumentException('Not enough points to simplify'); } $dmax = 0; $index = 0; $end = count($points) - 1; $start_end_line = [$points[0], $points[$end]]; for ($i = 1; $i < $end; $i++) { $dist = perpendicular_distance($points[$i], $start_end_line); if ($dist > $dmax) { $index = $i; $dmax = $dist; } } if ($dmax > $epsilon) { $new_start = ramer_douglas_peucker(array_slice($points, 0, $index + 1), $epsilon); $new_end = ramer_douglas_peucker(array_slice($points, $index), $epsilon); array_pop($new_start); return array_merge($new_start, $new_end); } return [ $points[0], $points[$end]]; } $polyline = [ [0,0], [1,0.1], [2,-0.1], [3,5], [4,6], [5,7], [6,8.1], [7,9], [8,9], [9,9], ]; $result = ramer_douglas_peucker($polyline, 1.0); print ; foreach ($result as $point) { print $point[0] . ',' . $point[1] . ; }
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 :: String -> Config -> Config addConfigValue raw config = case key of "fullname" -> config {fullName = values} "favouritefruit" -> config {favoriteFruit = values} "needspeeling" -> config {needsPeeling = True} "seedsremoved" -> config {seedsRemoved = True} "otherfamily" -> config {otherFamily = splitOn "," values} _ -> config where (k, vs) = span (/= ' ') raw key = map toLower k values = tail vs data Config = Config { fullName :: String , favoriteFruit :: String , needsPeeling :: Bool , seedsRemoved :: Bool , otherFamily :: [String] } deriving (Show) defaultConfig :: Config defaultConfig = Config "" "" False False []
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) -> fmt::Result { write!( f, "{:>6} {:>6} ms {:>2}. {}", self.digits, self.time_to_find, self.counter, self.number ) } } fn print_results(results: Vec<RareResults>) { if results.len()!= 0 {
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 fifo: yield n+1, fifo.pop(0) def sc_rank(iterable, start=1): lastresult, lastrank = None, None for n, item in enumerate(iterable, start): if item[0] == lastresult: yield lastrank, item else: yield n, item lastresult, lastrank = item[0], n def d_rank(iterable, start=1): lastresult, lastrank = None, start - 1, for item in iterable: if item[0] == lastresult: yield lastrank, item else: lastresult, lastrank = item[0], lastrank + 1 yield lastrank, item def o_rank(iterable, start=1): yield from enumerate(iterable, start) def f_rank(iterable, start=1): last, fifo = None, [] for n, item in enumerate(iterable, start): if item[0] != last: if fifo: mean = sum(f[0] for f in fifo) / len(fifo) while fifo: yield mean, fifo.pop(0)[1] last = item[0] fifo.append((n, item)) if fifo: mean = sum(f[0] for f in fifo) / len(fifo) while fifo: yield mean, fifo.pop(0)[1] if __name__ == '__main__': scores = [(44, 'Solomon'), (42, 'Jason'), (42, 'Errol'), (41, 'Garry'), (41, 'Bernard'), (41, 'Barry'), (39, 'Stephen')] print('\nScores to be ranked (best first):') for s in scores: print(' %2i%s'% (s )) for ranker in [sc_rank, mc_rank, d_rank, o_rank, f_rank]: print('\n%s:'% ranker.__doc__) for rank, score in ranker(scores): print(' %3g,%r'% (rank, score))
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