code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
var array = [];
array.push('abc');
array.push(123);
array.push(new MyClass);
console.log( array[2] ); | 1,037Collections
| 10javascript
| vrp25 |
' Boolean Evaluations
'
' > Greater Than
' < Less Than
' >= Greater Than Or Equal To
' <= Less Than Or Equal To
' = Equal to
x = 0
if x = 0 then print
' --------------------------
' if/then/else
if x = 0 then
print
else
print
end if
' --------------------------
' not
if x then
print
end if
if not(x) then
print
end if
' --------------------------
' if .. end if
if x = 0 then
print
goto [surprise]
end if
wait
if x = 0 then goto [surprise]
print
wait
[surprise]
print
wait
' --------------------------
' case numeric
num = 3
select case num
case 1
print
case 2
print
case 3
print
case else
print
end select
' --------------------------
' case character
var$=
select case var$
case
print
case
print
case else
print
end select | 1,023Conditional structures
| 14ruby
| hacjx |
def zero(f)
return lambda {|x| x}
end
Zero = lambda { |f| zero(f) }
def succ(n)
return lambda { |f| lambda { |x| f.(n.(f).(x)) } }
end
Three = succ(succ(succ(Zero)))
def add(n, m)
return lambda { |f| lambda { |x| m.(f).(n.(f).(x)) } }
end
def mult(n, m)
return lambda { |f| lambda { |x| m.(n.(f)).(x) } }
end
def power(b, e)
return e.(b)
end
def int_from_couch(f)
countup = lambda { |i| i+1 }
f.(countup).(0)
end
def couch_from_int(x)
countdown = lambda { |i|
case i
when 0 then Zero
else succ(countdown.(i-1))
end
}
countdown.(x)
end
Four = couch_from_int(4)
puts [ add(Three, Four),
mult(Three, Four),
power(Three, Four),
power(Four, Three) ].map {|f| int_from_couch(f) } | 1,039Church numerals
| 14ruby
| fyldr |
add (a, b) (x, y) = (a + x, b + y)
sub (a, b) (x, y) = (a - x, b - y)
magSqr (a, b) = (a ^^ 2) + (b ^^ 2)
mag a = sqrt $ magSqr a
mul (a, b) c = (a * c, b * c)
div2 (a, b) c = (a / c, b / c)
perp (a, b) = (negate b, a)
norm a = a `div2` mag a
circlePoints :: (Ord a, Floating a) =>
(a, a) -> (a, a) -> a -> Maybe ((a, a), (a, a))
circlePoints p q radius
| radius == 0 = Nothing
| p == q = Nothing
| diameter < magPQ = Nothing
| otherwise = Just (center1, center2)
where
diameter = radius * 2
pq = p `sub` q
magPQ = mag pq
midpoint = (p `add` q) `div2` 2
halfPQ = magPQ / 2
magMidC = sqrt . abs $ (radius ^^ 2) - (halfPQ ^^ 2)
midC = (norm $ perp pq) `mul` magMidC
center1 = midpoint `add` midC
center2 = midpoint `sub` midC
uncurry3 f (a, b, c) = f a b c
main :: IO ()
main = mapM_ (print . uncurry3 circlePoints)
[((0.1234, 0.9876), (0.8765, 0.2345), 2),
((0 , 2 ), (0 , 0 ), 1),
((0.1234, 0.9876), (0.1234, 0.9876), 2),
((0.1234, 0.9876), (0.8765, 0.2345), 0.5),
((0.1234, 0.9876), (0.1234, 0.1234), 0)] | 1,046Circles of given radius through two points
| 8haskell
| 6lm3k |
package main
import "fmt"
var (
animalString = []string{"Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake",
"Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig"}
stemYYString = []string{"Yang", "Yin"}
elementString = []string{"Wood", "Fire", "Earth", "Metal", "Water"}
stemCh = []rune("")
branchCh = []rune("")
)
func cz(yr int) (animal, yinYang, element, stemBranch string, cycleYear int) {
yr -= 4
stem := yr % 10
branch := yr % 12
return animalString[branch],
stemYYString[stem%2],
elementString[stem/2],
string([]rune{stemCh[stem], branchCh[branch]}),
yr%60 + 1
}
func main() {
for _, yr := range []int{1935, 1938, 1968, 1972, 1976} {
a, yy, e, sb, cy := cz(yr)
fmt.Printf("%d:%s%s,%s, Cycle year%d%s\n",
yr, e, a, yy, cy, sb)
}
} | 1,048Chinese zodiac
| 0go
| kekhz |
int check_reg(const char *path) {
struct stat sb;
return stat(path, &sb) == 0 && S_ISREG(sb.st_mode);
}
int check_dir(const char *path) {
struct stat sb;
return stat(path, &sb) == 0 && S_ISDIR(sb.st_mode);
}
int main() {
printf(,
check_reg() ? : );
printf(,
check_dir() ? : );
printf(,
check_reg() ? : );
printf(,
check_dir() ? : );
return 0;
} | 1,053Check that file exists
| 5c
| 0nast |
package main
import (
"bufio"
"flag"
"fmt"
"log"
"net"
"strings"
"time"
)
func main() {
log.SetPrefix("chat: ")
addr := flag.String("addr", "localhost:4000", "listen address")
flag.Parse()
log.Fatal(ListenAndServe(*addr))
} | 1,051Chat server
| 0go
| d38ne |
import java.time.Month;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class Main {
private static class Birthday {
private Month month;
private int day;
public Birthday(Month month, int day) {
this.month = month;
this.day = day;
}
public Month getMonth() {
return month;
}
public int getDay() {
return day;
}
@Override
public String toString() {
return month + " " + day;
}
}
public static void main(String[] args) {
List<Birthday> choices = List.of(
new Birthday(Month.MAY, 15),
new Birthday(Month.MAY, 16),
new Birthday(Month.MAY, 19),
new Birthday(Month.JUNE, 17),
new Birthday(Month.JUNE, 18),
new Birthday(Month.JULY, 14),
new Birthday(Month.JULY, 16),
new Birthday(Month.AUGUST, 14),
new Birthday(Month.AUGUST, 15),
new Birthday(Month.AUGUST, 17)
);
System.out.printf("There are%d candidates remaining.\n", choices.size()); | 1,049Cheryl's birthday
| 9java
| 0nqse |
import threading
import time
import random
def worker(workernum, barrier):
sleeptime = random.random()
print('Starting worker '+str(workernum)++str(sleeptime))
time.sleep(sleeptime)
print('Exiting worker'+str(workernum))
barrier.wait()
sleeptime = random.random()
print('Starting worker '+str(workernum)++str(sleeptime))
time.sleep(sleeptime)
print('Exiting worker'+str(workernum))
barrier = threading.Barrier(3)
w1 = threading.Thread(target=worker, args=((1,barrier)))
w2 = threading.Thread(target=worker, args=((2,barrier)))
w3 = threading.Thread(target=worker, args=((3,barrier)))
w1.start()
w2.start()
w3.start() | 1,043Checkpoint synchronization
| 3python
| gkk4h |
use strict;
use warnings;
use ntheory 'divisor_sum';
sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }
sub chowla {
my($n) = @_;
$n < 2 ? 0 : divisor_sum($n) - ($n + 1);
}
sub prime_cnt {
my($n) = @_;
my $cnt = 1;
for (3..$n) {
$cnt++ if $_%2 and chowla($_) == 0
}
$cnt;
}
sub perfect {
my($n) = @_;
my @p;
for my $i (1..$n) {
push @p, $i if $i > 1 and chowla($i) == $i-1;
}
@p;
}
printf "chowla(%2d) =%2d\n", $_, chowla($_) for 1..37;
print "\nCount of primes up to:\n";
printf "%10s%s\n", comma(10**$_), comma(prime_cnt(10**$_)) for 2..7;
my @perfect = perfect(my $limit = 35_000_000);
printf "\nThere are%d perfect numbers up to%s:%s\n",
1+$ | 1,041Chowla numbers
| 2perl
| xonw8 |
use std::rc::Rc;
use std::ops::{Add, Mul};
#[derive(Clone)]
struct Church<'a, T: 'a> {
runner: Rc<dyn Fn(Rc<dyn Fn(T) -> T + 'a>) -> Rc<dyn Fn(T) -> T + 'a> + 'a>,
}
impl<'a, T> Church<'a, T> {
fn zero() -> Self {
Church {
runner: Rc::new(|_f| {
Rc::new(|x| x)
})
}
}
fn succ(self) -> Self {
Church {
runner: Rc::new(move |f| {
let g = self.runner.clone();
Rc::new(move |x| f(g(f.clone())(x)))
})
}
}
fn run(&self, f: impl Fn(T) -> T + 'a) -> Rc<dyn Fn(T) -> T + 'a> {
(self.runner)(Rc::new(f))
}
fn exp(self, rhs: Church<'a, Rc<dyn Fn(T) -> T + 'a>>) -> Self
{
Church {
runner: (rhs.runner)(self.runner)
}
}
}
impl<'a, T> Add for Church<'a, T> {
type Output = Church<'a, T>;
fn add(self, rhs: Church<'a, T>) -> Church<T> {
Church {
runner: Rc::new(move |f| {
let self_runner = self.runner.clone();
let rhs_runner = rhs.runner.clone();
Rc::new(move |x| (self_runner)(f.clone())((rhs_runner)(f.clone())(x)))
})
}
}
}
impl<'a, T> Mul for Church<'a, T> {
type Output = Church<'a, T>;
fn mul(self, rhs: Church<'a, T>) -> Church<T> {
Church {
runner: Rc::new(move |f| {
(self.runner)((rhs.runner)(f))
})
}
}
}
impl<'a, T> From<i32> for Church<'a, T> {
fn from(n: i32) -> Church<'a, T> {
let mut ret = Church::zero();
for _ in 0..n {
ret = ret.succ();
}
ret
}
}
impl<'a> From<&Church<'a, i32>> for i32 {
fn from(c: &Church<'a, i32>) -> i32 {
c.run(|x| x + 1)(0)
}
}
fn three<'a, T>() -> Church<'a, T> {
Church::zero().succ().succ().succ()
}
fn four<'a, T>() -> Church<'a, T> {
Church::zero().succ().succ().succ().succ()
}
fn main() {
println!("three =\t{}", i32::from(&three()));
println!("four =\t{}", i32::from(&four()));
println!("three + four =\t{}", i32::from(&(three() + four())));
println!("three * four =\t{}", i32::from(&(three() * four())));
println!("three ^ four =\t{}", i32::from(&(three().exp(four()))));
println!("four ^ three =\t{}", i32::from(&(four().exp(three()))));
} | 1,039Church numerals
| 15rust
| tm2fd |
public class MyClass{ | 1,038Classes
| 9java
| bw8k3 |
null | 1,038Classes
| 10javascript
| w8fe2 |
class Zodiac {
final static String[] animals = ["Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake", "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig"]
final static String[] elements = ["Wood", "Fire", "Earth", "Metal", "Water"]
final static String[] animalChars = ["", "", "", "", "", "", "", "", "", "", "", ""]
static String[][] elementChars = [["", "", "", "", ""], ["", "", "", "", ""]]
static String getYY(int year) {
if (year % 2 == 0) {
return "yang"
} else {
return "yin"
}
}
static void main(String[] args) {
int[] years = [1935, 1938, 1968, 1972, 1976, 1984, 1985, 2017]
for (int i = 0; i < years.length; i++) {
println(years[i] + " is the year of the " + elements[(int) Math.floor((years[i] - 4) % 10 / 2)] + " " + animals[(years[i] - 4) % 12] + " (" + getYY(years[i]) + "). " + elementChars[years[i] % 2][(int) Math.floor((years[i] - 4) % 10 / 2)] + animalChars[(years[i] - 4) % 12])
}
}
} | 1,048Chinese zodiac
| 7groovy
| gkg46 |
class ChatServer implements Runnable {
private int port = 0
private List<Client> clientList = new ArrayList<>()
ChatServer(int port) {
this.port = port
}
@SuppressWarnings("GroovyInfiniteLoopStatement")
@Override
void run() {
try {
ServerSocket serverSocket = new ServerSocket(port)
while (true) {
Socket socket = serverSocket.accept()
new Thread(new Client(socket)).start()
}
} catch (Exception e) {
e.printStackTrace()
}
}
private synchronized boolean registerClient(Client client) {
for (Client other: clientList) {
if (other.clientName.equalsIgnoreCase(client.clientName)) {
return false
}
}
clientList.add(client)
return true
}
private void deRegisterClient(Client client) {
boolean wasRegistered
synchronized (this) {
wasRegistered = clientList.remove(client)
}
if (wasRegistered) {
broadcast(client, "--- " + client.clientName + " left ---")
}
}
private synchronized String getOnlineListCSV() {
StringBuilder sb = new StringBuilder()
sb.append(clientList.size()).append(" user(s) online: ")
def it = clientList.iterator()
if (it.hasNext()) {
sb.append(it.next().clientName)
}
while (it.hasNext()) {
sb.append(", ")
sb.append(it.next().clientName)
}
return sb.toString()
}
private void broadcast(Client fromClient, String msg) { | 1,051Chat server
| 7groovy
| 0nwsh |
import java.util.Arrays;
public class Cholesky {
public static double[][] chol(double[][] a){
int m = a.length;
double[][] l = new double[m][m]; | 1,042Cholesky decomposition
| 9java
| xoiwy |
(() => {
'use strict'; | 1,049Cheryl's birthday
| 10javascript
| d3inu |
null | 1,023Conditional structures
| 15rust
| kelh5 |
package main
import (
"fmt"
"math/big"
)
var one = big.NewInt(1)
func crt(a, n []*big.Int) (*big.Int, error) {
p := new(big.Int).Set(n[0])
for _, n1 := range n[1:] {
p.Mul(p, n1)
}
var x, q, s, z big.Int
for i, n1 := range n {
q.Div(p, n1)
z.GCD(nil, &s, n1, &q)
if z.Cmp(one) != 0 {
return nil, fmt.Errorf("%d not coprime", n1)
}
x.Add(&x, s.Mul(a[i], s.Mul(&s, &q)))
}
return x.Mod(&x, p), nil
}
func main() {
n := []*big.Int{
big.NewInt(3),
big.NewInt(5),
big.NewInt(7),
}
a := []*big.Int{
big.NewInt(2),
big.NewInt(3),
big.NewInt(2),
}
fmt.Println(crt(a, n))
} | 1,047Chinese remainder theorem
| 0go
| xoqwf |
func succ<A, B, C>(_ n: @escaping (@escaping (A) -> B) -> (C) -> A) -> (@escaping (A) -> B) -> (C) -> B {
return {f in
return {x in
return f(n(f)(x))
}
}
}
func zero<A, B>(_ a: A) -> (B) -> B {
return {b in
return b
}
}
func three<A>(_ f: @escaping (A) -> A) -> (A) -> A {
return {x in
return succ(succ(succ(zero)))(f)(x)
}
}
func four<A>(_ f: @escaping (A) -> A) -> (A) -> A {
return {x in
return succ(succ(succ(succ(zero))))(f)(x)
}
}
func add<A, B, C>(_ m: @escaping (B) -> (A) -> C) -> (@escaping (B) -> (C) -> A) -> (B) -> (C) -> C {
return {n in
return {f in
return {x in
return m(f)(n(f)(x))
}
}
}
}
func mult<A, B, C>(_ m: @escaping (A) -> B) -> (@escaping (C) -> A) -> (C) -> B {
return {n in
return {f in
return m(n(f))
}
}
}
func exp<A, B, C>(_ m: A) -> (@escaping (A) -> (B) -> (C) -> C) -> (B) -> (C) -> C {
return {n in
return {f in
return {x in
return n(m)(f)(x)
}
}
}
}
func church<A>(_ x: Int) -> (@escaping (A) -> A) -> (A) -> A {
guard x!= 0 else { return zero }
return {f in
return {a in
return f(church(x - 1)(f)(a))
}
}
}
func unchurch<A>(_ f: (@escaping (Int) -> Int) -> (Int) -> A) -> A {
return f({i in
return i + 1
})(0)
}
let a = unchurch(add(three)(four))
let b = unchurch(mult(three)(four)) | 1,039Church numerals
| 17swift
| d6cnh |
class MyClass(val myInt: Int) {
fun treble(): Int = myInt * 3
}
fun main(args: Array<String>) {
val mc = MyClass(24)
print("${mc.myInt}, ${mc.treble()}")
} | 1,038Classes
| 11kotlin
| rbwgo |
var funcs: [() -> Int] = []
for var i = 0; i < 10; i++ {
funcs.append({ i * i })
}
println(funcs[3]()) | 1,033Closures/Value capture
| 17swift
| kedhx |
import Data.Array (Array, listArray, (!))
ats :: Array Int (Char, String)
ats =
listArray (0, 9) $
zip
""
(words "ji y bng dng w j gng xn rn gi")
ads :: Array Int (String, String)
ads =
listArray (0, 11) $
zip
(chars "")
( words $
"z chu yn mo chn s "
<> "w wi shn yu x hi"
)
aws :: Array Int (String, String, String)
aws =
listArray (0, 4) $
zip3
(chars "")
(words "m hu t jn shu")
(words "wood fire earth metal water")
axs :: Array Int (String, String, String)
axs =
listArray (0, 11) $
zip3
(chars "")
( words $
"sh ni h t lng sh "
<> "m yng hu j gu zh"
)
( words $
"rat ox tiger rabbit dragon snake "
<> "horse goat monkey rooster dog pig"
)
ays :: Array Int (String, String)
ays =
listArray (0, 1) $
zip (chars "") (words "yng yn")
chars :: String -> [String]
chars = (flip (:) [] <$>)
f y =
let i = y - 4
i = rem i 10
i = rem i 12
(h, p) = ats ! i
(h, p) = ads ! i
(h, p, e) = aws ! quot i 2
(h, p, e) = axs ! i
(h, p) = ays ! rem i 2
in
[ [show y, h: h, h, h, h],
[[], p <> p, p, p, p],
[ [],
show (rem i 60 + 1) <> "/60",
e,
e,
[]
]
]
main :: IO ()
main =
mapM_ putStrLn $
showYear
<$> [1935, 1938, 1968, 1972, 1976, 1984, 2017]
fieldWidths :: [[Int]]
fieldWidths =
[ [6, 10, 7, 8, 3],
[6, 11, 8, 8, 4],
[6, 11, 8, 8, 4]
]
showYear :: Int -> String
showYear y =
unlines $
( \(ns, xs) ->
concat $
uncurry (`justifyLeft` ' ')
<$> zip ns xs
)
<$> zip fieldWidths (f y)
where
justifyLeft n c s = take n (s <> replicate n c) | 1,048Chinese zodiac
| 8haskell
| n3nie |
(dorun (map #(.exists (clojure.java.io/as-file %)) '("/input.txt" "/docs" "./input.txt" "./docs"))) | 1,053Check that file exists
| 6clojure
| d3snb |
import Network
import System.IO
import Control.Concurrent
import qualified Data.Text as T
import Data.Text (Text)
import qualified Data.Text.IO as T
import qualified Data.Map as M
import Data.Map (Map)
import Control.Monad.Reader
import Control.Monad.Error
import Control.Exception
import Data.Monoid
import Control.Applicative
type ServerApp = ReaderT ThreadData IO
data Speaker = Server | Client Text
data ThreadData = ThreadData { threadHandle :: Handle
, userTableMV :: MVar (Map Text Handle)}
echoLocal = liftIO . T.putStrLn
echoRemote = echoMessage . (">> "<>)
echoMessage msg = viewHandle >>= \h -> liftIO $ T.hPutStrLn h msg
getRemoteLine = viewHandle >>= liftIO . T.hGetLine
putMVarT = (liftIO.) . putMVar
takeMVarT = liftIO . takeMVar
readMVarT = liftIO . readMVar
modifyUserTable fn = viewUsers >>= \mv ->
liftIO $ modifyMVar_ mv (return . fn)
viewHandle = threadHandle <$> ask
viewUsers = userTableMV <$> ask
userChat :: ServerApp ()
userChat = do
name <- addUser
echoLocal name
h <- viewHandle
(flip catchError) (\_ -> removeUser name) $
do echoLocal $ "Accepted " <> name
forever $ getRemoteLine >>= broadcast (Client name)
removeUser :: Text -> ServerApp ()
removeUser name = do
echoLocal $ "Exception with " <> name <> ", removing from userTable"
broadcast Server $ name <> " has left the server"
modifyUserTable (M.delete name)
addUser :: ServerApp Text
addUser = do
h <- viewHandle
usersMV <- viewUsers
echoRemote "Enter username"
name <- T.filter (/='\r') <$> getRemoteLine
userTable <- takeMVarT usersMV
if name `M.member` userTable
then do echoRemote "Username already exists!"
putMVarT usersMV userTable
addUser
else do putMVarT usersMV (M.insert name h userTable)
broadcast Server $ name <> " has joined the server"
echoRemote "Welcome to the server!\n>> Other users:"
readMVarT usersMV >>=
mapM_ (echoRemote . ("*" <>) . fst)
. filter ((/=name). fst) . M.toList
return name
broadcast :: Speaker -> Text -> ServerApp ()
broadcast user msg =
viewUsers >>= readMVarT >>= mapM_ (f . snd) . fn . M.toList
where f h = liftIO $ T.hPutStrLn h $ nm <> msg
(fn, nm) = case user of
Server -> (id, ">> ")
Client t -> (filter ((/=t) . fst), t <> "> ")
clientLoop socket users = do
(h, _, _) <- accept socket
hSetBuffering h LineBuffering
forkIO $ runReaderT userChat (ThreadData h users)
clientLoop socket users
main = do
server <- listenOn $ PortNumber 5002
T.putStrLn "Server started"
newMVar (M.empty) >>= clientLoop server | 1,051Chat server
| 8haskell
| 57lug |
const cholesky = function (array) {
const zeros = [...Array(array.length)].map( _ => Array(array.length).fill(0));
const L = zeros.map((row, r, xL) => row.map((v, c) => {
const sum = row.reduce((s, _, i) => i < c ? s + xL[r][i] * xL[c][i] : s, 0);
return xL[r][c] = c < r + 1 ? r === c ? Math.sqrt(array[r][r] - sum) : (array[r][c] - sum) / xL[c][c] : v;
}));
return L;
}
let arr3 = [[25, 15, -5], [15, 18, 0], [-5, 0, 11]];
console.log(cholesky(arr3));
let arr4 = [[18, 22, 54, 42], [22, 70, 86, 62], [54, 86, 174, 134], [42, 62, 134, 106]];
console.log(cholesky(arr4)); | 1,042Cholesky decomposition
| 10javascript
| otz86 |
require 'socket'
class Workshop
def initialize
@sockets = {}
end
def add
child, parent = UNIXSocket.pair
wid = fork do
child.close
@sockets.each_value { |sibling| sibling.close }
Signal.trap() { exit! }
loop do
begin
command, args = Marshal.load(parent)
rescue EOFError
break
end
case command
when :work
result = yield *args
Marshal.dump(result, parent)
when :remove
break
else
fail
end
end
end
parent.close
@sockets[wid] = child
wid
end
def work(*args)
message = [:work, args]
@sockets.each_pair do |wid, child|
Marshal.dump(message, child)
end
result = {}
@sockets.each_pair do |wid, child|
begin
result[wid] = Marshal.load(child)
rescue EOFError
fail
end
end
result
end
def remove(wid)
unless child = @sockets.delete(wid)
raise ArgumentError,
else
Marshal.dump([:remove, nil], child)
child.close
Process.wait(wid)
end
end
end
require 'pp'
shop = Workshop.new
wids = []
@fixed_rand = false
def fix_rand
unless @fixed_rand; srand; @fixed_rand = true; end
end
6.times do
wids << shop.add do |i|
fix_rand
f = proc { |n| if n < 2 then n else f[n - 1] + f[n - 2] end }
[i, f[25 + rand(10)]]
end
end
6.times do |i|
pp shop.work(i)
victim = rand(wids.length)
shop.remove wids[victim]
wids.slice! victim
wids << shop.add do |j|
fix_rand
f = proc { |n| if n < 3 then n else f[n - 1] + f[n - 2] + f[n - 3] end }
[j, i, f[20 + rand(10)]]
end
end
wids.each { |wid| shop.remove wid }
pp shop.work(6) | 1,043Checkpoint synchronization
| 14ruby
| 7ppri |
import java.util.PriorityQueue
fun main(args: Array<String>) { | 1,037Collections
| 11kotlin
| tmuf0 |
class ChineseRemainderTheorem {
static int chineseRemainder(int[] n, int[] a) {
int prod = 1
for (int i = 0; i < n.length; i++) {
prod *= n[i]
}
int p, sm = 0
for (int i = 0; i < n.length; i++) {
p = prod.intdiv(n[i])
sm += a[i] * mulInv(p, n[i]) * p
}
return sm % prod
}
private static int mulInv(int a, int b) {
int b0 = b
int x0 = 0
int x1 = 1
if (b == 1) {
return 1
}
while (a > 1) {
int q = a.intdiv(b)
int amb = a % b
a = b
b = amb
int xqx = x1 - q * x0
x1 = x0
x0 = xqx
}
if (x1 < 0) {
x1 += b0
}
return x1
}
static void main(String[] args) {
int[] n = [3, 5, 7]
int[] a = [2, 3, 2]
println(chineseRemainder(n, a))
}
} | 1,047Chinese remainder theorem
| 7groovy
| px1bo |
import java.util.Objects;
public class Circles {
private static class Point {
private final double x, y;
public Point(Double x, Double y) {
this.x = x;
this.y = y;
}
public double distanceFrom(Point other) {
double dx = x - other.x;
double dy = y - other.y;
return Math.sqrt(dx * dx + dy * dy);
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
Point point = (Point) other;
return x == point.x && y == point.y;
}
@Override
public String toString() {
return String.format("(%.4f,%.4f)", x, y);
}
}
private static Point[] findCircles(Point p1, Point p2, double r) {
if (r < 0.0) throw new IllegalArgumentException("the radius can't be negative");
if (r == 0.0 && p1 != p2) throw new IllegalArgumentException("no circles can ever be drawn");
if (r == 0.0) return new Point[]{p1, p1};
if (Objects.equals(p1, p2)) throw new IllegalArgumentException("an infinite number of circles can be drawn");
double distance = p1.distanceFrom(p2);
double diameter = 2.0 * r;
if (distance > diameter) throw new IllegalArgumentException("the points are too far apart to draw a circle");
Point center = new Point((p1.x + p2.x) / 2.0, (p1.y + p2.y) / 2.0);
if (distance == diameter) return new Point[]{center, center};
double mirrorDistance = Math.sqrt(r * r - distance * distance / 4.0);
double dx = (p2.x - p1.x) * mirrorDistance / distance;
double dy = (p2.y - p1.y) * mirrorDistance / distance;
return new Point[]{
new Point(center.x - dy, center.y + dx),
new Point(center.x + dy, center.y - dx)
};
}
public static void main(String[] args) {
Point[] p = new Point[]{
new Point(0.1234, 0.9876),
new Point(0.8765, 0.2345),
new Point(0.0000, 2.0000),
new Point(0.0000, 0.0000)
};
Point[][] points = new Point[][]{
{p[0], p[1]},
{p[2], p[3]},
{p[0], p[0]},
{p[0], p[1]},
{p[0], p[0]},
};
double[] radii = new double[]{2.0, 1.0, 2.0, 0.5, 0.0};
for (int i = 0; i < radii.length; ++i) {
Point p1 = points[i][0];
Point p2 = points[i][1];
double r = radii[i];
System.out.printf("For points%s and%s with radius%f\n", p1, p2, r);
try {
Point[] circles = findCircles(p1, p2, r);
Point c1 = circles[0];
Point c2 = circles[1];
if (Objects.equals(c1, c2)) {
System.out.printf("there is just one circle with center at%s\n", c1);
} else {
System.out.printf("there are two circles with centers at%s and%s\n", c1, c2);
}
} catch (IllegalArgumentException ex) {
System.out.println(ex.getMessage());
}
System.out.println();
}
}
} | 1,046Circles of given radius through two points
| 9java
| n3fih |
null | 1,049Cheryl's birthday
| 11kotlin
| es1a4 |
null | 1,043Checkpoint synchronization
| 15rust
| j1172 |
import java.util.{Random, Scanner}
object CheckpointSync extends App {
val in = new Scanner(System.in)
private def runTasks(nTasks: Int): Unit = {
for (i <- 0 until nTasks) {
println("Starting task number " + (i + 1) + ".")
runThreads()
Worker.checkpoint()
}
}
private def runThreads(): Unit =
for (i <- 0 until Worker.nWorkers) new Thread(new Worker(i + 1)).start()
class Worker( var threadID: Int)
extends Runnable {
override def run(): Unit = {
work()
}
private def work(): Unit = {
try {
val workTime = Worker.rgen.nextInt(900) + 100
println("Worker " + threadID + " will work for " + workTime + " msec.")
Thread.sleep(workTime) | 1,043Checkpoint synchronization
| 16scala
| bwwk6 |
use ntheory qw/forcomb/;
forcomb { print "@_\n" } 5,3 | 1,031Combinations
| 2perl
| vrq20 |
if (n == 12) "twelve" else "not twelve"
today match {
case Monday =>
Compute_Starting_Balance;
case Friday =>
Compute_Ending_Balance;
case Tuesday =>
Accumulate_Sales
case _ => {}
} | 1,023Conditional structures
| 16scala
| 1qupf |
import Control.Monad (zipWithM)
egcd :: Int -> Int -> (Int, Int)
egcd _ 0 = (1, 0)
egcd a b = (t, s - q * t)
where
(s, t) = egcd b r
(q, r) = a `quotRem` b
modInv :: Int -> Int -> Either String Int
modInv a b =
case egcd a b of
(x, y)
| a * x + b * y == 1 -> Right x
| otherwise ->
Left $ "No modular inverse for " ++ show a ++ " and " ++ show b
chineseRemainder :: [Int] -> [Int] -> Either String Int
chineseRemainder residues modulii =
zipWithM modInv crtModulii modulii >>=
(Right . (`mod` modPI) . sum . zipWith (*) crtModulii . zipWith (*) residues)
where
modPI = product modulii
crtModulii = (modPI `div`) <$> modulii
main :: IO ()
main =
mapM_ (putStrLn . either id show) $
uncurry chineseRemainder <$>
[ ([10, 4, 12], [11, 12, 13])
, ([10, 4, 9], [11, 22, 19])
, ([2, 3, 2], [3, 5, 7])
] | 1,047Chinese remainder theorem
| 8haskell
| y2m66 |
const hDist = (p1, p2) => Math.hypot(...p1.map((e, i) => e - p2[i])) / 2;
const pAng = (p1, p2) => Math.atan(p1.map((e, i) => e - p2[i]).reduce((p, c) => c / p, 1));
const solveF = (p, r) => t => [r*Math.cos(t) + p[0], r*Math.sin(t) + p[1]];
const diamPoints = (p1, p2) => p1.map((e, i) => e + (p2[i] - e) / 2);
const findC = (...args) => {
const [p1, p2, s] = args;
const solve = solveF(p1, s);
const halfDist = hDist(p1, p2);
let msg = `p1: ${p1}, p2: ${p2}, r:${s} Result: `;
switch (Math.sign(s - halfDist)) {
case 0:
msg += s ? `Points on diameter. Circle at: ${diamPoints(p1, p2)}` :
'Radius Zero';
break;
case 1:
if (!halfDist) {
msg += 'Coincident point. Infinite solutions';
}
else {
let theta = pAng(p1, p2);
let theta2 = Math.acos(halfDist / s);
[1, -1].map(e => solve(theta + e * theta2)).forEach(
e => msg += `Circle at ${e} `);
}
break;
case -1:
msg += 'No intersection. Points further apart than circle diameter';
break;
}
return msg;
};
[
[[0.1234, 0.9876], [0.8765, 0.2345], 2.0],
[[0.0000, 2.0000], [0.0000, 0.0000], 1.0],
[[0.1234, 0.9876], [0.1234, 0.9876], 2.0],
[[0.1234, 0.9876], [0.8765, 0.2345], 0.5],
[[0.1234, 0.9876], [0.1234, 0.9876], 0.0]
].forEach((t,i) => console.log(`Test: ${i}: ${findC(...t)}`)); | 1,046Circles of given radius through two points
| 10javascript
| 3cyz0 |
public class Zodiac {
final static String animals[]={"Rat","Ox","Tiger","Rabbit","Dragon","Snake","Horse","Goat","Monkey","Rooster","Dog","Pig"};
final static String elements[]={"Wood","Fire","Earth","Metal","Water"};
final static String animalChars[]={"","","","","","","","","","","",""};
static String elementChars[][]={{"","","","",""},{"","","","",""}};
static String getYY(int year)
{
if(year%2==0)
{
return "yang";
}
else
{
return "yin";
}
}
public static void main(String[] args)
{
int years[]={1935,1938,1968,1972,1976,1984,1985,2017};
for(int i=0;i<years.length;i++)
{
System.out.println(years[i]+" is the year of the "+elements[(int) Math.floor((years[i]-4)%10/2)]+" "+animals[(years[i]-4)%12]+" ("+getYY(years[i])+"). "+elementChars[years[i]%2][(int) Math.floor((years[i]-4)%10/2)]+animalChars[(years[i]-4)%12]);
}
}
} | 1,048Chinese zodiac
| 9java
| qiqxa |
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer implements Runnable
{
private int port = 0;
private List<Client> clients = new ArrayList<Client>();
public ChatServer(int port)
{ this.port = port; }
public void run()
{
try
{
ServerSocket ss = new ServerSocket(port);
while (true)
{
Socket s = ss.accept();
new Thread(new Client(s)).start();
}
}
catch (Exception e)
{ e.printStackTrace(); }
}
private synchronized boolean registerClient(Client client)
{
for (Client otherClient : clients)
if (otherClient.clientName.equalsIgnoreCase(client.clientName))
return false;
clients.add(client);
return true;
}
private void deregisterClient(Client client)
{
boolean wasRegistered = false;
synchronized (this)
{ wasRegistered = clients.remove(client); }
if (wasRegistered)
broadcast(client, "--- " + client.clientName + " left ---");
}
private synchronized String getOnlineListCSV()
{
StringBuilder sb = new StringBuilder();
sb.append(clients.size()).append(" user(s) online: ");
for (int i = 0; i < clients.size(); i++)
sb.append((i > 0) ? ", " : "").append(clients.get(i).clientName);
return sb.toString();
}
private void broadcast(Client fromClient, String msg)
{ | 1,051Chat server
| 9java
| 9v3mu |
use Math::BigRat try=>"GMP";
sub taneval {
my($coef,$f) = @_;
$f = Math::BigRat->new($f) unless ref($f);
return 0 if $coef == 0;
return $f if $coef == 1;
return -taneval(-$coef, $f) if $coef < 0;
my($a,$b) = ( taneval($coef>>1, $f), taneval($coef-($coef>>1),$f) );
($a+$b)/(1-$a*$b);
}
sub tans {
my @xs=@_;
return taneval(@{$xs[0]}) if scalar(@xs)==1;
my($a,$b) = ( tans(@xs[0..($
($a+$b)/(1-$a*$b);
}
sub test {
printf "%5s (%s)\n", (tans(@_)==1)?"OK":"Error", join(" ",map{"[@$_]"} @_);
}
test([1,'1/2'], [1,'1/3']);
test([2,'1/3'], [1,'1/7']);
test([4,'1/5'], [-1,'1/239']);
test([5,'1/7'],[2,'3/79']);
test([5,'29/278'],[7,'3/79']);
test([1,'1/2'],[1,'1/5'],[1,'1/8']);
test([4,'1/5'],[-1,'1/70'],[1,'1/99']);
test([5,'1/7'],[4,'1/53'],[2,'1/4443']);
test([6,'1/8'],[2,'1/57'],[1,'1/239']);
test([8,'1/10'],[-1,'1/239'],[-4,'1/515']);
test([12,'1/18'],[8,'1/57'],[-5,'1/239']);
test([16,'1/21'],[3,'1/239'],[4,'3/1042']);
test([22,'1/28'],[2,'1/443'],[-5,'1/1393'],[-10,'1/11018']);
test([22,'1/38'],[17,'7/601'],[10,'7/8149']);
test([44,'1/57'],[7,'1/239'],[-12,'1/682'],[24,'1/12943']);
test([88,'1/172'],[51,'1/239'],[32,'1/682'],[44,'1/5357'],[68,'1/12943']);
test([88,'1/172'],[51,'1/239'],[32,'1/682'],[44,'1/5357'],[68,'1/12944']); | 1,050Check Machin-like formulas
| 2perl
| 572u2 |
null | 1,042Cholesky decomposition
| 11kotlin
| pxqb6 |
null | 1,049Cheryl's birthday
| 1lua
| w0aea |
from sympy import divisors
def chowla(n):
return 0 if n < 2 else sum(divisors(n, generator=True)) - 1 -n
def is_prime(n):
return chowla(n) == 0
def primes_to(n):
return sum(chowla(i) == 0 for i in range(2, n))
def perfect_between(n, m):
c = 0
print(f)
for i in range(n, m):
if i > 1 and chowla(i) == i - 1:
print(f)
c += 1
print(f)
if __name__ == '__main__':
for i in range(1, 38):
print(f)
for i in range(2, 6):
print(f)
perfect_between(1, 1_000_000)
print()
for i in range(6, 8):
print(f)
perfect_between(1_000_000, 35_000_000) | 1,041Chowla numbers
| 3python
| qidxi |
myclass = setmetatable({
__index = function(z,i) return myclass[i] end, | 1,038Classes
| 1lua
| 7pxru |
(() => {
"use strict"; | 1,048Chinese zodiac
| 10javascript
| iziol |
const net = require("net");
const EventEmitter = require("events").EventEmitter;
class ChatServer {
constructor() {
this.chatters = {};
this.server = net.createServer(this.handleConnection.bind(this));
this.server.listen(1212, "localhost");
}
isNicknameLegal(nickname) { | 1,051Chat server
| 10javascript
| urcvb |
int main() {
printf(, 'a');
printf(, 97);
return 0;
} | 1,054Character codes
| 5c
| d3qnv |
import static java.util.Arrays.stream;
public class ChineseRemainderTheorem {
public static int chineseRemainder(int[] n, int[] a) {
int prod = stream(n).reduce(1, (i, j) -> i * j);
int p, sm = 0;
for (int i = 0; i < n.length; i++) {
p = prod / n[i];
sm += a[i] * mulInv(p, n[i]) * p;
}
return sm % prod;
}
private static int mulInv(int a, int b) {
int b0 = b;
int x0 = 0;
int x1 = 1;
if (b == 1)
return 1;
while (a > 1) {
int q = a / b;
int amb = a % b;
a = b;
b = amb;
int xqx = x1 - q * x0;
x1 = x0;
x0 = xqx;
}
if (x1 < 0)
x1 += b0;
return x1;
}
public static void main(String[] args) {
int[] n = {3, 5, 7};
int[] a = {2, 3, 2};
System.out.println(chineseRemainder(n, a));
}
} | 1,047Chinese remainder theorem
| 9java
| d6fn9 |
import re
from fractions import Fraction
from pprint import pprint as pp
equationtext = '''\
pi/4 = arctan(1/2) + arctan(1/3)
pi/4 = 2*arctan(1/3) + arctan(1/7)
pi/4 = 4*arctan(1/5) - arctan(1/239)
pi/4 = 5*arctan(1/7) + 2*arctan(3/79)
pi/4 = 5*arctan(29/278) + 7*arctan(3/79)
pi/4 = arctan(1/2) + arctan(1/5) + arctan(1/8)
pi/4 = 4*arctan(1/5) - arctan(1/70) + arctan(1/99)
pi/4 = 5*arctan(1/7) + 4*arctan(1/53) + 2*arctan(1/4443)
pi/4 = 6*arctan(1/8) + 2*arctan(1/57) + arctan(1/239)
pi/4 = 8*arctan(1/10) - arctan(1/239) - 4*arctan(1/515)
pi/4 = 12*arctan(1/18) + 8*arctan(1/57) - 5*arctan(1/239)
pi/4 = 16*arctan(1/21) + 3*arctan(1/239) + 4*arctan(3/1042)
pi/4 = 22*arctan(1/28) + 2*arctan(1/443) - 5*arctan(1/1393) - 10*arctan(1/11018)
pi/4 = 22*arctan(1/38) + 17*arctan(7/601) + 10*arctan(7/8149)
pi/4 = 44*arctan(1/57) + 7*arctan(1/239) - 12*arctan(1/682) + 24*arctan(1/12943)
pi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12943)
pi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12944)
'''
def parse_eqn(equationtext=equationtext):
eqn_re = re.compile(r)
found = eqn_re.findall(equationtext)
machins, part = [], []
for lhs, sign, mult, numer, denom in eqn_re.findall(equationtext):
if lhs and part:
machins.append(part)
part = []
part.append( ( (-1 if sign == '-' else 1) * ( int(mult) if mult else 1),
Fraction(int(numer), (int(denom) if denom else 1)) ) )
machins.append(part)
return machins
def tans(xs):
xslen = len(xs)
if xslen == 1:
return tanEval(*xs[0])
aa, bb = xs[:xslen
a, b = tans(aa), tans(bb)
return (a + b) / (1 - a * b)
def tanEval(coef, f):
if coef == 1:
return f
if coef < 0:
return -tanEval(-coef, f)
ca = coef
cb = coef - ca
a, b = tanEval(ca, f), tanEval(cb, f)
return (a + b) / (1 - a * b)
if __name__ == '__main__':
machins = parse_eqn()
for machin, eqn in zip(machins, equationtext.split('\n')):
ans = tans(machin)
print('%5s:%s'% ( ('OK' if ans == 1 else 'ERROR'), eqn)) | 1,050Check Machin-like formulas
| 3python
| 4jv5k |
sub filter {
my($test,@dates) = @_;
my(%M,%D,@filtered);
for my $date (@dates) {
my($mon,$day) = split '-', $date;
$M{$mon}{cnt}++;
$D{$day}{cnt}++;
push @{$M{$mon}{day}}, $day;
push @{$D{$day}{mon}}, $mon;
push @{$M{$mon}{bday}}, "$mon-$day";
push @{$D{$day}{bday}}, "$mon-$day";
}
if ($test eq 'singleton') {
my %skip;
for my $day (grep { $D{$_}{cnt} == 1 } keys %D) { $skip{ @{$D{$day}{mon}}[0] }++ }
for my $mon (grep { ! $skip{$_} } keys %M) { push @filtered, @{$M{$mon}{bday}} }
} elsif ($test eq 'duplicate') {
for my $day (grep { $D{$_}{cnt} == 1 } keys %D) { push @filtered, @{$D{$day}{bday}} }
} elsif ($test eq 'multiple') {
for my $day (grep { $M{$_}{cnt} == 1 } keys %M) { push @filtered, @{$M{$day}{bday}} }
}
return @filtered;
}
my @dates = qw<5-15 5-16 5-19 6-17 6-18 7-14 7-16 8-14 8-15 8-17>;
@dates = filter($_, @dates) for qw<singleton duplicate multiple>;
my @months = qw<_ January February March April May June July August September October November December>;
my ($m, $d) = split '-', $dates[0];
print "Cheryl's birthday is $months[$m] $d.\n"; | 1,049Cheryl's birthday
| 2perl
| cum9a |
collection = {0, '1'}
print(collection[1]) | 1,037Collections
| 1lua
| z95ty |
<?php
$a=array(1,2,3,4,5);
$k=3;
$n=5;
$c=array_splice($a, $k);
$b=array_splice($a, 0, $k);
$j=$k-1;
print_r($b);
while (1) {
$m=array_search($b[$j]+1,$c);
if ($m!==false) {
$c[$m]-=1;
$b[$j]=$b[$j]+1;
print_r($b);
}
if ($b[$k-1]==$n) {
$i=$k-1;
while ($i >= 0) {
if ($i == 0 && $b[$i] == $n-$k+1) break 2;
$m=array_search($b[$i]+1,$c);
if ($m!==false) {
$c[$m]=$c[$m]-1;
$b[$i]=$b[$i]+1;
$g=$i;
while ($g != $k-1) {
array_unshift ($c, $b[$g+1]);
$b[$g+1]=$b[$g]+1;
$g++;
}
$c=array_diff($c,$b);
print_r($b);
break;
}
$i--;
}
}
}
?> | 1,031Combinations
| 12php
| 0dvsp |
function crt(num, rem) {
let sum = 0;
const prod = num.reduce((a, c) => a * c, 1);
for (let i = 0; i < num.length; i++) {
const [ni, ri] = [num[i], rem[i]];
const p = Math.floor(prod / ni);
sum += ri * p * mulInv(p, ni);
}
return sum % prod;
}
function mulInv(a, b) {
const b0 = b;
let [x0, x1] = [0, 1];
if (b === 1) {
return 1;
}
while (a > 1) {
const q = Math.floor(a / b);
[a, b] = [b, a % b];
[x0, x1] = [x1 - q * x0, x0];
}
if (x1 < 0) {
x1 += b0;
}
return x1;
}
console.log(crt([3,5,7], [2,3,2])) | 1,047Chinese remainder theorem
| 10javascript
| 6ly38 |
null | 1,046Circles of given radius through two points
| 11kotlin
| sn8q7 |
null | 1,048Chinese zodiac
| 11kotlin
| 1q1pd |
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import java.io.Writer
import java.net.ServerSocket
import java.net.Socket
import java.util.ArrayList
import java.util.Collections
class ChatServer private constructor(private val port: Int) : Runnable {
private val clients = ArrayList<Client>()
private val onlineListCSV: String
@Synchronized get() {
val sb = StringBuilder()
sb.append(clients.size).append(" user(s) online: ")
for (i in clients.indices) {
sb.append(if (i > 0) ", " else "").append(clients[i].clientName)
}
return sb.toString()
}
override fun run() {
try {
val ss = ServerSocket(port)
while (true) {
val s = ss.accept()
Thread(Client(s)).start()
}
} catch (e: Exception) {
e.printStackTrace()
}
}
@Synchronized
private fun registerClient(client: Client): Boolean {
for (otherClient in clients) {
if (otherClient.clientName!!.equals(client.clientName!!, ignoreCase = true)) {
return false
}
}
clients.add(client)
return true
}
private fun deRegisterClient(client: Client) {
var wasRegistered = false
synchronized(this) {
wasRegistered = clients.remove(client)
}
if (wasRegistered) {
broadcast(client, "--- " + client.clientName + " left ---")
}
}
private fun broadcast(fromClient: Client, msg: String) { | 1,051Chat server
| 11kotlin
| zmnts |
library(Rmpfr)
prec <- 1000
`%:%` <- function(e1, e2) '/'(mpfr(e1, prec), mpfr(e2, prec))
tanident_1 <- function(x) identical(round(tan(eval(parse(text = gsub("/", "%:%", deparse(substitute(x)))))), (prec/10)), mpfr(1, prec)) | 1,050Check Machin-like formulas
| 13r
| 249lg |
(print (int \a))
(print (char 97))
(print (int \))
(print (char 960))
(print (.codePointAt "" 0))
(print (String. (int-array 1 119136) 0 1)) | 1,054Character codes
| 6clojure
| 6ci3q |
def chowla(n)
sum = 0
i = 2
while i * i <= n do
if n % i == 0 then
sum = sum + i
j = n / i
if i!= j then
sum = sum + j
end
end
i = i + 1
end
return sum
end
def main
for n in 1 .. 37 do
puts % [n, chowla(n)]
end
count = 0
power = 100
for n in 2 .. 10000000 do
if chowla(n) == 0 then
count = count + 1
end
if n % power == 0 then
puts % [count, power]
power = power * 10
end
end
count = 0
limit = 350000000
k = 2
kk = 3
loop do
p = k * kk
if p > limit then
break
end
if chowla(p) == p - 1 then
puts % [p]
count = count + 1
end
k = kk + 1
kk = kk + k
end
puts % [count, limit]
end
main() | 1,041Chowla numbers
| 14ruby
| 0dtsu |
use strict;
use warnings;
use POSIX qw(ceil);
sub dist {
my ($a, $b) = @_;
return sqrt(($a->[0] - $b->[0])**2 +
($a->[1] - $b->[1])**2)
}
sub closest_pair_simple {
my @points = @{ shift @_ };
my ($a, $b, $d) = ( $points[0], $points[1], dist($points[0], $points[1]) );
while( @points ) {
my $p = pop @points;
for my $l (@points) {
my $t = dist($p, $l);
($a, $b, $d) = ($p, $l, $t) if $t < $d;
}
}
$a, $b, $d
}
sub closest_pair {
my @r = @{ shift @_ };
closest_pair_real( [sort { $a->[0] <=> $b->[0] } @r], [sort { $a->[1] <=> $b->[1] } @r] )
}
sub closest_pair_real {
my ($rx, $ry) = @_;
return closest_pair_simple($rx) if scalar(@$rx) <= 3;
my(@yR, @yL, @yS);
my $N = @$rx;
my $midx = ceil($N/2)-1;
my @PL = @$rx[ 0 .. $midx];
my @PR = @$rx[$midx+1 .. $N-1];
my $xm = $$rx[$midx]->[0];
$_->[0] <= $xm ? push @yR, $_ : push @yL, $_ for @$ry;
my ($al, $bl, $dL) = closest_pair_real(\@PL, \@yR);
my ($ar, $br, $dR) = closest_pair_real(\@PR, \@yL);
my ($w1, $w2, $closest) = $dR > $dL ? ($al, $bl, $dL) : ($ar, $br, $dR);
abs($xm - $_->[0]) < $closest and push @yS, $_ for @$ry;
for my $i (0 .. @yS-1) {
my $k = $i + 1;
while ( $k <= $
my $d = dist($yS[$k], $yS[$i]);
($w1, $w2, $closest) = ($yS[$k], $yS[$i], $d) if $d < $closest;
$k++;
}
}
$w1, $w2, $closest
}
my @points;
push @points, [rand(20)-10, rand(20)-10] for 1..5000;
printf "%.8f between (%.5f,%.5f), (%.5f,%.5f)\n", $_->[2], @{$$_[0]}, @{$$_[1]}
for [closest_pair_simple(\@points)], [closest_pair(\@points)]; | 1,036Closest-pair problem
| 2perl
| 9uhmn |
local ANIMALS = {"Rat","Ox","Tiger","Rabbit","Dragon","Snake","Horse","Goat","Monkey","Rooster","Dog","Pig"}
local ELEMENTS = {"Wood","Fire","Earth","Metal","Water"}
function element(year)
local idx = math.floor(((year - 4) % 10) / 2)
return ELEMENTS[idx + 1]
end
function animal(year)
local idx = (year - 4) % 12
return ANIMALS[idx + 1]
end
function yy(year)
if year % 2 == 0 then
return "yang"
else
return "yin"
end
end
function zodiac(year)
local e = element(year)
local a = animal(year)
local y = yy(year)
print(year.." is the year of the "..e.." "..a.." ("..y..")")
end
zodiac(1935)
zodiac(1938)
zodiac(1968)
zodiac(1972)
zodiac(1976)
zodiac(2017) | 1,048Chinese zodiac
| 1lua
| asa1v |
package main
import (
"fmt"
"image"
"image/color"
"image/draw"
"image/gif"
"log"
"math"
"math/rand"
"os"
"time"
)
var bwPalette = color.Palette{
color.Transparent,
color.White,
color.RGBA{R: 0xff, A: 0xff},
color.RGBA{G: 0xff, A: 0xff},
color.RGBA{B: 0xff, A: 0xff},
}
func main() {
const (
width = 160
frames = 100
pointsPerFrame = 50
delay = 100 * time.Millisecond
filename = "chaos_anim.gif"
)
var tan60 = math.Sin(math.Pi / 3)
height := int(math.Round(float64(width) * tan60))
b := image.Rect(0, 0, width, height)
vertices := [...]image.Point{
{0, height}, {width, height}, {width / 2, 0},
} | 1,052Chaos game
| 0go
| jp57d |
'''Cheryl's Birthday'''
from itertools import groupby
from re import split
def main():
'''Derivation of the date.'''
month, day = 0, 1
print(
uniquePairing(month)(
uniquePairing(day)(
monthsWithUniqueDays(False)([
tuple(x.split()) for x in
split(
', ',
'May 15, May 16, May 19, ' +
'June 17, June 18, ' +
'July 14, July 16, ' +
'Aug 14, Aug 15, Aug 17'
)
])
)
)
)
def monthsWithUniqueDays(blnInclude):
'''The subset of months with (or without) unique days.
'''
def go(xs):
month, day = 0, 1
months = [fst(x) for x in uniquePairing(day)(xs)]
return [
md for md in xs
if blnInclude or not (md[month] in months)
]
return go
def uniquePairing(i):
'''Subset of months (or days) with a unique intersection.
'''
def go(xs):
def inner(md):
dct = md[i]
uniques = [
k for k in dct.keys()
if 1 == len(dct[k])
]
return [tpl for tpl in xs if tpl[i] in uniques]
return inner
return ap(bindPairs)(go)
def bindPairs(xs):
'''List monad injection operator for lists
of (Month, Day) pairs.
'''
return lambda f: f(
(
dictFromPairs(xs),
dictFromPairs(
[(b, a) for (a, b) in xs]
)
)
)
def dictFromPairs(xs):
'''A dictionary derived from a list of
month day pairs.
'''
return {
k: [snd(x) for x in m] for k, m in groupby(
sorted(xs, key=fst), key=fst
)
}
def ap(f):
'''Applicative instance for functions.
'''
def go(g):
def fxgx(x):
return f(x)(
g(x)
)
return fxgx
return go
def fst(tpl):
'''First component of a pair.
'''
return tpl[0]
def snd(tpl):
'''Second component of a pair.
'''
return tpl[1]
if __name__ == '__main__':
main() | 1,049Cheryl's birthday
| 3python
| l59cv |
null | 1,047Chinese remainder theorem
| 11kotlin
| 0d8sf |
object ChowlaNumbers {
def main(args: Array[String]): Unit = {
println("Chowla Numbers...")
for(n <- 1 to 37){println(s"$n: ${chowlaNum(n)}")}
println("\nPrime Counts...")
for(i <- (2 to 7).map(math.pow(10, _).toInt)){println(f"$i%,d: ${primesPar(i).size}%,d")}
println("\nPerfect Numbers...")
print(perfectsPar(35000000).toVector.sorted.zipWithIndex.map{case (n, i) => f"${i + 1}%,d: $n%,d"}.mkString("\n"))
}
def primesPar(num: Int): ParVector[Int] = ParVector.range(2, num + 1).filter(n => chowlaNum(n) == 0)
def perfectsPar(num: Int): ParVector[Int] = ParVector.range(6, num + 1).filter(n => chowlaNum(n) + 1 == n)
def chowlaNum(num: Int): Int = Iterator.range(2, math.sqrt(num).toInt + 1).filter(n => num%n == 0).foldLeft(0){case (s, n) => if(n*n == num) s + n else s + n + (num/n)}
} | 1,041Chowla numbers
| 16scala
| n3yic |
import javafx.animation.AnimationTimer
import javafx.application.Application
import javafx.scene.Scene
import javafx.scene.layout.Pane
import javafx.scene.paint.Color
import javafx.scene.shape.Circle
import javafx.stage.Stage
class ChaosGame extends Application {
final randomNumberGenerator = new Random()
@Override
void start(Stage primaryStage) {
primaryStage.title = 'Chaos Game'
primaryStage.scene = getScene()
primaryStage.show()
}
def getScene() {
def colors = [Color.RED, Color.GREEN, Color.BLUE]
final width = 640, height = 640, margin = 60
final size = width - 2 * margin
def points = [
new Circle(width / 2, margin, 1, colors[0]),
new Circle(margin, size, 1, colors[1]),
new Circle(margin + size, size, 1, colors[2])
]
def pane = new Pane()
pane.style = '-fx-background-color: black;'
points.each {
pane.children.add it
}
def currentPoint = new Circle().with {
centerX = randomNumberGenerator.nextInt(size - margin) + margin
centerY = randomNumberGenerator.nextInt(size - margin) + margin
it
}
({
def newPoint = generatePoint(currentPoint, points, colors)
pane.children.add newPoint
currentPoint = newPoint
} as AnimationTimer).start()
new Scene(pane, width, height)
}
def generatePoint(currentPoint, points, colors) {
def selection = randomNumberGenerator.nextInt 3
new Circle().with {
centerX = (currentPoint.centerX + points[selection].centerX) / 2
centerY = (currentPoint.centerY + points[selection].centerY) / 2
radius = 1
fill = colors[selection]
it
}
}
static main(args) {
launch(ChaosGame)
}
} | 1,052Chaos game
| 7groovy
| 57cuv |
options <- dplyr::tibble(mon = rep(c("May", "June", "July", "August"),times = c(3,2,2,3)),
day = c(15, 16, 19, 17, 18, 14, 16, 14, 15, 17))
okMonths <- c()
for (i in unique(options$mon)){
if(all(options$day[options$mon == i]%in% options$day[options$mon!= i])) {okMonths <- c(okMonths, i)}
}
okDays <- c()
for (i in unique(options$day)){
if(!all(options$mon[options$day == i]%in% options$mon[(options$mon%in% okMonths)])) {okDays <- c(okDays, i)}
}
remaining <- options[(options$mon%in% okMonths) & (options$day%in% okDays), ]
for(i in unique(remaining$mon)){
if(sum(remaining$mon == i) == 1) {print(remaining[remaining$mon == i,])}
} | 1,049Cheryl's birthday
| 13r
| yl36h |
import Foundation
@inlinable
public func chowla<T: BinaryInteger>(n: T) -> T {
stride(from: 2, to: T(Double(n).squareRoot()+1), by: 1)
.lazy
.filter({ n% $0 == 0 })
.reduce(0, {(s: T, m: T) in
m*m == n? s + m: s + m + (n / m)
})
}
extension Dictionary where Key == ClosedRange<Int> {
subscript(n: Int) -> Value {
get {
guard let key = keys.first(where: { $0.contains(n) }) else {
fatalError("dict does not contain range for \(n)")
}
return self[key]!
}
set {
guard let key = keys.first(where: { $0.contains(n) }) else {
fatalError("dict does not contain range for \(n)")
}
self[key] = newValue
}
}
}
let lock = DispatchSemaphore(value: 1)
var perfect = [Int]()
var primeCounts = [
1...100: 0,
101...1_000: 0,
1_001...10_000: 0,
10_001...100_000: 0,
100_001...1_000_000: 0,
1_000_001...10_000_000: 0
]
for i in 1...37 {
print("chowla(\(i)) = \(chowla(n: i))")
}
DispatchQueue.concurrentPerform(iterations: 35_000_000) {i in
let chowled = chowla(n: i)
if chowled == 0 && i > 1 && i < 10_000_000 {
lock.wait()
primeCounts[i] += 1
lock.signal()
}
if chowled == i - 1 && i > 1 {
lock.wait()
perfect.append(i)
lock.signal()
}
}
let numPrimes = primeCounts
.sorted(by: { $0.key.lowerBound < $1.key.lowerBound })
.reduce(into: [(Int, Int)](), {counts, oneCount in
guard!counts.isEmpty else {
counts.append((oneCount.key.upperBound, oneCount.value))
return
}
counts.append((oneCount.key.upperBound, counts.last!.1 + oneCount.value))
})
for (upper, count) in numPrimes {
print("Number of primes < \(upper) = \(count)")
}
for p in perfect {
print("\(p) is a perfect number")
} | 1,041Chowla numbers
| 17swift
| snfqt |
function distance(p1, p2)
local dx = (p1.x-p2.x)
local dy = (p1.y-p2.y)
return math.sqrt(dx*dx + dy*dy)
end
function findCircles(p1, p2, radius)
local seperation = distance(p1, p2)
if seperation == 0.0 then
if radius == 0.0 then
print("No circles can be drawn through ("..p1.x..", "..p1.y..")")
else
print("Infinitely many circles can be drawn through ("..p1.x..", "..p1.y..")")
end
elseif seperation == 2*radius then
local cx = (p1.x+p2.x)/2
local cy = (p1.y+p2.y)/2
print("Given points are opposite ends of a diameter of the circle with center ("..cx..", "..cy..") and radius "..radius)
elseif seperation > 2*radius then
print("Given points are further away from each other than a diameter of a circle with radius "..radius)
else
local mirrorDistance = math.sqrt(math.pow(radius,2) - math.pow(seperation/2,2))
local dx = p2.x - p1.x
local dy = p1.y - p2.y
local ax = (p1.x + p2.x) / 2
local ay = (p1.y + p2.y) / 2
local mx = mirrorDistance * dx / seperation
local my = mirrorDistance * dy / seperation
c1 = {x=ax+my, y=ay+mx}
c2 = {x=ax-my, y=ay-mx}
print("Two circles are possible.")
print("Circle C1 with center ("..c1.x..", "..c1.y.."), radius "..radius)
print("Circle C2 with center ("..c2.x..", "..c2.y.."), radius "..radius)
end
print()
end
cases = {
{x=0.1234, y=0.9876}, {x=0.8765, y=0.2345},
{x=0.0000, y=2.0000}, {x=0.0000, y=0.0000},
{x=0.1234, y=0.9876}, {x=0.1234, y=0.9876},
{x=0.1234, y=0.9876}, {x=0.8765, y=0.2345},
{x=0.1234, y=0.9876}, {x=0.1234, y=0.9876}
}
radii = { 2.0, 1.0, 2.0, 0.5, 0.0 }
for i=1, #radii do
print("Case "..i)
findCircles(cases[i*2-1], cases[i*2], radii[i])
end | 1,046Circles of given radius through two points
| 1lua
| 0dosd |
import Control.Monad (replicateM)
import Control.Monad.Random (fromList)
type Point = (Float,Float)
type Transformations = [(Point -> Point, Float)]
gameOfChaos :: MonadRandom m => Int -> Transformations -> Point -> m [Point]
gameOfChaos n transformations x = iterateA (fromList transformations) x
where iterateA f x = scanr ($) x <$> replicateM n f | 1,052Chaos game
| 8haskell
| ofx8p |
null | 1,047Chinese remainder theorem
| 1lua
| 8fo0e |
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
public class ChaosGame extends JPanel {
static class ColoredPoint extends Point {
int colorIndex;
ColoredPoint(int x, int y, int idx) {
super(x, y);
colorIndex = idx;
}
}
Stack<ColoredPoint> stack = new Stack<>();
Point[] points = new Point[3];
Color[] colors = {Color.red, Color.green, Color.blue};
Random r = new Random();
public ChaosGame() {
Dimension dim = new Dimension(640, 640);
setPreferredSize(dim);
setBackground(Color.white);
int margin = 60;
int size = dim.width - 2 * margin;
points[0] = new Point(dim.width / 2, margin);
points[1] = new Point(margin, size);
points[2] = new Point(margin + size, size);
stack.push(new ColoredPoint(-1, -1, 0));
new Timer(10, (ActionEvent e) -> {
if (stack.size() < 50_000) {
for (int i = 0; i < 1000; i++)
addPoint();
repaint();
}
}).start();
}
private void addPoint() {
try {
int colorIndex = r.nextInt(3);
Point p1 = stack.peek();
Point p2 = points[colorIndex];
stack.add(halfwayPoint(p1, p2, colorIndex));
} catch (EmptyStackException e) {
e.printStackTrace();
}
}
void drawPoints(Graphics2D g) {
for (ColoredPoint p : stack) {
g.setColor(colors[p.colorIndex]);
g.fillOval(p.x, p.y, 1, 1);
}
}
ColoredPoint halfwayPoint(Point a, Point b, int idx) {
return new ColoredPoint((a.x + b.x) / 2, (a.y + b.y) / 2, idx);
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawPoints(g);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Chaos Game");
f.setResizable(false);
f.add(new ChaosGame(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
} | 1,052Chaos game
| 9java
| w0bej |
use 5.010;
use strict;
use warnings;
use threads;
use threads::shared;
use IO::Socket::INET;
use Time::HiRes qw(sleep ualarm);
my $HOST = "localhost";
my $PORT = 4004;
my @open;
my %users : shared;
sub broadcast {
my ($id, $message) = @_;
print "$message\n";
foreach my $i (keys %users) {
if ($i != $id) {
$open[$i]->send("$message\n");
}
}
}
sub sign_in {
my ($conn) = @_;
state $id = 0;
threads->new(
sub {
while (1) {
$conn->send("Please enter your name: ");
$conn->recv(my $name, 1024, 0);
if (defined $name) {
$name = unpack('A*', $name);
if (exists $users{$name}) {
$conn->send("Name entered is already in use.\n");
}
elsif ($name ne '') {
$users{$id} = $name;
broadcast($id, "+++ $name arrived +++");
last;
}
}
}
}
);
++$id;
push @open, $conn;
}
my $server = IO::Socket::INET->new(
Timeout => 0,
LocalPort => $PORT,
Proto => "tcp",
LocalAddr => $HOST,
Blocking => 0,
Listen => 1,
Reuse => 1,
);
local $| = 1;
print "Listening on $HOST:$PORT\n";
while (1) {
my ($conn) = $server->accept;
if (defined($conn)) {
sign_in($conn);
}
foreach my $i (keys %users) {
my $conn = $open[$i];
my $message;
eval {
local $SIG{ALRM} = sub { die "alarm\n" };
ualarm(500);
$conn->recv($message, 1024, 0);
ualarm(0);
};
if ($@ eq "alarm\n") {
next;
}
if (defined($message)) {
if ($message ne '') {
$message = unpack('A*', $message);
broadcast($i, "$users{$i}> $message");
}
else {
broadcast($i, "--- $users{$i} leaves ---");
delete $users{$i};
undef $open[$i];
}
}
}
sleep(0.1);
} | 1,051Chat server
| 2perl
| be7k4 |
<html>
<head>
<meta charset="UTF-8">
<title>Chaos Game</title>
</head>
<body>
<p>
<canvas id="sierpinski" width=400 height=346></canvas>
</p>
<p>
<button onclick="chaosGame()">Click here to see a Sierpiski triangle</button>
</p>
<script>
function chaosGame() {
var canv = document.getElementById('sierpinski').getContext('2d');
var x = Math.random() * 400;
var y = Math.random() * 346;
for (var i=0; i<30000; i++) {
var vertex = Math.floor(Math.random() * 3);
switch(vertex) {
case 0:
x = x / 2;
y = y / 2;
canv.fillStyle = 'green';
break;
case 1:
x = 200 + (200 - x) / 2
y = 346 - (346 - y) / 2
canv.fillStyle = 'red';
break;
case 2:
x = 400 - (400 - x) / 2
y = y / 2;
canv.fillStyle = 'blue';
}
canv.fillRect(x,y, 1,1);
}
}
</script>
</body>
</html> | 1,052Chaos game
| 10javascript
| 8dw0l |
dates = [
[, 15],
[, 16],
[, 19],
[, 17],
[, 18],
[, 14],
[, 16],
[, 14],
[, 15],
[, 17],
]
print dates.length,
uniqueMonths = dates.group_by { |m,d| d }
.select { |k,v| v.size == 1 }
.map { |k,v| v.flatten }
.map { |m,d| m }
dates.delete_if { |m,d| uniqueMonths.include? m }
print dates.length,
dates = dates .group_by { |m,d| d }
.select { |k,v| v.size == 1 }
.map { |k,v| v.flatten }
print dates.length,
dates = dates .group_by { |m,d| m }
.select { |k,v| v.size == 1 }
.map { |k,v| v }
.flatten
print dates | 1,049Cheryl's birthday
| 14ruby
| vgl2n |
sub zodiac {
my $year = shift;
my @animals = qw/Rat Ox Tiger Rabbit Dragon Snake Horse Goat Monkey Rooster Dog Pig/;
my @elements = qw/Wood Fire Earth Metal Water/;
my @terrestrial_han = qw/ /;
my @terrestrial_pinyin = qw/z chu yn mo chn s w wi shn yu x hi/;
my @celestial_han = qw/ /;
my @celestial_pinyin = qw/ji y bng dng w j gng xn rn gi/;
my @aspect = qw/yang yin/;
my $cycle_year = ($year-4) % 60;
my($i2, $i10, $i12) = ($cycle_year % 2, $cycle_year % 10, $cycle_year % 12);
($year,
$celestial_han[$i10], $terrestrial_han[$i12],
$celestial_pinyin[$i10], $terrestrial_pinyin[$i12],
$elements[$i10 >> 1], $animals[$i12], $aspect[$i2], $cycle_year+1);
}
printf("%4d:%s%s (%s-%s)%s%s;%s - year%d of the cycle\n", zodiac($_))
for (1935, 1938, 1968, 1972, 1976, 2017); | 1,048Chinese zodiac
| 2perl
| mvmyz |
null | 1,052Chaos game
| 11kotlin
| berkb |
null | 1,049Cheryl's birthday
| 15rust
| ur2vj |
import java.time.format.DateTimeFormatter
import java.time.{LocalDate, Month}
object Cheryl {
def main(args: Array[String]): Unit = {
val choices = List(
LocalDate.of(2019, Month.MAY, 15),
LocalDate.of(2019, Month.MAY, 16),
LocalDate.of(2019, Month.MAY, 19),
LocalDate.of(2019, Month.JUNE, 17),
LocalDate.of(2019, Month.JUNE, 18),
LocalDate.of(2019, Month.JULY, 14),
LocalDate.of(2019, Month.JULY, 16),
LocalDate.of(2019, Month.AUGUST, 14),
LocalDate.of(2019, Month.AUGUST, 15),
LocalDate.of(2019, Month.AUGUST, 17)
) | 1,049Cheryl's birthday
| 16scala
| gh54i |
from random import randint, randrange
from operator import itemgetter, attrgetter
infinity = float('inf')
def bruteForceClosestPair(point):
numPoints = len(point)
if numPoints < 2:
return infinity, (None, None)
return min( ((abs(point[i] - point[j]), (point[i], point[j]))
for i in range(numPoints-1)
for j in range(i+1,numPoints)),
key=itemgetter(0))
def closestPair(point):
xP = sorted(point, key= attrgetter('real'))
yP = sorted(point, key= attrgetter('imag'))
return _closestPair(xP, yP)
def _closestPair(xP, yP):
numPoints = len(xP)
if numPoints <= 3:
return bruteForceClosestPair(xP)
Pl = xP[:numPoints/2]
Pr = xP[numPoints/2:]
Yl, Yr = [], []
xDivider = Pl[-1].real
for p in yP:
if p.real <= xDivider:
Yl.append(p)
else:
Yr.append(p)
dl, pairl = _closestPair(Pl, Yl)
dr, pairr = _closestPair(Pr, Yr)
dm, pairm = (dl, pairl) if dl < dr else (dr, pairr)
closeY = [p for p in yP if abs(p.real - xDivider) < dm]
numCloseY = len(closeY)
if numCloseY > 1:
closestY = min( ((abs(closeY[i] - closeY[j]), (closeY[i], closeY[j]))
for i in range(numCloseY-1)
for j in range(i+1,min(i+8, numCloseY))),
key=itemgetter(0))
return (dm, pairm) if dm <= closestY[0] else closestY
else:
return dm, pairm
def times():
''' Time the different functions
'''
import timeit
functions = [bruteForceClosestPair, closestPair]
for f in functions:
print 'Time for', f.__name__, timeit.Timer(
'%s(pointList)'% f.__name__,
'from closestpair import%s, pointList'% f.__name__).timeit(number=1)
pointList = [randint(0,1000)+1j*randint(0,1000) for i in range(2000)]
if __name__ == '__main__':
pointList = [(5+9j), (9+3j), (2+0j), (8+4j), (7+4j), (9+10j), (1+9j), (8+2j), 10j, (9+6j)]
print pointList
print ' bruteForceClosestPair:', bruteForceClosestPair(pointList)
print ' closestPair:', closestPair(pointList)
for i in range(10):
pointList = [randrange(11)+1j*randrange(11) for i in range(10)]
print '\n', pointList
print ' bruteForceClosestPair:', bruteForceClosestPair(pointList)
print ' closestPair:', closestPair(pointList)
print '\n'
times()
times()
times() | 1,036Closest-pair problem
| 3python
| c5k9q |
math.randomseed( os.time() )
colors, orig = { { 255, 0, 0 }, { 0, 255, 0 }, { 0, 0, 255 } }, {}
function love.load()
wid, hei = love.graphics.getWidth(), love.graphics.getHeight()
orig[1] = { wid / 2, 3 }
orig[2] = { 3, hei - 3 }
orig[3] = { wid - 3, hei - 3 }
local w, h = math.random( 10, 40 ), math.random( 10, 40 )
if math.random() < .5 then w = -w end
if math.random() < .5 then h = -h end
orig[4] = { wid / 2 + w, hei / 2 + h }
canvas = love.graphics.newCanvas( wid, hei )
love.graphics.setCanvas( canvas ); love.graphics.clear()
love.graphics.setColor( 255, 255, 255 )
love.graphics.points( orig )
love.graphics.setCanvas()
end
function love.draw()
local iter = 100 | 1,052Chaos game
| 1lua
| pw7bw |
sub cholesky {
my $matrix = shift;
my $chol = [ map { [(0) x @$matrix ] } @$matrix ];
for my $row (0..@$matrix-1) {
for my $col (0..$row) {
my $x = $$matrix[$row][$col];
$x -= $$chol[$row][$_]*$$chol[$col][$_] for 0..$col;
$$chol[$row][$col] = $row == $col ? sqrt $x : $x/$$chol[$col][$col];
}
}
return $chol;
}
my $example1 = [ [ 25, 15, -5 ],
[ 15, 18, 0 ],
[ -5, 0, 11 ] ];
print "Example 1:\n";
print +(map { sprintf "%7.4f\t", $_ } @$_), "\n" for @{ cholesky $example1 };
my $example2 = [ [ 18, 22, 54, 42],
[ 22, 70, 86, 62],
[ 54, 86, 174, 134],
[ 42, 62, 134, 106] ];
print "\nExample 2:\n";
print +(map { sprintf "%7.4f\t", $_ } @$_), "\n" for @{ cholesky $example2 }; | 1,042Cholesky decomposition
| 2perl
| y2v6u |
CASE WHEN a THEN b ELSE c END
DECLARE @n INT
SET @n=124
print CASE WHEN @n=123 THEN 'equal' ELSE 'not equal' END
--If/ElseIf expression
SET @n=5
print CASE WHEN @n=3 THEN 'Three' WHEN @n=4 THEN 'Four' ELSE 'Other' END | 1,023Conditional structures
| 19sql
| w8gex |
closest_pair_brute <-function(x,y,plotxy=F) {
xy = cbind(x,y)
cp = bruteforce(xy)
cat("\n\nShortest path found = \n From:\t\t(",cp[1],',',cp[2],")\n To:\t\t(",cp[3],',',cp[4],")\n Distance:\t",cp[5],"\n\n",sep="")
if(plotxy) {
plot(x,y,pch=19,col='black',main="Closest Pair", asp=1)
points(cp[1],cp[2],pch=19,col='red')
points(cp[3],cp[4],pch=19,col='red')
}
distance <- function(p1,p2) {
x1 = (p1[1])
y1 = (p1[2])
x2 = (p2[1])
y2 = (p2[2])
sqrt((x2-x1)^2 + (y2-y1)^2)
}
bf_iter <- function(m,p,idx=NA,d=NA,n=1) {
dd = distance(p,m[n,])
if((is.na(d) || dd<=d) && p!=m[n,]){d = dd; idx=n;}
if(n == length(m[,1])) { c(m[idx,],d) }
else bf_iter(m,p,idx,d,n+1)
}
bruteforce <- function(pmatrix,n=1,pd=c(NA,NA,NA,NA,NA)) {
p = pmatrix[n,]
ppd = c(p,bf_iter(pmatrix,p))
if(ppd[5]<pd[5] || is.na(pd[5])) pd = ppd
if(n==length(pmatrix[,1])) pd
else bruteforce(pmatrix,n+1,pd)
}
} | 1,036Closest-pair problem
| 13r
| 6lr3e |
import socket
import thread
import time
HOST =
PORT = 4004
def accept(conn):
def threaded():
while True:
conn.send()
try:
name = conn.recv(1024).strip()
except socket.error:
continue
if name in users:
conn.send()
elif name:
conn.setblocking(False)
users[name] = conn
broadcast(name, % name)
break
thread.start_new_thread(threaded, ())
def broadcast(name, message):
print message
for to_name, conn in users.items():
if to_name != name:
try:
conn.send(message + )
except socket.error:
pass
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.setblocking(False)
server.bind((HOST, PORT))
server.listen(1)
print % (% server.getsockname())
users = {}
while True:
try:
while True:
try:
conn, addr = server.accept()
except socket.error:
break
accept(conn)
for name, conn in users.items():
try:
message = conn.recv(1024)
except socket.error:
continue
if not message:
del users[name]
broadcast(name, % name)
else:
broadcast(name, % (name, message.strip()))
time.sleep(.1)
except (SystemExit, KeyboardInterrupt):
break | 1,051Chat server
| 3python
| pwjbm |
struct MonthDay: CustomStringConvertible {
static let months = [
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
]
var month: Int
var day: Int
var description: String { "\(MonthDay.months[month - 1]) \(day)" }
private func isUniqueIn(months: [MonthDay], by prop: KeyPath<MonthDay, Int>) -> Bool {
return months.lazy.filter({ $0[keyPath: prop] == self[keyPath: prop] }).count == 1
}
func monthIsUniqueIn(months: [MonthDay]) -> Bool {
return isUniqueIn(months: months, by: \.month)
}
func dayIsUniqueIn(months: [MonthDay]) -> Bool {
return isUniqueIn(months: months, by: \.day)
}
func monthWithUniqueDayIn(months: [MonthDay]) -> Bool {
return months.firstIndex(where: { $0.month == month && $0.dayIsUniqueIn(months: months) })!= nil
}
}
let choices = [
MonthDay(month: 5, day: 15),
MonthDay(month: 5, day: 16),
MonthDay(month: 5, day: 19),
MonthDay(month: 6, day: 17),
MonthDay(month: 6, day: 18),
MonthDay(month: 7, day: 14),
MonthDay(month: 7, day: 16),
MonthDay(month: 8, day: 14),
MonthDay(month: 8, day: 15),
MonthDay(month: 8, day: 17)
] | 1,049Cheryl's birthday
| 17swift
| 24clj |
>>> from itertools import combinations
>>> list(combinations(range(5),3))
[(0, 1, 2), (0, 1, 3), (0, 1, 4), (0, 2, 3), (0, 2, 4), (0, 3, 4), (1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)] | 1,031Combinations
| 3python
| u7svd |
package main
import (
"fmt"
"os"
)
func printStat(p string) {
switch i, err := os.Stat(p); {
case err != nil:
fmt.Println(err)
case i.IsDir():
fmt.Println(p, "is a directory")
default:
fmt.Println(p, "is a file")
}
}
func main() {
printStat("input.txt")
printStat("/input.txt")
printStat("docs")
printStat("/docs")
} | 1,053Check that file exists
| 0go
| urmvt |
println new File('input.txt').exists()
println new File('/input.txt').exists()
println new File('docs').exists()
println new File('/docs').exists() | 1,053Check that file exists
| 7groovy
| 9vtm4 |
chat_loop <- function(server, sockets, delay = 0.5) {
repeat {
Sys.sleep(delay)
while (in_queue(server))
sockets <- new_socket_entry(server, sockets)
sockets <- check_messages(sockets)
if (nrow(sockets) == 0)
next
if (all(!sockets$message_ready))
next
sockets <- read_messages(sockets)
sockets <- drop_dead(sockets)
if (nrow(sockets) == 0)
next
sockets <- update_nicknames(sockets)
sockets <- send_messages(sockets)
}
}
check_messages <- function(sockets) {
if (nrow(sockets)!= 0)
sockets$message_ready <- socketSelect(sockets$conn, timeout = 0)
sockets
}
drop_dead <- function(sockets) {
lapply(with(sockets, conn[!alive]), close)
dropped <- with(sockets, nickname[nickname_exists(sockets) &!alive])
sockets <- sockets[sockets$alive, ]
if (length(dropped)!= 0) {
send_named(sockets, paste0(dropped, " has disconnected."))
}
sockets
}
in_queue <- function(server) socketSelect(list(server), timeout = 0)
is_valid_name <- function(nicks) gsub("[A-Za-z0-9]*", "", nicks) == ""
message_exists <- function(sockets)!is.na(sockets$message)
new_row <- function(df) {
df[nrow(df) + 1, ] <- NA
df
}
new_socket_entry <- function(server, sockets) {
sockets <- new_row(sockets)
n <- nrow(sockets)
within(sockets, {
conn[[n]] <- new_user(server)
alive[n] <- TRUE
message_ready[n] <- FALSE
})
}
new_user <- function(server) {
conn <- socketAccept(server)
writeLines("Hello! Please enter a nickname.", conn)
conn
}
nickname_exists <- function(sockets)!is.na(sockets$nickname)
read_messages <- function(sockets) {
if (all(!sockets$message_ready))
return(sockets)
msgs <- lapply(with(sockets, conn[message_ready]), readLines, n = 1)
empty_msgs <- sapply(msgs, identical, character(0))
sockets <- within(sockets, alive[message_ready & empty_msgs] <- FALSE)
msgs <- unlist(ifelse(empty_msgs, NA, msgs))
within(sockets, message[message_ready] <- msgs)
}
send_messages <- function(sockets) {
named_message <- message_exists(sockets) & nickname_exists(sockets)
if (all(!named_message))
return(sockets)
rows <- which(named_message)
socksub <- sockets[rows, ]
time <- format(Sys.time(), "[%H:%M:%S] ")
with(socksub, send_named(sockets, paste0(time, nickname, ": ", message)))
within(sockets, message[rows] <- NA)
}
send_named <- function(sockets, msg) {
has_nickname <- nickname_exists(sockets)
invisible(lapply(sockets$conn[has_nickname], writeLines, text = msg))
}
start_chat_server <- function(port = 50525) {
server <- serverSocket(port)
on.exit(closeAllConnections())
sockets <- data.frame(conn = I(list()), nickname = character(),
message = character(), alive = logical(),
message_ready = logical())
chat_loop(server, sockets)
}
update_nicknames <- function(sockets) {
sent_nickname <- message_exists(sockets) &!nickname_exists(sockets)
nickname_valid <- is_valid_name(sockets$message)
if (all(!sent_nickname))
return(sockets)
is_taken <- with(sockets, (tolower(message)%in% tolower(sockets$nickname)) &
!is.na(message))
sent_ok <- sent_nickname & nickname_valid &!is_taken
sockets <- within(sockets, {
nickname[sent_ok] <- message[sent_ok]
message[sent_nickname] <- NA
lapply(conn[sent_nickname &!nickname_valid], writeLines,
text = "Alphanumeric characters only. Try again.")
lapply(conn[is_taken], writeLines,
text = "Name already taken. Try again.")
})
if (any(sent_ok))
send_named(sockets, paste0(sockets$nickname[sent_ok], " has connected."))
sockets
}
start_chat_server() | 1,051Chat server
| 13r
| jp478 |
use ntheory qw/chinese/;
say chinese([2,3], [3,5], [2,7]); | 1,047Chinese remainder theorem
| 2perl
| 5j4u2 |
import System.Directory (doesFileExist, doesDirectoryExist)
check :: (FilePath -> IO Bool) -> FilePath -> IO ()
check p s = do
result <- p s
putStrLn $
s ++
if result
then " does exist"
else " does not exist"
main :: IO ()
main = do
check doesFileExist "input.txt"
check doesDirectoryExist "docs"
check doesFileExist "/input.txt"
check doesDirectoryExist "/docs" | 1,053Check that file exists
| 8haskell
| w0ked |
print(combn(0:4, 3)) | 1,031Combinations
| 13r
| c5e95 |
{
package MyClass;
sub new {
my $class = shift;
bless {variable => 0}, $class;
}
sub some_method {
my $self = shift;
$self->{variable} = 1;
}
} | 1,038Classes
| 2perl
| d6lnw |
from __future__ import print_function
from datetime import datetime
pinyin = {
'': 'ji',
'': 'y',
'': 'bng',
'': 'dng',
'': 'w',
'': 'j',
'': 'gng',
'': 'xn',
'': 'rn',
'': 'gi',
'': 'z',
'': 'chu',
'': 'yn',
'': 'mo',
'': 'chn',
'': 's',
'': 'w',
'': 'wi',
'': 'shn',
'': 'yu',
'': 'x',
'': 'hi'
}
animals = ['Rat', 'Ox', 'Tiger', 'Rabbit', 'Dragon', 'Snake',
'Horse', 'Goat', 'Monkey', 'Rooster', 'Dog', 'Pig']
elements = ['Wood', 'Fire', 'Earth', 'Metal', 'Water']
celestial = ['', '', '', '', '', '', '', '', '', '']
terrestrial = ['', '', '', '', '', '', '', '', '', '', '', '']
aspects = ['yang', 'yin']
def calculate(year):
BASE = 4
year = int(year)
cycle_year = year - BASE
stem_number = cycle_year% 10
stem_han = celestial[stem_number]
stem_pinyin = pinyin[stem_han]
element_number = stem_number
element = elements[element_number]
branch_number = cycle_year% 12
branch_han = terrestrial[branch_number]
branch_pinyin = pinyin[branch_han]
animal = animals[branch_number]
aspect_number = cycle_year% 2
aspect = aspects[aspect_number]
index = cycle_year% 60 + 1
print(
.format(year, stem_han, branch_han,
stem_pinyin, branch_pinyin, element, animal, aspect, index))
current_year = datetime.now().year
years = [1935, 1938, 1968, 1972, 1976, current_year]
for year in years:
calculate(year) | 1,048Chinese zodiac
| 3python
| 9u9mf |
use Imager;
my $width = 1000;
my $height = 1000;
my @points = (
[ $width/2, 0],
[ 0, $height-1],
[$height-1, $height-1],
);
my $img = Imager->new(
xsize => $width,
ysize => $height,
channels => 3,
);
my $color = Imager::Color->new('
my $r = [int(rand($width)), int(rand($height))];
foreach my $i (1 .. 100000) {
my $p = $points[rand @points];
my $h = [
int(($p->[0] + $r->[0]) / 2),
int(($p->[1] + $r->[1]) / 2),
];
$img->setpixel(
x => $h->[0],
y => $h->[1],
color => $color,
);
$r = $h;
}
$img->write(file => 'chaos_game_triangle.png'); | 1,052Chaos game
| 2perl
| 6cd36 |
require 'gserver'
class ChatServer < GServer
def initialize *args
super
@chatters = []
@mutex = Mutex.new
end
def broadcast message, sender = nil
message = message.strip <<
@mutex.synchronize do
@chatters.each do |chatter|
begin
chatter.print message unless chatter == sender
rescue
@chatters.delete chatter
end
end
end
end
def serve io
io.print 'Name: '
name = io.gets
return if name.nil?
name.strip!
broadcast
@mutex.synchronize do
@chatters << io
end
loop do
message = io.gets
if message
broadcast , io
else
break
end
end
broadcast
end
end
ChatServer.new(7000, '0.0.0.0', 100, $stderr, true).start.join | 1,051Chat server
| 14ruby
| aqk1s |
from __future__ import print_function
from pprint import pprint
from math import sqrt
def cholesky(A):
L = [[0.0] * len(A) for _ in xrange(len(A))]
for i in xrange(len(A)):
for j in xrange(i+1):
s = sum(L[i][k] * L[j][k] for k in xrange(j))
L[i][j] = sqrt(A[i][i] - s) if (i == j) else \
(1.0 / L[j][j] * (A[i][j] - s))
return L
if __name__ == :
m1 = [[25, 15, -5],
[15, 18, 0],
[-5, 0, 11]]
pprint(cholesky(m1))
print()
m2 = [[18, 22, 54, 42],
[22, 70, 86, 62],
[54, 86, 174, 134],
[42, 62, 134, 106]]
pprint(cholesky(m2), width=120) | 1,042Cholesky decomposition
| 3python
| mvuyh |
def chinese_remainder(n, a):
sum = 0
prod = reduce(lambda a, b: a*b, n)
for n_i, a_i in zip(n, a):
p = prod / n_i
sum += a_i * mul_inv(p, n_i) * p
return sum% prod
def mul_inv(a, b):
b0 = b
x0, x1 = 0, 1
if b == 1: return 1
while a > 1:
q = a / b
a, b = b, a%b
x0, x1 = x1 - q * x0, x0
if x1 < 0: x1 += b0
return x1
if __name__ == '__main__':
n = [3, 5, 7]
a = [2, 3, 2]
print chinese_remainder(n, a) | 1,047Chinese remainder theorem
| 3python
| 4hg5k |
class MyClass {
public static $classVar;
public $instanceVar;
function __construct() {
$this->instanceVar = 0;
}
function someMethod() {
$this->instanceVar = 1;
self::$classVar = 3;
}
}
$myObj = new MyClass(); | 1,038Classes
| 12php
| j1q7z |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.