code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
(defn cfrac [a b n] (letfn [(cfrac-iter [[x k]] [(+ (a k) (/ (b (inc k)) x)) (dec k)])] (ffirst (take 1 (drop (inc n) (iterate cfrac-iter [1 n])))))) (def sq2 (cfrac #(if (zero? %) 1.0 2.0) (constantly 1.0) 100)) (def e (cfrac #(if (zero? %) 2.0 %) #(if (= 1 %) 1.0 (double (dec %))) 100)) (def pi (cfrac #(if (zero? %) 3.0 6.0) #(let [x (- (* 2.0 %) 1.0)] (* x x)) 900000))
1,001Continued fraction
6clojure
bxikz
use strict; use warnings; use feature 'say'; use ntheory 'primes'; use List::AllUtils <indexes max>; my $limit = 1000000; my @primes = @{primes( $limit )}; sub runs { my($op) = @_; my @diff = my $diff = my $run = 1; push @diff, map { my $next = $primes[$_] - $primes[$_ - 1]; if ($op eq '>') { if ($next > $diff) { ++$run } else { $run = 1 } } else { if ($next < $diff) { ++$run } else { $run = 1 } } $diff = $next; $run } 1 .. $ my @prime_run; my $max = max @diff; for my $r ( indexes { $_ == $max } @diff ) { push @prime_run, join ' ', map { $primes[$r - $_] } reverse 0..$max } @prime_run } say "Longest run(s) of ascending prime gaps up to $limit:\n" . join "\n", runs('>'); say "\nLongest run(s) of descending prime gaps up to $limit:\n" . join "\n", runs('<');
1,000Consecutive primes with ascending or descending differences
2perl
95kmn
class Foodbox def initialize (*food) raise ArgumentError, unless food.all?{|f| f.respond_to?(:eat)} @box = food end end class Fruit def eat; end end class Apple < Fruit; end p Foodbox.new(Fruit.new, Apple.new) p Foodbox.new(Apple.new, )
999Constrained genericity
14ruby
dy5ns
null
999Constrained genericity
15rust
fm4d6
type Eatable = { def eat: Unit } class FoodBox(coll: List[Eatable]) case class Fish(name: String) { def eat { println("Eating "+name) } } val foodBox = new FoodBox(List(new Fish("salmon")))
999Constrained genericity
16scala
3l7zy
typedef struct tPoint { int x, y; } Point; bool ccw(const Point *a, const Point *b, const Point *c) { return (b->x - a->x) * (c->y - a->y) > (b->y - a->y) * (c->x - a->x); } int comparePoints(const void *lhs, const void *rhs) { const Point* lp = lhs; const Point* rp = rhs; if (lp->x < rp->x) return -1; if (rp->x < lp->x) return 1; if (lp->y < rp->y) return -1; if (rp->y < lp->y) return 1; return 0; } void fatal(const char* message) { fprintf(stderr, , message); exit(1); } void* xmalloc(size_t n) { void* ptr = malloc(n); if (ptr == NULL) fatal(); return ptr; } void* xrealloc(void* p, size_t n) { void* ptr = realloc(p, n); if (ptr == NULL) fatal(); return ptr; } void printPoints(const Point* points, int len) { printf(); if (len > 0) { const Point* ptr = points; const Point* end = points + len; printf(, ptr->x, ptr->y); ++ptr; for (; ptr < end; ++ptr) printf(, ptr->x, ptr->y); } printf(); } Point* convexHull(Point p[], int len, int* hsize) { if (len == 0) { *hsize = 0; return NULL; } int i, size = 0, capacity = 4; Point* hull = xmalloc(capacity * sizeof(Point)); qsort(p, len, sizeof(Point), comparePoints); for (i = 0; i < len; ++i) { while (size >= 2 && !ccw(&hull[size - 2], &hull[size - 1], &p[i])) --size; if (size == capacity) { capacity *= 2; hull = xrealloc(hull, capacity * sizeof(Point)); } assert(size >= 0 && size < capacity); hull[size++] = p[i]; } int t = size + 1; for (i = len - 1; i >= 0; i--) { while (size >= t && !ccw(&hull[size - 2], &hull[size - 1], &p[i])) --size; if (size == capacity) { capacity *= 2; hull = xrealloc(hull, capacity * sizeof(Point)); } assert(size >= 0 && size < capacity); hull[size++] = p[i]; } --size; assert(size >= 0); hull = xrealloc(hull, size * sizeof(Point)); *hsize = size; return hull; } int main() { Point points[] = { {16, 3}, {12, 17}, { 0, 6}, {-4, -6}, {16, 6}, {16, -7}, {16, -3}, {17, -4}, { 5, 19}, {19, -8}, { 3, 16}, {12, 13}, { 3, -4}, {17, 5}, {-3, 15}, {-3, -9}, { 0, 11}, {-9, -3}, {-4, -2}, {12, 10} }; int hsize; Point* hull = convexHull(points, sizeof(points)/sizeof(Point), &hsize); printf(); printPoints(hull, hsize); printf(); free(hull); return 0; }
1,002Convex hull
5c
8tm04
protocol Eatable { func eat() }
999Constrained genericity
17swift
n6uil
from sympy import sieve primelist = list(sieve.primerange(2,1000000)) listlen = len(primelist) pindex = 1 old_diff = -1 curr_list=[primelist[0]] longest_list=[] while pindex < listlen: diff = primelist[pindex] - primelist[pindex-1] if diff > old_diff: curr_list.append(primelist[pindex]) if len(curr_list) > len(longest_list): longest_list = curr_list else: curr_list = [primelist[pindex-1],primelist[pindex]] old_diff = diff pindex += 1 print(longest_list) pindex = 1 old_diff = -1 curr_list=[primelist[0]] longest_list=[] while pindex < listlen: diff = primelist[pindex] - primelist[pindex-1] if diff < old_diff: curr_list.append(primelist[pindex]) if len(curr_list) > len(longest_list): longest_list = curr_list else: curr_list = [primelist[pindex-1],primelist[pindex]] old_diff = diff pindex += 1 print(longest_list)
1,000Consecutive primes with ascending or descending differences
3python
c4b9q
src := "Hello" dst := src
997Copy a string
0go
ozu8q
def string = 'Scooby-doo-bee-doo'
997Copy a string
7groovy
xi9wl
require limit = 1_000_000 puts p Prime.each(limit).each_cons(2).chunk_while{|(i1,i2), (j1,j2)| j1-i1 < j2-i2 }.max_by(&:size).flatten.uniq puts p Prime.each(limit).each_cons(2).chunk_while{|(i1,i2), (j1,j2)| j1-i1 > j2-i2 }.max_by(&:size).flatten.uniq
1,000Consecutive primes with ascending or descending differences
14ruby
2r1lw
null
1,000Consecutive primes with ascending or descending differences
15rust
v7a2t
src = "Hello World" dst = src
997Copy a string
8haskell
2rwll
inline int randn(int m) { int rand_max = RAND_MAX - (RAND_MAX % m); int r; while ((r = rand()) > rand_max); return r / (rand_max / m); } int main() { int i, x, y, r2; unsigned long buf[31] = {0}; for (i = 0; i < 100; ) { x = randn(31) - 15; y = randn(31) - 15; r2 = x * x + y * y; if (r2 >= 100 && r2 <= 225) { buf[15 + y] |= 1 << (x + 15); i++; } } for (y = 0; y < 31; y++) { for (x = 0; x < 31; x++) printf((buf[y] & 1 << x) ? : ); printf(); } return 0; }
1,003Constrained random points on a circle
5c
sd3q5
String src = "Hello"; String newAlias = src; String strCopy = new String(src);
997Copy a string
9java
62k3z
var container = {myString: "Hello"}; var containerCopy = container;
997Copy a string
10javascript
lgecf
(ns rosettacode.circle-random-points (:import [java.awt Color Graphics Dimension] [javax.swing JFrame JPanel])) (let [points (->> (for [x (range -15 16), y (range -15 16) :when (<= 10 (Math/hypot x y) 15)] [(+ x 15) (+ y 15)]) shuffle (take 100))] (doto (JFrame.) (.add (doto (proxy [JPanel] [] (paint [^Graphics g] (doseq [[x y] points] (.fillRect g (* 10 x) (* 10 y) 10 10)))) (.setPreferredSize (Dimension. 310 310)))) (.setResizable false) (.setDefaultCloseOperation JFrame/DISPOSE_ON_CLOSE) .pack .show))
1,003Constrained random points on a circle
6clojure
n6cik
package main import ( "fmt" "rcu" "strconv" "strings" ) func main() { count := 0 k := 11 * 11 var res []int for count < 20 { if k%3 == 0 || k%5 == 0 || k%7 == 0 { k += 2 continue } factors := rcu.PrimeFactors(k) if len(factors) > 1 { s := strconv.Itoa(k) includesAll := true prev := -1 for _, f := range factors { if f == prev { continue } fs := strconv.Itoa(f) if strings.Index(s, fs) == -1 { includesAll = false break } } if includesAll { res = append(res, k) count++ } } k += 2 } for _, e := range res[0:10] { fmt.Printf("%10s ", rcu.Commatize(e)) } fmt.Println() for _, e := range res[10:20] { fmt.Printf("%10s ", rcu.Commatize(e)) } fmt.Println() }
1,004Composite numbers k with no single digit factors whose factors are all substrings of k
0go
4k152
use strict; use warnings; use ntheory qw<is_prime factor gcd>; my($values,$cnt); LOOP: for (my $k = 11; $k < 1E10; $k += 2) { next if 1 < gcd($k,2*3*5*7) or is_prime $k; map { next if index($k, $_) < 0 } factor $k; $values .= sprintf "%10d", $k; last LOOP if ++$cnt == 20; } print $values =~ s/.{1,100}\K/\n/gr;
1,004Composite numbers k with no single digit factors whose factors are all substrings of k
2perl
fmld7
val s = "Hello" val alias = s
997Copy a string
11kotlin
dygnz
package main import ( "fmt" "image" "sort" )
1,002Convex hull
0go
5haul
package main import "fmt" func main(){ fmt.Println(TimeStr(7259)) fmt.Println(TimeStr(86400)) fmt.Println(TimeStr(6000000)) } func TimeStr(sec int)(res string){ wks, sec := sec / 604800,sec % 604800 ds, sec := sec / 86400, sec % 86400 hrs, sec := sec / 3600, sec % 3600 mins, sec := sec / 60, sec % 60 CommaRequired := false if wks != 0 { res += fmt.Sprintf("%d wk",wks) CommaRequired = true } if ds != 0 { if CommaRequired { res += ", " } res += fmt.Sprintf("%d d",ds) CommaRequired = true } if hrs != 0 { if CommaRequired { res += ", " } res += fmt.Sprintf("%d hr",hrs) CommaRequired = true } if mins != 0 { if CommaRequired { res += ", " } res += fmt.Sprintf("%d min",mins) CommaRequired = true } if sec != 0 { if CommaRequired { res += ", " } res += fmt.Sprintf("%d sec",sec) } return }
998Convert seconds to compound duration
0go
8t20g
package main import "fmt" type cfTerm struct { a, b int }
1,001Continued fraction
0go
n62i1
class ConvexHull { private static class Point implements Comparable<Point> { private int x, y Point(int x, int y) { this.x = x this.y = y } @Override int compareTo(Point o) { return Integer.compare(x, o.x) } @Override String toString() { return String.format("(%d,%d)", x, y) } } private static List<Point> convexHull(List<Point> p) { if (p.isEmpty()) return Collections.emptyList() p.sort(new Comparator<Point>() { @Override int compare(Point o1, Point o2) { return o1 <=> o2 } }) List<Point> h = new ArrayList<>()
1,002Convex hull
7groovy
c4h9i
import Control.Monad (forM_) import Data.List (intercalate, mapAccumR) import System.Environment (getArgs) import Text.Printf (printf) import Text.Read (readMaybe) reduceBy :: Integral a => a -> [a] -> [a] n `reduceBy` xs = n': ys where (n', ys) = mapAccumR quotRem n xs durLabs :: [(Integer, String)] durLabs = [(undefined, "wk"), (7, "d"), (24, "hr"), (60, "min"), (60, "sec")] compdurs :: Integer -> [(Integer, String)] compdurs t = let ds = t `reduceBy` (map fst $ tail durLabs) in filter ((/=0) . fst) $ zip ds (map snd durLabs) compoundDuration :: Integer -> String compoundDuration = intercalate ", " . map (uncurry $ printf "%d%s") . compdurs main :: IO () main = do args <- getArgs forM_ args $ \arg -> case readMaybe arg of Just n -> printf "%7d seconds =%s\n" n (compoundDuration n) Nothing -> putStrLn $ "Invalid number of seconds: " ++ arg
998Convert seconds to compound duration
8haskell
lgach
import java.util.function.Function import static java.lang.Math.pow class Test { static double calc(Function<Integer, Integer[]> f, int n) { double temp = 0 for (int ni = n; ni >= 1; ni--) { Integer[] p = f.apply(ni) temp = p[1] / (double) (p[0] + temp) } return f.apply(0)[0] + temp } static void main(String[] args) { List<Function<Integer, Integer[]>> fList = new ArrayList<>() fList.add({ n -> [n > 0 ? 2: 1, 1] }) fList.add({ n -> [n > 0 ? n: 2, n > 1 ? (n - 1): 1] }) fList.add({ n -> [n > 0 ? 6: 3, (int) pow(2 * n - 1, 2)] }) for (Function<Integer, Integer[]> f: fList) System.out.println(calc(f, 200)) } }
1,001Continued fraction
7groovy
sdyq1
import Data.List (sortBy, groupBy, maximumBy) import Data.Ord (comparing) (x, y) = ((!! 0), (!! 1)) compareFrom :: (Num a, Ord a) => [a] -> [a] -> [a] -> Ordering compareFrom o l r = compare ((x l - x o) * (y r - y o)) ((y l - y o) * (x r - x o)) distanceFrom :: Floating a => [a] -> [a] -> a distanceFrom from to = ((x to - x from) ** 2 + (y to - y from) ** 2) ** (1 / 2) convexHull :: (Floating a, Ord a) => [[a]] -> [[a]] convexHull points = let o = minimum points presorted = sortBy (compareFrom o) (filter (/= o) points) collinears = groupBy (((EQ ==) .) . compareFrom o) presorted outmost = maximumBy (comparing (distanceFrom o)) <$> collinears in dropConcavities [o] outmost dropConcavities :: (Num a, Ord a) => [[a]] -> [[a]] -> [[a]] dropConcavities (left:lefter) (right:righter:rightest) = case compareFrom left right righter of LT -> dropConcavities (right: left: lefter) (righter: rightest) EQ -> dropConcavities (left: lefter) (righter: rightest) GT -> dropConcavities lefter (left: righter: rightest) dropConcavities output lastInput = lastInput ++ output main :: IO () main = mapM_ print $ convexHull [ [16, 3] , [12, 17] , [0, 6] , [-4, -6] , [16, 6] , [16, -7] , [16, -3] , [17, -4] , [5, 19] , [19, -8] , [3, 16] , [12, 13] , [3, -4] , [17, 5] , [-3, 15] , [-3, -9] , [0, 11] , [-9, -3] , [-4, -2] , [12, 10] ]
1,002Convex hull
8haskell
xizw4
import Data.List (unfoldr) import Data.Char (intToDigit) sqrt2, napier, myPi :: [(Integer, Integer)] sqrt2 = zip (1: [2,2 ..]) [1,1 ..] napier = zip (2: [1 ..]) (1: [1 ..]) myPi = zip (3: [6,6 ..]) ((^ 2) <$> [1,3 ..]) approxCF :: (Integral a, Fractional b) => Int -> [(a, a)] -> b approxCF t = foldr (\(a, b) z -> fromIntegral a + fromIntegral b / z) 1 . take t decString :: RealFrac a => a -> String decString frac = show i ++ '.': decString_ f where (i, f) = properFraction frac decString_ = map intToDigit . unfoldr (Just . properFraction . (10 *)) main :: IO () main = mapM_ (putStrLn . take 200 . decString . (approxCF 950 :: [(Integer, Integer)] -> Rational)) [sqrt2, napier, myPi]
1,001Continued fraction
8haskell
ujav2
public class CompoundDuration { public static void main(String[] args) { compound(7259); compound(86400); compound(6000_000); } private static void compound(long seconds) { StringBuilder sb = new StringBuilder(); seconds = addUnit(sb, seconds, 604800, " wk, "); seconds = addUnit(sb, seconds, 86400, " d, "); seconds = addUnit(sb, seconds, 3600, " hr, "); seconds = addUnit(sb, seconds, 60, " min, "); addUnit(sb, seconds, 1, " sec, "); sb.setLength(sb.length() > 2 ? sb.length() - 2 : 0); System.out.println(sb); } private static long addUnit(StringBuilder sb, long sec, long unit, String s) { long n; if ((n = sec / unit) > 0) { sb.append(n).append(s); sec %= (n * unit); } return sec; } }
998Convert seconds to compound duration
9java
3ljzg
(function () { 'use strict';
998Convert seconds to compound duration
10javascript
c419j
typedef struct { int rows, cols; complex **z; } matrix; matrix transpose (matrix a) { int i, j; matrix b; b.rows = a.cols; b.cols = a.rows; b.z = malloc (b.rows * sizeof (complex *)); for (i = 0; i < b.rows; i++) { b.z[i] = malloc (b.cols * sizeof (complex)); for (j = 0; j < b.cols; j++) { b.z[i][j] = conj (a.z[j][i]); } } return b; } int isHermitian (matrix a) { int i, j; matrix b = transpose (a); if (b.rows == a.rows && b.cols == a.cols) { for (i = 0; i < b.rows; i++) { for (j = 0; j < b.cols; j++) { if (b.z[i][j] != a.z[i][j]) return 0; } } } else return 0; return 1; } matrix multiply (matrix a, matrix b) { matrix c; int i, j; if (a.cols == b.rows) { c.rows = a.rows; c.cols = b.cols; c.z = malloc (c.rows * (sizeof (complex *))); for (i = 0; i < c.rows; i++) { c.z[i] = malloc (c.cols * sizeof (complex)); c.z[i][j] = 0 + 0 * I; for (j = 0; j < b.cols; j++) { c.z[i][j] += a.z[i][j] * b.z[j][i]; } } } return c; } int isNormal (matrix a) { int i, j; matrix a_ah, ah_a; if (a.rows != a.cols) return 0; a_ah = multiply (a, transpose (a)); ah_a = multiply (transpose (a), a); for (i = 0; i < a.rows; i++) { for (j = 0; j < a.cols; j++) { if (a_ah.z[i][j] != ah_a.z[i][j]) return 0; } } return 1; } int isUnitary (matrix a) { matrix b; int i, j; if (isNormal (a) == 1) { b = multiply (a, transpose(a)); for (i = 0; i < b.rows; i++) { for (j = 0; j < b.cols; j++) { if ((i == j && b.z[i][j] != 1) || (i != j && b.z[i][j] != 0)) return 0; } } return 1; } return 0; } int main () { complex z = 3 + 4 * I; matrix a, aT; int i, j; printf (); scanf (, &a.rows, &a.cols); a.z = malloc (a.rows * sizeof (complex *)); printf (); for (i = 0; i < a.rows; i++) { printf (); a.z[i] = malloc (a.cols * sizeof (complex)); for (j = 0; j < a.cols; j++) { a.z[i][j] = rand () % 10 + rand () % 10 * I; printf (, creal (a.z[i][j]), cimag (a.z[i][j])); } } aT = transpose (a); printf (); for (i = 0; i < aT.rows; i++) { printf (); aT.z[i] = malloc (aT.cols * sizeof (complex)); for (j = 0; j < aT.cols; j++) { aT.z[i][j] = rand () % 10 + rand () % 10 * I; printf (, creal (aT.z[i][j]), cimag (aT.z[i][j])); } } printf (, isHermitian (a) == 1 ? : ); printf (, isUnitary (a) == 1 ? : ); printf (, isNormal (a) == 1 ? : ); return 0; }
1,005Conjugate transpose
5c
1s8pj
import static java.lang.Math.pow; import java.util.*; import java.util.function.Function; public class Test { static double calc(Function<Integer, Integer[]> f, int n) { double temp = 0; for (int ni = n; ni >= 1; ni--) { Integer[] p = f.apply(ni); temp = p[1] / (double) (p[0] + temp); } return f.apply(0)[0] + temp; } public static void main(String[] args) { List<Function<Integer, Integer[]>> fList = new ArrayList<>(); fList.add(n -> new Integer[]{n > 0 ? 2 : 1, 1}); fList.add(n -> new Integer[]{n > 0 ? n : 2, n > 1 ? (n - 1) : 1}); fList.add(n -> new Integer[]{n > 0 ? 6 : 3, (int) pow(2 * n - 1, 2)}); for (Function<Integer, Integer[]> f : fList) System.out.println(calc(f, 200)); } }
1,001Continued fraction
9java
mujym
a = "string" b = a print(a == b)
997Copy a string
1lua
fmrdp
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import static java.util.Collections.emptyList; public class ConvexHull { private static class Point implements Comparable<Point> { private int x, y; public Point(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(Point o) { return Integer.compare(x, o.x); } @Override public String toString() { return String.format("(%d,%d)", x, y); } } private static List<Point> convexHull(List<Point> p) { if (p.isEmpty()) return emptyList(); p.sort(Point::compareTo); List<Point> h = new ArrayList<>();
1,002Convex hull
9java
bxok3
fun compoundDuration(n: Int): String { if (n < 0) return ""
998Convert seconds to compound duration
11kotlin
n65ij
null
1,001Continued fraction
11kotlin
t95f0
function convexHull(points) { points.sort(comparison); var L = []; for (var i = 0; i < points.length; i++) { while (L.length >= 2 && cross(L[L.length - 2], L[L.length - 1], points[i]) <= 0) { L.pop(); } L.push(points[i]); } var U = []; for (var i = points.length - 1; i >= 0; i--) { while (U.length >= 2 && cross(U[U.length - 2], U[U.length - 1], points[i]) <= 0) { U.pop(); } U.push(points[i]); } L.pop(); U.pop(); return L.concat(U); } function comparison(a, b) { return a.x == b.x ? a.y - b.y : a.x - b.x; } function cross(a, b, o) { return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x); }
1,002Convex hull
10javascript
wote2
function duration (secs) local units, dur = {"wk", "d", "hr", "min"}, "" for i, v in ipairs({604800, 86400, 3600, 60}) do if secs >= v then dur = dur .. math.floor(secs / v) .. " " .. units[i] .. ", " secs = secs % v end end if secs == 0 then return dur:sub(1, -3) else return dur .. secs .. " sec" end end print(duration(7259)) print(duration(86400)) print(duration(6000000))
998Convert seconds to compound duration
1lua
dy4nq
function calc(fa, fb, expansions) local a = 0.0 local b = 0.0 local r = 0.0 local i = expansions while i > 0 do a = fa(i) b = fb(i) r = b / (a + r) i = i - 1 end a = fa(0) return a + r end function sqrt2a(n) if n ~= 0 then return 2.0 else return 1.0 end end function sqrt2b(n) return 1.0 end function napiera(n) if n ~= 0 then return n else return 2.0 end end function napierb(n) if n > 1.0 then return n - 1.0 else return 1.0 end end function pia(n) if n ~= 0 then return 6.0 else return 3.0 end end function pib(n) local c = 2.0 * n - 1.0 return c * c end function main() local sqrt2 = calc(sqrt2a, sqrt2b, 1000) local napier = calc(napiera, napierb, 1000) local pi = calc(pia, pib, 1000) print(sqrt2) print(napier) print(pi) end main()
1,001Continued fraction
1lua
zc4ty
pthread_mutex_t condm = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; int bang = 0; pthread_mutex_lock(&condm); \ while( bang == 0 ) \ { \ pthread_cond_wait(&cond, &condm); \ } \ pthread_mutex_unlock(&condm); } while(0);\ void *t_enjoy(void *p) { WAITBANG(); printf(); pthread_exit(0); } void *t_rosetta(void *p) { WAITBANG(); printf(); pthread_exit(0); } void *t_code(void *p) { WAITBANG(); printf(); pthread_exit(0); } typedef void *(*threadfunc)(void *); int main() { int i; pthread_t a[3]; threadfunc p[3] = {t_enjoy, t_rosetta, t_code}; for(i=0;i<3;i++) { pthread_create(&a[i], NULL, p[i], NULL); } sleep(1); bang = 1; pthread_cond_broadcast(&cond); for(i=0;i<3;i++) { pthread_join(a[i], NULL); } }
1,006Concurrent computing
5c
t9cf4
null
1,002Convex hull
11kotlin
rpxgo
function print_point(p) io.write("("..p.x..", "..p.y..")") return nil end function print_points(pl) io.write("[") for i,p in pairs(pl) do if i>1 then io.write(", ") end print_point(p) end io.write("]") return nil end function ccw(a,b,c) return (b.x - a.x) * (c.y - a.y) > (b.y - a.y) * (c.x - a.x) end function pop_back(ta) table.remove(ta,#ta) return ta end function convexHull(pl) if #pl == 0 then return {} end table.sort(pl, function(left,right) return left.x < right.x end) local h = {}
1,002Convex hull
1lua
71qru
(doseq [text ["Enjoy" "Rosetta" "Code"]] (future (println text)))
1,006Concurrent computing
6clojure
mu5yq
package main import ( "fmt" "math" "math/cmplx" )
1,005Conjugate transpose
0go
yv564
package main import ( "bytes" "fmt" "math/rand" "time" ) const ( nPts = 100 rMin = 10 rMax = 15 ) func main() { rand.Seed(time.Now().Unix()) span := rMax + 1 + rMax rows := make([][]byte, span) for r := range rows { rows[r] = bytes.Repeat([]byte{' '}, span*2) } u := 0
1,003Constrained random points on a circle
0go
v7b2m
import Data.Complex (Complex(..), conjugate) import Data.List (transpose) type Matrix a = [[a]] main :: IO () main = mapM_ (\a -> do putStrLn "\nMatrix:" mapM_ print a putStrLn "Conjugate Transpose:" mapM_ print (conjTranspose a) putStrLn $ "Hermitian? " ++ show (isHermitianMatrix a) putStrLn $ "Normal? " ++ show (isNormalMatrix a) putStrLn $ "Unitary? " ++ show (isUnitaryMatrix a)) ([ [[3, 2:+ 1], [2:+ (-1), 1]] , [[1, 1, 0], [0, 1, 1], [1, 0, 1]] , [ [sqrt 2 / 2:+ 0, sqrt 2 / 2:+ 0, 0] , [0:+ sqrt 2 / 2, 0:+ (-sqrt 2 / 2), 0] , [0, 0, 0:+ 1] ] ] :: [Matrix (Complex Double)]) isHermitianMatrix, isNormalMatrix, isUnitaryMatrix :: RealFloat a => Matrix (Complex a) -> Bool isHermitianMatrix = mTest id conjTranspose isNormalMatrix = mTest mmct (mmul =<< conjTranspose) isUnitaryMatrix = mTest mmct (ident . length) mTest :: RealFloat a => (a2 -> Matrix (Complex a)) -> (a2 -> Matrix (Complex a)) -> a2 -> Bool mTest f g = (approxEqualMatrix . f) <*> g mmct :: RealFloat a => Matrix (Complex a) -> Matrix (Complex a) mmct = mmul <*> conjTranspose approxEqualMatrix :: (Fractional a, Ord a) => Matrix (Complex a) -> Matrix (Complex a) -> Bool approxEqualMatrix a b = length a == length b && length (head a) == length (head b) && and (zipWith approxEqualComplex (concat a) (concat b)) where approxEqualComplex (rx:+ ix) (ry:+ iy) = abs (rx - ry) < eps && abs (ix - iy) < eps eps = 1e-14 mmul :: Num a => Matrix a -> Matrix a -> Matrix a mmul a b = [ [ sum (zipWith (*) row column) | column <- transpose b ] | row <- a ] ident :: Num a => Int -> Matrix a ident size = [ [ fromIntegral $ div a b * div b a | a <- [1 .. size] ] | b <- [1 .. size] ] conjTranspose :: Num a => Matrix (Complex a) -> Matrix (Complex a) conjTranspose = map (map conjugate) . transpose
1,005Conjugate transpose
8haskell
hexju
import Data.List import Control.Monad import Control.Arrow import Rosetta.Knuthshuffle task = do let blanco = replicate (31*31) " " cs = sequence [[-15,-14..15],[-15,-14..15]] :: [[Int]] constraint = uncurry(&&).((<= 15*15) &&& (10*10 <=)). sum. map (join (*)) pts <- knuthShuffle $ filter constraint cs let canvas = foldl (\cs [x,y] -> replaceAt (31*(x+15)+y+15) "/ " cs ) blanco (take 100 pts) mapM_ (putStrLn.concat). takeWhile(not.null). unfoldr (Just . splitAt 31) $ canvas
1,003Constrained random points on a circle
8haskell
e8dai
use strict; use warnings; sub compound_duration { my $sec = shift; no warnings 'numeric'; return join ', ', grep { $_ > 0 } int($sec/60/60/24/7) . " wk", int($sec/60/60/24) % 7 . " d", int($sec/60/60) % 24 . " hr", int($sec/60) % 60 . " min", int($sec) % 60 . " sec"; } for (7259, 86400, 6000000) { printf "%7d sec = %s\n", $_, compound_duration($_) }
998Convert seconds to compound duration
2perl
71orh
use strict; use warnings; no warnings 'recursion'; use experimental 'signatures'; sub continued_fraction ($a, $b, $n = 100) { $a->() + ($n and $b->() / continued_fraction($a, $b, $n-1)); } printf "2 %.9f\n", continued_fraction do { my $n; sub { $n++ ? 2 : 1 } }, sub { 1 }; printf "e %.9f\n", continued_fraction do { my $n; sub { $n++ or 2 } }, do { my $n; sub { $n++ or 1 } }; printf " %.9f\n", continued_fraction do { my $n; sub { $n++ ? 6 : 3 } }, do { my $n; sub { (2*$n++ + 1)**2 } }, 1000; printf "/2 %.9f\n", continued_fraction do { my $n; sub { 1/($n++ or 1) } }, sub { 1 }, 1000;
1,001Continued fraction
2perl
kwohc
import 'dart:math' show Random; main(){ enjoy() .then( (e) => print(e) ); rosetta() .then( (r) => print(r) ); code() .then( (c) => print(c) ); }
1,006Concurrent computing
18dart
8tz0y
null
1,005Conjugate transpose
11kotlin
c4r98
typedef struct Point { int x; int y; } Point;
1,007Compound data type
5c
2rrlo
(defrecord Point [x y])
1,007Compound data type
6clojure
gbb4f
import java.util.Random; public class FuzzyCircle { static final Random rnd = new Random(); public static void main(String[] args){ char[][] field = new char[31][31]; for(int i = 0; i < field.length; i++){ for(int j = 0; j < field[i].length; j++){ field[i][j] = ' '; } } int pointsInDisc = 0; while(pointsInDisc < 100){ int x = rnd.nextInt(31) - 15; int y = rnd.nextInt(31) - 15; double dist = Math.hypot(x, y); if(dist >= 10 && dist <= 15 && field[x + 15][y + 15] == ' '){ field[x + 15][y + 15] = 'X'; pointsInDisc++; } } for(char[] row:field){ for(char space:row){ System.out.print(space); } System.out.println(); } } }
1,003Constrained random points on a circle
9java
hesjm
use strict; use English; use Math::Complex; use Math::MatrixReal; my @examples = (example1(), example2(), example3()); foreach my $m (@examples) { print "Starting matrix:\n", cmat_as_string($m), "\n"; my $m_ct = conjugate_transpose($m); print "Its conjugate transpose:\n", cmat_as_string($m_ct), "\n"; print "Is Hermitian? ", (cmats_are_equal($m, $m_ct) ? 'TRUE' : 'FALSE'), "\n"; my $product = $m_ct * $m; print "Is normal? ", (cmats_are_equal($product, $m * $m_ct) ? 'TRUE' : 'FALSE'), "\n"; my $I = identity(($m->dim())[0]); print "Is unitary? ", (cmats_are_equal($product, $I) ? 'TRUE' : 'FALSE'), "\n"; print "\n"; } exit 0; sub cmats_are_equal { my ($m1, $m2) = @ARG; my $max_norm = 1.0e-7; return abs($m1 - $m2) < $max_norm; } sub conjugate_transpose { my $m_T = ~ shift; my $result = $m_T->each(sub {~ $ARG[0]}); return $result; } sub cmat_as_string { my $m = shift; my $n_rows = ($m->dim())[0]; my @row_strings = map { q{[} . join(q{, }, $m->row($ARG)->as_list) . q{]} } (1 .. $n_rows); return join("\n", @row_strings); } sub identity { my $N = shift; my $m = new Math::MatrixReal($N, $N); $m->one(); return $m; } sub example1 { my $m = new Math::MatrixReal(2, 2); $m->assign(1, 1, cplx(3, 0)); $m->assign(1, 2, cplx(2, 1)); $m->assign(2, 1, cplx(2, -1)); $m->assign(2, 2, cplx(1, 0)); return $m; } sub example2 { my $m = new Math::MatrixReal(3, 3); $m->assign(1, 1, cplx(1, 0)); $m->assign(1, 2, cplx(1, 0)); $m->assign(1, 3, cplx(0, 0)); $m->assign(2, 1, cplx(0, 0)); $m->assign(2, 2, cplx(1, 0)); $m->assign(2, 3, cplx(1, 0)); $m->assign(3, 1, cplx(1, 0)); $m->assign(3, 2, cplx(0, 0)); $m->assign(3, 3, cplx(1, 0)); return $m; } sub example3 { my $m = new Math::MatrixReal(3, 3); $m->assign(1, 1, cplx(0.70710677, 0)); $m->assign(1, 2, cplx(0.70710677, 0)); $m->assign(1, 3, cplx(0, 0)); $m->assign(2, 1, cplx(0, -0.70710677)); $m->assign(2, 2, cplx(0, 0.70710677)); $m->assign(2, 3, cplx(0, 0)); $m->assign(3, 1, cplx(0, 0)); $m->assign(3, 2, cplx(0, 0)); $m->assign(3, 3, cplx(0, 1)); return $m; }
1,005Conjugate transpose
2perl
xidw8
<html><head><title>Circle</title></head> <body> <canvas id="cv" width="320" height="320"></canvas> <script type="application/javascript"> var cv = document.getElementById('cv'); var ctx = cv.getContext('2d'); var w = cv.width; var h = cv.height;
1,003Constrained random points on a circle
10javascript
a0n10
>>> def duration(seconds): t= [] for dm in (60, 60, 24, 7): seconds, m = divmod(seconds, dm) t.append(m) t.append(seconds) return ', '.join('%d%s'% (num, unit) for num, unit in zip(t[::-1], 'wk d hr min sec'.split()) if num) >>> for seconds in [7259, 86400, 6000000]: print(% (seconds, duration(seconds))) 7259 sec = 2 hr, 59 sec 86400 sec = 1 d 6000000 sec = 9 wk, 6 d, 10 hr, 40 min >>>
998Convert seconds to compound duration
3python
jai7p
from fractions import Fraction import itertools try: zip = itertools.izip except: pass def CF(a, b, t): terms = list(itertools.islice(zip(a, b), t)) z = Fraction(1,1) for a, b in reversed(terms): z = a + b / z return z def pRes(x, d): q, x = divmod(x, 1) res = str(q) res += for i in range(d): x *= 10 q, x = divmod(x, 1) res += str(q) return res def sqrt2_a(): yield 1 for x in itertools.repeat(2): yield x def sqrt2_b(): for x in itertools.repeat(1): yield x cf = CF(sqrt2_a(), sqrt2_b(), 950) print(pRes(cf, 200)) def Napier_a(): yield 2 for x in itertools.count(1): yield x def Napier_b(): yield 1 for x in itertools.count(1): yield x cf = CF(Napier_a(), Napier_b(), 950) print(pRes(cf, 200)) def Pi_a(): yield 3 for x in itertools.repeat(6): yield x def Pi_b(): for x in itertools.count(1,2): yield x*x cf = CF(Pi_a(), Pi_b(), 950) print(pRes(cf, 10))
1,001Continued fraction
3python
bxikr
null
1,003Constrained random points on a circle
11kotlin
4ka57
use strict; use warnings; use feature 'say'; { package Point; use Class::Struct; struct( x => '$', y => '$',); sub print { '(' . $_->x . ', ' . $_->y . ')' } } sub ccw { my($a, $b, $c) = @_; ($b->x - $a->x)*($c->y - $a->y) - ($b->y - $a->y)*($c->x - $a->x); } sub tangent { my($a, $b) = @_; my $opp = $b->x - $a->x; my $adj = $b->y - $a->y; $adj != 0 ? $opp / $adj : 1E99; } sub graham_scan { our @coords; local *coords = shift; my @sp = sort { $a->y <=> $b->y or $a->x <=> $b->x } map { Point->new( x => $_->[0], y => $_->[1] ) } @coords; return @sp if @sp < 3; my @h = shift @sp; @sp = map { $sp[$_->[0]] } sort { $b->[1] <=> $a->[1] or $a->[2] <=> $b->[2] } map { [$_, tangent($h[0], $sp[$_]), $sp[$_]->x] } 0..$ push @h, shift @sp; for my $point (@sp) { if (ccw( @h[-2,-1], $point ) >= 0) { push @h, $point; } else { pop @h; redo; } } @h } my @hull_1 = graham_scan( [[16, 3], [12,17], [ 0, 6], [-4,-6], [16, 6], [16,-7], [16,-3], [17,-4], [ 5,19], [19,-8], [ 3,16], [12,13], [ 3,-4], [17, 5], [-3,15], [-3,-9], [ 0,11], [-9,-3], [-4,-2], [12,10]] ); my @hull_2 = graham_scan( [[16, 3], [12,17], [ 0, 6], [-4,-6], [16, 6], [16,-7], [16,-3], [17,-4], [ 5,19], [19,-8], [ 3,16], [12,13], [ 3,-4], [17, 5], [-3,15], [-3,-9], [ 0,11], [-9,-3], [-4,-2], [12,10], [14,-9], [1,-9]] ); my $list = join ' ', map { Point::print($_) } @hull_1; say "Convex Hull (@{[scalar @hull_1]} points): [$list]"; $list = join ' ', map { Point::print($_) } @hull_2; say "Convex Hull (@{[scalar @hull_2]} points): [$list]";
1,002Convex hull
2perl
dy2nw
def conjugate_transpose(m): return tuple(tuple(n.conjugate() for n in row) for row in zip(*m)) def mmul( ma, mb): return tuple(tuple(sum( ea*eb for ea,eb in zip(a,b)) for b in zip(*mb)) for a in ma) def mi(size): 'Complex Identity matrix' sz = range(size) m = [[0 + 0j for i in sz] for j in sz] for i in range(size): m[i][i] = 1 + 0j return tuple(tuple(row) for row in m) def __allsame(vector): first, rest = vector[0], vector[1:] return all(i == first for i in rest) def __allnearsame(vector, eps=1e-14): first, rest = vector[0], vector[1:] return all(abs(first.real - i.real) < eps and abs(first.imag - i.imag) < eps for i in rest) def isequal(matrices, eps=1e-14): 'Check any number of matrices for equality within eps' x = [len(m) for m in matrices] if not __allsame(x): return False y = [len(m[0]) for m in matrices] if not __allsame(y): return False for s in range(x[0]): for t in range(y[0]): if not __allnearsame([m[s][t] for m in matrices], eps): return False return True def ishermitian(m, ct): return isequal([m, ct]) def isnormal(m, ct): return isequal([mmul(m, ct), mmul(ct, m)]) def isunitary(m, ct): mct, ctm = mmul(m, ct), mmul(ct, m) mctx, mcty, cmx, ctmy = len(mct), len(mct[0]), len(ctm), len(ctm[0]) ident = mi(mctx) return isequal([mct, ctm, ident]) def printm(comment, m): print(comment) fields = [['%g%+gj'% (f.real, f.imag) for f in row] for row in m] width = max(max(len(f) for f in row) for row in fields) lines = (', '.join('%*s'% (width, f) for f in row) for row in fields) print('\n'.join(lines)) if __name__ == '__main__': for matrix in [ ((( 3.000+0.000j), (+2.000+1.000j)), (( 2.000-1.000j), (+1.000+0.000j))), ((( 1.000+0.000j), (+1.000+0.000j), (+0.000+0.000j)), (( 0.000+0.000j), (+1.000+0.000j), (+1.000+0.000j)), (( 1.000+0.000j), (+0.000+0.000j), (+1.000+0.000j))), ((( 2**0.5/2+0.000j), (+2**0.5/2+0.000j), (+0.000+0.000j)), (( 0.000+2**0.5/2j), (+0.000-2**0.5/2j), (+0.000+0.000j)), (( 0.000+0.000j), (+0.000+0.000j), (+0.000+1.000j)))]: printm('\nMatrix:', matrix) ct = conjugate_transpose(matrix) printm('Its conjugate transpose:', ct) print('Hermitian?%s.'% ishermitian(matrix, ct)) print('Normal? %s.'% isnormal(matrix, ct)) print('Unitary? %s.'% isunitary(matrix, ct))
1,005Conjugate transpose
3python
qnfxi
package main import ( "fmt" "golang.org/x/exp/rand" "time" ) func main() { words := []string{"Enjoy", "Rosetta", "Code"} seed := uint64(time.Now().UnixNano()) q := make(chan string) for i, w := range words { go func(w string, seed uint64) { r := rand.New(rand.NewSource(seed)) time.Sleep(time.Duration(r.Int63n(1e9))) q <- w }(w, seed+uint64(i)) } for i := 0; i < len(words); i++ { fmt.Println(<-q) } }
1,006Concurrent computing
0go
hewjq
my $original = 'Hello.'; my $new = $original; $new = 'Goodbye.'; print "$original\n";
997Copy a string
2perl
jan7f
from __future__ import print_function from shapely.geometry import MultiPoint if __name__==: pts = MultiPoint([(16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2), (12,10)]) print (pts.convex_hull)
1,002Convex hull
3python
fmvde
'Enjoy Rosetta Code'.tokenize().collect { w -> Thread.start { Thread.sleep(1000 * Math.random() as int) println w } }.each { it.join() }
1,006Concurrent computing
7groovy
4kb5f
import Control.Concurrent main = mapM_ forkIO [process1, process2, process3] where process1 = putStrLn "Enjoy" process2 = putStrLn "Rosetta" process3 = putStrLn "Code"
1,006Concurrent computing
8haskell
i36or
require 'bigdecimal' sqrt2 = Object.new def sqrt2.a(n); n == 1? 1: 2; end def sqrt2.b(n); 1; end napier = Object.new def napier.a(n); n == 1? 2: n - 1; end def napier.b(n); n == 1? 1: n - 1; end pi = Object.new def pi.a(n); n == 1? 3: 6; end def pi.b(n); (2*n - 1)**2; end def estimate(cfrac, prec) last_result = nil terms = prec loop do result = cfrac.a(terms) (terms - 1).downto(1) do |n| a = BigDecimal cfrac.a(n) b = BigDecimal cfrac.b(n) digits = [b.div(result, 1).exponent + prec, 1].max result = a + b.div(result, digits) end result = result.round(prec) if result == last_result return result else last_result = result terms *= 2 end end end puts estimate(sqrt2, 50).to_s('F') puts estimate(napier, 50).to_s('F') puts estimate(pi, 10).to_s('F')
1,001Continued fraction
14ruby
1sdpw
$src = ; $dst = $src;
997Copy a string
12php
t97f1
MINUTE = 60 HOUR = MINUTE*60 DAY = HOUR*24 WEEK = DAY*7 def sec_to_str(sec) w, rem = sec.divmod(WEEK) d, rem = rem.divmod(DAY) h, rem = rem.divmod(HOUR) m, s = rem.divmod(MINUTE) units = [, , , , ] units.reject{|str| str.start_with?()}.join() end [7259, 86400, 6000000].each{|t| puts }
998Convert seconds to compound duration
14ruby
kwdhg
require 'matrix' i = Complex::I matrix = Matrix[[i, 0, 0], [0, i, 0], [0, 0, i]] conjt = matrix.conj.t print 'conjugate tranpose: '; puts conjt if matrix.square? print 'Hermitian? '; puts matrix.hermitian? print ' normal? '; puts matrix.normal? print ' unitary? '; puts matrix.unitary? else print 'Hermitian? false' print ' normal? false' print ' unitary? false' end
1,005Conjugate transpose
14ruby
0fzsu
use std::iter;
1,001Continued fraction
15rust
a0f14
t, n = {}, 0 for y=1,31 do t[y]={} for x=1,31 do t[y][x]=" " end end repeat x, y = math.random(-15,15), math.random(-15,15) rsq = x*x + y*y if rsq>=100 and rsq<=225 and t[y+16][x+16]==" " then t[y+16][x+16], n = "", n+1 end until n==100 for y=1,31 do print(table.concat(t[y])) end
1,003Constrained random points on a circle
1lua
gbe4j
use std::fmt; struct CompoundTime { w: usize, d: usize, h: usize, m: usize, s: usize, } macro_rules! reduce { ($s: ident, $(($from: ident, $to: ident, $factor: expr)),+) => {{ $( $s.$to += $s.$from / $factor; $s.$from%= $factor; )+ }} } impl CompoundTime { #[inline] fn new(w: usize, d: usize, h: usize, m: usize, s: usize) -> Self{ CompoundTime { w: w, d: d, h: h, m: m, s: s, } } #[inline] fn balance(&mut self) { reduce!(self, (s, m, 60), (m, h, 60), (h, d, 24), (d, w, 7)); } } impl fmt::Display for CompoundTime { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}w {}d {}h {}m {}s", self.w, self.d, self.h, self.m, self.s) } } fn main() { let mut ct = CompoundTime::new(0,3,182,345,2412); println!("Before: {}", ct); ct.balance(); println!("After: {}", ct); }
998Convert seconds to compound duration
15rust
bxfkx
import java.util.concurrent.CyclicBarrier; public class Threads { public static class DelayedMessagePrinter implements Runnable { private CyclicBarrier barrier; private String msg; public DelayedMessagePrinter(CyclicBarrier barrier, String msg) { this.barrier = barrier; this.msg = msg; } public void run() { try { barrier.await(); } catch (Exception e) { } System.out.println(msg); } } public static void main(String[] args) { CyclicBarrier barrier = new CyclicBarrier(3); new Thread(new DelayedMessagePrinter(barrier, "Enjoy")).start(); new Thread(new DelayedMessagePrinter(barrier, "Rosetta")).start(); new Thread(new DelayedMessagePrinter(barrier, "Code")).start(); } }
1,006Concurrent computing
9java
xinwy
self.addEventListener('message', function (event) { self.postMessage(event.data); self.close(); }, false);
1,006Concurrent computing
10javascript
oz386
extern crate num;
1,005Conjugate transpose
15rust
8t307
object ConjugateTranspose { case class Complex(re: Double, im: Double) { def conjugate(): Complex = Complex(re, -im) def +(other: Complex) = Complex(re + other.re, im + other.im) def *(other: Complex) = Complex(re * other.re - im * other.im, re * other.im + im * other.re) override def toString(): String = { if (im < 0) { s"${re}${im}i" } else { s"${re}+${im}i" } } } case class Matrix(val entries: Vector[Vector[Complex]]) { def *(other: Matrix): Matrix = { new Matrix( Vector.tabulate(entries.size, other.entries(0).size)((r, c) => { val rightRow = entries(r) val leftCol = other.entries.map(_(c)) rightRow.zip(leftCol) .map{ case (x, y) => x * y }
1,005Conjugate transpose
16scala
n6mic
object CF extends App { import Stream._ val sqrt2 = 1 #:: from(2,0) zip from(1,0) val napier = 2 #:: from(1) zip (1 #:: from(1)) val pi = 3 #:: from(6,0) zip (from(1,2) map {x=>x*x})
1,001Continued fraction
16scala
xi3wg
null
998Convert seconds to compound duration
16scala
a031n
null
1,006Concurrent computing
11kotlin
pqsb6
8fn(8X, 8seq_fold(8times, 1, 8seq_iota(1, 8inc(8X)))) ) int main(void) { printf(, ORDER_PP( 8to_lit( 8fac(10) ) ) ); return 0; }
1,008Compile-time calculation
5c
pqxby
class Point include Comparable attr :x, :y def initialize(x, y) @x = x @y = y end def <=>(other) x <=> other.x end def to_s % [@x, @y] end def to_str to_s() end end def ccw(a, b, c) ((b.x - a.x) * (c.y - a.y)) > ((b.y - a.y) * (c.x - a.x)) end def convexHull(p) if p.length == 0 then return [] end p = p.sort h = [] p.each { |pt| while h.length >= 2 and not ccw(h[-2], h[-1], pt) h.pop() end h << pt } t = h.length + 1 p.reverse.each { |pt| while h.length >= t and not ccw(h[-2], h[-1], pt) h.pop() end h << pt } h.pop() h end def main points = [ Point.new(16, 3), Point.new(12, 17), Point.new( 0, 6), Point.new(-4, -6), Point.new(16, 6), Point.new(16, -7), Point.new(16, -3), Point.new(17, -4), Point.new( 5, 19), Point.new(19, -8), Point.new( 3, 16), Point.new(12, 13), Point.new( 3, -4), Point.new(17, 5), Point.new(-3, 15), Point.new(-3, -9), Point.new( 0, 11), Point.new(-9, -3), Point.new(-4, -2), Point.new(12, 10) ] hull = convexHull(points) print , hull.join(), end main()
1,002Convex hull
14ruby
zc5tw
co = {} co[1] = coroutine.create( function() print "Enjoy" end ) co[2] = coroutine.create( function() print "Rosetta" end ) co[3] = coroutine.create( function() print "Code" end ) math.randomseed( os.time() ) h = {} i = 0 repeat j = math.random(3) if h[j] == nil then coroutine.resume( co[j] ) h[j] = true i = i + 1 end until i == 3
1,006Concurrent computing
1lua
1s0po
(defn fac [n] (apply * (range 1 (inc n)))) (defmacro ct-factorial [n] (fac n))
1,008Compile-time calculation
6clojure
xiowk
extension BinaryInteger { @inlinable public func power(_ n: Self) -> Self { return stride(from: 0, to: n, by: 1).lazy.map({_ in self }).reduce(1, *) } } public struct CycledSequence<WrappedSequence: Sequence> { private var seq: WrappedSequence private var iter: WrappedSequence.Iterator init(seq: WrappedSequence) { self.seq = seq self.iter = seq.makeIterator() } } extension CycledSequence: Sequence, IteratorProtocol { public mutating func next() -> WrappedSequence.Element? { if let ele = iter.next() { return ele } else { iter = seq.makeIterator() return iter.next() } } } extension Sequence { public func cycled() -> CycledSequence<Self> { return CycledSequence(seq: self) } } public struct ChainedSequence<Element> { private var sequences: [AnySequence<Element>] private var iter: AnyIterator<Element> private var curSeq = 0 init(chain: ChainedSequence) { self.sequences = chain.sequences self.iter = chain.iter self.curSeq = chain.curSeq } init<Seq: Sequence>(_ seq: Seq) where Seq.Element == Element { sequences = [AnySequence(seq)] iter = sequences[curSeq].makeIterator() } func chained<Seq: Sequence>(with seq: Seq) -> ChainedSequence where Seq.Element == Element { var res = ChainedSequence(chain: self) res.sequences.append(AnySequence(seq)) return res } } extension ChainedSequence: Sequence, IteratorProtocol { public mutating func next() -> Element? { if let el = iter.next() { return el } curSeq += 1 guard curSeq!= sequences.endIndex else { return nil } iter = sequences[curSeq].makeIterator() return iter.next() } } extension Sequence { public func chained<Seq: Sequence>(with other: Seq) -> ChainedSequence<Element> where Seq.Element == Element { return ChainedSequence(self).chained(with: other) } } func continuedFraction<T: Sequence, V: Sequence>( _ seq1: T, _ seq2: V, iterations: Int = 1000 ) -> Double where T.Element: BinaryInteger, T.Element == V.Element { return zip(seq1, seq2).prefix(iterations).reversed().reduce(0.0, { Double($1.0) + (Double($1.1) / $0) }) } let sqrtA = [1].chained(with: [2].cycled()) let sqrtB = [1].cycled() print("2 \(continuedFraction(sqrtA, sqrtB))") let napierA = [2].chained(with: 1...) let napierB = [1].chained(with: 1...) print("e \(continuedFraction(napierA, napierB))") let piA = [3].chained(with: [6].cycled()) let piB = (1...).lazy.map({ (2 * $0 - 1).power(2) }) print(" \(continuedFraction(piA, piB))")
1,001Continued fraction
17swift
pqnbl
>>> src = >>> a = src >>> b = src[:] >>> import copy >>> c = copy.copy(src) >>> d = copy.deepcopy(src) >>> src is a is b is c is d True
997Copy a string
3python
hedjw
#[derive(Debug, Clone)] struct Point { x: f32, y: f32 } fn calculate_convex_hull(points: &Vec<Point>) -> Vec<Point> {
1,002Convex hull
15rust
3l4z8
func duration (_ secs:Int) -> String { if secs <= 0 { return "" } let units = [(604800,"wk"), (86400,"d"), (3600,"hr"), (60,"min")] var secs = secs var result = "" for (period, unit) in units { if secs >= period { result += "\(secs/period) \(unit), " secs = secs% period } } if secs == 0 { result.removeLast(2)
998Convert seconds to compound duration
17swift
henj0
type point struct { x, y float64 }
1,007Compound data type
0go
qnnxz
str1 <- "abc" str2 <- str1
997Copy a string
13r
gb847
object convex_hull{ def get_hull(points:List[(Double,Double)], hull:List[(Double,Double)]):List[(Double,Double)] = points match{ case Nil => join_tail(hull,hull.size -1) case head :: tail => get_hull(tail,reduce(head::hull)) } def reduce(hull:List[(Double,Double)]):List[(Double,Double)] = hull match{ case p1::p2::p3::rest => { if(check_point(p1,p2,p3)) hull else reduce(p1::p3::rest) } case _ => hull } def check_point(pnt:(Double,Double), p2:(Double,Double),p1:(Double,Double)): Boolean = { val (x,y) = (pnt._1,pnt._2) val (x1,y1) = (p1._1,p1._2) val (x2,y2) = (p2._1,p2._2) ((x-x1)*(y2-y1) - (x2-x1)*(y-y1)) <= 0 } def m(p1:(Double,Double), p2:(Double,Double)):Double = { if(p2._1 == p1._1 && p1._2>p2._2) 90 else if(p2._1 == p1._1 && p1._2<p2._2) -90 else if(p1._1<p2._1) 180 - Math.toDegrees(Math.atan(-(p1._2 - p2._2)/(p1._1 - p2._1))) else Math.toDegrees(Math.atan((p1._2 - p2._2)/(p1._1 - p2._1))) } def join_tail(hull:List[(Double,Double)],len:Int):List[(Double,Double)] = { if(m(hull(len),hull(0)) > m(hull(len-1),hull(0))) join_tail(hull.slice(0,len),len-1) else hull } def main(args:Array[String]){ val points = List[(Double,Double)]((16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2), (12,10)) val sorted_points = points.sortWith(m(_,(0.0,0.0)) < m(_,(0.0,0.0))) println(f"Points:\n" + points + f"\n\nConvex Hull:\n" +get_hull(sorted_points,List[(Double,Double)]())) } }
1,002Convex hull
16scala
mu7yc
class Point { int x int y
1,007Compound data type
7groovy
1ssp6
data Tree = Empty | Leaf Int | Node Tree Tree deriving (Eq, Show) t1 = Node (Leaf 1) (Node (Leaf 2) (Leaf 3))
1,007Compound data type
8haskell
muuyf
package main import "fmt" func main() { fmt.Println(2*3*4*5*6*7*8*9*10) }
1,008Compile-time calculation
0go
62l3p
module Factorial where import Language.Haskell.TH.Syntax fact n = product [1..n] factQ :: Integer -> Q Exp factQ = lift . fact
1,008Compile-time calculation
8haskell
ja17g
null
1,008Compile-time calculation
11kotlin
95umh
local factorial = 10*9*8*7*6*5*4*3*2*1 print(factorial)
1,008Compile-time calculation
1lua
c4592
public class Point { public int x, y; public Point() { this(0); } public Point(int x0) { this(x0,0); } public Point(int x0, int y0) { x = x0; y = y0; } public static void main(String args[]) { Point point = new Point(1,2); System.out.println("x = " + point.x ); System.out.println("y = " + point.y ); } }
1,007Compound data type
9java
fmmdv
my @points; while (@points < 100) { my ($x, $y) = (int(rand(31))-15, int(rand(31)) - 15); my $r2 = $x*$x + $y*$y; next if $r2 < 100 || $r2 > 225; push @points, [$x, $y]; } print << 'HEAD'; %!PS-Adobe-3.0 EPSF-3.0 %%BoundingBox 0 0 400 400 200 200 translate 10 10 scale 0 setlinewidth 1 0 0 setrgbcolor 0 0 10 0 360 arc stroke 0 0 15 360 0 arcn stroke 0 setgray /pt { .1 0 360 arc fill } def HEAD print "@$_ pt\n" for @points; print "%%EOF";
1,003Constrained random points on a circle
2perl
i39o3
null
1,007Compound data type
10javascript
yvv6r