code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
import re txt = def haspunctotype(s): return 'S' if '.' in s else 'E' if '!' in s else 'Q' if '?' in s else 'N' txt = re.sub('\n', '', txt) pars = [s.strip() for s in re.split(, txt)] if len(pars)% 2: pars.append('') for i in range(0, len(pars)-1, 2): print((pars[i] + pars[i + 1]).ljust(54), , haspunc...
937Determine sentence type
3python
83t0o
int dot_product(int *, int *, size_t); int main(void) { int a[3] = {1, 3, -5}; int b[3] = {4, -2, -1}; printf(, dot_product(a, b, sizeof(a) / sizeof(a[0]))); return EXIT_SUCCESS; } int dot_product(int *a, int *b, size_t n) { int sum = 0; size_t i; for (i = 0;...
938Dot product
5c
cr59c
int verbose = 0; typedef int(*condition)(int *); int solution[N_FLOORS] = { 0 }; int occupied[N_FLOORS] = { 0 }; enum tenants { baker = 0, cooper, fletcher, miller, smith, phantom_of_the_opera, }; const char *names[] = { , , , , , }; COND(c0, s[baker] != TOP); COND(c1, s[cooper] != 0); COND(c2, s[fle...
939Dinesman's multiple-dwelling problem
5c
l75cy
typedef uint32_t uint; typedef uint64_t ulong; ulong ipow(const uint x, const uint y) { ulong result = 1; for (uint i = 1; i <= y; i++) result *= x; return result; } uint min(const uint x, const uint y) { return (x < y) ? x : y; } void throw_die(const uint n_sides, const uint n_dice, const ui...
940Dice game probabilities
5c
z2ytx
(defn dot-product [& matrix] {:pre [(apply == (map count matrix))]} (apply + (apply map * matrix))) (defn dot-product2 [x y] (->> (interleave x y) (partition 2 2) (map #(apply * %)) (reduce +))) (defn dot-product3 "Dot product of vectors. Tested on version 1.8.0." [v1 v2] {:pre [(= (count...
938Dot product
6clojure
5bjuz
const char *names[N] = { , , , , }; pthread_mutex_t forks[N]; const char *topic[M] = { , , , , }; void print(int y, int x, const char *fmt, ...) { static pthread_mutex_t screen = PTHREAD_MUTEX_INITIALIZER; va_list ap; va_start(ap, fmt); lock(&screen); xy(y + 1, x), vprintf(fmt, ap); xy(N + 1, 1), fflush...
941Dining philosophers
5c
6um32
typedef struct { int vertex; int weight; } edge_t; typedef struct { edge_t **edges; int edges_len; int edges_size; int dist; int prev; int visited; } vertex_t; typedef struct { vertex_t **vertices; int vertices_len; int vertices_size; } graph_t; typedef struct { int *d...
942Dijkstra's algorithm
5c
l72cy
(ns rosettacode.dinesman (:use [clojure.core.logic] [clojure.tools.macro:as macro])) (defne aboveo [x y s] ([_ _ (x y .?rest)]) ([_ _ [_ .?rest]] (aboveo x y?rest))) (defne highero [x y s] ([_ _ (x .?rest)] (membero y?rest)) ([_ _ (_ .?rest)] (highero x y?rest))) (defn nonadj...
939Dinesman's multiple-dwelling problem
6clojure
4pj5o
package main import( "math" "fmt" ) func minOf(x, y uint) uint { if x < y { return x } return y } func throwDie(nSides, nDice, s uint, counts []uint) { if nDice == 0 { counts[s]++ return } for i := uint(1); i <= nSides; i++ { throwDie(nSides, nDice - 1,...
940Dice game probabilities
0go
kq1hz
import Control.Monad (replicateM) import Data.List (group, sort) succeeds :: (Int, Int) -> (Int, Int) -> Double succeeds p1 p2 = sum [ realToFrac (c1 * c2) / totalOutcomes | (s1, c1) <- countSums p1 , (s2, c2) <- countSums p2 , s1 > s2 ] where totalOutcomes = realToFrac $ uncurry (^) p1 * unc...
940Dice game probabilities
8haskell
nmtie
void fail(const char *message) { perror(message); exit(1); } static char *ooi_path; void ooi_unlink(void) { unlink(ooi_path); } void only_one_instance(void) { struct flock fl; size_t dirlen; int fd; char *dir; dir = getenv(); if (dir == NULL || dir[0] != '/') { fputs(, stderr); exit(1); } dirlen ...
943Determine if only one instance is running
5c
7e7rg
(defn make-fork [] (ref true)) (defn make-philosopher [name forks food-amt] (ref {:name name:forks forks:eating? false:food food-amt})) (defn start-eating [phil] (dosync (if (every? true? (map ensure (:forks @phil))) (do (doseq [f (:forks @phil)] (alter f not)) (alter phil assoc:eat...
941Dining philosophers
6clojure
l7vcb
import java.util.Random; public class Dice{ private static int roll(int nDice, int nSides){ int sum = 0; Random rand = new Random(); for(int i = 0; i < nDice; i++){ sum += rand.nextInt(nSides) + 1; } return sum; } private static int diceGame(int p1Dice, int p1Sides, int p2Dice, int p2Sides, int rolls)...
940Dice game probabilities
9java
qf8xa
(import (java.net ServerSocket InetAddress)) (def *port* 12345) (try (new ServerSocket *port* 10 (. InetAddress getLocalHost)) (catch IOException e (System/exit 0)))
943Determine if only one instance is running
6clojure
p0pbd
(declare neighbours process-neighbour prepare-costs get-next-node unwind-path all-shortest-paths) (defn dijkstra "Given two nodes A and B, and graph, finds shortest path from point A to point B. Given one node and graph, finds all shortest paths to all other nodes. ...
942Dijkstra's algorithm
6clojure
4pg5o
package main import "fmt"
936Digital root/Multiplicative digital root
0go
6uv3p
(x) == 2? :\ (x) == 3? :\ (x) == 4? :\ ) (x) == 1? :\ (x) == 2? :\ (x) == 3? :\ ) char * ddate( int y, int d ){ int dyear = 1166 + y; char * result = m...
944Discordian date
5c
f9nd3
import Control.Arrow import Data.Array import Data.LazyArray import Data.List (unfoldr) import Data.Tuple import Text.Printf mpmdr :: Integer -> (Int, Integer) mpmdr = (length *** head) . span (> 9) . iterate (product . digits) mdrNums :: Int -> [(Integer, [Integer])] mdrNums k = assocs $ lArrayMap (take k) (0,9)...
936Digital root/Multiplicative digital root
8haskell
jwe7g
from collections import deque some_list = deque([, , ]) print(some_list) some_list.appendleft() print(some_list) for value in reversed(some_list): print(value)
934Doubly-linked list/Definition
3python
m4gyh
package main import ( "fmt" "net" "time" ) const lNet = "tcp" const lAddr = ":12345" func main() { if _, err := net.Listen(lNet, lAddr); err != nil { fmt.Println("an instance was already running") return } fmt.Println("single instance started") time.Sleep(10 * time.Second)...
943Determine if only one instance is running
0go
d9dne
import Control.Concurrent import System.Directory (doesFileExist, getAppUserDataDirectory, removeFile) import System.IO (withFile, Handle, IOMode(WriteMode), hPutStr) oneInstance :: IO () oneInstance = do user <- getAppUserDataDirectory "myapp.lock" locked <- doesFileExist user if locked then ...
943Determine if only one instance is running
8haskell
5b5ug
int droot(long long int x, int base, int *pers) { int d = 0; if (pers) for (*pers = 0; x >= base; x = d, (*pers)++) for (d = 0; x; d += x % base, x /= base); else if (x && !(d = x % (base - 1))) d = base - 1; return d; } int main(void) { int i, d, pers; long long x[] = {627615, 39390, 588225, 3939005882...
945Digital root
5c
0txst
num dot(List<num> A, List<num> B){ if (A.length!= B.length){ throw new Exception('Vectors must be of equal size'); } num result = 0; for (int i = 0; i < A.length; i++){ result += A[i] * B[i]; } return result; } void main(){ var l = [1,3,-5]; var k = [4,-2,-1]; print(dot(l,k)); }
938Dot product
18dart
z29te
null
940Dice game probabilities
11kotlin
18wpd
import java.io.IOException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.UnknownHostException; public class SingletonApp { private static final int PORT = 65000;
943Determine if only one instance is running
9java
9g9mu
local function simu(ndice1, nsides1, ndice2, nsides2) local function roll(ndice, nsides) local result = 0; for i = 1, ndice do result = result + math.random(nsides) end return result end local wins, coms = 0, 1000000 for i = 1, coms do local roll1 = roll(ndice1, nsides1) local roll...
940Dice game probabilities
1lua
aox1v
null
943Determine if only one instance is running
11kotlin
z2zts
(require '[clj-time.core:as tc]) (def seasons ["Chaos" "Discord" "Confusion" "Bureaucracy" "The Aftermath"]) (def weekdays ["Sweetmorn" "Boomtime" "Pungenday" "Prickle-Prickle" "Setting Orange"]) (def year-offset 1166) (defn leap-year? [year] (= 29 (tc/number-of-days-in-the-month year 2))) (defn discordian-day [da...
944Discordian date
6clojure
yu36b
import java.util.*; public class MultiplicativeDigitalRoot { public static void main(String[] args) { System.out.println("NUMBER MDR MP"); for (long n : new long[]{123321, 7739, 893, 899998}) { long[] a = multiplicativeDigitalRoot(n); System.out.printf("%6d%4d%4d%n", a[...
936Digital root/Multiplicative digital root
9java
ukhvv
(defn dig-root [value] (let [digits (fn [n] (map #(- (byte %) (byte \0)) (str n))) sum (fn [nums] (reduce + nums))] (loop [n value step 0] (if (< n 10) {:n value:add-persist step:digital-root n} (recur (sum (dig...
945Digital root
6clojure
dmonb
(cond-expand (r7rs) (chicken (import r7rs))) (import (scheme base)) (import (scheme write)) (import (scheme case-lambda)) (import (scheme process-context)) ;; A doubly-linked list will be represented by a reference to any of ;; its nodes. This is possible because the is marked as ;; such. (define-record-type <dl...
934Doubly-linked list/Definition
14ruby
cr79k
use List::Util qw(sum0 max); sub comb { my ($s, $n) = @_; $n || return (1); my @r = (0) x ($n - max(@$s) + 1); my @c = comb($s, $n - 1); foreach my $i (0 .. $ $c[$i] || next; foreach my $k (@$s) { $r[$i + $k] += $c[$i]; } } return @r; } sub winning { ...
940Dice game probabilities
2perl
m4lyz
use Fcntl ':flock'; INIT { die "Not able to open $0\n" unless (open ME, $0); die "I'm already running!!\n" unless(flock ME, LOCK_EX|LOCK_NB); } sleep 60;
943Determine if only one instance is running
2perl
bsbk4
package main import ( "container/heap" "fmt" )
942Dijkstra's algorithm
0go
xdqwf
null
936Digital root/Multiplicative digital root
11kotlin
9g4mh
import __main__, os def isOnlyInstance(): return os.system( + __main__.__file__[0] + + __main__.__file__[1:] + ) != 0
943Determine if only one instance is running
3python
p0pbm
import Data.Array import Data.Array.MArray import Data.Array.ST import Control.Monad.ST import Control.Monad (foldM) import Data.Set as S dijkstra :: (Ix v, Num w, Ord w, Bounded w) => v -> v -> Array v [(v,w)] -> (Array v w, Array v v) dijkstra src invalid_index adj_list = runST $ do min_distance <- newSTArray b ma...
942Dijkstra's algorithm
8haskell
y5m66
package main import "fmt"
939Dinesman's multiple-dwelling problem
0go
xd8wf
typealias NodePtr<T> = UnsafeMutablePointer<Node<T>> class Node<T> { var value: T fileprivate var prev: NodePtr<T>? fileprivate var next: NodePtr<T>? init(value: T, prev: NodePtr<T>? = nil, next: NodePtr<T>? = nil) { self.value = value self.prev = prev self.next = next } } struct DoublyLinkedLi...
934Doubly-linked list/Definition
17swift
9grmj
import Data.List (permutations) import Control.Monad (guard) dinesman :: [(Int,Int,Int,Int,Int)] dinesman = do [baker, cooper, fletcher, miller, smith] <- permutations [1..5] guard $ baker /= 5 guard $ cooper /= 1 guard $ fletcher /= 5 && fletcher /= 1 guard $ miller > cooper ...
939Dinesman's multiple-dwelling problem
8haskell
y5l66
from itertools import product def gen_dict(n_faces, n_dice): counts = [0] * ((n_faces + 1) * n_dice) for t in product(range(1, n_faces + 1), repeat=n_dice): counts[sum(t)] += 1 return counts, n_faces ** n_dice def beating_probability(n_sides1, n_dice1, n_sides2, n_dice2): c1, p1 = gen_dict(n_s...
940Dice game probabilities
3python
9g2mf
def main puts sleep 20 puts :done end if $0 == __FILE__ if File.new(__FILE__).flock(File::LOCK_EX | File::LOCK_NB) main else raise end end __END__
943Determine if only one instance is running
14ruby
aoa1s
use std::net::TcpListener; fn create_app_lock(port: u16) -> TcpListener { match TcpListener::bind(("0.0.0.0", port)) { Ok(socket) => { socket }, Err(_) => { panic!("Couldn't lock port {}: another instance already running?", port); } } } fn remove_app_loc...
943Determine if only one instance is running
15rust
eieaj
package main import ( "hash/fnv" "log" "math/rand" "os" "time" )
941Dining philosophers
0go
p0abg
typedef struct charList{ char c; struct charList *next; } charList; int strcmpi(char str1[100],char str2[100]){ int len1 = strlen(str1), len2 = strlen(str2), i; if(len1!=len2){ return 1; } else{ for(i=0;i<len1;i++){ if((str1[i]>='A'&&str1[i]<='Z')&&(str2[i]>='a'&...
946Determine if a string is squeezable
5c
dm8nv
probability <- function(facesCount1, diceCount1, facesCount2, diceCount2) { mean(replicate(10^6, sum(sample(facesCount1, diceCount1, replace = TRUE)) > sum(sample(facesCount2, diceCount2, replace = TRUE)))) } cat("Player 1's probability of victory is", probability(4, 9, 6, 6), "in the first game and", probability...
940Dice game probabilities
13r
3vmzt
import java.io.IOException import java.net.{InetAddress, ServerSocket} object SingletonApp extends App { private val port = 65000 try { val s = new ServerSocket(port, 10, InetAddress.getLocalHost) } catch { case _: IOException =>
943Determine if only one instance is running
16scala
qfqxw
import Foundation let globalCenter = NSDistributedNotificationCenter.defaultCenter() let time = NSDate().timeIntervalSince1970 globalCenter.addObserverForName("OnlyOne", object: nil, queue: NSOperationQueue.mainQueue()) {not in if let senderTime = not.userInfo?["time"] as? NSTimeInterval where senderTime!= time {...
943Determine if only one instance is running
17swift
181pt
import groovy.transform.Canonical import java.util.concurrent.locks.Lock import java.util.concurrent.locks.ReentrantLock @Canonical class Fork { String name Lock lock = new ReentrantLock() void pickUp(String philosopher) { lock.lock() println " $philosopher picked up $name" } vo...
941Dining philosophers
7groovy
7ehrz
module Philosophers where import Control.Monad import Control.Concurrent import Control.Concurrent.STM import System.Random type Fork = TMVar Int newFork :: Int -> IO Fork newFork i = newTMVarIO i takeFork :: Fork -> STM Int takeFork fork = takeTMVar fork releaseFork :: Int -> Fork -> STM () releaseFork i f...
941Dining philosophers
8haskell
fczd1
package ddate import ( "strconv" "strings" "time" )
944Discordian date
0go
jer7d
import java.io.*; import java.util.*; public class Dijkstra { private static final Graph.Edge[] GRAPH = { new Graph.Edge("a", "b", 7), new Graph.Edge("a", "c", 9), new Graph.Edge("a", "f", 14), new Graph.Edge("b", "c", 10), new Graph.Edge("b", "d", 15), new Graph.Edge("c", "d", 1...
942Dijkstra's algorithm
9java
d9fn9
import java.util.*; class DinesmanMultipleDwelling { private static void generatePermutations(String[] apartmentDwellers, Set<String> set, String curPermutation) { for (String s : apartmentDwellers) { if (!curPermutation.contains(s)) { String nextPermutation = curPermutation + ...
939Dinesman's multiple-dwelling problem
9java
d93n9
double det_in(double **in, int n, int perm) { if (n == 1) return in[0][0]; double sum = 0, *m[--n]; for (int i = 0; i < n; i++) m[i] = in[i + 1] + 1; for (int i = 0, sgn = 1; i <= n; i++) { sum += sgn * (in[i][0] * det_in(m, n, perm)); if (i == n) break; m[i] = in[i] + 1; if (!perm) sgn = -sgn; } ret...
947Determinant and permanent
5c
eokav
typedef struct charList{ char c; struct charList *next; } charList; int strcmpi(char* str1,char* str2){ int len1 = strlen(str1), len2 = strlen(str2), i; if(len1!=len2){ return 1; } else{ for(i=0;i<len1;i++){ if((str1[i]>='A'&&str1[i]<='Z')&&(str2[i]>='a'&&str2[i]...
948Determine if a string is collapsible
5c
xnbwu
int main(int argc,char** argv) { int i,len; char reference; if(argc>2){ printf(,argv[0]); return 0; } if(argc==1||strlen(argv[1])==1){ printf(%s\,argc==1?:argv[1],argc==1?0:(int)strlen(argv[1])); return 0; } reference = argv[1][0]; len = strlen(argv[1])...
949Determine if a string has all the same characters
5c
yun6f
import Data.Time (isLeapYear) import Data.Time.Calendar.MonthDay (monthAndDayToDayOfYear) import Text.Printf (printf) type Year = Integer type Day = Int type Month = Int data DDate = DDate Weekday Season Day Year | StTibsDay Year deriving (Eq, Ord) data Season = Chaos | Discord | C...
944Discordian date
8haskell
o308p
const dijkstra = (edges,source,target) => { const Q = new Set(), prev = {}, dist = {}, adj = {} const vertex_with_min_dist = (Q,dist) => { let min_distance = Infinity, u = null for (let v of Q) { if (dist[v] < min_distance) { ...
942Dijkstra's algorithm
10javascript
6uy38
use warnings; use strict; sub mdr { my $n = shift; my($count, $mdr) = (0, $n); while ($mdr > 9) { my($m, $dm) = ($mdr, 1); while ($m) { $dm *= $m % 10; $m = int($m/10); } $mdr = $dm; $count++; } ($count, $mdr); } print "Number: (MP, MDR)\n====== =========\n"; foreach my $n (...
936Digital root/Multiplicative digital root
2perl
wnie6
(() => { 'use strict';
939Dinesman's multiple-dwelling problem
10javascript
6uc38
(defn squeeze [s c] (let [spans (partition-by #(= c %) s) span-out (fn [span] (if (= c (first span)) (str c) (apply str span)))] (apply str (map span-out spans)))) (defn test-squeeze [s c] (let [out (squeeze s c)] (println (format "Input:...
946Determine if a string is squeezable
6clojure
6vf3q
def roll_dice(n_dice, n_faces) return [[0,1]] if n_dice.zero? one = [1] * n_faces zero = [0] * (n_faces-1) (1...n_dice).inject(one){|ary,_| (zero + ary + zero).each_cons(n_faces).map{|a| a.inject(:+)} }.map.with_index(n_dice){|n,sum| [sum,n]} end def game(dice1, faces1, dice2, faces2) p1 = roll_dice...
940Dice game probabilities
14ruby
l7ucl
typedef struct { double x, y; } Point; double det2D(const Point * const p1, const Point * const p2, const Point * const p3) { return p1->x * (p2->y - p3->y) + p2->x * (p3->y - p1->y) + p3->x * (p1->y - p2->y); } void checkTriWinding(Point * p1, Point * p2, Point * p3, bool allowReversed) { ...
950Determine if two triangles overlap
5c
vj32o
(defn collapse [s] (let [runs (partition-by identity s)] (apply str (map first runs)))) (defn run-test [s] (let [out (collapse s)] (str (format "Input: <<<%s>>> (len%d)\n" s (count s)) (format "becomes: <<<%s>>> (len%d)\n" out (count out)))))
948Determine if a string is collapsible
6clojure
o3w8j
null
940Dice game probabilities
15rust
2j5lt
package diningphilosophers; import java.util.ArrayList; import java.util.Random; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; enum PhilosopherState { Get, Eat, Pon } class Fork { public static final int ON_TABLE = -1; static int instances = 0; public...
941Dining philosophers
9java
0zose
package main import ( "fmt" "rcu" "sort" "strconv" ) func combinations(a []int, k int) [][]int { n := len(a) c := make([]int, k) var combs [][]int var combine func(start, end, index int) combine = func(start, end, index int) { if index == k { t := make([]int, le...
951Descending primes
0go
0tbsk
typedef struct positionList{ int position; struct positionList *next; }positionList; typedef struct letterList{ char letter; int repititions; positionList* positions; struct letterList *next; }letterList; letterList* letterSet; bool duplicatesFound = false; void checkAndUpdateLetterList(char ...
952Determine if a string has all unique characters
5c
gpy45
(defn check-all-chars-same [s] (println (format "String (%s) of len:%d" s (count s))) (let [num-same (-> (take-while #(= (first s) %) s) count)] (if (= num-same (count s)) (println "...all characters the same") (println (format "...character%d differs - it is 0x%x" ...
949Determine if a string has all the same characters
6clojure
273l1
import java.util.Calendar; import java.util.GregorianCalendar; public class DiscordianDate { final static String[] seasons = {"Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"}; final static String[] weekday = {"Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle", "Setting Ora...
944Discordian date
9java
wiaej
null
942Dijkstra's algorithm
11kotlin
0z8sf
try: from functools import reduce except: pass def mdroot(n): 'Multiplicative digital root' mdr = [n] while mdr[-1] > 9: mdr.append(reduce(int.__mul__, (int(dig) for dig in str(mdr[-1])), 1)) return len(mdr) - 1, mdr[-1] if __name__ == '__main__': print('Number: (MP, MDR)\n====== ...
936Digital root/Multiplicative digital root
3python
xdnwr
local function is_prime(n) if n < 2 then return false end if n % 2 == 0 then return n==2 end if n % 3 == 0 then return n==3 end for f = 5, n^0.5, 6 do if n%f==0 or n%(f+2)==0 then return false end end return true end local function descending_primes() local digits, candidates, primes = {9,8,7,6,5,4,3...
951Descending primes
1lua
nyei8
var seasons = [ "Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath" ]; var weekday = [ "Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle", "Setting Orange" ]; var apostle = [ "Mungday", "Mojoday", "Syaday", "Zaraday", "Maladay" ]; var holiday = [ "Chaoflux", "Discoflux", "Confuflux", ...
944Discordian date
10javascript
8zs0l
null
942Dijkstra's algorithm
1lua
83o0e
null
939Dinesman's multiple-dwelling problem
11kotlin
0znsf
use strict; use warnings; use ntheory qw( is_prime ); print join('', sort map { sprintf "%9d", $_ } grep /./ && is_prime($_), glob join '', map "{$_,}", reverse 1 .. 9) =~ s/.{45}\K/\n/gr;
951Descending primes
2perl
r19gd
static sigjmp_buf fpe_env; static void fpe_handler(int signal, siginfo_t *w, void *a) { siglongjmp(fpe_env, w->si_code); } void try_division(int x, int y) { struct sigaction act, old; int code; volatile int result; code = sigsetjmp(fpe_env, 1); if (code == 0) { act.sa_sigaction = fpe_handler; si...
953Detect division by zero
5c
27dlo
null
941Dining philosophers
11kotlin
eixa4
local wrap, yield = coroutine.wrap, coroutine.yield local function perm(n) local r = {} for i=1,n do r[i]=i end return wrap(function() local function swap(m) if m==0 then yield(r) else for i=m,1,-1 do r[i],r[m]=r[m],r[i] swap(m-1) r[i],...
939Dinesman's multiple-dwelling problem
1lua
83d0e
package main import "fmt"
946Determine if a string is squeezable
0go
7a5r2
package main import ( "fmt" "math" ) type rule func(float64, float64) float64 var dxs = []float64{ -0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001, -0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014, 0...
954Deming's Funnel
0go
r16gm
from sympy import isprime def descending(xs=range(10)): for x in xs: yield x yield from descending(x*10 + d for d in range(x%10)) for i, p in enumerate(sorted(filter(isprime, descending()))): print(f'{p:9d}', end=' ' if (1 + i)%8 else '\n') print()
951Descending primes
3python
7acrm
(defn uniq-char-string [s] (let [len (count s)] (if (= len (count (set s))) (println (format "All%d chars unique in: '%s'" len s)) (loop [prev-chars #{} idx 0 chars (vec s)] (let [c (first chars)] (if (contains? prev-chars c) (println (format "...
952Determine if a string has all unique characters
6clojure
kx2hs
package main import "fmt"
948Determine if a string is collapsible
0go
lr3cw
class StringSqueezable { static void main(String[] args) { String[] testStrings = [ "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I...
946Determine if a string is squeezable
7groovy
uhcv9
import Data.List (mapAccumL, genericLength) import Text.Printf funnel :: (Num a) => (a -> a -> a) -> [a] -> [a] funnel rule = snd . mapAccumL (\x dx -> (rule x dx, x + dx)) 0 mean :: (Fractional a) => [a] -> a mean xs = sum xs / genericLength xs stddev :: (Floating a) => [a] -> a stddev xs = sqrt $ sum [(x-m)**2 | ...
954Deming's Funnel
8haskell
0tjs7
typedef const char * (*Responder)( int p1); typedef struct sDelegate { Responder operation; } *Delegate; Delegate NewDelegate( Responder rspndr ) { Delegate dl = malloc(sizeof(struct sDelegate)); dl->operation = rspndr; return dl; } const char *DelegateThing(Delegate dl, int p1) { return (dl->...
955Delegates
5c
jey70
(defn safe-/ [x y] (try (/ x y) (catch ArithmeticException _ (println "Division by zero caught!") (cond (> x 0) Double/POSITIVE_INFINITY (zero? x) Double/NaN :else Double/NEGATIVE_INFINITY) )))
953Detect division by zero
6clojure
gp64f
class StringCollapsible { static void main(String[] args) { for ( String s: [ "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never...
948Determine if a string is collapsible
7groovy
6vn3o
import java.util.Calendar import java.util.GregorianCalendar enum class Season { Chaos, Discord, Confusion, Bureaucracy, Aftermath; companion object { fun from(i: Int) = values()[i / 73] } } enum class Weekday { Sweetmorn, Boomtime, Pungenday, Prickle_Prickle, Setting_Orange; companion object { fun fro...
944Discordian date
11kotlin
bqhkb
package main import ( "fmt" "log" "strconv" ) func Sum(i uint64, base int) (sum int) { b64 := uint64(base) for ; i > 0; i /= b64 { sum += int(i % b64) } return } func DigitalRoot(n uint64, base int) (persistence, root int) { root = int(n) for x := n; x >= uint64(base); x = uint64(root) { root = Sum(x, b...
945Digital root
0go
uhlvt
package main import ( "errors" "fmt" "log" ) var ( v1 = []int{1, 3, -5} v2 = []int{4, -2, -1} ) func dot(x, y []int) (r int, err error) { if len(x) != len(y) { return 0, errors.New("incompatible lengths") } for i, xi := range x { r += xi * y[i] } return } func...
938Dot product
0go
wn8eg
import Text.Printf (printf) input :: [(String, Char)] input = [ ("", ' ') , ("The better the 4-wheel drive, the further you'll be from help when ya get stuck!", 'e') , ("headmistressship", 's') , ("\"If I were two-faced, would I be wearing this one?\" , ("..1111111111111111111111111111...
946Determine if a string is squeezable
8haskell
8zx0z
import Text.Printf (printf) import Data.Maybe (catMaybes) import Control.Monad (guard) input :: [String] input = [ "" , "The better the 4-wheel drive, the further you'll be from help when ya get stuck!" , "headmistressship" , "\"If I were two-faced, would I be wearing this one?\" , ".....
948Determine if a string is collapsible
8haskell
107ps
class DigitalRoot { static int[] calcDigitalRoot(String number, int base) { BigInteger bi = new BigInteger(number, base) int additivePersistence = 0 if (bi.signum() < 0) { bi = bi.negate() } BigInteger biBase = BigInteger.valueOf(base) while (bi >= biBase)...
945Digital root
7groovy
946m4
def mdroot(n) mdr, persist = n, 0 until mdr < 10 do mdr = mdr.digits.inject(:*) persist += 1 end [mdr, persist] end puts , [123321, 7739, 893, 899998].each{|n| puts % [n, *mdroot(n)]} counter = Hash.new{|h,k| h[k]=[]} 0.step do |i| counter[mdroot(i).first] << i break if counter.values.all?{|v| v...
936Digital root/Multiplicative digital root
14ruby
stfqw
def dotProduct = { x, y -> assert x && y && x.size() == y.size() [x, y].transpose().collect{ xx, yy -> xx * yy }.sum() }
938Dot product
7groovy
bswky
null
946Determine if a string is squeezable
9java
eoba5
import static java.lang.Math.*; import java.util.Arrays; import java.util.function.BiFunction; public class DemingsFunnel { public static void main(String[] args) { double[] dxs = { -0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251, -0.231, -0.401, 0.269, 0.491, 0....
954Deming's Funnel
9java
a8u1y