code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
julia> x = [1, 2, 3]
julia> ptr = pointer_from_objref(x)
Ptr{Void} @0x000000010282e4a0
julia> unsafe_pointer_to_objref(ptr)
3-element Array{Int64,1}:
1
2
3 | 1,156Address of a variable
| 9java
| qsaxa |
(require '[clojure.java.io:as io])
(def groups
(with-open [r (io/reader wordfile)]
(group-by sort (line-seq r))))
(let [wordlists (sort-by (comp - count) (vals groups))
maxlength (count (first wordlists))]
(doseq [wordlist (take-while #(= (count %) maxlength) wordlists)]
(println wordlist)) | 1,152Anagrams
| 6clojure
| xsqwk |
null | 1,144Amicable pairs
| 11kotlin
| awi13 |
<?php
$ldap = ldap_connect($hostname, $port);
$success = ldap_bind($ldap, $username, $password); | 1,150Active Directory/Connect
| 12php
| awx12 |
import ldap
l = ldap.initialize()
try:
l.protocol_version = ldap.VERSION3
l.set_option(ldap.OPT_REFERRALS, 0)
bind = l.simple_bind_s(, )
finally:
l.unbind() | 1,150Active Directory/Connect
| 3python
| mclyh |
e = {} | 1,155Add a variable to a class instance at runtime
| 10javascript
| 6yt38 |
null | 1,156Address of a variable
| 11kotlin
| 1ahpd |
(defn c
"kth coefficient of (x - 1)^n"
[n k]
(/ (apply *' (range n (- n k) -1))
(apply *' (range k 0 -1))
(if (and (even? k) (< k n)) -1 1)))
(defn cs
"coefficient series for (x - 1)^n, k=[0..n]"
[n]
(map #(c n %) (range (inc n))))
(defn aks? [p] (->> (cs p) rest butlast (every? #(-> % (mod p) zero?))))
(println "coefficient series n (k[0] .. k[n])")
(doseq [n (range 10)] (println n (cs n)))
(println)
(println "primes < 50 per AKS:" (filter aks? (range 2 50))) | 1,153AKS test for primes
| 6clojure
| 8i805 |
from __future__ import annotations
from enum import Enum
from typing import NamedTuple
from typing import Optional
class Color(Enum):
B = 0
R = 1
class Tree(NamedTuple):
color: Color
left: Optional[Tree]
value: int
right: Optional[Tree]
def insert(self, val: int) -> Tree:
return self._insert(val).make_black()
def _insert(self, val: int) -> Tree:
match compare(val, self.value):
case _ if self == EMPTY:
return Tree(Color.R, EMPTY, val, EMPTY)
case -1:
assert self.left is not None
return Tree(
self.color, self.left._insert(val), self.value, self.right
).balance()
case 1:
assert self.right is not None
return Tree(
self.color, self.left, self.value, self.right._insert(val)
).balance()
case _:
return self
def balance(self) -> Tree:
match self:
case (Color.B, (Color.R, (Color.R, a, x, b), y, c), z, d):
return Tree(Color.R, Tree(Color.B, a, x, b), y, Tree(Color.B, c, z, d))
case (Color.B, (Color.R, a, x, (Color.R, b, y, c)), z, d):
return Tree(Color.R, Tree(Color.B, a, x, b), y, Tree(Color.B, c, z, d))
case (Color.B, a, x, (Color.R, (Color.R, b, y, c), z, d)):
return Tree(Color.R, Tree(Color.B, a, x, b), y, Tree(Color.B, c, z, d))
case (Color.B, a, x, (Color.R, b, y, (Color.R, c, z, d))):
return Tree(Color.R, Tree(Color.B, a, x, b), y, Tree(Color.B, c, z, d))
case _:
return self
def make_black(self) -> Tree:
return self._replace(color=Color.B)
def __str__(self) -> str:
if self == EMPTY:
return
return f
def print(self, indent: int = 0) -> None:
if self != EMPTY:
assert self.right is not None
self.right.print(indent + 1)
print(f)
if self != EMPTY:
assert self.left is not None
self.left.print(indent + 1)
EMPTY = Tree(Color.B, None, 0, None)
def compare(x: int, y: int) -> int:
if x > y:
return 1
if x < y:
return -1
return 0
def main():
tree = EMPTY
for i in range(1, 17):
tree = tree.insert(i)
tree.print()
if __name__ == :
main() | 1,146Algebraic data types
| 3python
| fz9de |
function sumDivs (n)
local sum = 1
for d = 2, math.sqrt(n) do
if n % d == 0 then
sum = sum + d
sum = sum + n / d
end
end
return sum
end
for n = 2, 20000 do
m = sumDivs(n)
if m > n then
if sumDivs(m) == n then print(n, m) end
end
end | 1,144Amicable pairs
| 1lua
| exnac |
use strict;
use warnings;
use Tk;
use Math::Trig qw/:pi/;
my $root = new MainWindow( -title => 'Pendulum Animation' );
my $canvas = $root->Canvas(-width => 320, -height => 200);
my $after_id;
for ($canvas) {
$_->createLine( 0, 25, 320, 25, -tags => [qw/plate/], -width => 2, -fill => 'grey50' );
$_->createOval( 155, 20, 165, 30, -tags => [qw/pivot outline/], -fill => 'grey50' );
$_->createLine( 1, 1, 1, 1, -tags => [qw/rod width/], -width => 3, -fill => 'black' );
$_->createOval( 1, 1, 2, 2, -tags => [qw/bob outline/], -fill => 'yellow' );
}
$canvas->raise('pivot');
$canvas->pack(-fill => 'both', -expand => 1);
my ($Theta, $dTheta, $length, $homeX, $homeY) =
(45, 0, 150, 160, 25);
sub show_pendulum {
my $angle = $Theta * pi() / 180;
my $x = $homeX + $length * sin($angle);
my $y = $homeY + $length * cos($angle);
$canvas->coords('rod', $homeX, $homeY, $x, $y);
$canvas->coords('bob', $x-15, $y-15, $x+15, $y+15);
}
sub recompute_angle {
my $scaling = 3000.0 / ($length ** 2);
my $firstDDTheta = -sin($Theta * pi / 180) * $scaling;
my $midDTheta = $dTheta + $firstDDTheta;
my $midTheta = $Theta + ($dTheta + $midDTheta)/2;
my $midDDTheta = -sin($midTheta * pi/ 180) * $scaling;
$midDTheta = $dTheta + ($firstDDTheta + $midDDTheta)/2;
$midTheta = $Theta + ($dTheta + $midDTheta)/2;
$midDDTheta = -sin($midTheta * pi/ 180) * $scaling;
my $lastDTheta = $midDTheta + $midDDTheta;
my $lastTheta = $midTheta + ($midDTheta + $lastDTheta)/2;
my $lastDDTheta = -sin($lastTheta * pi/180) * $scaling;
$lastDTheta = $midDTheta + ($midDDTheta + $lastDDTheta)/2;
$lastTheta = $midTheta + ($midDTheta + $lastDTheta)/2;
$dTheta = $lastDTheta;
$Theta = $lastTheta;
}
sub animate {
recompute_angle;
show_pendulum;
$after_id = $root->after(15 => sub {animate() });
}
show_pendulum;
$after_id = $root->after(500 => sub {animate});
$canvas->bind('<Destroy>' => sub {$after_id->cancel});
MainLoop; | 1,143Animate a pendulum
| 2perl
| onm8x |
require 'rubygems'
require 'net/ldap'
ldap = Net::LDAP.new(:host => 'ldap.example.com', :base => 'o=companyname')
ldap.authenticate('bind_dn', 'bind_pass') | 1,150Active Directory/Connect
| 14ruby
| c2v9k |
let conn = ldap3::LdapConn::new("ldap: | 1,150Active Directory/Connect
| 15rust
| lvucc |
import java.io.IOException
import org.apache.directory.api.ldap.model.exception.LdapException
import org.apache.directory.ldap.client.api.{LdapConnection, LdapNetworkConnection}
object LdapConnectionDemo {
@throws[LdapException]
@throws[IOException]
def main(args: Array[String]): Unit = {
try {
val connection: LdapConnection = new LdapNetworkConnection("localhost", 10389)
try {
connection.bind()
connection.unBind()
} finally if (connection != null) connection.close()
}
}
} | 1,150Active Directory/Connect
| 16scala
| u4gv8 |
null | 1,155Add a variable to a class instance at runtime
| 11kotlin
| 08xsf |
t = {}
print(t)
f = function() end
print(f)
c = coroutine.create(function() end)
print(c)
u = io.open("/dev/null","w")
print(u)
print(_G, _ENV) | 1,156Address of a variable
| 1lua
| aek1v |
package main
import "fmt"
func kPrime(n, k int) bool {
nf := 0
for i := 2; i <= n; i++ {
for n%i == 0 {
if nf == k {
return false
}
nf++
n /= i
}
}
return nf == k
}
func gen(k, n int) []int {
r := make([]int, n)
n = 2
for i := range r {
for !kPrime(n, k) {
n++
}
r[i] = n
n++
}
return r
}
func main() {
for k := 1; k <= 5; k++ {
fmt.Println(k, gen(k, 10))
}
} | 1,147Almost prime
| 0go
| v572m |
(ns active-object
(:import (java.util Timer TimerTask)))
(defn input [integrator k]
(send integrator assoc:k k))
(defn output [integrator]
(:s @integrator))
(defn tick [integrator t1]
(send integrator
(fn [{:keys [k s t0]:as m}]
(assoc m:s (+ s (/ (* (+ (k t1) (k t0)) (- t1 t0)) 2.0)):t0 t1))))
(defn start-timer [integrator interval]
(let [timer (Timer. true)
start (System/currentTimeMillis)]
(.scheduleAtFixedRate timer
(proxy [TimerTask] []
(run [] (tick integrator (double (/ (- (System/currentTimeMillis) start) 1000)))))
(long 0)
(long interval))
#(.cancel timer)))
(defn test-integrator []
(let [integrator (agent {:k (constantly 0.0):s 0.0:t0 0.0})
stop-timer (start-timer integrator 10)]
(input integrator #(Math/sin (* 2.0 Math/PI 0.5 %)))
(Thread/sleep 2000)
(input integrator (constantly 0.0))
(Thread/sleep 500)
(println (output integrator))
(stop-timer)))
user> (test-integrator)
1.414065859052494E-5 | 1,157Active object
| 6clojure
| l26cb |
public class almostprime
{
public static boolean kprime(int n,int k)
{
int i,div=0;
for(i=2;(i*i <= n) && (div<k);i++)
{
while(n%i==0)
{
n = n/i;
div++;
}
}
return div + ((n > 1)?1:0) == k;
}
public static void main(String[] args)
{
int i,l,k;
for(k=1;k<=5;k++)
{
println("k = " + k + ":");
l = 0;
for(i=2;l<10;i++)
{
if(kprime(i,k))
{
print(i + " ");
l++;
}
}
println();
}
}
} | 1,147Almost prime
| 7groovy
| mcuy5 |
use POSIX 'fmod';
sub angle {
my($b1,$b2) = @_;
my $b = fmod( ($b2 - $b1 + 720) , 360);
$b -= 360 if $b > 180;
$b += 360 if $b < -180;
return $b;
}
@bearings = (
20, 45,
-45, 45,
-85, 90,
-95, 90,
-45, 125,
-45, 145,
29.4803, -88.6381,
-78.3251, -159.036,
-70099.74233810938, 29840.67437876723,
-165313.6666297357, 33693.9894517456,
1174.8380510598456, -154146.66490124757,
60175.77306795546, 42213.07192354373
);
while(my ($b1,$b2) = splice(@bearings,0,2)) {
printf "%10.2f%10.2f =%8.2f\n", $b1, $b2, angle($b1,$b2);
} | 1,142Angle difference between two bearings
| 2perl
| 7hqrh |
import urllib.request
from collections import defaultdict
from itertools import combinations
def getwords(url='http:
return list(set(urllib.request.urlopen(url).read().decode().split()))
def find_anagrams(words):
anagram = defaultdict(list)
for word in words:
anagram[tuple(sorted(word))].append( word )
return dict((key, words) for key, words in anagram.items()
if len(words) > 1)
def is_deranged(words):
'returns pairs of words that have no character in the same position'
return [ (word1, word2)
for word1,word2 in combinations(words, 2)
if all(ch1 != ch2 for ch1, ch2 in zip(word1, word2)) ]
def largest_deranged_ana(anagrams):
ordered_anagrams = sorted(anagrams.items(),
key=lambda x:(-len(x[0]), x[0]))
for _, words in ordered_anagrams:
deranged_pairs = is_deranged(words)
if deranged_pairs:
return deranged_pairs
return []
if __name__ == '__main__':
words = getwords('http:
print(, len(words))
anagrams = find_anagrams(words)
print(, len(anagrams),)
print()
print(' ' + '\n '.join(', '.join(pairs)
for pairs in largest_deranged_ana(anagrams))) | 1,139Anagrams/Deranged anagrams
| 3python
| u4wvd |
package main
import (
"fmt"
"math"
"sort"
)
func totient(n int) int {
tot := n
i := 2
for i*i <= n {
if n%i == 0 {
for n%i == 0 {
n /= i
}
tot -= tot / i
}
if i == 2 {
i = 1
}
i += 2
}
if n > 1 {
tot -= tot / n
}
return tot
}
var pps = make(map[int]bool)
func getPerfectPowers(maxExp int) {
upper := math.Pow(10, float64(maxExp))
for i := 2; i <= int(math.Sqrt(upper)); i++ {
fi := float64(i)
p := fi
for {
p *= fi
if p >= upper {
break
}
pps[int(p)] = true
}
}
}
func getAchilles(minExp, maxExp int) map[int]bool {
lower := math.Pow(10, float64(minExp))
upper := math.Pow(10, float64(maxExp))
achilles := make(map[int]bool)
for b := 1; b <= int(math.Cbrt(upper)); b++ {
b3 := b * b * b
for a := 1; a <= int(math.Sqrt(upper)); a++ {
p := b3 * a * a
if p >= int(upper) {
break
}
if p >= int(lower) {
if _, ok := pps[p]; !ok {
achilles[p] = true
}
}
}
}
return achilles
}
func main() {
maxDigits := 15
getPerfectPowers(maxDigits)
achillesSet := getAchilles(1, 5) | 1,158Achilles numbers
| 0go
| xqbwf |
empty = {}
empty.foo = 1 | 1,155Add a variable to a class instance at runtime
| 1lua
| 8oq0e |
#![feature(box_patterns, box_syntax)]
use self::Color::*;
use std::cmp::Ordering::*;
enum Color {R,B}
type Link<T> = Option<Box<N<T>>>;
struct N<T> {
c: Color,
l: Link<T>,
val: T,
r: Link<T>,
}
impl<T: Ord> N<T> {
fn balance(col: Color, n1: Link<T>, z: T, n2: Link<T>) -> Link<T> {
Some(box
match (col,n1,n2) {
(B, Some(box N {c: R, l: Some(box N {c: R, l: a, val: x, r: b}), val: y, r: c}), d)
| (B, Some(box N {c: R, l: a, val: x, r: Some (box N {c: R, l: b, val: y, r: c})}), d)
=> N {c: R, l: Some(box N {c: B, l: a, val: x, r: b}), val: y, r: Some(box N {c: B, l: c, val: z, r: d})},
(B, a, Some(box N {c: R, l: Some(box N {c: R, l: b, val: y, r: c}), val: v, r: d}))
| (B, a, Some(box N {c: R, l: b, val: y, r: Some(box N {c: R, l: c, val: v, r: d})}))
=> N {c: R, l: Some(box N {c: B, l: a, val: z, r: b}), val: y, r: Some(box N {c: B, l: c, val: v, r: d})},
(col, a, b) => N {c: col, l: a, val: z, r: b},
})
}
fn insert(x: T, n: Link<T>) -> Link<T> {
match n {
None => Some(box N { c: R, l: None, val: x, r: None }),
Some(n) => {
let n = *n;
let N {c: col, l: a, val: y, r: b} = n;
match x.cmp(&y) {
Greater => Self::balance(col, a,y,Self::insert(x,b)),
Less => Self::balance(col, Self::insert(x,a),y,b),
Equal => Some(box N {c: col, l: a, val: y, r: b})
}
}
}
}
} | 1,146Algebraic data types
| 15rust
| 3y2z8 |
class RedBlackTree[A](implicit ord: Ordering[A]) {
sealed abstract class Color
case object R extends Color
case object B extends Color
sealed abstract class Tree {
def insert(x: A): Tree = ins(x) match {
case T(_, a, y, b) => T(B, a, y, b)
case E => E
}
def ins(x: A): Tree
}
case object E extends Tree {
override def ins(x: A): Tree = T(R, E, x, E)
}
case class T(c: Color, left: Tree, a: A, right: Tree) extends Tree {
private def balance: Tree = (c, left, a, right) match {
case (B, T(R, T(R, a, x, b), y, c), z, d ) => T(R, T(B, a, x, b), y, T(B, c, z, d))
case (B, T(R, a, x, T(R, b, y, c)), z, d ) => T(R, T(B, a, x, b), y, T(B, c, z, d))
case (B, a, x, T(R, T(R, b, y, c), z, d )) => T(R, T(B, a, x, b), y, T(B, c, z, d))
case (B, a, x, T(R, b, y, T(R, c, z, d))) => T(R, T(B, a, x, b), y, T(B, c, z, d))
case _ => this
}
override def ins(x: A): Tree = ord.compare(x, a) match {
case -1 => T(c, left ins x, a, right ).balance
case 1 => T(c, left, a, right ins x).balance
case 0 => this
}
}
} | 1,146Algebraic data types
| 16scala
| mc5yc |
package main
import (
"fmt"
"sync"
)
func ambStrings(ss []string) chan []string {
c := make(chan []string)
go func() {
for _, s := range ss {
c <- []string{s}
}
close(c)
}()
return c
}
func ambChain(ss []string, cIn chan []string) chan []string {
cOut := make(chan []string)
go func() {
var w sync.WaitGroup
for chain := range cIn {
w.Add(1)
go func(chain []string) {
for s1 := range ambStrings(ss) {
if s1[0][len(s1[0])-1] == chain[0][0] {
cOut <- append(s1, chain...)
}
}
w.Done()
}(chain)
}
w.Wait()
close(cOut)
}()
return cOut
}
func main() {
s1 := []string{"the", "that", "a"}
s2 := []string{"frog", "elephant", "thing"}
s3 := []string{"walked", "treaded", "grows"}
s4 := []string{"slowly", "quickly"}
c := ambChain(s1, ambChain(s2, ambChain(s3, ambStrings(s4))))
for s := range c {
fmt.Println(s)
}
} | 1,148Amb
| 0go
| 4rh52 |
enum Color { case R, B }
enum Tree<A> {
case E
indirect case T(Color, Tree<A>, A, Tree<A>)
}
func balance<A>(input: (Color, Tree<A>, A, Tree<A>)) -> Tree<A> {
switch input {
case let (.B, .T(.R, .T(.R,a,x,b), y, c), z, d): return .T(.R, .T(.B,a,x,b), y, .T(.B,c,z,d))
case let (.B, .T(.R, a, x, .T(.R,b,y,c)), z, d): return .T(.R, .T(.B,a,x,b), y, .T(.B,c,z,d))
case let (.B, a, x, .T(.R, .T(.R,b,y,c), z, d)): return .T(.R, .T(.B,a,x,b), y, .T(.B,c,z,d))
case let (.B, a, x, .T(.R, b, y, .T(.R,c,z,d))): return .T(.R, .T(.B,a,x,b), y, .T(.B,c,z,d))
case let (col, a, x, b) : return .T(col, a, x, b)
}
}
func insert<A: Comparable>(x: A, s: Tree<A>) -> Tree<A> {
func ins(s: Tree<A>) -> Tree<A> {
switch s {
case .E : return .T(.R,.E,x,.E)
case let .T(col,a,y,b):
if x < y {
return balance((col, ins(a), y, b))
} else if x > y {
return balance((col, a, y, ins(b)))
} else {
return s
}
}
}
switch ins(s) {
case let .T(_,a,y,b): return .T(.B,a,y,b)
case .E:
assert(false)
return .E
}
} | 1,146Algebraic data types
| 17swift
| t3cfl |
isPrime :: Integral a => a -> Bool
isPrime n = not $ any ((0 ==) . (mod n)) [2..(truncate $ sqrt $ fromIntegral n)]
primes :: [Integer]
primes = filter isPrime [2..]
isKPrime :: (Num a, Eq a) => a -> Integer -> Bool
isKPrime 1 n = isPrime n
isKPrime k n = any (isKPrime (k - 1)) sprimes
where
sprimes = map fst $ filter ((0 ==) . snd) $ map (divMod n) $ takeWhile (< n) primes
kPrimes :: (Num a, Eq a) => a -> [Integer]
kPrimes k = filter (isKPrime k) [2..]
main :: IO ()
main = flip mapM_ [1..5] $ \k ->
putStrLn $ "k = " ++ show k ++ ": " ++ (unwords $ map show (take 10 $ kPrimes k)) | 1,147Almost prime
| 8haskell
| ex8ai |
puzzlers.dict <- readLines("http://www.puzzlers.org/pub/wordlists/unixdict.txt")
longest.deranged.anagram <- function(dict=puzzlers.dict) {
anagram.groups <- function(word.group) {
sorted <- sapply(lapply(strsplit(word.group,""),sort),paste, collapse="")
grouped <- tapply(word.group, sorted, force, simplify=FALSE)
grouped <- grouped[sapply(grouped, length) > 1]
grouped[order(-nchar(names(grouped)))]
}
derangements <- function(anagram.group) {
pairs <- expand.grid(a = anagram.group, b = anagram.group,
stringsAsFactors=FALSE)
pairs <- subset(pairs, a < b)
deranged <- with(pairs, mapply(function(a,b) all(a!=b),
strsplit(a,""), strsplit(b,"")))
pairs[which(deranged),]
}
for (anagram.group in anagram.groups(dict)) {
if (nrow(d <- derangements(anagram.group)) > 0) {
return(d[1,])
}
}
} | 1,139Anagrams/Deranged anagrams
| 13r
| c2p95 |
import Control.Monad
amb = id
joins left right = last left == head right
example = do
w1 <- amb ["the", "that", "a"]
w2 <- amb ["frog", "elephant", "thing"]
w3 <- amb ["walked", "treaded", "grows"]
w4 <- amb ["slowly", "quickly"]
guard (w1 `joins` w2)
guard (w2 `joins` w3)
guard (w3 `joins` w4)
pure $ unwords [w1, w2, w3, w4] | 1,148Amb
| 8haskell
| q0ix9 |
use strict;
use warnings;
use feature <say current_sub>;
use experimental 'signatures';
use List::AllUtils <max head uniqint>;
use ntheory <is_square_free is_power euler_phi>;
use Math::AnyNum <:overload idiv iroot ipow is_coprime>;
sub table { my $t = shift() * (my $c = 1 + length max @_); ( sprintf( ('%'.$c.'d')x@_, @_) ) =~ s/.{1,$t}\K/\n/gr }
sub powerful_numbers ($n, $k = 2) {
my @powerful;
sub ($m, $r) {
$r < $k and push @powerful, $m and return;
for my $v (1 .. iroot(idiv($n, $m), $r)) {
if ($r > $k) { next unless is_square_free($v) and is_coprime($m, $v) }
__SUB__->($m * ipow($v, $r), $r - 1);
}
}->(1, 2*$k - 1);
sort { $a <=> $b } @powerful;
}
my(@P, @achilles, %Ahash, @strong);
@P = uniqint @P, powerful_numbers(10**9, $_) for 2..9; shift @P;
!is_power($_) and push @achilles, $_ and $Ahash{$_}++ for @P;
$Ahash{euler_phi $_} and push @strong, $_ for @achilles;
say "First 50 Achilles numbers:\n" . table 10, head 50, @achilles;
say "First 30 strong Achilles numbers:\n" . table 10, head 30, @strong;
say "Number of Achilles numbers with:\n";
for my $l (2..9) {
my $c; $l == length and $c++ for @achilles;
say "$l digits: $c";
} | 1,158Achilles numbers
| 2perl
| 549u2 |
package main
import (
"fmt"
"math"
"strings"
)
const threshold = uint64(1) << 47
func indexOf(s []uint64, search uint64) int {
for i, e := range s {
if e == search {
return i
}
}
return -1
}
func contains(s []uint64, search uint64) bool {
return indexOf(s, search) > -1
}
func maxOf(i1, i2 int) int {
if i1 > i2 {
return i1
}
return i2
}
func sumProperDivisors(n uint64) uint64 {
if n < 2 {
return 0
}
sqrt := uint64(math.Sqrt(float64(n)))
sum := uint64(1)
for i := uint64(2); i <= sqrt; i++ {
if n % i != 0 {
continue
}
sum += i + n / i
}
if sqrt * sqrt == n {
sum -= sqrt
}
return sum
}
func classifySequence(k uint64) ([]uint64, string) {
if k == 0 {
panic("Argument must be positive.")
}
last := k
var seq []uint64
seq = append(seq, k)
for {
last = sumProperDivisors(last)
seq = append(seq, last)
n := len(seq)
aliquot := ""
switch {
case last == 0:
aliquot = "Terminating"
case n == 2 && last == k:
aliquot = "Perfect"
case n == 3 && last == k:
aliquot = "Amicable"
case n >= 4 && last == k:
aliquot = fmt.Sprintf("Sociable[%d]", n - 1)
case last == seq[n - 2]:
aliquot = "Aspiring"
case contains(seq[1 : maxOf(1, n - 2)], last):
aliquot = fmt.Sprintf("Cyclic[%d]", n - 1 - indexOf(seq[:], last))
case n == 16 || last > threshold:
aliquot = "Non-Terminating"
}
if aliquot != "" {
return seq, aliquot
}
}
}
func joinWithCommas(seq []uint64) string {
res := fmt.Sprint(seq)
res = strings.Replace(res, " ", ", ", -1)
return res
}
func main() {
fmt.Println("Aliquot classifications - periods for Sociable/Cyclic in square brackets:\n")
for k := uint64(1); k <= 10; k++ {
seq, aliquot := classifySequence(k)
fmt.Printf("%2d:%-15s%s\n", k, aliquot, joinWithCommas(seq))
}
fmt.Println()
s := []uint64{
11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488,
}
for _, k := range s {
seq, aliquot := classifySequence(k)
fmt.Printf("%7d:%-15s%s\n", k, aliquot, joinWithCommas(seq))
}
fmt.Println()
k := uint64(15355717786080)
seq, aliquot := classifySequence(k)
fmt.Printf("%d:%-15s%s\n", k, aliquot, joinWithCommas(seq))
} | 1,151Aliquot sequence classifications
| 0go
| q00xz |
use Scalar::Util qw(refaddr);
print refaddr(\my $v), "\n"; | 1,156Address of a variable
| 2perl
| m9zyz |
divisors :: (Integral a) => a -> [a]
divisors n = filter ((0 ==) . (n `mod`)) [1 .. (n `div` 2)]
data Class
= Terminating
| Perfect
| Amicable
| Sociable
| Aspiring
| Cyclic
| Nonterminating
deriving (Show)
aliquot :: (Integral a) => a -> [a]
aliquot 0 = [0]
aliquot n = n: (aliquot $ sum $ divisors n)
classify :: (Num a, Eq a) => [a] -> Class
classify [] = Nonterminating
classify [0] = Terminating
classify [_] = Nonterminating
classify [a,b]
| a == b = Perfect
| b == 0 = Terminating
| otherwise = Nonterminating
classify x@(a:b:c:_)
| a == b = Perfect
| a == c = Amicable
| a `elem` (drop 1 x) = Sociable
| otherwise =
case classify (drop 1 x) of
Perfect -> Aspiring
Amicable -> Cyclic
Sociable -> Cyclic
d -> d
main :: IO ()
main = do
let cls n = let ali = take 16 $ aliquot n in (classify ali, ali)
mapM_ (print . cls) $ [1..10] ++
[11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488] | 1,151Aliquot sequence classifications
| 8haskell
| mccyf |
package Empty;
sub new { return bless {}, shift; }
package main;
my $o = Empty->new;
$o->{'foo'} = 1; | 1,155Add a variable to a class instance at runtime
| 2perl
| 542u2 |
package main
import "fmt"
func isPrime(n int) bool {
switch {
case n < 2:
return false
case n%2 == 0:
return n == 2
case n%3 == 0:
return n == 3
default:
d := 5
for d*d <= n {
if n%d == 0 {
return false
}
d += 2
if n%d == 0 {
return false
}
d += 4
}
return true
}
}
func sumDigits(n int) int {
sum := 0
for n > 0 {
sum += n % 10
n /= 10
}
return sum
}
func main() {
fmt.Println("Additive primes less than 500:")
i := 2
count := 0
for {
if isPrime(i) && isPrime(sumDigits(i)) {
count++
fmt.Printf("%3d ", i)
if count%10 == 0 {
fmt.Println()
}
}
if i > 2 {
i += 2
} else {
i++
}
if i > 499 {
break
}
}
fmt.Printf("\n\n%d additive primes found.\n", count)
} | 1,154Additive primes
| 0go
| wxaeg |
import pygame, sys
from pygame.locals import *
from math import sin, cos, radians
pygame.init()
WINDOWSIZE = 250
TIMETICK = 100
BOBSIZE = 15
window = pygame.display.set_mode((WINDOWSIZE, WINDOWSIZE))
pygame.display.set_caption()
screen = pygame.display.get_surface()
screen.fill((255,255,255))
PIVOT = (WINDOWSIZE/2, WINDOWSIZE/10)
SWINGLENGTH = PIVOT[1]*4
class BobMass(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.theta = 45
self.dtheta = 0
self.rect = pygame.Rect(PIVOT[0]-SWINGLENGTH*cos(radians(self.theta)),
PIVOT[1]+SWINGLENGTH*sin(radians(self.theta)),
1,1)
self.draw()
def recomputeAngle(self):
scaling = 3000.0/(SWINGLENGTH**2)
firstDDtheta = -sin(radians(self.theta))*scaling
midDtheta = self.dtheta + firstDDtheta
midtheta = self.theta + (self.dtheta + midDtheta)/2.0
midDDtheta = -sin(radians(midtheta))*scaling
midDtheta = self.dtheta + (firstDDtheta + midDDtheta)/2
midtheta = self.theta + (self.dtheta + midDtheta)/2
midDDtheta = -sin(radians(midtheta)) * scaling
lastDtheta = midDtheta + midDDtheta
lasttheta = midtheta + (midDtheta + lastDtheta)/2.0
lastDDtheta = -sin(radians(lasttheta)) * scaling
lastDtheta = midDtheta + (midDDtheta + lastDDtheta)/2.0
lasttheta = midtheta + (midDtheta + lastDtheta)/2.0
self.dtheta = lastDtheta
self.theta = lasttheta
self.rect = pygame.Rect(PIVOT[0]-
SWINGLENGTH*sin(radians(self.theta)),
PIVOT[1]+
SWINGLENGTH*cos(radians(self.theta)),1,1)
def draw(self):
pygame.draw.circle(screen, (0,0,0), PIVOT, 5, 0)
pygame.draw.circle(screen, (0,0,0), self.rect.center, BOBSIZE, 0)
pygame.draw.aaline(screen, (0,0,0), PIVOT, self.rect.center)
pygame.draw.line(screen, (0,0,0), (0, PIVOT[1]), (WINDOWSIZE, PIVOT[1]))
def update(self):
self.recomputeAngle()
screen.fill((255,255,255))
self.draw()
bob = BobMass()
TICK = USEREVENT + 2
pygame.time.set_timer(TICK, TIMETICK)
def input(events):
for event in events:
if event.type == QUIT:
sys.exit(0)
elif event.type == TICK:
bob.update()
while True:
input(pygame.event.get())
pygame.display.flip() | 1,143Animate a pendulum
| 3python
| id9of |
class E {};
$e=new E();
$e->foo=1;
$e->{} = 1;
$x = ;
$e->$x = 1; | 1,155Add a variable to a class instance at runtime
| 12php
| ois85 |
public class additivePrimes {
public static void main(String[] args) {
int additive_primes = 0;
for (int i = 2; i < 500; i++) {
if(isPrime(i) && isPrime(digitSum(i))){
additive_primes++;
System.out.print(i + " ");
}
}
System.out.print("\nFound " + additive_primes + " additive primes less than 500");
}
static boolean isPrime(int n) {
int counter = 1;
if (n < 2 || (n != 2 && n % 2 == 0) || (n != 3 && n % 3 == 0)) {
return false;
}
while (counter * 6 - 1 <= Math.sqrt(n)) {
if (n % (counter * 6 - 1) == 0 || n % (counter * 6 + 1) == 0) {
return false;
} else {
counter++;
}
}
return true;
}
static int digitSum(int n) {
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
return sum;
}
} | 1,154Additive primes
| 9java
| ndoih |
public class AlmostPrime {
public static void main(String[] args) {
for (int k = 1; k <= 5; k++) {
System.out.print("k = " + k + ":");
for (int i = 2, c = 0; c < 10; i++) {
if (kprime(i, k)) {
System.out.print(" " + i);
c++;
}
}
System.out.println("");
}
}
public static boolean kprime(int n, int k) {
int f = 0;
for (int p = 2; f < k && p * p <= n; p++) {
while (n % p == 0) {
n /= p;
f++;
}
}
return f + ((n > 1) ? 1 : 0) == k;
}
} | 1,147Almost prime
| 9java
| hbejm |
from __future__ import print_function
def getDifference(b1, b2):
r = (b2 - b1)% 360.0
if r >= 180.0:
r -= 360.0
return r
if __name__ == :
print ()
print (getDifference(20.0, 45.0))
print (getDifference(-45.0, 45.0))
print (getDifference(-85.0, 90.0))
print (getDifference(-95.0, 90.0))
print (getDifference(-45.0, 125.0))
print (getDifference(-45.0, 145.0))
print (getDifference(-45.0, 125.0))
print (getDifference(-45.0, 145.0))
print (getDifference(29.4803, -88.6381))
print (getDifference(-78.3251, -159.036))
print ()
print (getDifference(-70099.74233810938, 29840.67437876723))
print (getDifference(-165313.6666297357, 33693.9894517456))
print (getDifference(1174.8380510598456, -154146.66490124757))
print (getDifference(60175.77306795546, 42213.07192354373)) | 1,142Angle difference between two bearings
| 3python
| jks7p |
static __typeof__(n) _n=n; LOGIC; }
ACCUMULATOR(x,1.0)
ACCUMULATOR(y,3)
ACCUMULATOR(z,'a')
int main (void) {
printf (, x(5));
printf (, x(2.3));
printf (, y(5.0));
printf (, y(3.3));
printf (, z(5));
return 0;
} | 1,159Accumulator factory
| 5c
| 7j2rg |
fn perfect_powers(n: u128) -> Vec<u128> {
let mut powers = Vec::<u128>::new();
let sqrt = (n as f64).sqrt() as u128;
for i in 2..=sqrt {
let mut p = i * i;
while p < n {
powers.push(p);
p *= i;
}
}
powers.sort();
powers.dedup();
powers
}
fn bsearch<T: Ord>(vector: &Vec<T>, value: &T) -> bool {
match vector.binary_search(value) {
Ok(_) => true,
_ => false,
}
}
fn achilles(from: u128, to: u128, pps: &Vec<u128>) -> Vec<u128> {
let mut result = Vec::<u128>::new();
let cbrt = ((to / 4) as f64).cbrt() as u128;
let sqrt = ((to / 8) as f64).sqrt() as u128;
for b in 2..=cbrt {
let b3 = b * b * b;
for a in 2..=sqrt {
let p = b3 * a * a;
if p >= to {
break;
}
if p >= from &&!bsearch(&pps, &p) {
result.push(p);
}
}
}
result.sort();
result.dedup();
result
}
fn totient(mut n: u128) -> u128 {
let mut tot = n;
if (n & 1) == 0 {
while (n & 1) == 0 {
n >>= 1;
}
tot -= tot >> 1;
}
let mut p = 3;
while p * p <= n {
if n% p == 0 {
while n% p == 0 {
n /= p;
}
tot -= tot / p;
}
p += 2;
}
if n > 1 {
tot -= tot / n;
}
tot
}
fn main() {
use std::time::Instant;
let t0 = Instant::now();
let limit = 1000000000000000u128;
let pps = perfect_powers(limit);
let ach = achilles(1, 1000000, &pps);
println!("First 50 Achilles numbers:");
for i in 0..50 {
print!("{:4}{}", ach[i], if (i + 1)% 10 == 0 { "\n" } else { " " });
}
println!("\nFirst 50 strong Achilles numbers:");
for (i, n) in ach
.iter()
.filter(|&x| bsearch(&ach, &totient(*x)))
.take(50)
.enumerate()
{
print!("{:6}{}", n, if (i + 1)% 10 == 0 { "\n" } else { " " });
}
println!();
let mut from = 1u128;
let mut to = 100u128;
let mut digits = 2;
while to <= limit {
let count = achilles(from, to, &pps).len();
println!("{:2} digits: {}", digits, count);
from = to;
to *= 10;
digits += 1;
}
let duration = t0.elapsed();
println!("\nElapsed time: {} milliseconds", duration.as_millis());
} | 1,158Achilles numbers
| 15rust
| 7jvrc |
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.LongStream;
public class AliquotSequenceClassifications {
private static Long properDivsSum(long n) {
return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum();
}
static boolean aliquot(long n, int maxLen, long maxTerm) {
List<Long> s = new ArrayList<>(maxLen);
s.add(n);
long newN = n;
while (s.size() <= maxLen && newN < maxTerm) {
newN = properDivsSum(s.get(s.size() - 1));
if (s.contains(newN)) {
if (s.get(0) == newN) {
switch (s.size()) {
case 1:
return report("Perfect", s);
case 2:
return report("Amicable", s);
default:
return report("Sociable of length " + s.size(), s);
}
} else if (s.get(s.size() - 1) == newN) {
return report("Aspiring", s);
} else
return report("Cyclic back to " + newN, s);
} else {
s.add(newN);
if (newN == 0)
return report("Terminating", s);
}
}
return report("Non-terminating", s);
}
static boolean report(String msg, List<Long> result) {
System.out.println(msg + ": " + result);
return false;
}
public static void main(String[] args) {
long[] arr = {
11, 12, 28, 496, 220, 1184, 12496, 1264460,
790, 909, 562, 1064, 1488};
LongStream.rangeClosed(1, 10).forEach(n -> aliquot(n, 16, 1L << 47));
System.out.println();
Arrays.stream(arr).forEach(n -> aliquot(n, 16, 1L << 47));
}
} | 1,151Aliquot sequence classifications
| 9java
| fzzdv |
class empty(object):
pass
e = empty() | 1,155Add a variable to a class instance at runtime
| 3python
| 4gv5k |
foo = object()
address = id(foo) | 1,156Address of a variable
| 3python
| 9c3mf |
import Data.List (unfoldr)
primes = 2: sieve [3,5..]
where sieve (x:xs) = x: sieve (filter (\y -> y `mod` x /= 0) xs)
isPrime n = all (\p -> n `mod` p /= 0) $ takeWhile (< sqrtN) primes
where sqrtN = round . sqrt . fromIntegral $ n
digits = unfoldr f
where f 0 = Nothing
f n = let (q, r) = divMod n 10 in Just (r,q)
isAdditivePrime n = isPrime n && (isPrime . sum . digits) n | 1,154Additive primes
| 8haskell
| 6yz3k |
function almostPrime (n, k) {
var divisor = 2, count = 0
while(count < k + 1 && n != 1) {
if (n % divisor == 0) {
n = n / divisor
count = count + 1
} else {
divisor++
}
}
return count == k
}
for (var k = 1; k <= 5; k++) {
document.write("<br>k=", k, ": ")
var count = 0, n = 0
while (count <= 10) {
n++
if (almostPrime(n, k)) {
document.write(n, " ")
count++
}
}
} | 1,147Almost prime
| 10javascript
| aw010 |
library(DescTools)
pendulum<-function(length=5,radius=1,circle.color="white",bg.color="white"){
tseq = c(seq(0,pi,by=.1),seq(pi,0,by=-.1))
slow=.27;fast=.07
sseq = c(seq(slow,fast,length.out = length(tseq)/4),seq(fast,slow,length.out = length(tseq)/4),seq(slow,fast,length.out = length(tseq)/4),seq(fast,slow,length.out = length(tseq)/4))
plot(0,0,xlim=c((-length-radius)*1.2,(length+radius)*1.2),ylim=c((-length-radius)*1.2,0),xaxt="n",yaxt="n",xlab="",ylab="")
cat("Press Esc to end animation")
while(T){
for(i in 1:length(tseq)){
rect(par("usr")[1],par("usr")[3],par("usr")[2],par("usr")[4],col = bg.color)
abline(h=0,col="grey")
points(0,0)
DrawCircle((radius+length)*cos(tseq[i]),(radius+length)*-sin(tseq[i]),r.out=radius,col=circle.color)
lines(c(0,length*cos(tseq[i])),c(0,length*-sin(tseq[i])))
Sys.sleep(sseq[i])
}
}
}
pendulum(5,1,"gold","lightblue") | 1,143Animate a pendulum
| 13r
| s83qy |
function ambRun(func) {
var choices = [];
var index;
function amb(values) {
if (values.length == 0) {
fail();
}
if (index == choices.length) {
choices.push({i: 0,
count: values.length});
}
var choice = choices[index++];
return values[choice.i];
}
function fail() { throw fail; }
while (true) {
try {
index = 0;
return func(amb, fail);
} catch (e) {
if (e != fail) {
throw e;
}
var choice;
while ((choice = choices.pop()) && ++choice.i == choice.count) {}
if (choice == undefined) {
return undefined;
}
choices.push(choice);
}
}
}
ambRun(function(amb, fail) {
function linked(s1, s2) {
return s1.slice(-1) == s2.slice(0, 1);
}
var w1 = amb(["the", "that", "a"]);
var w2 = amb(["frog", "elephant", "thing"]);
if (!linked(w1, w2)) fail();
var w3 = amb(["walked", "treaded", "grows"]);
if (!linked(w2, w3)) fail();
var w4 = amb(["slowly", "quickly"]);
if (!linked(w3, w4)) fail();
return [w1, w2, w3, w4].join(' ');
}); | 1,148Amb
| 10javascript
| xsow9 |
x <- 5
y <- x
pryr::address(x)
pryr::address(y)
y <- y + 1
pryr::address(x)
pryr::address(y) | 1,156Address of a variable
| 13r
| 36dzt |
fun isPrime(n: Int): Boolean {
if (n <= 3) return n > 1
if (n% 2 == 0 || n% 3 == 0) return false
var i = 5
while (i * i <= n) {
if (n% i == 0 || n% (i + 2) == 0) return false
i += 6
}
return true
}
fun digitSum(n: Int): Int {
var sum = 0
var num = n
while (num > 0) {
sum += num% 10
num /= 10
}
return sum
}
fun main() {
var additivePrimes = 0
for (i in 2 until 500) {
if (isPrime(i) and isPrime(digitSum(i))) {
additivePrimes++
print("$i ")
}
}
println("\nFound $additivePrimes additive primes less than 500")
} | 1,154Additive primes
| 11kotlin
| s0xq7 |
def deranged?(a, b)
a.chars.zip(b.chars).all? {|char_a, char_b| char_a!= char_b}
end
def find_derangements(list)
list.combination(2) {|a,b| return a,b if deranged?(a,b)}
nil
end
require 'open-uri'
anagram = open('http:
f.read.split.group_by {|s| s.each_char.sort}
end
anagram = anagram.select{|k,list| list.size>1}.sort_by{|k,list| -k.size}
anagram.each do |k,list|
if derangements = find_derangements(list)
puts
break
end
end | 1,139Anagrams/Deranged anagrams
| 14ruby
| 4rq5p |
sub recur (&@) {
my $f = shift;
local *recurse = $f;
$f->(@_);
}
sub fibo {
my $n = shift;
$n < 0 and die 'Negative argument';
recur {
my $m = shift;
$m < 3 ? 1 : recurse($m - 1) + recurse($m - 2);
} $n;
} | 1,138Anonymous recursion
| 2perl
| g704e |
class Empty
end
e = Empty.new
class << e
attr_accessor:foo
end
e.foo = 1
puts e.foo
f = Empty.new
f.foo = 1 | 1,155Add a variable to a class instance at runtime
| 14ruby
| r75gs |
import language.dynamics
import scala.collection.mutable.HashMap
class A extends Dynamic {
private val map = new HashMap[String, Any]
def selectDynamic(name: String): Any = {
return map(name)
}
def updateDynamic(name:String)(value: Any) = {
map(name) = value
}
} | 1,155Add a variable to a class instance at runtime
| 16scala
| kb7hk |
>foo = Object.new
>id = foo.object_id
> % (id << 1) | 1,156Address of a variable
| 14ruby
| l2ycl |
function sumdigits(n)
local sum = 0
while n > 0 do
sum = sum + n % 10
n = math.floor(n/10)
end
return sum
end
primegen:generate(nil, 500)
aprimes = primegen:filter(function(n) return primegen.tbd(sumdigits(n)) end)
print(table.concat(aprimes, " "))
print("Count:", #aprimes) | 1,154Additive primes
| 1lua
| 08qsd |
fun Int.k_prime(x: Int): Boolean {
var n = x
var f = 0
var p = 2
while (f < this && p * p <= n) {
while (0 == n % p) { n /= p; f++ }
p++
}
return f + (if (n > 1) 1 else 0) == this
}
fun Int.primes(n : Int) : List<Int> {
var i = 2
var list = mutableListOf<Int>()
while (list.size < n) {
if (k_prime(i)) list.add(i)
i++
}
return list
}
fun main(args: Array<String>) {
for (k in 1..5)
println("k = $k: " + k.primes(10))
} | 1,147Almost prime
| 11kotlin
| 4rk57 |
(defn accum [n]
(let [acc (atom n)]
(fn [m] (swap! acc + m)))) | 1,159Accumulator factory
| 6clojure
| p1gbd |
null | 1,151Aliquot sequence classifications
| 11kotlin
| 8ii0q |
import Foundation
let fooKey = UnsafeMutablePointer<UInt8>.alloc(1)
class MyClass { }
let e = MyClass() | 1,155Add a variable to a class instance at runtime
| 17swift
| gru49 |
let v1 = vec![vec![1,2,3]; 10];
println!("Original address: {:p}", &v1);
let mut v2; | 1,156Address of a variable
| 15rust
| 2vmlt |
var n = 42;
say Sys.refaddr(\n); # prints the address of the variable
say Sys.refaddr(n); # prints the address of the object at which the variable points to | 1,156Address of a variable
| 16scala
| 54lut |
def getDifference(b1, b2)
r = (b2 - b1) % 360.0
if r >= 180.0
r -= 360.0
end
return r
end
if __FILE__ == $PROGRAM_NAME
puts
puts getDifference(20.0, 45.0)
puts getDifference(-45.0, 45.0)
puts getDifference(-85.0, 90.0)
puts getDifference(-95.0, 90.0)
puts getDifference(-45.0, 125.0)
puts getDifference(-45.0, 145.0)
puts getDifference(-45.0, 125.0)
puts getDifference(-45.0, 145.0)
puts getDifference(29.4803, -88.6381)
puts getDifference(-78.3251, -159.036)
puts
puts getDifference(-70099.74233810938, 29840.67437876723)
puts getDifference(-165313.6666297357, 33693.9894517456)
puts getDifference(1174.8380510598456, -154146.66490124757)
puts getDifference(60175.77306795546, 42213.07192354373)
end | 1,142Angle difference between two bearings
| 14ruby
| kp8hg |
null | 1,139Anagrams/Deranged anagrams
| 15rust
| g7s4o |
<?php
function fib($n) {
if ($n < 0)
throw new Exception('Negative numbers not allowed');
$f = function($n) {
if ($n < 2)
return 1;
else {
$g = debug_backtrace()[1]['args'][0];
return call_user_func($g, $n-1) + call_user_func($g, $n-2);
}
};
return call_user_func($f, $n);
}
echo fib(8), ;
?> | 1,138Anonymous recursion
| 12php
| nf5ig |
use ntheory qw/divisor_sum/;
for my $x (1..20000) {
my $y = divisor_sum($x)-$x;
say "$x $y" if $y > $x && $x == divisor_sum($y)-$y;
} | 1,144Amicable pairs
| 2perl
| 9lrmn |
null | 1,148Amb
| 11kotlin
| 7hpr4 |
package main
import (
"fmt"
"math"
"time"
) | 1,157Active object
| 0go
| p17bg |
class MyClass { }
func printAddress<T>(of pointer: UnsafePointer<T>) {
print(pointer)
}
func test() {
var x = 42
var y = 3.14
var z = "foo"
var obj = MyClass() | 1,156Address of a variable
| 17swift
| cl69t |
null | 1,147Almost prime
| 1lua
| g7b4j |
null | 1,142Angle difference between two bearings
| 15rust
| b1okx |
object DerangedAnagrams {
def groupAnagrams(words: Iterable[String]): Map[String, Set[String]] =
words.foldLeft (Map[String, Set[String]]()) { (map, word) =>
val sorted = word.sorted
val entry = map.getOrElse(sorted, Set.empty)
map + (sorted -> (entry + word))
}
def isDeranged(ss: (String, String)): Boolean =
ss._1 zip ss._2 forall { case (c1, c2) => c1 != c2 }
def pairWords(as: Iterable[String]): Iterable[(String, String)] =
if (as.size < 2) Seq() else (as.tail map (as.head -> _)) ++ pairWords(as.tail)
def readLines(url: String): Iterable[String] =
io.Source.fromURL(url).getLines().toIterable
val wordsURL = "http: | 1,139Anagrams/Deranged anagrams
| 16scala
| jko7i |
makeAccumulator(s) => (n) => s += n; | 1,159Accumulator factory
| 18dart
| vu62j |
class Integrator {
interface Function {
double apply(double timeSinceStartInSeconds)
}
private final long start
private volatile boolean running
private Function func
private double t0
private double v0
private double sum
Integrator(Function func) {
this.start = System.nanoTime()
setFunc(func)
new Thread({ this.&integrate() }).start()
}
void setFunc(Function func) {
this.func = func
def temp = func.apply(0.0.toDouble())
v0 = temp
t0 = 0.0.doubleValue()
}
double getOutput() {
return sum
}
void stop() {
running = false
}
private void integrate() {
running = true
while (running) {
try {
Thread.sleep(1)
update()
} catch (InterruptedException ignored) {
return
}
}
}
private void update() {
double t1 = (System.nanoTime() - start) / 1.0e9
double v1 = func.apply(t1)
double rect = (t1 - t0) * (v0 + v1) / 2.0
this.sum += rect
t0 = t1
v0 = v1
}
static void main(String[] args) {
Integrator integrator = new Integrator({ t -> Math.sin(Math.PI * t) })
Thread.sleep(2000)
integrator.setFunc({ t -> 0.0.toDouble() })
Thread.sleep(500)
integrator.stop()
System.out.println(integrator.getOutput())
}
} | 1,157Active object
| 7groovy
| 7jurz |
object AngleDifference extends App {
private def getDifference(b1: Double, b2: Double) = {
val r = (b2 - b1) % 360.0
if (r < -180.0) r + 360.0 else if (r >= 180.0) r - 360.0 else r
}
println("Input in -180 to +180 range")
println(getDifference(20.0, 45.0))
println(getDifference(-45.0, 45.0))
println(getDifference(-85.0, 90.0))
println(getDifference(-95.0, 90.0))
println(getDifference(-45.0, 125.0))
println(getDifference(-45.0, 145.0))
println(getDifference(-45.0, 125.0))
println(getDifference(-45.0, 145.0))
println(getDifference(29.4803, -88.6381))
println(getDifference(-78.3251, -159.036))
println("Input in wider range")
println(getDifference(-70099.74233810938, 29840.67437876723))
println(getDifference(-165313.6666297357, 33693.9894517456))
println(getDifference(1174.8380510598456, -154146.66490124757))
println(getDifference(60175.77306795546, 42213.07192354373))
} | 1,142Angle difference between two bearings
| 16scala
| awd1n |
module Integrator (
newIntegrator, input, output, stop,
Time, timeInterval
) where
import Control.Concurrent (forkIO, threadDelay)
import Control.Concurrent.MVar (MVar, newMVar, modifyMVar_, modifyMVar, readMVar)
import Control.Exception (evaluate)
import Data.Time (UTCTime)
import Data.Time.Clock (getCurrentTime, diffUTCTime)
main = do let f = 0.5
t0 <- getCurrentTime
i <- newIntegrator
input i (\t -> sin(2*pi * f * timeInterval t0 t))
threadDelay 2000000
input i (const 0)
threadDelay 500000
result <- output i
stop i
print result
type Time = UTCTime
type Func a = Time -> a
timeInterval t0 t1 = realToFrac $ diffUTCTime t1 t0
newIntegrator :: Fractional a => IO (Integrator a)
input :: Integrator a -> Func a -> IO ()
output :: Integrator a -> IO a
stop :: Integrator a -> IO ()
data Integrator a = Integrator (MVar (IntState a))
deriving Eq
data IntState a = IntState { func :: Func a,
run :: Bool,
value :: a,
time :: Time }
newIntegrator = do
now <- getCurrentTime
state <- newMVar $ IntState { func = const 0,
run = True,
value = 0,
time = now }
thread <- forkIO (intThread state)
return (Integrator state)
input (Integrator stv) f = modifyMVar_ stv (\st -> return st { func = f })
output (Integrator stv) = fmap value $ readMVar stv
stop (Integrator stv) = modifyMVar_ stv (\st -> return st { run = False })
intThread :: Fractional a => MVar (IntState a) -> IO ()
intThread stv = whileM $ modifyMVar stv updateAndCheckRun
where updateAndCheckRun st = do
now <- getCurrentTime
let value' = integrate (func st) (value st) (time st) now
evaluate value'
return (st { value = value', time = now },
run st)
integrate:: Fractional a => Func a -> a -> Time -> Time -> a
integrate f value t0 t1 = value + (f t0 + f t1)/2 * dt
where dt = timeInterval t0 t1
whileM action = do b <- action; if b then whileM action else return () | 1,157Active object
| 8haskell
| ft8d1 |
package main
import "fmt"
func bc(p int) []int64 {
c := make([]int64, p+1)
r := int64(1)
for i, half := 0, p/2; i <= half; i++ {
c[i] = r
c[p-i] = r
r = r * int64(p-i) / int64(i+1)
}
for i := p - 1; i >= 0; i -= 2 {
c[i] = -c[i]
}
return c
}
func main() {
for p := 0; p <= 7; p++ {
fmt.Printf("%d: %s\n", p, pp(bc(p)))
}
for p := 2; p < 50; p++ {
if aks(p) {
fmt.Print(p, " ")
}
}
fmt.Println()
}
var e = []rune("")
func pp(c []int64) (s string) {
if len(c) == 1 {
return fmt.Sprint(c[0])
}
p := len(c) - 1
if c[p] != 1 {
s = fmt.Sprint(c[p])
}
for i := p; i > 0; i-- {
s += "x"
if i != 1 {
s += string(e[i-2])
}
if d := c[i-1]; d < 0 {
s += fmt.Sprintf(" -%d", -d)
} else {
s += fmt.Sprintf(" +%d", d)
}
}
return
}
func aks(p int) bool {
c := bc(p)
c[p]--
c[0]++
for _, d := range c {
if d%int64(p) != 0 {
return false
}
}
return true
} | 1,153AKS test for primes
| 0go
| c2c9g |
use strict;
use warnings;
use ntheory 'is_prime';
use List::Util <sum max>;
sub pp {
my $format = ('%' . (my $cw = 1+length max @_) . 'd') x @_;
my $width = ".{@{[$cw * int 60/$cw]}}";
(sprintf($format, @_)) =~ s/($width)/$1\n/gr;
}
my($limit, @ap) = 500;
is_prime($_) and is_prime(sum(split '',$_)) and push @ap, $_ for 1..$limit;
print @ap . " additive primes < $limit:\n" . pp(@ap); | 1,154Additive primes
| 2perl
| u52vr |
<?php
function sumDivs ($n) {
$sum = 1;
for ($d = 2; $d <= sqrt($n); $d++) {
if ($n % $d == 0) $sum += $n / $d + $d;
}
return $sum;
}
for ($n = 2; $n < 20000; $n++) {
$m = sumDivs($n);
if ($m > $n) {
if (sumDivs($m) == $n) echo $n..$m.;
}
}
?> | 1,144Amicable pairs
| 12php
| wqdep |
require 'tk'
$root = TkRoot.new( => )
$canvas = TkCanvas.new($root) do
width 320
height 200
create TkcLine, 0,25,320,25, 'tags' => 'plate', 'width' => 2, 'fill' => 'grey50'
create TkcOval, 155,20,165,30, 'tags' => 'pivot', 'outline' => , 'fill' => 'grey50'
create TkcLine, 1,1,1,1, 'tags' => 'rod', 'width' => 3, 'fill' => 'black'
create TkcOval, 1,1,2,2, 'tags' => 'bob', 'outline' => 'black', 'fill' => 'yellow'
end
$canvas.raise('pivot')
$canvas.pack('fill' => 'both', 'expand' => true)
$Theta = 45.0
$dTheta = 0.0
$length = 150
$homeX = 160
$homeY = 25
def show_pendulum
angle = $Theta * Math::PI / 180
x = $homeX + $length * Math.sin(angle)
y = $homeY + $length * Math.cos(angle)
$canvas.coords('rod', $homeX, $homeY, x, y)
$canvas.coords('bob', x-15, y-15, x+15, y+15)
end
def recompute_angle
scaling = 3000.0 / ($length ** 2)
firstDDTheta = -Math.sin($Theta * Math::PI / 180) * scaling
midDTheta = $dTheta + firstDDTheta
midTheta = $Theta + ($dTheta + midDTheta)/2
midDDTheta = -Math.sin(midTheta * Math::PI / 180) * scaling
midDTheta = $dTheta + (firstDDTheta + midDDTheta)/2
midTheta = $Theta + ($dTheta + midDTheta)/2
midDDTheta = -Math.sin(midTheta * Math::PI / 180) * scaling
lastDTheta = midDTheta + midDDTheta
lastTheta = midTheta + (midDTheta + lastDTheta)/2
lastDDTheta = -Math.sin(lastTheta * Math::PI/180) * scaling
lastDTheta = midDTheta + (midDDTheta + lastDDTheta)/2
lastTheta = midTheta + (midDTheta + lastDTheta)/2
$dTheta = lastDTheta
$Theta = lastTheta
end
def animate
recompute_angle
show_pendulum
$after_id = $root.after(15) {animate}
end
show_pendulum
$after_id = $root.after(500) {animate}
$canvas.bind('<Destroy>') {$root.after_cancel($after_id)}
Tk.mainloop | 1,143Animate a pendulum
| 14ruby
| dtlns |
function amb (set)
local workset = {}
if (#set == 0) or (type(set) ~= 'table') then return end
if #set == 1 then return set end
if #set > 2 then
local first = table.remove(set,1)
set = amb(set)
for i,v in next,first do
for j,u in next,set do
if v:byte(#v) == u[1]:byte(1) then table.insert(workset, {v,unpack(u)}) end
end
end
return workset
end
for i,v in next,set[1] do
for j,u in next,set[2] do
if v:byte(#v) == u:byte(1) then table.insert(workset,{v,u}) end
end
end
return workset
end | 1,148Amb
| 1lua
| jk171 |
public class Integrator {
public interface Function {
double apply(double timeSinceStartInSeconds);
}
private final long start;
private volatile boolean running;
private Function func;
private double t0;
private double v0;
private double sum;
public Integrator(Function func) {
this.start = System.nanoTime();
setFunc(func);
new Thread(this::integrate).start();
}
public void setFunc(Function func) {
this.func = func;
v0 = func.apply(0.0);
t0 = 0;
}
public double getOutput() {
return sum;
}
public void stop() {
running = false;
}
private void integrate() {
running = true;
while (running) {
try {
Thread.sleep(1);
update();
} catch (InterruptedException e) {
return;
}
}
}
private void update() {
double t1 = (System.nanoTime() - start) / 1.0e9;
double v1 = func.apply(t1);
double rect = (t1 - t0) * (v0 + v1) / 2;
this.sum += rect;
t0 = t1;
v0 = v1;
}
public static void main(String[] args) throws InterruptedException {
Integrator integrator = new Integrator(t -> Math.sin(Math.PI * t));
Thread.sleep(2000);
integrator.setFunc(t -> 0.0);
Thread.sleep(500);
integrator.stop();
System.out.println(integrator.getOutput());
}
} | 1,157Active object
| 9java
| 08ese |
expand p = scanl (\z i -> z * (p-i+1) `div` i) 1 [1..p]
test p | p < 2 = False
| otherwise = and [mod n p == 0 | n <- init . tail $ expand p]
printPoly [1] = "1"
printPoly p = concat [ unwords [pow i, sgn (l-i), show (p!!(i-1))]
| i <- [l-1,l-2..1] ] where
l = length p
sgn i = if even i then "+" else "-"
pow i = take i "x^" ++ if i > 1 then show i else ""
main = do
putStrLn "
putStrLn $ unlines [show i ++ ": " ++ printPoly (expand i) | i <- [0..10]]
putStrLn "
print (filter test [1..100]) | 1,153AKS test for primes
| 8haskell
| papbt |
>>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))
>>> fib = lambda f: lambda n: None if n < 0 else (0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2)))
>>> [ Y(fib)(i) for i in range(-2, 10) ]
[None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34] | 1,138Anonymous recursion
| 3python
| rj8gq |
null | 1,143Animate a pendulum
| 15rust
| fz2d6 |
function Integrator(sampleIntervalMS) {
var inputF = function () { return 0.0 };
var sum = 0.0;
var t1 = new Date().getTime();
var input1 = inputF(t1 / 1000);
function update() {
var t2 = new Date().getTime();
var input2 = inputF(t2 / 1000);
var dt = (t2 - t1) / 1000;
sum += (input1 + input2) * dt / 2;
t1 = t2;
input1 = input2;
}
var updater = setInterval(update, sampleIntervalMS);
return ({
input: function (newF) { inputF = newF },
output: function () { return sum },
shutdown: function () { clearInterval(updater) },
});
} | 1,157Active object
| 10javascript
| df0nu |
import java.awt.Color
import java.util.concurrent.{Executors, TimeUnit}
import scala.swing.{Graphics2D, MainFrame, Panel, SimpleSwingApplication}
import scala.swing.Swing.pair2Dimension
object Pendulum extends SimpleSwingApplication {
val length = 100
lazy val ui = new Panel {
import scala.math.{cos, Pi, sin}
background = Color.white
preferredSize = (2 * length + 50, length / 2 * 3)
peer.setDoubleBuffered(true)
var angle: Double = Pi / 2
override def paintComponent(g: Graphics2D): Unit = {
super.paintComponent(g)
val (anchorX, anchorY) = (size.width / 2, size.height / 4)
val (ballX, ballY) =
(anchorX + (sin(angle) * length).toInt, anchorY + (cos(angle) * length).toInt)
g.setColor(Color.lightGray)
g.drawLine(anchorX - 2 * length, anchorY, anchorX + 2 * length, anchorY)
g.setColor(Color.black)
g.drawLine(anchorX, anchorY, ballX, ballY)
g.fillOval(anchorX - 3, anchorY - 4, 7, 7)
g.drawOval(ballX - 7, ballY - 7, 14, 14)
g.setColor(Color.yellow)
g.fillOval(ballX - 7, ballY - 7, 14, 14)
}
val animate: Runnable = new Runnable {
var angleVelocity = 0.0
var dt = 0.1
override def run(): Unit = {
angleVelocity += -9.81 / length * Math.sin(angle) * dt
angle += angleVelocity * dt
repaint()
}
}
}
override def top = new MainFrame {
title = "Rosetta Code >>> Task: Animate a pendulum | Language: Scala"
contents = ui
centerOnScreen()
Executors.
newSingleThreadScheduledExecutor().
scheduleAtFixedRate(ui.animate, 0, 15, TimeUnit.MILLISECONDS)
}
} | 1,143Animate a pendulum
| 16scala
| 3y5zy |
null | 1,157Active object
| 11kotlin
| ewka4 |
use ntheory qw/divisor_sum/;
sub aliquot {
my($n, $maxterms, $maxn) = @_;
$maxterms = 16 unless defined $maxterms;
$maxn = 2**47 unless defined $maxn;
my %terms = ($n => 1);
my @allterms = ($n);
for my $term (2 .. $maxterms) {
$n = divisor_sum($n)-$n;
last if $n > $maxn;
return ("terminates",@allterms, 0) if $n == 0;
if (defined $terms{$n}) {
return ("perfect",@allterms) if $term == 2 && $terms{$n} == 1;
return ("amicible",@allterms) if $term == 3 && $terms{$n} == 1;
return ("sociable-".($term-1),@allterms) if $term > 3 && $terms{$n} == 1;
return ("aspiring",@allterms) if $terms{$n} == $term-1;
return ("cyclic-".($term-$terms{$n}),@allterms) if $terms{$n} < $term-1;
}
$terms{$n} = $term;
push @allterms, $n;
}
("non-term",@allterms);
}
for my $n (1..10) {
my($class, @seq) = aliquot($n);
printf "%14d%10s [@seq]\n", $n, $class;
}
print "\n";
for my $n (qw/11 12 28 496 220 1184 12496 1264460 790 909 562 1064 1488 15355717786080/) {
my($class, @seq) = aliquot($n);
printf "%14d%10s [@seq]\n", $n, $class;
} | 1,151Aliquot sequence classifications
| 2perl
| 4rr5d |
func angleDifference(a1: Double, a2: Double) -> Double {
let diff = (a2 - a1).truncatingRemainder(dividingBy: 360)
if diff < -180.0 {
return 360.0 + diff
} else if diff > 180.0 {
return -360.0 + diff
} else {
return diff
}
}
let testCases = [
(20.0, 45.0),
(-45, 45),
(-85, 90),
(-95, 90),
(-45, 125),
(-45, 145),
(29.4803, -88.6381),
(-78.3251, -159.036),
(-70099.74233810938, 29840.67437876723),
(-165313.6666297357, 33693.9894517456),
(1174.8380510598456, -154146.66490124757),
(60175.77306795546, 42213.07192354373)
]
print(testCases.map(angleDifference)) | 1,142Angle difference between two bearings
| 17swift
| hb0j0 |
local seconds = os.clock
local integrator = {
new = function(self, fn)
return setmetatable({fn=fn,t0=seconds(),v0=0,sum=0,nup=0},self)
end,
update = function(self)
self.t1 = seconds()
self.v1 = self.fn(self.t1)
self.sum = self.sum + (self.v0 + self.v1) * (self.t1 - self.t0) / 2
self.t0, self.v0, self.nup = self.t1, self.v1, self.nup+1
end,
input = function(self, fn) self.fn = fn end,
output = function(self) return self.sum end,
}
integrator.__index = integrator | 1,157Active object
| 1lua
| wxbea |
public class AksTest {
private static final long[] c = new long[64];
public static void main(String[] args) {
for (int n = 0; n < 10; n++) {
coeff(n);
show(n);
}
System.out.print("Primes:");
for (int n = 1; n < c.length; n++)
if (isPrime(n))
System.out.printf("%d", n);
System.out.println();
}
static void coeff(int n) {
c[0] = 1;
for (int i = 0; i < n; c[0] = -c[0], i++) {
c[1 + i] = 1;
for (int j = i; j > 0; j--)
c[j] = c[j - 1] - c[j];
}
}
static boolean isPrime(int n) {
coeff(n);
c[0]++;
c[n]--;
int i = n;
while (i-- != 0 && c[i] % n == 0)
continue;
return i < 0;
}
static void show(int n) {
System.out.print("(x-1)^" + n + " =");
for (int i = n; i >= 0; i--) {
System.out.print(" + " + c[i] + "x^" + i);
}
System.out.println();
}
} | 1,153AKS test for primes
| 9java
| rjrg0 |
using System;
class ColumnAlignerProgram
{
delegate string Justification(string s, int width);
static string[] AlignColumns(string[] lines, Justification justification)
{
const char Separator = '$';
string[][] table = new string[lines.Length][];
int columns = 0;
for (int i = 0; i < lines.Length; i++)
{
string[] row = lines[i].TrimEnd(Separator).Split(Separator);
if (columns < row.Length) columns = row.Length;
table[i] = row;
}
string[][] formattedTable = new string[table.Length][];
for (int i = 0; i < formattedTable.Length; i++)
{
formattedTable[i] = new string[columns];
}
for (int j = 0; j < columns; j++)
{
int columnWidth = 0;
for (int i = 0; i < table.Length; i++)
{
if (j < table[i].Length && columnWidth < table[i][j].Length)
columnWidth = table[i][j].Length;
}
for (int i = 0; i < formattedTable.Length; i++)
{
if (j < table[i].Length)
formattedTable[i][j] = justification(table[i][j], columnWidth);
else
formattedTable[i][j] = new String(' ', columnWidth);
}
}
string[] result = new string[formattedTable.Length];
for (int i = 0; i < result.Length; i++)
{
result[i] = String.Join(, formattedTable[i]);
}
return result;
}
static string JustifyLeft(string s, int width) { return s.PadRight(width); }
static string JustifyRight(string s, int width) { return s.PadLeft(width); }
static string JustifyCenter(string s, int width)
{
return s.PadLeft((width + s.Length) / 2).PadRight(width);
}
static void Main()
{
string[] input = {
,
,
,
,
,
,
};
foreach (string line in AlignColumns(input, JustifyCenter))
{
Console.WriteLine(line);
}
}
} | 1,160Align columns
| 5c
| ftqd3 |
var i, p, pascal, primerow, primes, show, _i;
pascal = function() {
var a;
a = [];
return function() {
var b, i;
if (a.length === 0) {
return a = [1];
} else {
b = (function() {
var _i, _ref, _results;
_results = [];
for (i = _i = 0, _ref = a.length - 1; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
_results.push(a[i] + a[i + 1]);
}
return _results;
})();
return a = [1].concat(b).concat([1]);
}
};
};
show = function(a) {
var degree, i, sgn, show_x, str, _i, _ref;
show_x = function(e) {
switch (e) {
case 0:
return "";
case 1:
return "x";
default:
return "x^" + e;
}
};
degree = a.length - 1;
str = "(x - 1)^" + degree + " =";
sgn = 1;
for (i = _i = 0, _ref = a.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
str += ' ' + (sgn > 0 ? "+" : "-") + ' ' + a[i] + show_x(degree - i);
sgn = -sgn;
}
return str;
};
primerow = function(row) {
var degree;
degree = row.length - 1;
return row.slice(1, degree).every(function(x) {
return x % degree === 0;
});
};
p = pascal();
for (i = _i = 0; _i <= 7; i = ++_i) {
console.log(show(p()));
}
p = pascal();
p();
p();
primes = (function() {
var _j, _results;
_results = [];
for (i = _j = 1; _j <= 49; i = ++_j) {
if (primerow(p())) {
_results.push(i + 1);
}
}
return _results;
})();
console.log("");
console.log("The primes upto 50 are: " + primes); | 1,153AKS test for primes
| 10javascript
| b1bki |
use ntheory qw/factor/;
sub almost {
my($k,$n) = @_;
my $i = 1;
map { $i++ while scalar factor($i) != $k; $i++ } 1..$n;
}
say "$_: ", join(" ", almost($_,10)) for 1..5; | 1,147Almost prime
| 2perl
| id3o3 |
fib2 <- function(n) {
(n >= 0) || stop("bad argument")
( function(n) if (n <= 1) 1 else Recall(n-1)+Recall(n-2) )(n)
} | 1,138Anonymous recursion
| 13r
| u4xvx |
def is_prime(n: int) -> bool:
if n <= 3:
return n > 1
if n% 2 == 0 or n% 3 == 0:
return False
i = 5
while i ** 2 <= n:
if n% i == 0 or n% (i + 2) == 0:
return False
i += 6
return True
def digit_sum(n: int) -> int:
sum = 0
while n > 0:
sum += n% 10
n
return sum
def main() -> None:
additive_primes = 0
for i in range(2, 500):
if is_prime(i) and is_prime(digit_sum(i)):
additive_primes += 1
print(i, end=)
print(f)
if __name__ == :
main() | 1,154Additive primes
| 3python
| 54vux |
package main
import "fmt"
func accumulator(sum interface{}) func(interface{}) interface{} {
return func(nv interface{}) interface{} {
switch s := sum.(type) {
case int:
switch n := nv.(type) {
case int:
sum = s + n
case float64:
sum = float64(s) + n
}
case float64:
switch n := nv.(type) {
case int:
sum = s + float64(n)
case float64:
sum = s + n
}
default:
sum = nv
}
return sum
}
}
func main() {
x := accumulator(1)
x(5)
accumulator(3)
fmt.Println(x(2.3))
} | 1,159Accumulator factory
| 0go
| dfqne |