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), , haspunctotype(pars[i + 1])) | 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; i < n; i++) {
sum += a[i] * b[i];
}
return sum;
} | 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[fletcher] != 0 && s[fletcher] != TOP);
COND(c3, s[miller] > s[cooper]);
COND(c4, abs(s[smith] - s[fletcher]) != 1);
COND(c5, abs(s[cooper] - s[fletcher]) != 1);
condition cond[] = { c0, c1, c2, c3, c4, c5 };
int solve(int person)
{
int i, j;
if (person == phantom_of_the_opera) {
for (i = 0; i < N_CONDITIONS; i++) {
if (cond[i](solution)) continue;
if (verbose) {
for (j = 0; j < N_FLOORS; j++)
printf(, solution[j], names[j]);
printf(, i);
}
return 0;
}
printf();
for (i = 0; i < N_FLOORS; i++)
printf(, solution[i], names[i]);
return 1;
}
for (i = 0; i < N_FLOORS; i++) {
if (occupied[i]) continue;
solution[person] = i;
occupied[i] = 1;
if (solve(person + 1)) return 1;
occupied[i] = 0;
}
return 0;
}
int main()
{
verbose = 0;
if (!solve(0)) printf();
return 0;
} | 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 uint s, uint counts[]) {
if (n_dice == 0) {
counts[s]++;
return;
}
for (uint i = 1; i < n_sides + 1; i++)
throw_die(n_sides, n_dice - 1, s + i, counts);
}
double beating_probability(const uint n_sides1, const uint n_dice1,
const uint n_sides2, const uint n_dice2) {
const uint len1 = (n_sides1 + 1) * n_dice1;
uint C1[len1];
for (uint i = 0; i < len1; i++)
C1[i] = 0;
throw_die(n_sides1, n_dice1, 0, C1);
const uint len2 = (n_sides2 + 1) * n_dice2;
uint C2[len2];
for (uint j = 0; j < len2; j++)
C2[j] = 0;
throw_die(n_sides2, n_dice2, 0, C2);
const double p12 = (double)(ipow(n_sides1, n_dice1) * ipow(n_sides2, n_dice2));
double tot = 0;
for (uint i = 0; i < len1; i++)
for (uint j = 0; j < min(i, len2); j++)
tot += (double)C1[i] * C2[j] / p12;
return tot;
}
int main() {
printf(, beating_probability(4, 9, 6, 6));
printf(, beating_probability(10, 5, 7, 6));
return 0;
} | 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 v1) (count v2))]}
(reduce + (map * v1 v2)))
(println (dot-product [1 3 -5] [4 -2 -1]))
(println (dot-product2 [1 3 -5] [4 -2 -1]))
(println (dot-product3 [1 3 -5] [4 -2 -1])) | 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(stdout);
unlock(&screen);
}
void eat(int id)
{
int f[2], ration, i;
f[0] = f[1] = id;
f[id & 1] = (id + 1) % N;
clear_eol(id);
print(id, 12, );
for (i = 0; i < 2; i++) {
lock(forks + f[i]);
if (!i) clear_eol(id);
print(id, 12 + (f[i] != id) * 6, , f[i]);
sleep(1);
}
for (i = 0, ration = 3 + rand() % 8; i < ration; i++)
print(id, 24 + i * 4, ), sleep(1);
for (i = 0; i < 2; i++) unlock(forks + f[i]);
}
void think(int id)
{
int i, t;
char buf[64] = {0};
do {
clear_eol(id);
sprintf(buf, , topic[t = rand() % M]);
for (i = 0; buf[i]; i++) {
print(id, i+12, , buf[i]);
if (i < 5) usleep(200000);
}
usleep(500000 + rand() % 1000000);
} while (t);
}
void* philosophize(void *a)
{
int id = *(int*)a;
print(id, 1, , names[id]);
while(1) think(id), eat(id);
}
int main()
{
int i, id[N];
pthread_t tid[N];
for (i = 0; i < N; i++)
pthread_mutex_init(forks + (id[i] = i), 0);
for (i = 0; i < N; i++)
pthread_create(tid + i, 0, philosophize, id + i);
return pthread_join(tid[0], 0);
} | 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 *data;
int *prio;
int *index;
int len;
int size;
} heap_t;
void add_vertex (graph_t *g, int i) {
if (g->vertices_size < i + 1) {
int size = g->vertices_size * 2 > i ? g->vertices_size * 2 : i + 4;
g->vertices = realloc(g->vertices, size * sizeof (vertex_t *));
for (int j = g->vertices_size; j < size; j++)
g->vertices[j] = NULL;
g->vertices_size = size;
}
if (!g->vertices[i]) {
g->vertices[i] = calloc(1, sizeof (vertex_t));
g->vertices_len++;
}
}
void add_edge (graph_t *g, int a, int b, int w) {
a = a - 'a';
b = b - 'a';
add_vertex(g, a);
add_vertex(g, b);
vertex_t *v = g->vertices[a];
if (v->edges_len >= v->edges_size) {
v->edges_size = v->edges_size ? v->edges_size * 2 : 4;
v->edges = realloc(v->edges, v->edges_size * sizeof (edge_t *));
}
edge_t *e = calloc(1, sizeof (edge_t));
e->vertex = b;
e->weight = w;
v->edges[v->edges_len++] = e;
}
heap_t *create_heap (int n) {
heap_t *h = calloc(1, sizeof (heap_t));
h->data = calloc(n + 1, sizeof (int));
h->prio = calloc(n + 1, sizeof (int));
h->index = calloc(n, sizeof (int));
return h;
}
void push_heap (heap_t *h, int v, int p) {
int i = h->index[v] == 0 ? ++h->len : h->index[v];
int j = i / 2;
while (i > 1) {
if (h->prio[j] < p)
break;
h->data[i] = h->data[j];
h->prio[i] = h->prio[j];
h->index[h->data[i]] = i;
i = j;
j = j / 2;
}
h->data[i] = v;
h->prio[i] = p;
h->index[v] = i;
}
int min (heap_t *h, int i, int j, int k) {
int m = i;
if (j <= h->len && h->prio[j] < h->prio[m])
m = j;
if (k <= h->len && h->prio[k] < h->prio[m])
m = k;
return m;
}
int pop_heap (heap_t *h) {
int v = h->data[1];
int i = 1;
while (1) {
int j = min(h, h->len, 2 * i, 2 * i + 1);
if (j == h->len)
break;
h->data[i] = h->data[j];
h->prio[i] = h->prio[j];
h->index[h->data[i]] = i;
i = j;
}
h->data[i] = h->data[h->len];
h->prio[i] = h->prio[h->len];
h->index[h->data[i]] = i;
h->len--;
return v;
}
void dijkstra (graph_t *g, int a, int b) {
int i, j;
a = a - 'a';
b = b - 'a';
for (i = 0; i < g->vertices_len; i++) {
vertex_t *v = g->vertices[i];
v->dist = INT_MAX;
v->prev = 0;
v->visited = 0;
}
vertex_t *v = g->vertices[a];
v->dist = 0;
heap_t *h = create_heap(g->vertices_len);
push_heap(h, a, v->dist);
while (h->len) {
i = pop_heap(h);
if (i == b)
break;
v = g->vertices[i];
v->visited = 1;
for (j = 0; j < v->edges_len; j++) {
edge_t *e = v->edges[j];
vertex_t *u = g->vertices[e->vertex];
if (!u->visited && v->dist + e->weight <= u->dist) {
u->prev = i;
u->dist = v->dist + e->weight;
push_heap(h, e->vertex, u->dist);
}
}
}
}
void print_path (graph_t *g, int i) {
int n, j;
vertex_t *v, *u;
i = i - 'a';
v = g->vertices[i];
if (v->dist == INT_MAX) {
printf();
return;
}
for (n = 1, u = v; u->dist; u = g->vertices[u->prev], n++)
;
char *path = malloc(n);
path[n - 1] = 'a' + i;
for (j = 0, u = v; u->dist; u = g->vertices[u->prev], j++)
path[n - j - 2] = 'a' + u->prev;
printf(, v->dist, n, path);
}
int main () {
graph_t *g = calloc(1, sizeof (graph_t));
add_edge(g, 'a', 'b', 7);
add_edge(g, 'a', 'c', 9);
add_edge(g, 'a', 'f', 14);
add_edge(g, 'b', 'c', 10);
add_edge(g, 'b', 'd', 15);
add_edge(g, 'c', 'd', 11);
add_edge(g, 'c', 'f', 2);
add_edge(g, 'd', 'e', 6);
add_edge(g, 'e', 'f', 9);
dijkstra(g, 'a', 'e');
print_path(g, 'e');
return 0;
} | 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 nonadjacento [x y s]
(conda
((aboveo x y s) fail)
((aboveo y x s) fail)
(succeed)))
(defn dinesmano [rs]
(macro/symbol-macrolet [_ (lvar)]
(all
(permuteo ['Baker 'Cooper 'Fletcher 'Miller 'Smith] rs)
(aboveo _ 'Baker rs)
(aboveo 'Cooper _ rs)
(aboveo 'Fletcher _ rs)
(aboveo _ 'Fletcher rs)
(highero 'Miller 'Cooper rs)
(nonadjacento 'Smith 'Fletcher rs)
(nonadjacento 'Fletcher 'Cooper rs))))
(let [solns (run* [q] (dinesmano q))]
(println "solution count:" (count solns))
(println "solution(s) highest to lowest floor:")
(doseq [soln solns] (println " " soln))) | 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, s + i, counts)
}
}
func beatingProbability(nSides1, nDice1, nSides2, nDice2 uint) float64 {
len1 := (nSides1 + 1) * nDice1
c1 := make([]uint, len1) | 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 * uncurry (^) p2
countSums (nFaces, nDice) = f [1 .. nFaces]
where
f =
fmap (((,) . head) <*> (pred . length)) .
group . sort . fmap sum . replicateM nDice
main :: IO ()
main = do
print $ (4, 9) `succeeds` (6, 6)
print $ (10, 5) `succeeds` (7, 6) | 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 = strlen(dir);
ooi_path = malloc(dirlen + sizeof( INSTANCE_LOCK));
if (ooi_path == NULL)
fail();
memcpy(ooi_path, dir, dirlen);
memcpy(ooi_path + dirlen, INSTANCE_LOCK,
sizeof( INSTANCE_LOCK));
fd = open(ooi_path, O_RDWR | O_CREAT, 0600);
if (fd < 0)
fail(ooi_path);
fl.l_start = 0;
fl.l_len = 0;
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
if (fcntl(fd, F_SETLK, &fl) < 0) {
fputs(,
stderr);
exit(1);
}
atexit(ooi_unlink);
}
int
main()
{
int i;
only_one_instance();
for(i = 10; i > 0; i--) {
printf(, i, i % 5 == 1 ? : );
fflush(stdout);
sleep(1);
}
puts();
return 0;
} | 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:eating? true)
(alter phil update-in [:food] dec)
true)
false)))
(defn stop-eating [phil]
(dosync
(when (:eating? @phil)
(alter phil assoc:eating? false)
(doseq [f (:forks @phil)] (alter f not)))))
(defn dine [phil retry-interval max-eat-duration max-think-duration]
(while (pos? (:food @phil))
(if (start-eating phil)
(do
(Thread/sleep (rand-int max-eat-duration))
(stop-eating phil)
(Thread/sleep (rand-int max-think-duration)))
(Thread/sleep retry-interval)))) | 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){
int p1Wins = 0;
for(int i = 0; i < rolls; i++){
int p1Roll = roll(p1Dice, p1Sides);
int p2Roll = roll(p2Dice, p2Sides);
if(p1Roll > p2Roll) p1Wins++;
}
return p1Wins;
}
public static void main(String[] args){
int p1Dice = 9; int p1Sides = 4;
int p2Dice = 6; int p2Sides = 6;
int rolls = 10000;
int p1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);
System.out.println(rolls + " rolls, p1 = " + p1Dice + "d" + p1Sides + ", p2 = " + p2Dice + "d" + p2Sides);
System.out.println("p1 wins " + (100.0 * p1Wins / rolls) + "% of the time");
System.out.println();
p1Dice = 5; p1Sides = 10;
p2Dice = 6; p2Sides = 7;
rolls = 10000;
p1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);
System.out.println(rolls + " rolls, p1 = " + p1Dice + "d" + p1Sides + ", p2 = " + p2Dice + "d" + p2Sides);
System.out.println("p1 wins " + (100.0 * p1Wins / rolls) + "% of the time");
System.out.println();
p1Dice = 9; p1Sides = 4;
p2Dice = 6; p2Sides = 6;
rolls = 1000000;
p1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);
System.out.println(rolls + " rolls, p1 = " + p1Dice + "d" + p1Sides + ", p2 = " + p2Dice + "d" + p2Sides);
System.out.println("p1 wins " + (100.0 * p1Wins / rolls) + "% of the time");
System.out.println();
p1Dice = 5; p1Sides = 10;
p2Dice = 6; p2Sides = 7;
rolls = 1000000;
p1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);
System.out.println(rolls + " rolls, p1 = " + p1Dice + "d" + p1Sides + ", p2 = " + p2Dice + "d" + p2Sides);
System.out.println("p1 wins " + (100.0 * p1Wins / rolls) + "% of the time");
}
} | 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.
Graph example: {1 {2 7 3 9 6 14}
2 {1 7 3 10 4 15}
3 {1 9 2 10 4 11 6 2}
4 {2 15 3 11 5 6}
5 {6 9 4 6}
6 {1 14 3 2 5 9}}
^ ^ ^
| | |
node label | |
neighbour label--- |
edge cost------
From example in Wikipedia: https://en.wikipedia.org/wiki/Dijkstra's_algorithm
Output example: [20 [1 3 6 5]]
^ ^
| |
shortest path cost |
shortest path---"
([a b graph]
(loop [costs (prepare-costs a graph)
unvisited (set (keys graph))]
(let [current-node (get-next-node costs unvisited)
current-cost (first (costs current-node))]
(cond (nil? current-node)
(all-shortest-paths a costs)
(= current-node b)
[current-cost (unwind-path a b costs)]
:else
(recur (reduce (partial process-neighbour
current-node
current-cost)
costs
(filter (comp unvisited first)
(neighbours current-node graph costs)))
(disj unvisited current-node))))))
([a graph] (dijkstra a nil graph)))
(defn prepare-costs
"For given start node A ang graph prepare map of costs to start with
(assign maximum value for all nodes and zero for starting one).
Also save info about most advantageous parent.
Example output: {2 [2147483647 7], 6 [2147483647 14]}
^ ^ ^
| | |
node | |
cost----- |
parent---------------"
[start graph]
(assoc (zipmap (keys graph)
(repeat [Integer/MAX_VALUE nil]))
start [0 start]))
(defn neighbours
"Get given node's neighbours along with their own costs and costs of corresponding edges.
Example output is: {1 [7 10] 2 [4 15]}
^ ^ ^
| | |
neighbour node label | |
neighbour cost --- |
edge cost ------"
[node graph costs]
(->> (graph node)
(map (fn [[neighbour edge-cost]]
[neighbour [(first (costs neighbour)) edge-cost]]))
(into {})))
(defn process-neighbour
[parent
parent-cost
costs
[neighbour [old-cost edge-cost]]]
(let [new-cost (+ parent-cost edge-cost)]
(if (< new-cost old-cost)
(assoc costs
neighbour
[new-cost parent])
costs)))
(defn get-next-node [costs unvisited]
(->> costs
(filter (comp unvisited first))
(sort-by (comp first second))
ffirst))
(defn unwind-path
"Restore path from A to B based on costs data"
[a b costs]
(letfn [(f [a b costs]
(when-not (= a b)
(cons b (f a (second (costs b)) costs))))]
(cons a (reverse (f a b costs)))))
(defn all-shortest-paths
"Get shortest paths for all nodes, along with their costs"
[start costs]
(let [paths (->> (keys costs)
(remove #{start})
(map (fn [n] [n (unwind-path start n costs)])))]
(into (hash-map)
(map (fn [[n p]]
[n [(first (costs n)) p]])
paths))))
(require '[clojure.pprint:refer [print-table]])
(defn print-solution [solution]
(print-table
(map (fn [[node [cost path]]]
{'node node 'cost cost 'path path})
solution)))
(def rosetta-graph
'{a {b 7 c 9 f 14}
b {c 10 d 15}
c {d 11 f 2}
d {e 6}
e {f 9}
f {}})
(def task-2-solution
(dijkstra 'a rosetta-graph))
(print-solution task-2-solution)
(print-solution (select-keys task-2-solution '[e f])) | 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 = malloc( 100 * sizeof( char ) );
if( leap_year( y ) ){
if( d == 60 ){
sprintf( result, , dyear );
return result;
} else if( d >= 60 ){
-- d;
}
}
sprintf( result, ,
day_of_week(d%5), season(((d%73)==0?d-1:d)/73 ), date( d ), dyear );
return result;
}
int day_of_year( int y, int m, int d ){
int month_lengths[ 12 ] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
for( ; m > 1; m -- ){
d += month_lengths[ m - 2 ];
if( m == 3 && leap_year( y ) ){
++ d;
}
}
return d;
}
int main( int argc, char * argv[] ){
time_t now;
struct tm * now_time;
int year, doy;
if( argc == 1 ){
now = time( NULL );
now_time = localtime( &now );
year = now_time->tm_year + 1900; doy = now_time->tm_yday + 1;
} else if( argc == 4 ){
year = atoi( argv[ 1 ] ); doy = day_of_year( atoi( argv[ 1 ] ), atoi( argv[ 2 ] ), atoi( argv[ 3 ] ) );
}
char * result = ddate( year, doy );
puts( result );
free( result );
return 0;
} | 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) [(snd $ mpmdr n, n) | n <- [0..]]
digits :: Integral t => t -> [t]
digits 0 = [0]
digits n = unfoldr step n
where step 0 = Nothing
step k = Just (swap $ quotRem k 10)
printMpMdrs :: [Integer] -> IO ()
printMpMdrs ns = do
putStrLn "Number MP MDR"
putStrLn "====== == ==="
sequence_ [printf "%6d%2d%2d\n" n p r | n <- ns, let (p,r) = mpmdr n]
printMdrNums:: Int -> IO ()
printMdrNums k = do
putStrLn "MDR Numbers"
putStrLn "=== ======="
let showNums = unwords . map show
sequence_ [printf "%2d %s\n" mdr $ showNums ns | (mdr,ns) <- mdrNums k]
main :: IO ()
main = do
printMpMdrs [123321, 7739, 893, 899998]
putStrLn ""
printMdrNums 5 | 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 print "There is already one instance of this program running."
else do
t <- myThreadId
withFile user WriteMode (do_program t)
removeFile user
do_program :: ThreadId -> Handle -> IO ()
do_program t h = do
let s = "Locked by thread: " ++ show t
putStrLn s
hPutStr h s
threadDelay 1000000
main :: IO ()
main = do
forkIO oneInstance
threadDelay 500000
forkIO oneInstance
return () | 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, 393900588225LL};
for (i = 0; i < 4; i++) {
d = droot(x[i], 10, &pers);
printf(, x[i], pers, d);
}
return 0;
} | 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 roll2 = roll(ndice2, nsides2)
if (roll1 > roll2) then
wins = wins + 1
end
end
print("simulated: p1 = "..ndice1.."d"..nsides1..", p2 = "..ndice2.."d"..nsides2..", prob = "..wins.." / "..coms.." = "..(wins/coms))
end
simu(9, 4, 6, 6)
simu(5, 10, 6, 7) | 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 [day leap]
(let [offset (if (and leap (>= day 59)) 1 0)
day-off (- day offset)
day-num (inc (rem day-off 73))
season (seasons (quot day-off 73))
weekday (weekdays (mod day-off 5))]
(if (and (= day 59) (= offset 1))
"St. Tib's Day"
(str weekday ", " season " " day-num))))
(defn discordian-date [year month day]
(let [day-of-year (dec (.getDayOfYear (tc/date-time year month day)))
dday (discordian-day day-of-year (leap-year? year))]
(format "%s, YOLD%s" dday (+ year year-offset)))) | 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[0], a[1], a[2]);
}
System.out.println();
Map<Long, List<Long>> table = new HashMap<>();
for (long i = 0; i < 10; i++)
table.put(i, new ArrayList<>());
for (long cnt = 0, n = 0; cnt < 10;) {
long[] res = multiplicativeDigitalRoot(n++);
List<Long> list = table.get(res[1]);
if (list.size() < 5) {
list.add(res[0]);
cnt = list.size() == 5 ? cnt + 1 : cnt;
}
}
System.out.println("MDR: first five numbers with same MDR");
table.forEach((key, lst) -> {
System.out.printf("%3d: ", key);
lst.forEach(e -> System.out.printf("%6s ", e));
System.out.println();
});
}
public static long[] multiplicativeDigitalRoot(long n) {
int mp = 0;
long mdr = n;
while (mdr > 9) {
long m = mdr;
long total = 1;
while (m > 0) {
total *= m % 10;
m /= 10;
}
mdr = total;
mp++;
}
return new long[]{n, mdr, mp};
}
} | 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 (digits n))
(inc step)))))) | 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 <dllist>
(%dllist root? prev next element)
dllist?
(root? dllist-root?)
(prev dllist-prev %dllist-set-prev!)
(next dllist-next %dllist-set-next!)
(element %dllist-element))
(define (dllist-element node)
;; Get the element in a node. It is an error if the node is the
;; root.
(when (dllist-root? node)
(display (current-error-port))
(exit 1))
(%dllist-element node))
(define (dllist . elements)
;; Make a doubly-linked list from the given elements.
(list->dllist elements))
(define (make-dllist)
;; Return a node marked as being a root, and which points to itself.
(let ((root (%dllist
(%dllist-set-prev! root root)
(%dllist-set-next! root root)
root))
(define (dllist-root node)
;; Given a reference to any node of a <dllist>, return a reference
;; to the list's root node.
(if (dllist-root? node)
node
(dllist-root (dllist-prev node))))
(define (dllist-insert-after! node element)
;; Insert an element after the given node, which may be either the
;; root or some other node.
(let* ((next-node (dllist-next node))
(new-node (%dllist
(%dllist-set-next! node new-node)
(%dllist-set-prev! next-node new-node)))
(define (dllist-insert-before! node element)
;; Insert an element before the given node, which may be either the
;; root or some other node.
(let* ((prev-node (dllist-prev node))
(new-node (%dllist
(%dllist-set-next! prev-node new-node)
(%dllist-set-prev! node new-node)))
(define (dllist-remove! node)
;; Remove a node from a <dllist>. It is an error if the node is the
;; root.
(when (dllist-root? node)
(display (current-error-port))
(exit 1))
(let ((prev (dllist-prev node))
(next (dllist-next node)))
(%dllist-set-next! prev next)
(%dllist-set-prev! next prev)))
(define dllist-make-generator
;; Make a thunk that returns the elements of the list, starting at
;; the root and going in either direction.
(case-lambda
((node) (dllist-make-generator node 1))
((node direction)
(if (negative? direction)
(let ((p (dllist-prev (dllist-root node))))
(lambda ()
(and (not (dllist-root? p))
(let ((element (dllist-element p)))
(set! p (dllist-prev p))
element))))
(let ((p (dllist-next (dllist-root node))))
(lambda ()
(and (not (dllist-root? p))
(let ((element (dllist-element p)))
(set! p (dllist-next p))
element))))))))
(define (list->dllist lst)
;; Make a doubly-linked list from the elements of an ordinary list.
(let loop ((node (make-dllist))
(lst lst))
(if (null? lst)
(dllist-next node)
(begin
(dllist-insert-after! node (car lst))
(loop (dllist-next node) (cdr lst))))))
(define (dllist->list node)
;; Make an ordinary list from the elements of a doubly-linked list.
(let loop ((lst '())
(node (dllist-prev (dllist-root node))))
(if (dllist-root? node)
lst
(loop (cons (dllist-element node) lst) (dllist-prev node)))))
;;;
;;; Some demonstration.
;;;
(define (print-it node)
(let ((gen (dllist-make-generator node)))
(do ((x (gen) (gen)))
((not x))
(display )
(write x))
(newline)))
(define dl (dllist 10 20 30 40 50))
(let ((gen (dllist-make-generator dl)))
(display )
(do ((x (gen) (gen)))
((not x))
(display )
(write x))
(newline))
(let ((gen (dllist-make-generator dl -1)))
(display )
(do ((x (gen) (gen)))
((not x))
(display )
(write x))
(newline))
(display )
(dllist-insert-after! dl 5)
(print-it dl)
(display )
(dllist-insert-before! dl 55)
(print-it dl)
(display )
(dllist-insert-after! (dllist-next (dllist-next dl)) 15)
(print-it dl)
(display )
(dllist-insert-before! (dllist-prev (dllist-prev dl)) 45)
(print-it dl)
(display )
(let ((node (let loop ((node (dllist-next dl)))
(if (= (dllist-element node) 30)
node
(loop (dllist-next node))))))
(dllist-remove! node))
(print-it dl)
(display )
(print-it (dllist-next (dllist-next (dllist-next dl))))
(display )
(display (dllist->list dl))
(newline)
(display )
(print-it (list->dllist (list ))) | 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 {
my ($s1, $n1, $s2, $n2) = @_;
my @p1 = comb($s1, $n1);
my @p2 = comb($s2, $n2);
my ($win, $loss, $tie) = (0, 0, 0);
foreach my $i (0 .. $
$win += $p1[$i] * sum0(@p2[0 .. $i - 1]);
$tie += $p1[$i] * sum0(@p2[$i .. $i ]);
$loss += $p1[$i] * sum0(@p2[$i+1 .. $
}
my $total = sum0(@p1) * sum0(@p2);
map { $_ / $total } ($win, $tie, $loss);
}
print '(', join(', ', winning([1 .. 4], 9, [1 .. 6], 6)), ")\n";
print '(', join(', ', winning([1 .. 10], 5, [1 .. 7], 6)), ")\n"; | 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 maxBound
writeArray min_distance src 0
previous <- newSTArray b invalid_index
let aux vertex_queue =
case S.minView vertex_queue of
Nothing -> return ()
Just ((dist, u), vertex_queue') ->
let edges = adj_list! u
f vertex_queue (v, weight) = do
let dist_thru_u = dist + weight
old_dist <- readArray min_distance v
if dist_thru_u >= old_dist then
return vertex_queue
else do
let vertex_queue' = S.delete (old_dist, v) vertex_queue
writeArray min_distance v dist_thru_u
writeArray previous v u
return $ S.insert (dist_thru_u, v) vertex_queue'
in
foldM f vertex_queue' edges >>= aux
aux (S.singleton (0, src))
m <- freeze min_distance
p <- freeze previous
return (m, p)
where b = bounds adj_list
newSTArray :: Ix i => (i,i) -> e -> ST s (STArray s i e)
newSTArray = newArray
shortest_path_to :: (Ix v) => v -> v -> Array v v -> [v]
shortest_path_to target invalid_index previous =
aux target [] where
aux vertex acc | vertex == invalid_index = acc
| otherwise = aux (previous ! vertex) (vertex: acc)
adj_list :: Array Char [(Char, Int)]
adj_list = listArray ('a', 'f') [ [('b',7), ('c',9), ('f',14)],
[('a',7), ('c',10), ('d',15)],
[('a',9), ('b',10), ('d',11), ('f',2)],
[('b',15), ('c',11), ('e',6)],
[('d',6), ('f',9)],
[('a',14), ('c',2), ('e',9)] ]
main :: IO ()
main = do
let (min_distance, previous) = dijkstra 'a' ' ' adj_list
putStrLn $ "Distance from a to e: " ++ show (min_distance ! 'e')
let path = shortest_path_to 'e' ' ' previous
putStrLn $ "Path: " ++ show path | 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 DoublyLinkedList<T> {
fileprivate var head: NodePtr<T>?
fileprivate var tail: NodePtr<T>?
@discardableResult
mutating func insert(_ val: T, at: InsertLoc<T> = .last) -> Node<T> {
let node = NodePtr<T>.allocate(capacity: 1)
node.initialize(to: Node(value: val))
if head == nil && tail == nil {
head = node
tail = node
return node.pointee
}
switch at {
case .first:
node.pointee.next = head
head?.pointee.prev = node
head = node
case .last:
node.pointee.prev = tail
tail?.pointee.next = node
tail = node
case let .after(insertNode):
var n = head
while n!= nil {
if n!.pointee!== insertNode {
n = n?.pointee.next
continue
}
node.pointee.prev = n
node.pointee.next = n!.pointee.next
n!.pointee.next = node
if n == tail {
tail = node
}
break
}
}
return node.pointee
}
@discardableResult
mutating func remove(_ node: Node<T>) -> T? {
var n = head
while n!= nil {
if n!.pointee!== node {
n = n?.pointee.next
continue
}
if n == head {
n?.pointee.next?.pointee.prev = nil
head = n?.pointee.next
} else if n == tail {
n?.pointee.prev?.pointee.next = nil
tail = n?.pointee.prev
} else {
n?.pointee.prev?.pointee.next = n?.pointee.next
n?.pointee.next?.pointee.prev = n?.pointee.prev
}
break
}
if n == nil {
return nil
}
defer {
n?.deinitialize(count: 1)
n?.deallocate()
}
return n?.pointee.value
}
enum InsertLoc<T> {
case first
case last
case after(Node<T>)
}
}
extension DoublyLinkedList: CustomStringConvertible {
var description: String {
var res = "["
var node = head
while node!= nil {
res += "\(node!.pointee.value), "
node = node?.pointee.next
}
return (res.count > 1? String(res.dropLast(2)): res) + "]"
}
}
var list = DoublyLinkedList<Int>()
var node: Node<Int>!
for i in 0..<10 {
let insertedNode = list.insert(i)
if i == 5 {
node = insertedNode
}
}
print(list)
list.insert(100, at: .after(node!))
print(list)
list.remove(node!)
print(list) | 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
guard $ abs (smith - fletcher) /= 1
guard $ abs (fletcher - cooper) /= 1
return (baker, cooper, fletcher, miller, smith)
main :: IO ()
main = do
print $ head dinesman
print dinesman | 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_sides1, n_dice1)
c2, p2 = gen_dict(n_sides2, n_dice2)
p12 = float(p1 * p2)
return sum(p[1] * q[1] / p12
for p, q in product(enumerate(c1), enumerate(c2))
if p[0] > q[0])
print beating_probability(4, 9, 6, 6)
print beating_probability(10, 5, 7, 6) | 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_lock(socket: TcpListener) {
drop(socket);
}
fn main() {
let lock_socket = create_app_lock(12345); | 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'&&str2[i]<='z')&&(str2[i]-65!=str1[i]))
return 1;
else if((str2[i]>='A'&&str2[i]<='Z')&&(str1[i]>='a'&&str1[i]<='z')&&(str1[i]-65!=str2[i]))
return 1;
else if(str1[i]!=str2[i])
return 1;
}
}
return 0;
}
charList *strToCharList(char* str){
int len = strlen(str),i;
charList *list, *iterator, *nextChar;
list = (charList*)malloc(sizeof(charList));
list->c = str[0];
list->next = NULL;
iterator = list;
for(i=1;i<len;i++){
nextChar = (charList*)malloc(sizeof(charList));
nextChar->c = str[i];
nextChar->next = NULL;
iterator->next = nextChar;
iterator = nextChar;
}
return list;
}
char* charListToString(charList* list){
charList* iterator = list;
int count = 0,i;
char* str;
while(iterator!=NULL){
count++;
iterator = iterator->next;
}
str = (char*)malloc((count+1)*sizeof(char));
iterator = list;
for(i=0;i<count;i++){
str[i] = iterator->c;
iterator = iterator->next;
}
free(list);
str[i] = '\0';
return str;
}
char* processString(char str[100],int operation, char squeezeChar){
charList *strList = strToCharList(str),*iterator = strList, *scout;
if(operation==SQUEEZE){
while(iterator!=NULL){
if(iterator->c==squeezeChar){
scout = iterator->next;
while(scout!=NULL && scout->c==squeezeChar){
iterator->next = scout->next;
scout->next = NULL;
free(scout);
scout = iterator->next;
}
}
iterator = iterator->next;
}
}
else{
while(iterator!=NULL && iterator->next!=NULL){
if(iterator->c == (iterator->next)->c){
scout = iterator->next;
squeezeChar = iterator->c;
while(scout!=NULL && scout->c==squeezeChar){
iterator->next = scout->next;
scout->next = NULL;
free(scout);
scout = iterator->next;
}
}
iterator = iterator->next;
}
}
return charListToString(strList);
}
void printResults(char originalString[100], char finalString[100], int operation, char squeezeChar){
if(operation==SQUEEZE){
printf(,squeezeChar);
}
else
printf();
printf(,174,174,174,originalString,175,175,175,(int)strlen(originalString));
printf(,174,174,174,finalString,175,175,175,(int)strlen(finalString));
}
int main(int argc, char** argv){
int operation;
char squeezeChar;
if(argc<3||argc>4){
printf(,argv[0]);
return 0;
}
if(strcmpi(argv[1],)==0 && argc!=4){
scanf(,&squeezeChar);
operation = SQUEEZE;
}
else if(argc==4){
operation = SQUEEZE;
squeezeChar = argv[3][0];
}
else if(strcmpi(argv[1],)==0){
operation = COLLAPSE;
}
if(strlen(argv[2])<2){
printResults(argv[2],argv[2],operation,squeezeChar);
}
else{
printResults(argv[2],processString(argv[2],operation,squeezeChar),operation,squeezeChar);
}
return 0;
} | 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(10, 5, 7, 6), "in the second.") | 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 {
println("More than one running")
exit(0)
} else {
println("Only one")
}
}
func send() {
globalCenter.postNotificationName("OnlyOne", object: nil, userInfo: ["time": time])
let waitTime = dispatch_time(DISPATCH_TIME_NOW, Int64(3 * NSEC_PER_SEC))
dispatch_after(waitTime, dispatch_get_main_queue()) {
send()
}
}
send()
CFRunLoopRun() | 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"
}
void putDown(String philosopher) {
lock.unlock()
println " $philosopher put down $name"
}
}
@Canonical
class Philosopher extends Thread {
Fork f1
Fork f2
@Override
void run() {
def random = new Random()
(1..20).each { bite ->
println "$name is hungry"
f1.pickUp name
f2.pickUp name
println "$name is eating bite $bite"
Thread.sleep random.nextInt(300) + 100
f2.putDown name
f1.putDown name
}
}
}
void diningPhilosophers(names) {
def forks = (1..names.size()).collect { new Fork(name: "Fork $it") }
def philosophers = []
names.eachWithIndex{ n, i ->
def (i1, i2) = [i, (i + 1) % 5]
if (i2 < i1) (i1, i2) = [i2, i]
def p = new Philosopher(name: n, f1: forks[i1], f2: forks[i2])
p.start()
philosophers << p
}
philosophers.each { it.join() }
}
diningPhilosophers(['Aristotle', 'Kant', 'Spinoza', 'Marx', 'Russell']) | 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 fork = putTMVar fork i
type Name = String
runPhilosopher :: Name -> (Fork, Fork) -> IO ()
runPhilosopher name (left, right) = forever $ do
putStrLn (name ++ " is hungry.")
(leftNum, rightNum) <- atomically $ do
leftNum <- takeFork left
rightNum <- takeFork right
return (leftNum, rightNum)
putStrLn (name ++ " got forks " ++ show leftNum ++ " and " ++ show rightNum ++ " and is now eating.")
delay <- randomRIO (1,10)
threadDelay (delay * 1000000)
putStrLn (name ++ " is done eating. Going back to thinking.")
atomically $ do
releaseFork leftNum left
releaseFork rightNum right
delay <- randomRIO (1, 10)
threadDelay (delay * 1000000)
philosophers :: [String]
philosophers = ["Aristotle", "Kant", "Spinoza", "Marx", "Russel"]
main = do
forks <- mapM newFork [1..5]
let namedPhilosophers = map runPhilosopher philosophers
forkPairs = zip forks (tail . cycle $ forks)
philosophersWithForks = zipWith ($) namedPhilosophers forkPairs
putStrLn "Running the philosophers. Press enter to quit."
mapM_ forkIO philosophersWithForks
getLine | 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", 11),
new Graph.Edge("c", "f", 2),
new Graph.Edge("d", "e", 6),
new Graph.Edge("e", "f", 9),
};
private static final String START = "a";
private static final String END = "e";
public static void main(String[] args) {
Graph g = new Graph(GRAPH);
g.dijkstra(START);
g.printPath(END); | 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 + s;
if (nextPermutation.length() == apartmentDwellers.length) {
set.add(nextPermutation);
} else {
generatePermutations(apartmentDwellers, set, nextPermutation);
}
}
}
}
private static boolean topFloor(String permutation, String person) { | 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;
}
return sum;
}
double det(double *in, int n, int perm)
{
double *m[n];
for (int i = 0; i < n; i++)
m[i] = in + (n * i);
return det_in(m, n, perm);
}
int main(void)
{
double x[] = { 0, 1, 2, 3, 4,
5, 6, 7, 8, 9,
10, 11, 12, 13, 14,
15, 16, 17, 18, 19,
20, 21, 22, 23, 24 };
printf(, det(x, 5, 0));
printf(, det(x, 5, 1));
return 0;
} | 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]<='z')&&(str2[i]-65!=str1[i]))
return 1;
else if((str2[i]>='A'&&str2[i]<='Z')&&(str1[i]>='a'&&str1[i]<='z')&&(str1[i]-65!=str2[i]))
return 1;
else if(str1[i]!=str2[i])
return 1;
}
}
return 0;
}
charList *strToCharList(char* str){
int len = strlen(str),i;
charList *list, *iterator, *nextChar;
list = (charList*)malloc(sizeof(charList));
list->c = str[0];
list->next = NULL;
iterator = list;
for(i=1;i<len;i++){
nextChar = (charList*)malloc(sizeof(charList));
nextChar->c = str[i];
nextChar->next = NULL;
iterator->next = nextChar;
iterator = nextChar;
}
return list;
}
char* charListToString(charList* list){
charList* iterator = list;
int count = 0,i;
char* str;
while(iterator!=NULL){
count++;
iterator = iterator->next;
}
str = (char*)malloc((count+1)*sizeof(char));
iterator = list;
for(i=0;i<count;i++){
str[i] = iterator->c;
iterator = iterator->next;
}
free(list);
str[i] = '\0';
return str;
}
char* processString(char str[100],int operation, char squeezeChar){
charList *strList = strToCharList(str),*iterator = strList, *scout;
if(operation==SQUEEZE){
while(iterator!=NULL){
if(iterator->c==squeezeChar){
scout = iterator->next;
while(scout!=NULL && scout->c==squeezeChar){
iterator->next = scout->next;
scout->next = NULL;
free(scout);
scout = iterator->next;
}
}
iterator = iterator->next;
}
}
else{
while(iterator!=NULL && iterator->next!=NULL){
if(iterator->c == (iterator->next)->c){
scout = iterator->next;
squeezeChar = iterator->c;
while(scout!=NULL && scout->c==squeezeChar){
iterator->next = scout->next;
scout->next = NULL;
free(scout);
scout = iterator->next;
}
}
iterator = iterator->next;
}
}
return charListToString(strList);
}
void printResults(char originalString[100], char finalString[100], int operation, char squeezeChar){
if(operation==SQUEEZE){
printf(,squeezeChar);
}
else
printf();
printf(,174,174,174,originalString,175,175,175,(int)strlen(originalString));
printf(,174,174,174,finalString,175,175,175,(int)strlen(finalString));
}
int main(int argc, char** argv){
int operation;
char squeezeChar;
if(argc<3||argc>4){
printf(,argv[0]);
return 0;
}
if(strcmpi(argv[1],)==0 && argc!=4){
scanf(,&squeezeChar);
operation = SQUEEZE;
}
else if(argc==4){
operation = SQUEEZE;
squeezeChar = argv[3][0];
}
else if(strcmpi(argv[1],)==0){
operation = COLLAPSE;
}
if(strlen(argv[2])<2){
printResults(argv[2],argv[2],operation,squeezeChar);
}
else{
printResults(argv[2],processString(argv[2],operation,squeezeChar),operation,squeezeChar);
}
return 0;
} | 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]);
for(i=1;i<len;i++){
if(argv[1][i]!=reference){
printf(%s\%c\,argv[1],len,argv[1][i],argv[1][i],i+1);
return 0;
}
}
printf(%s\,argv[1],len);
return 0;
} | 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
| Confusion
| Bureaucracy
| TheAftermath
deriving (Show, Enum, Eq, Ord, Bounded)
data Weekday = Sweetmorn
| Boomtime
| Pungenday
| PricklePrickle
| SettingOrange
deriving (Show, Enum, Eq, Ord, Bounded)
instance Show DDate where
show (StTibsDay y) = printf "St. Tib's Day,%d YOLD" y
show (DDate w s d y) = printf "%s,%s%d,%d YOLD" (show w) (show s) d y
fromYMD :: (Year, Month, Day) -> DDate
fromYMD (y, m, d)
| leap && dayOfYear == 59 = StTibsDay yold
| leap && dayOfYear >= 60 = mkDDate $ dayOfYear - 1
| otherwise = mkDDate dayOfYear
where
yold = y + 1166
dayOfYear = monthAndDayToDayOfYear leap m d - 1
leap = isLeapYear y
mkDDate dayOfYear = DDate weekday season dayOfSeason yold
where
weekday = toEnum $ dayOfYear `mod` 5
season = toEnum $ dayOfYear `div` 73
dayOfSeason = 1 + dayOfYear `mod` 73 | 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) {
min_distance = dist[v]
u = v
}
}
return u
}
for (let i=0;i<edges.length;i++) {
let v1 = edges[i][0],
v2 = edges[i][1],
len = edges[i][2]
Q.add(v1)
Q.add(v2)
dist[v1] = Infinity
dist[v2] = Infinity
if (adj[v1] === undefined) adj[v1] = {}
if (adj[v2] === undefined) adj[v2] = {}
adj[v1][v2] = len
adj[v2][v1] = len
}
dist[source] = 0
while (Q.size) {
let u = vertex_with_min_dist(Q,dist),
neighbors = Object.keys(adj[u]).filter(v=>Q.has(v)) | 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 (123321, 7739, 893, 899998) {
printf "%6d: (%d,%d)\n", $n, mdr($n);
}
print "\nMP: [n0..n4]\n== ========\n";
foreach my $target (0..9) {
my $i = 0;
my @n = map { $i++ while (mdr($i))[1] != $target; $i++; } 1..5;
print " $target: [", join(", ", @n), "]\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: <<<%s>>> (len%d)\n" s (count s))
(format "becomes: <<<%s>>> (len%d)" out (count out))))) | 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(dice1, faces1)
p2 = roll_dice(dice2, faces2)
p1.product(p2).each_with_object([0,0,0]) do |((sum1, n1), (sum2, n2)), win|
win[sum1 <=> sum2] += n1 * n2
end
end
[[9, 4, 6, 6], [5, 10, 6, 7]].each do |d1, f1, d2, f2|
puts
puts
win = game(d1, f1, d2, f2)
sum = win.inject(:+)
puts ,
,
end | 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) {
double detTri = det2D(p1, p2, p3);
if (detTri < 0.0) {
if (allowReversed) {
double t = p3->x;
p3->x = p2->x;
p2->x = t;
t = p3->y;
p3->y = p2->y;
p2->y = t;
} else {
errno = 1;
}
}
}
bool boundaryCollideChk(const Point *p1, const Point *p2, const Point *p3, double eps) {
return det2D(p1, p2, p3) < eps;
}
bool boundaryDoesntCollideChk(const Point *p1, const Point *p2, const Point *p3, double eps) {
return det2D(p1, p2, p3) <= eps;
}
bool triTri2D(Point t1[], Point t2[], double eps, bool allowReversed, bool onBoundary) {
bool(*chkEdge)(Point*, Point*, Point*, double);
int i;
checkTriWinding(&t1[0], &t1[1], &t1[2], allowReversed);
if (errno != 0) {
return false;
}
checkTriWinding(&t2[0], &t2[1], &t2[2], allowReversed);
if (errno != 0) {
return false;
}
if (onBoundary) {
chkEdge = boundaryCollideChk;
} else {
chkEdge = boundaryDoesntCollideChk;
}
for (i = 0; i < 3; ++i) {
int j = (i + 1) % 3;
if (chkEdge(&t1[i], &t1[j], &t2[0], eps) &&
chkEdge(&t1[i], &t1[j], &t2[1], eps) &&
chkEdge(&t1[i], &t1[j], &t2[2], eps)) {
return false;
}
}
for (i = 0; i < 3; i++) {
int j = (i + 1) % 3;
if (chkEdge(&t2[i], &t2[j], &t1[0], eps) &&
chkEdge(&t2[i], &t2[j], &t1[1], eps) &&
chkEdge(&t2[i], &t2[j], &t1[2], eps))
return false;
}
return true;
}
int main() {
{
Point t1[] = { {0, 0}, {5, 0}, {0, 5} };
Point t2[] = { {0, 0}, {5, 0}, {0, 6} };
printf(, triTri2D(t1, t2, 0.0, false, true));
}
{
Point t1[] = { {0, 0}, {0, 5}, {5, 0} };
Point t2[] = { {0, 0}, {0, 5}, {5, 0} };
printf(, triTri2D(t1, t2, 0.0, true, true));
}
{
Point t1[] = { {0, 0}, {5, 0}, {0, 5} };
Point t2[] = { {-10, 0}, {-5, 0}, {-1, 6} };
printf(, triTri2D(t1, t2, 0.0, false, true));
}
{
Point t1[] = { {0, 0}, {5, 0}, {2.5, 5} };
Point t2[] = { {0, 4}, {2.5, -1}, {5, 4} };
printf(, triTri2D(t1, t2, 0.0, false, true));
}
{
Point t1[] = { {0, 0}, {1, 1}, {0, 2} };
Point t2[] = { {2, 1}, {3, 0}, {3, 2} };
printf(, triTri2D(t1, t2, 0.0, false, true));
}
{
Point t1[] = { {0, 0}, {1, 1}, {0, 2} };
Point t2[] = { {2, 1}, {3, -2}, {3, 4} };
printf(, triTri2D(t1, t2, 0.0, false, true));
}
{
Point t1[] = { {0, 0}, {1, 0}, {0, 1} };
Point t2[] = { {1, 0}, {2, 0}, {1, 1} };
printf(, triTri2D(t1, t2, 0.0, false, true));
}
{
Point t1[] = { {0, 0}, {1, 0}, {0, 1} };
Point t2[] = { {1, 0}, {2, 0}, {1, 1} };
printf(, triTri2D(t1, t2, 0.0, false, false));
}
return EXIT_SUCCESS;
} | 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 int id;
public AtomicInteger holder = new AtomicInteger(ON_TABLE);
Fork() { id = instances++; }
}
class Philosopher implements Runnable {
static final int maxWaitMs = 100; | 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, len(c))
copy(t, c)
combs = append(combs, t)
return
}
for i := start; i <= end && end-i+1 >= k-index; i++ {
c[index] = a[i]
combine(i+1, end, index+1)
}
}
combine(0, n-1, 0)
return combs
}
func powerset(a []int) (res [][]int) {
if len(a) == 0 {
return
}
for i := 1; i <= len(a); i++ {
res = append(res, combinations(a, i)...)
}
return
}
func main() {
ps := powerset([]int{9, 8, 7, 6, 5, 4, 3, 2, 1})
var descPrimes []int
for i := 1; i < len(ps); i++ {
s := ""
for _, e := range ps[i] {
s += string(e + '0')
}
p, _ := strconv.Atoi(s)
if rcu.IsPrime(p) {
descPrimes = append(descPrimes, p)
}
}
sort.Ints(descPrimes)
fmt.Println("There are", len(descPrimes), "descending primes, namely:")
for i := 0; i < len(descPrimes); i++ {
fmt.Printf("%8d ", descPrimes[i])
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Println()
} | 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 c,int pos){
bool letterOccurs = false;
letterList *letterIterator,*newLetter;
positionList *positionIterator,*newPosition;
if(letterSet==NULL){
letterSet = (letterList*)malloc(sizeof(letterList));
letterSet->letter = c;
letterSet->repititions = 0;
letterSet->positions = (positionList*)malloc(sizeof(positionList));
letterSet->positions->position = pos;
letterSet->positions->next = NULL;
letterSet->next = NULL;
}
else{
letterIterator = letterSet;
while(letterIterator!=NULL){
if(letterIterator->letter==c){
letterOccurs = true;
duplicatesFound = true;
letterIterator->repititions++;
positionIterator = letterIterator->positions;
while(positionIterator->next!=NULL)
positionIterator = positionIterator->next;
newPosition = (positionList*)malloc(sizeof(positionList));
newPosition->position = pos;
newPosition->next = NULL;
positionIterator->next = newPosition;
}
if(letterOccurs==false && letterIterator->next==NULL)
break;
else
letterIterator = letterIterator->next;
}
if(letterOccurs==false){
newLetter = (letterList*)malloc(sizeof(letterList));
newLetter->letter = c;
newLetter->repititions = 0;
newLetter->positions = (positionList*)malloc(sizeof(positionList));
newLetter->positions->position = pos;
newLetter->positions->next = NULL;
newLetter->next = NULL;
letterIterator->next = newLetter;
}
}
}
void printLetterList(){
positionList* positionIterator;
letterList* letterIterator = letterSet;
while(letterIterator!=NULL){
if(letterIterator->repititions>0){
printf(,letterIterator->letter,letterIterator->letter);
positionIterator = letterIterator->positions;
while(positionIterator!=NULL){
printf(,positionIterator->position + 1);
positionIterator = positionIterator->next;
}
}
letterIterator = letterIterator->next;
}
printf();
}
int main(int argc,char** argv)
{
int i,len;
if(argc>2){
printf(,argv[0]);
return 0;
}
if(argc==1||strlen(argv[1])==1){
printf(%s\,argc==1?:argv[1],argc==1?0:1);
return 0;
}
len = strlen(argv[1]);
for(i=0;i<len;i++){
checkAndUpdateLetterList(argv[1][i],i);
}
printf(%s\,argv[1],len,duplicatesFound==false?:);
if(duplicatesFound==true)
printLetterList();
return 0;
} | 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"
num-same
(byte (nth s num-same)))))))
(map check-all-chars-same
[""
" "
"2"
"333"
".55"
"tttTTT"
"4444 444k"]) | 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 Orange"};
final static String[] apostle = {"Mungday", "Mojoday", "Syaday",
"Zaraday", "Maladay"};
final static String[] holiday = {"Chaoflux", "Discoflux", "Confuflux",
"Bureflux", "Afflux"};
public static String discordianDate(final GregorianCalendar date) {
int y = date.get(Calendar.YEAR);
int yold = y + 1166;
int dayOfYear = date.get(Calendar.DAY_OF_YEAR);
if (date.isLeapYear(y)) {
if (dayOfYear == 60)
return "St. Tib's Day, in the YOLD " + yold;
else if (dayOfYear > 60)
dayOfYear--;
}
dayOfYear--;
int seasonDay = dayOfYear % 73 + 1;
if (seasonDay == 5)
return apostle[dayOfYear / 73] + ", in the YOLD " + yold;
if (seasonDay == 50)
return holiday[dayOfYear / 73] + ", in the YOLD " + yold;
String season = seasons[dayOfYear / 73];
String dayOfWeek = weekday[dayOfYear % 5];
return String.format("%s, day%s of%s in the YOLD%s",
dayOfWeek, seasonDay, season, yold);
}
public static void main(String[] args) {
System.out.println(discordianDate(new GregorianCalendar()));
test(2010, 6, 22, "Pungenday, day 57 of Confusion in the YOLD 3176");
test(2012, 1, 28, "Prickle-Prickle, day 59 of Chaos in the YOLD 3178");
test(2012, 1, 29, "St. Tib's Day, in the YOLD 3178");
test(2012, 2, 1, "Setting Orange, day 60 of Chaos in the YOLD 3178");
test(2010, 0, 5, "Mungday, in the YOLD 3176");
test(2011, 4, 3, "Discoflux, in the YOLD 3177");
test(2015, 9, 19, "Boomtime, day 73 of Bureaucracy in the YOLD 3181");
}
private static void test(int y, int m, int d, final String result) {
assert (discordianDate(new GregorianCalendar(y, m, d)).equals(result));
}
} | 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====== =========')
for n in (123321, 7739, 893, 899998):
print('%6i:%r'% (n, mdroot(n)))
table, n = {i: [] for i in range(10)}, 0
while min(len(row) for row in table.values()) < 5:
mpersistence, mdr = mdroot(n)
table[mdr].append(n)
n += 1
print('\nMP: [n0..n4]\n== ========')
for mp, val in sorted(table.items()):
print('%2i:%r'% (mp, val[:5])) | 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,2,1}, {0}, {}
for i = 1, #digits do
for j = 1, #candidates do
local value = candidates[j] * 10 + digits[i]
if is_prime(value) then primes[#primes+1] = value end
candidates[#candidates+1] = value
end
end
table.sort(primes)
return primes
end
print(table.concat(descending_primes(), ", ")) | 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",
"Bureflux", "Afflux"
];
Date.prototype.isLeapYear = function() {
var year = this.getFullYear();
if( (year & 3) !== 0 ) { return false; }
return ((year % 100) !== 0 || (year % 400) === 0);
}; | 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;
sigemptyset(&act.sa_mask);
act.sa_flags = SA_SIGINFO;
if (sigaction(SIGFPE, &act, &old) < 0) {
perror();
exit(1);
}
result = x / y;
if (sigaction(SIGFPE, &old, NULL) < 0) {
perror();
exit(1);
}
printf(, x, y, result);
} else {
if (sigaction(SIGFPE, &old, NULL) < 0) {
perror();
exit(1);
}
switch (code) {
case FPE_INTDIV:
case FPE_FLTDIV:
printf(, x, y);
break;
default:
printf(, x, y);
break;
}
}
}
int
main()
{
try_division(-44, 0);
try_division(-44, 5);
try_division(0, 5);
try_division(0, 0);
try_division(INT_MIN, -1);
return 0;
} | 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],r[m]=r[m],r[i]
end
end
end
swap(n)
end)
end
local function iden(...)return ... end
local function imap(t,f)
local r,fn = {m=imap, c=table.concat, u=table.unpack}, f or iden
for i=1,#t do r[i]=fn(t[i])end
return r
end
local tenants = {'Baker', 'Cooper', 'Fletcher', 'Miller', 'Smith'}
local conds = {
'Baker ~= TOP',
'Cooper ~= BOTTOM',
'Fletcher ~= TOP and Fletcher~= BOTTOM',
'Miller > Cooper',
'Smith + 1 ~= Fletcher and Smith - 1 ~= Fletcher',
'Cooper + 1 ~= Fletcher and Cooper - 1 ~= Fletcher',
}
local function makePredicate(conds, tenants)
return load('return function('..imap(tenants):c','..
') return ' ..
imap(conds,function(c)
return string.format("(%s)",c)
end):c"and "..
" end ",'-',nil,{TOP=5, BOTTOM=1})()
end
local function solve (conds, tenants)
local try, pred, upk = perm(#tenants), makePredicate(conds, tenants), table.unpack
local answer = try()
while answer and not pred(upk(answer)) do answer = try()end
if answer then
local floor = 0
return imap(answer, function(person)
floor=floor+1;
return string.format("%s lives on floor%d",tenants[floor],person)
end):c"\n"
else
return nil, 'no solution'
end
end
print(solve (conds, tenants)) | 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.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047,
-0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021,
-0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315,
0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181,
-0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658,
0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774,
-1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106,
0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017,
0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598,
0.443, -0.521, -0.799, 0.087,
}
var dys = []float64{
0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395,
0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000,
0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208,
0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096,
-0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007,
0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226,
0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295,
1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217,
-0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219,
0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104,
-0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477,
1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224,
-0.947, -1.424, -0.542, -1.032,
}
func funnel(fa []float64, r rule) []float64 {
x := 0.0
result := make([]float64, len(fa))
for i, f := range fa {
result[i] = x + f
x = r(x, f)
}
return result
}
func mean(fa []float64) float64 {
sum := 0.0
for _, f := range fa {
sum += f
}
return sum / float64(len(fa))
}
func stdDev(fa []float64) float64 {
m := mean(fa)
sum := 0.0
for _, f := range fa {
sum += (f - m) * (f - m)
}
return math.Sqrt(sum / float64(len(fa)))
}
func experiment(label string, r rule) {
rxs := funnel(dxs, r)
rys := funnel(dys, r)
fmt.Println(label, ": x y")
fmt.Printf("Mean : %7.4f,%7.4f\n", mean(rxs), mean(rys))
fmt.Printf("Std Dev: %7.4f,%7.4f\n", stdDev(rxs), stdDev(rys))
fmt.Println()
}
func main() {
experiment("Rule 1", func(_, _ float64) float64 {
return 0.0
})
experiment("Rule 2", func(_, dz float64) float64 {
return -dz
})
experiment("Rule 3", func(z, dz float64) float64 {
return -(z + dz)
})
experiment("Rule 4", func(z, dz float64) float64 {
return z + dz
})
} | 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 "'%s' (len:%d) has '%c' duplicated at idx:%d"
s len c idx))
(recur (conj prev-chars c)
(inc idx)
(rest chars)))))))) | 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 never give 'em hell, I just tell the truth, and they think it's hell. ",
" --- Harry S Truman ",
"122333444455555666666777777788888888999999999",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship"
]
String[] testChar = [" ", "-", "7", ".", " -r", "5", "e", "s"]
for (int testNum = 0; testNum < testStrings.length; testNum++) {
String s = testStrings[testNum]
for (char c: testChar[testNum].toCharArray()) {
String result = squeeze(s, c)
System.out.printf("use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result)
}
}
}
private static String squeeze(String input, char include) {
StringBuilder sb = new StringBuilder()
for (int i = 0; i < input.length(); i++) {
if (i == 0 || input.charAt(i - 1) != input.charAt(i) || (input.charAt(i - 1) == input.charAt(i) && input.charAt(i) != include)) {
sb.append(input.charAt(i))
}
}
return sb.toString()
}
} | 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 | x <- xs] / genericLength xs where
m = mean xs
experiment :: String -> [Double] -> [Double] -> (Double -> Double -> Double) -> IO ()
experiment label dxs dys rule = do
let rxs = funnel rule dxs
rys = funnel rule dys
putStrLn label
printf "Mean x, y :%7.4f,%7.4f\n" (mean rxs) (mean rys)
printf "Std dev x, y:%7.4f,%7.4f\n" (stddev rxs) (stddev rys)
putStrLn ""
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.951, 1.150, 0.001,
-0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014,
0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047,
-0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021,
-0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315,
0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181,
-0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658,
0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774,
-1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106,
0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017,
0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598,
0.443, -0.521, -0.799, 0.087]
dys = [ 0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395,
0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000,
0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208,
0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096,
-0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007,
0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226,
0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295,
1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217,
-0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219,
0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104,
-0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477,
1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224,
-0.947, -1.424, -0.542, -1.032]
main :: IO ()
main = do
experiment "Rule 1:" dxs dys (\_ _ -> 0)
experiment "Rule 2:" dxs dys (\_ dz -> -dz)
experiment "Rule 3:" dxs dys (\z dz -> -(z+dz))
experiment "Rule 4:" dxs dys (\z dz -> z+dz) | 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->operation)? (*dl->operation)(p1) : NULL;
}
typedef struct sDelegator {
int param;
char *phrase;
Delegate delegate;
} *Delegator;
const char * defaultResponse( int p1)
{
return ;
}
static struct sDelegate defaultDel = { &defaultResponse };
Delegator NewDelegator( int p, char *phrase)
{
Delegator d = malloc(sizeof(struct sDelegator));
d->param = p;
d->phrase = phrase;
d->delegate = &defaultDel;
return d;
}
const char *Delegator_Operation( Delegator theDelegator, int p1, Delegate delroy)
{
const char *rtn;
if (delroy) {
rtn = DelegateThing(delroy, p1);
if (!rtn) {
rtn = DelegateThing(theDelegator->delegate, p1);
}
}
else
rtn = DelegateThing(theDelegator->delegate, p1);
printf(, theDelegator->phrase );
return rtn;
}
const char *thing1( int p1)
{
printf( , p1);
return ;
}
int main()
{
Delegate del1 = NewDelegate(&thing1);
Delegate del2 = NewDelegate(NULL);
Delegator theDelegator = NewDelegator( 14, );
printf(,
Delegator_Operation( theDelegator, 3, NULL));
printf(,
Delegator_Operation( theDelegator, 3, del1));
printf(,
Delegator_Operation( theDelegator, 3, del2));
return 0;
} | 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 give 'em hell, I just tell the truth, and they think it's hell. ",
" --- Harry S Truman ",
"122333444455555666666777777788888888999999999",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship"]) {
String result = collapse(s)
System.out.printf("old: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", s.length(), s, result.length(), result)
}
}
private static String collapse(String input) {
StringBuilder sb = new StringBuilder()
for ( int i = 0 ; i < input.length() ; i++ ) {
if ( i == 0 || input.charAt(i-1) != input.charAt(i) ) {
sb.append(input.charAt(i))
}
}
return sb.toString()
}
} | 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 from(i: Int) = values()[i % 5] }
}
enum class Apostle {
Mungday, Mojoday, Syaday, Zaraday, Maladay;
companion object { fun from(i: Int) = values()[i / 73] }
}
enum class Holiday {
Chaoflux, Discoflux, Confuflux, Bureflux, Afflux;
companion object { fun from(i: Int) = values()[i / 73] }
}
fun GregorianCalendar.discordianDate(): String {
val y = get(Calendar.YEAR)
val yold = y + 1166
var dayOfYear = get(Calendar.DAY_OF_YEAR)
if (isLeapYear(y)) {
if (dayOfYear == 60)
return "St. Tib's Day, in the YOLD " + yold
else if (dayOfYear > 60)
dayOfYear--
}
val seasonDay = --dayOfYear % 73 + 1
return when (seasonDay) {
5 -> "" + Apostle.from(dayOfYear) + ", in the YOLD " + yold
50 -> "" + Holiday.from(dayOfYear) + ", in the YOLD " + yold
else -> "" + Weekday.from(dayOfYear) + ", day " + seasonDay + " of " + Season.from(dayOfYear) + " in the YOLD " + yold
}
}
internal fun test(y: Int, m: Int, d: Int, result: String) {
assert(GregorianCalendar(y, m, d).discordianDate() == result)
}
fun main(args: Array<String>) {
println(GregorianCalendar().discordianDate())
test(2010, 6, 22, "Pungenday, day 57 of Confusion in the YOLD 3176")
test(2012, 1, 28, "Prickle-Prickle, day 59 of Chaos in the YOLD 3178")
test(2012, 1, 29, "St. Tib's Day, in the YOLD 3178")
test(2012, 2, 1, "Setting Orange, day 60 of Chaos in the YOLD 3178")
test(2010, 0, 5, "Mungday, in the YOLD 3176")
test(2011, 4, 3, "Discoflux, in the YOLD 3177")
test(2015, 9, 19, "Boomtime, day 73 of Bureaucracy in the YOLD 3181")
} | 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, base)
persistence++
}
return
} | 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 main() {
d, err := dot([]int{1, 3, -5}, []int{4, -2, -1})
if err != nil {
log.Fatal(err)
}
fmt.Println(d)
} | 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?\"
, ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7')
, ("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.')
, ("
, ("aardvark", 'a')
, ("", '')
]
collapse :: Eq a => [a] -> a -> [a]
collapse s c = go s
where go [] = []
go (x:y:xs)
| x == y && x == c = go (y:xs)
| otherwise = x: go (y:xs)
go xs = xs
main :: IO ()
main =
mapM_ (\(a, b, c) -> printf "squeeze: '%c'\nold:%3d %s\nnew:%3d %s\n\n" c (length a) a (length b) b)
$ (\(s, c) -> (s, collapse s c, c)) <$> input | 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?\"
, "..1111111111111111111111111111111111111111111111111111111111111117777888"
, "I never give 'em hell, I just tell the truth, and they think it's hell. "
, "
, ""
]
collapse :: Eq a => [a] -> [a]
collapse = catMaybes . (\xs -> zipWith (\a b -> guard (a /= b) >> a) (Nothing: xs) (xs <> [Nothing])) . map Just
main :: IO ()
main =
mapM_ (\(a, b) -> printf "old:%3d %s\nnew:%3d %s\n\n" (length a) a (length b) b)
$ ((,) <*> collapse) <$> input | 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) {
number = bi.toString(base)
bi = BigInteger.ZERO
for (int i = 0; i < number.length(); i++) {
bi = bi.add(new BigInteger(number.substring(i, i + 1), base))
}
additivePersistence++
}
return [additivePersistence, bi.intValue()]
}
static void main(String[] args) {
for (String arg: [627615, 39390, 588225, 393900588225]) {
int[] results = calcDigitalRoot(arg, 10)
println("$arg has additive persistence ${results[0]} and digital root of ${results[1]}")
}
}
} | 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.size >= 5 }
end
puts , ,
10.times{|i| puts % [i, counter[i].first(5)]} | 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.951, 1.150, 0.001,
-0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014,
0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047,
-0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021,
-0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315,
0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181,
-0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658,
0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774,
-1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106,
0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017,
0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598,
0.443, -0.521, -0.799, 0.087};
double[] dys = {
0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395,
0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000,
0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208,
0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096,
-0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007,
0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226,
0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295,
1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217,
-0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219,
0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104,
-0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477,
1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224,
-0.947, -1.424, -0.542, -1.032};
experiment("Rule 1:", dxs, dys, (z, dz) -> 0.0);
experiment("Rule 2:", dxs, dys, (z, dz) -> -dz);
experiment("Rule 3:", dxs, dys, (z, dz) -> -(z + dz));
experiment("Rule 4:", dxs, dys, (z, dz) -> z + dz);
}
static void experiment(String label, double[] dxs, double[] dys,
BiFunction<Double, Double, Double> rule) {
double[] resx = funnel(dxs, rule);
double[] resy = funnel(dys, rule);
System.out.println(label);
System.out.printf("Mean x, y: %.4f,%.4f%n", mean(resx), mean(resy));
System.out.printf("Std dev x, y:%.4f,%.4f%n", stdDev(resx), stdDev(resy));
System.out.println();
}
static double[] funnel(double[] input, BiFunction<Double, Double, Double> rule) {
double x = 0;
double[] result = new double[input.length];
for (int i = 0; i < input.length; i++) {
double rx = x + input[i];
x = rule.apply(x, input[i]);
result[i] = rx;
}
return result;
}
static double mean(double[] xs) {
return Arrays.stream(xs).sum() / xs.length;
}
static double stdDev(double[] xs) {
double m = mean(xs);
return sqrt(Arrays.stream(xs).map(x -> pow((x - m), 2)).sum() / xs.length);
}
} | 954Deming's Funnel
| 9java
| a8u1y |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.