code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
import java.util.Base64 object Base64Decode extends App { def text2BinaryDecoding(encoded: String): String = { val decoded = Base64.getDecoder.decode(encoded) new String(decoded, "UTF-8") } def data = "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g=" println(text2BinaryDecoding(data)) }
1,112Base64 decode data
16scala
925m5
void barnsleyFern(int windowWidth, unsigned long iter){ double x0=0,y0=0,x1,y1; int diceThrow; time_t t; srand((unsigned)time(&t)); while(iter>0){ diceThrow = rand()%100; if(diceThrow==0){ x1 = 0; y1 = 0.16*y0; } else if(diceThrow>=1 && diceThrow<=7){ x1 = -0.15*x0 + 0.28*y0; y1 = 0.26*x0 + 0.24*y0 + 0.44; } else if(diceThrow>=8 && diceThrow<=15){ x1 = 0.2*x0 - 0.26*y0; y1 = 0.23*x0 + 0.22*y0 + 1.6; } else{ x1 = 0.85*x0 + 0.04*y0; y1 = -0.04*x0 + 0.85*y0 + 1.6; } putpixel(30*x1 + windowWidth/2.0,30*y1,GREEN); x0 = x1; y0 = y1; iter--; } } int main() { unsigned long num; printf(); scanf(,&num); initwindow(500,500,); barnsleyFern(500,num); getch(); closegraph(); return 0; }
1,114Barnsley fern
5c
t6yf4
package main import ( "fmt" "math" ) func main() { const n = 10 sum := 0. for x := 1.; x <= n; x++ { sum += x * x } fmt.Println(math.Sqrt(sum / n)) }
1,113Averages/Root mean square
0go
yc264
def quadMean = { list -> list == null \ ? null \ : list.empty \ ? 0 \ : ((list.collect { it*it }.sum()) / list.size()) ** 0.5 }
1,113Averages/Root mean square
7groovy
f3ydn
main = print $ mean 2 [1 .. 10]
1,113Averages/Root mean square
8haskell
hpaju
public class RootMeanSquare { public static double rootMeanSquare(double... nums) { double sum = 0.0; for (double num : nums) sum += num * num; return Math.sqrt(sum / nums.length); } public static void main(String[] args) { double[] nums = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0}; System.out.println("The RMS of the numbers from 1 to 10 is " + rootMeanSquare(nums)); } }
1,113Averages/Root mean square
9java
5rjuf
function root_mean_square(ary) { var sum_of_squares = ary.reduce(function(s,x) {return (s + x*x)}, 0); return Math.sqrt(sum_of_squares / ary.length); } print( root_mean_square([1,2,3,4,5,6,7,8,9,10]) );
1,113Averages/Root mean square
10javascript
jb17n
null
1,113Averages/Root mean square
11kotlin
cv598
function sumsq(a, ...) return a and a^2 + sumsq(...) or 0 end function rms(t) return (sumsq(unpack(t)) / #t)^.5 end print(rms{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
1,113Averages/Root mean square
1lua
lu4ck
package main import ( "image" "image/color" "image/draw" "image/png" "log" "math/rand" "os" )
1,114Barnsley fern
0go
hp1jq
import javafx.animation.AnimationTimer import javafx.application.Application import javafx.scene.Group import javafx.scene.Scene import javafx.scene.image.ImageView import javafx.scene.image.WritableImage import javafx.scene.paint.Color import javafx.stage.Stage class BarnsleyFern extends Application { @Override void start(Stage primaryStage) { primaryStage.title = 'Barnsley Fern' primaryStage.scene = getScene() primaryStage.show() } def getScene() { def root = new Group() def scene = new Scene(root, 640, 640) def imageWriter = new WritableImage(640, 640) def imageView = new ImageView(imageWriter) root.children.add imageView def pixelWriter = imageWriter.pixelWriter def x = 0, y = 0 ({ 50.times { def r = Math.random() if (r <= 0.01) { x = 0 y = 0.16 * y } else if (r <= 0.08) { x = 0.2 * x - 0.26 * y y = 0.23 * x + 0.22 * y + 1.6 } else if (r <= 0.15) { x = -0.15 * x + 0.28 * y y = 0.26 * x + 0.24 * y + 0.44 } else { x = 0.85 * x + 0.04 * y y = -0.04 * x + 0.85 * y + 1.6 } pixelWriter.setColor(Math.round(640 / 2 + x * 640 / 11) as Integer, Math.round(640 - y * 640 / 11) as Integer, Color.GREEN) } } as AnimationTimer).start() scene } static void main(args) { launch(BarnsleyFern) } }
1,114Barnsley fern
7groovy
47j5f
import Data.List (scanl') import Diagrams.Backend.Rasterific.CmdLine import Diagrams.Prelude import System.Random type Pt = (Double, Double) f1, f2, f3, f4:: Pt -> Pt f1 (x, y) = ( 0, 0.16 * y) f2 (x, y) = ( 0.85 * x + 0.04 * y , -0.04 * x + 0.85 * y + 1.60) f3 (x, y) = ( 0.20 * x - 0.26 * y , 0.23 * x + 0.22 * y + 1.60) f4 (x, y) = (-0.15 * x + 0.28 * y , 0.26 * x + 0.24 * y + 0.44) func:: Pt -> Double -> Pt func p r | r < 0.01 = f1 p | r < 0.86 = f2 p | r < 0.93 = f3 p | otherwise = f4 p fern:: [Double] -> [Pt] fern = scanl' func (0, 0) drawFern :: [Double] -> Int -> Diagram B drawFern rs n = frame 0.5 . diagramFrom . take n $ fern rs where diagramFrom = flip atPoints (repeat dot) . map p2 dot = circle 0.005 # lc green main :: IO () main = do rand <- getStdGen mainWith $ drawFern (randomRs (0, 1) rand)
1,114Barnsley fern
8haskell
iftor
typedef struct sma_obj { double sma; double sum; int period; double *values; int lv; } sma_obj_t; typedef union sma_result { sma_obj_t *handle; double sma; double *values; } sma_result_t; enum Action { SMA_NEW, SMA_FREE, SMA_VALUES, SMA_ADD, SMA_MEAN }; sma_result_t sma(enum Action action, ...) { va_list vl; sma_result_t r; sma_obj_t *o; double v; va_start(vl, action); switch(action) { case SMA_NEW: r.handle = malloc(sizeof(sma_obj_t)); r.handle->sma = 0.0; r.handle->period = va_arg(vl, int); r.handle->values = malloc(r.handle->period * sizeof(double)); r.handle->lv = 0; r.handle->sum = 0.0; break; case SMA_FREE: r.handle = va_arg(vl, sma_obj_t *); free(r.handle->values); free(r.handle); r.handle = NULL; break; case SMA_VALUES: o = va_arg(vl, sma_obj_t *); r.values = o->values; break; case SMA_MEAN: o = va_arg(vl, sma_obj_t *); r.sma = o->sma; break; case SMA_ADD: o = va_arg(vl, sma_obj_t *); v = va_arg(vl, double); if ( o->lv < o->period ) { o->values[o->lv++] = v; o->sum += v; o->sma = o->sum / o->lv; } else { o->sum -= o->values[ o->lv % o->period]; o->sum += v; o->sma = o->sum / o->period; o->values[ o->lv % o->period ] = v; o->lv++; } r.sma = o->sma; break; } va_end(vl); return r; }
1,115Averages/Simple moving average
5c
255lo
import java.awt.*; import java.awt.image.BufferedImage; import javax.swing.*; public class BarnsleyFern extends JPanel { BufferedImage img; public BarnsleyFern() { final int dim = 640; setPreferredSize(new Dimension(dim, dim)); setBackground(Color.white); img = new BufferedImage(dim, dim, BufferedImage.TYPE_INT_ARGB); createFern(dim, dim); } void createFern(int w, int h) { double x = 0; double y = 0; for (int i = 0; i < 200_000; i++) { double tmpx, tmpy; double r = Math.random(); if (r <= 0.01) { tmpx = 0; tmpy = 0.16 * y; } else if (r <= 0.08) { tmpx = 0.2 * x - 0.26 * y; tmpy = 0.23 * x + 0.22 * y + 1.6; } else if (r <= 0.15) { tmpx = -0.15 * x + 0.28 * y; tmpy = 0.26 * x + 0.24 * y + 0.44; } else { tmpx = 0.85 * x + 0.04 * y; tmpy = -0.04 * x + 0.85 * y + 1.6; } x = tmpx; y = tmpy; img.setRGB((int) Math.round(w / 2 + x * w / 11), (int) Math.round(h - y * h / 11), 0xFF32CD32); } } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.drawImage(img, 0, 0, null); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Barnsley Fern"); f.setResizable(false); f.add(new BarnsleyFern(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
1,114Barnsley fern
9java
x08wy
(import '[clojure.lang PersistentQueue]) (defn enqueue-max [q p n] (let [q (conj q n)] (if (<= (count q) p) q (pop q)))) (defn avg [coll] (/ (reduce + coll) (count coll))) (defn init-moving-avg [p] (let [state (atom PersistentQueue/EMPTY)] (fn [n] (avg (swap! state enqueue-max p n)))))
1,115Averages/Simple moving average
6clojure
gjj4f
null
1,114Barnsley fern
10javascript
odf86
null
1,114Barnsley fern
11kotlin
pewb6
use v5.10.0; sub rms { my $r = 0; $r += $_**2 for @_; sqrt( $r/@_ ); } say rms(1..10);
1,113Averages/Root mean square
2perl
x0ow8
<?php function rms(array $numbers) { $sum = 0; foreach ($numbers as $number) { $sum += $number**2; } return sqrt($sum / count($numbers)); } echo rms(array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
1,113Averages/Root mean square
12php
25gl4
g = love.graphics wid, hei = g.getWidth(), g.getHeight() function choose( i, j ) local r = math.random() if r < .01 then return 0, .16 * j elseif r < .07 then return .2 * i - .26 * j, .23 * i + .22 * j + 1.6 elseif r < .14 then return -.15 * i + .28 * j, .26 * i + .24 * j + .44 else return .85 * i + .04 * j, -.04 * i + .85 * j + 1.6 end end function createFern( iterations ) local hw, x, y, scale = wid / 2, 0, 0, 45 local pts = {} for k = 1, iterations do pts[1] = { hw + x * scale, hei - 15 - y * scale, 20 + math.random( 80 ), 128 + math.random( 128 ), 20 + math.random( 80 ), 150 } g.points( pts ) x, y = choose( x, y ) end end function love.load() math.randomseed( os.time() ) canvas = g.newCanvas( wid, hei ) g.setCanvas( canvas ) createFern( 15e4 ) g.setCanvas() end function love.draw() g.draw( canvas ) end
1,114Barnsley fern
1lua
1wxpo
int main() { int current = 0, square; while (((square=current*current) % 1000000 != 269696) && (square<INT_MAX)) { current++; } if (square>+INT_MAX) printf(); else printf (, current); return 0 ; }
1,116Babbage problem
5c
peaby
use Imager; my $w = 640; my $h = 640; my $img = Imager->new(xsize => $w, ysize => $h, channels => 3); my $green = Imager::Color->new(' my ($x, $y) = (0, 0); foreach (1 .. 2e5) { my $r = rand(100); ($x, $y) = do { if ($r <= 1) { ( 0.00 * $x - 0.00 * $y, 0.00 * $x + 0.16 * $y + 0.00) } elsif ($r <= 8) { ( 0.20 * $x - 0.26 * $y, 0.23 * $x + 0.22 * $y + 1.60) } elsif ($r <= 15) { (-0.15 * $x + 0.28 * $y, 0.26 * $x + 0.24 * $y + 0.44) } else { ( 0.85 * $x + 0.04 * $y, -0.04 * $x + 0.85 * $y + 1.60) } }; $img->setpixel(x => $w / 2 + $x * 60, y => $y * 60, color => $green); } $img->flip(dir => 'v'); $img->write(file => 'barnsleyFern.png');
1,114Barnsley fern
2perl
ycl6u
>>> from math import sqrt >>> def qmean(num): return sqrt(sum(n*n for n in num)/len(num)) >>> qmean(range(1,11)) 6.2048368229954285
1,113Averages/Root mean square
3python
q8ixi
RMS <- function(x, na.rm = F) sqrt(mean(x^2, na.rm = na.rm)) RMS(1:10) RMS(c(NA, 1:10)) RMS(c(NA, 1:10), na.rm = T)
1,113Averages/Root mean square
13r
axs1z
(defn babbage? [n] (let [square (* n n)] (= 269696 (mod square 1000000)))) (first (filter babbage? (range)))
1,116Babbage problem
6clojure
x0swk
import random from PIL import Image class BarnsleyFern(object): def __init__(self, img_width, img_height, paint_color=(0, 150, 0), bg_color=(255, 255, 255)): self.img_width, self.img_height = img_width, img_height self.paint_color = paint_color self.x, self.y = 0, 0 self.age = 0 self.fern = Image.new('RGB', (img_width, img_height), bg_color) self.pix = self.fern.load() self.pix[self.scale(0, 0)] = paint_color def scale(self, x, y): h = (x + 2.182)*(self.img_width - 1)/4.8378 k = (9.9983 - y)*(self.img_height - 1)/9.9983 return h, k def transform(self, x, y): rand = random.uniform(0, 100) if rand < 1: return 0, 0.16*y elif 1 <= rand < 86: return 0.85*x + 0.04*y, -0.04*x + 0.85*y + 1.6 elif 86 <= rand < 93: return 0.2*x - 0.26*y, 0.23*x + 0.22*y + 1.6 else: return -0.15*x + 0.28*y, 0.26*x + 0.24*y + 0.44 def iterate(self, iterations): for _ in range(iterations): self.x, self.y = self.transform(self.x, self.y) self.pix[self.scale(self.x, self.y)] = self.paint_color self.age += iterations fern = BarnsleyFern(500, 500) fern.iterate(1000000) fern.fern.show()
1,114Barnsley fern
3python
ml2yh
class Array def quadratic_mean Math.sqrt( self.inject(0.0) {|s, y| s + y*y} / self.length ) end end class Range def quadratic_mean self.to_a.quadratic_mean end end (1..10).quadratic_mean
1,113Averages/Root mean square
14ruby
0idsu
pBarnsleyFern <- function(fn, n, clr, ttl, psz=600) { cat(" *** START:", date(), "n=", n, "clr=", clr, "psz=", psz, "\n"); cat(" *** File name -", fn, "\n"); pf = paste0(fn,".png"); A1 <- matrix(c(0,0,0,0.16,0.85,-0.04,0.04,0.85,0.2,0.23,-0.26,0.22,-0.15,0.26,0.28,0.24), ncol=4, nrow=4, byrow=TRUE); A2 <- matrix(c(0,0,0,1.6,0,1.6,0,0.44), ncol=2, nrow=4, byrow=TRUE); P <- c(.01,.85,.07,.07); M1=vector("list", 4); M2 = vector("list", 4); for (i in 1:4) { M1[[i]] <- matrix(c(A1[i,1:4]), nrow=2); M2[[i]] <- matrix(c(A2[i, 1:2]), nrow=2); } x <- numeric(n); y <- numeric(n); x[1] <- y[1] <- 0; for (i in 1:(n-1)) { k <- sample(1:4, prob=P, size=1); M <- as.matrix(M1[[k]]); z <- M%*%c(x[i],y[i]) + M2[[k]]; x[i+1] <- z[1]; y[i+1] <- z[2]; } plot(x, y, main=ttl, axes=FALSE, xlab="", ylab="", col=clr, cex=0.1); dev.copy(png, filename=pf,width=psz,height=psz); dev.off(); graphics.off(); cat(" *** END:",date(),"\n"); } pBarnsleyFern("BarnsleyFernR", 100000, "dark green", "Barnsley Fern Fractal", psz=600)
1,114Barnsley fern
13r
zymth
fn root_mean_square(vec: Vec<i32>) -> f32 { let sum_squares = vec.iter().fold(0, |acc, &x| acc + x.pow(2)); return ((sum_squares as f32)/(vec.len() as f32)).sqrt(); } fn main() { let vec = (1..11).collect(); println!("The root mean square is: {}", root_mean_square(vec)); }
1,113Averages/Root mean square
15rust
8nf07
def rms(nums: Seq[Int]) = math.sqrt(nums.map(math.pow(_, 2)).sum / nums.size) println(rms(1 to 10))
1,113Averages/Root mean square
16scala
nt3ic
main() { var x = 0; while((x*x)% 1000000!= 269696) { x++;} print('$x'); }
1,116Babbage problem
18dart
rhjgz
package main import "fmt" func sma(period int) func(float64) float64 { var i int var sum float64 var storage = make([]float64, 0, period) return func(input float64) (avrg float64) { if len(storage) < period { sum += input storage = append(storage, input) } sum += input - storage[i] storage[i], i = input, (i+1)%period avrg = sum / float64(len(storage)) return } } func main() { sma3 := sma(3) sma5 := sma(5) fmt.Println("x sma3 sma5") for _, x := range []float64{1, 2, 3, 4, 5, 5, 4, 3, 2, 1} { fmt.Printf("%5.3f %5.3f %5.3f\n", x, sma3(x), sma5(x)) } }
1,115Averages/Simple moving average
0go
q88xz
def simple_moving_average = { size -> def nums = [] double total = 0.0 return { newElement -> nums += newElement oldestElement = nums.size() > size ? nums.remove(0): 0 total += newElement - oldestElement total / nums.size() } } ma5 = simple_moving_average(5) (1..5).each{ printf( "%1.1f ", ma5(it)) } (5..1).each{ printf( "%1.1f ", ma5(it)) }
1,115Averages/Simple moving average
7groovy
1wwp6
MAX_ITERATIONS = 200_000 def setup sketch_title 'Barnsley Fern' no_loop puts 'Be patient. This takes about 10 seconds to render.' end def draw background 0 load_pixels x0 = 0.0 y0 = 0.0 x = 0.0 y = 0.0 MAX_ITERATIONS.times do r = rand(100) if r < 85 x = 0.85 * x0 + 0.04 * y0 y = -0.04 * x0 + 0.85 * y0 + 1.6 elsif r < 92 x = 0.2 * x0 - 0.26 * y0 y = 0.23 * x0 + 0.22 * y0 + 1.6 elsif r < 99 x = -0.15 * x0 + 0.28 * y0 y = 0.26 * x0 + 0.24 * y0 + 0.44 else x = 0 y = 0.16 * y end i = height - (y * 48).to_i j = width / 2 + (x * 48).to_i pixels[i * height + j] += 2_560 x0 = x y0 = y end update_pixels end def settings size 500, 500 end
1,114Barnsley fern
14ruby
cvu9k
import Control.Monad import Data.List import Data.IORef data Pair a b = Pair !a !b mean :: Fractional a => [a] -> a mean = divl . foldl' (\(Pair s l) x -> Pair (s+x) (l+1)) (Pair 0.0 0) where divl (_,0) = 0.0 divl (s,l) = s / fromIntegral l series = [1,2,3,4,5,5,4,3,2,1] mkSMA:: Int -> IO (Double -> IO Double) mkSMA period = avgr <$> newIORef [] where avgr nsref x = readIORef nsref >>= (\ns -> let xs = take period (x:ns) in writeIORef nsref xs $> mean xs) main = mkSMA 3 >>= (\sma3 -> mkSMA 5 >>= (\sma5 -> mapM_ (str <$> pure n <*> sma3 <*> sma5) series)) where str n mm3 mm5 = concat ["Next number = ",show n,", SMA_3 = ",show mm3,", SMA_5 = ",show mm5]
1,115Averages/Simple moving average
8haskell
mllyf
extern crate rand; extern crate raster; use rand::Rng; fn main() { let max_iterations = 200_000u32; let height = 640i32; let width = 640i32; let mut rng = rand::thread_rng(); let mut image = raster::Image::blank(width, height); raster::editor::fill(&mut image, raster::Color::white()).unwrap(); let mut x = 0.; let mut y = 0.; for _ in 0..max_iterations { let r = rng.gen::<f32>(); let cx: f64; let cy: f64; if r <= 0.01 { cx = 0f64; cy = 0.16 * y as f64; } else if r <= 0.08 { cx = 0.2 * x as f64 - 0.26 * y as f64; cy = 0.23 * x as f64 + 0.22 * y as f64 + 1.6; } else if r <= 0.15 { cx = -0.15 * x as f64 + 0.28 * y as f64; cy = 0.26 * x as f64 + 0.26 * y as f64 + 0.44; } else { cx = 0.85 * x as f64 + 0.04 * y as f64; cy = -0.04 * x as f64 + 0.85 * y as f64 + 1.6; } x = cx; y = cy; let _ = image.set_pixel( ((width as f64) / 2. + x * (width as f64) / 11.).round() as i32, ((height as f64) - y * (height as f64) / 11.).round() as i32, raster::Color::rgb(50, 205, 50)); } raster::save(&image, "fractal.png").unwrap(); }
1,114Barnsley fern
15rust
lu5cc
import java.awt._ import java.awt.image.BufferedImage import javax.swing._ object BarnsleyFern extends App { SwingUtilities.invokeLater(() => new JFrame("Barnsley Fern") { private class BarnsleyFern extends JPanel { val dim = 640 val img = new BufferedImage(dim, dim, BufferedImage.TYPE_INT_ARGB) private def createFern(w: Int, h: Int): Unit = { var x, y = 0.0 for (i <- 0 until 200000) { var tmpx, tmpy = .0 val r = math.random if (r <= 0.01) { tmpx = 0 tmpy = 0.16 * y } else if (r <= 0.08) { tmpx = 0.2 * x - 0.26 * y tmpy = 0.23 * x + 0.22 * y + 1.6 } else if (r <= 0.15) { tmpx = -0.15 * x + 0.28 * y tmpy = 0.26 * x + 0.24 * y + 0.44 } else { tmpx = 0.85 * x + 0.04 * y tmpy = -0.04 * x + 0.85 * y + 1.6 } x = tmpx y = tmpy img.setRGB((w / 2 + tmpx * w / 11).round.toInt, (h - tmpy * h / 11).round.toInt, 0xFF32CD32) } } override def paintComponent(gg: Graphics): Unit = { super.paintComponent(gg) val g = gg.asInstanceOf[Graphics2D] g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) g.drawImage(img, 0, 0, null) } setBackground(Color.white) setPreferredSize(new Dimension(dim, dim)) createFern(dim, dim) } add(new BarnsleyFern, BorderLayout.CENTER) pack() setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE) setLocationRelativeTo(null) setResizable(false) setVisible(true) }) }
1,114Barnsley fern
16scala
ugrv8
extension Collection where Element: FloatingPoint { @inlinable public func rms() -> Element { return (lazy.map({ $0 * $0 }).reduce(0, +) / Element(count)).squareRoot() } } print("RMS of 1...10: \((1...10).map(Double.init).rms())")
1,113Averages/Root mean square
17swift
sonqt
import java.util.LinkedList; import java.util.Queue; public class MovingAverage { private final Queue<Double> window = new LinkedList<Double>(); private final int period; private double sum; public MovingAverage(int period) { assert period > 0: "Period must be a positive integer"; this.period = period; } public void newNum(double num) { sum += num; window.add(num); if (window.size() > period) { sum -= window.remove(); } } public double getAvg() { if (window.isEmpty()) return 0.0;
1,115Averages/Simple moving average
9java
f33dv
function simple_moving_averager(period) { var nums = []; return function(num) { nums.push(num); if (nums.length > period) nums.splice(0,1);
1,115Averages/Simple moving average
10javascript
ycc6r
import UIKit import CoreImage import PlaygroundSupport let imageWH = 300 let context = CGContext(data: nil, width: imageWH, height: imageWH, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue)! var x0 = 0.0 var x1 = 0.0 var y0 = 0.0 var y1 = 0.0 context.setFillColor(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)) context.fill(CGRect(x: 0, y: 0, width: imageWH, height: imageWH)) context.setFillColor(#colorLiteral(red: 0.539716677, green: 1, blue: 0.265400682, alpha: 1)) for _ in 0..<100_000 { switch Int(arc4random())% 100 { case 0: x1 = 0 y1 = 0.16 * y0 case 1...7: x1 = -0.15 * x0 + 0.28 * y0 y1 = 0.26 * x0 + 0.24 * y0 + 0.44 case 8...15: x1 = 0.2 * x0 - 0.26 * y0 y1 = 0.23 * x0 + 0.22 * y0 + 1.6 default: x1 = 0.85 * x0 + 0.04 * y0 y1 = -0.04 * x0 + 0.85 * y0 + 1.6 } context.fill(CGRect(x: 30 * x1 + Double(imageWH) / 2.0, y: 30 * y1, width: 1, height: 1)) (x0, y0) = (x1, y1) } let uiImage = UIImage(cgImage: context.makeImage()!)
1,114Barnsley fern
17swift
92vmj
null
1,115Averages/Simple moving average
11kotlin
8nn0q
function sma(period) local t = {} function sum(a, ...) if a then return a+sum(...) else return 0 end end function average(n) if #t == period then table.remove(t, 1) end t[#t + 1] = n return sum(unpack(t)) / #t end return average end sma5 = sma(5) sma10 = sma(10) print("SMA 5") for v=1,15 do print(sma5(v)) end print("\nSMA 10") for v=1,15 do print(sma10(v)) end
1,115Averages/Simple moving average
1lua
odd8h
int main(int argc, char* argv[]) { int i, count=0; double f, sum=0.0, prod=1.0, resum=0.0; for (i=1; i<argc; ++i) { f = atof(argv[i]); count++; sum += f; prod *= f; resum += (1.0/f); } printf(,sum/count); printf(,pow(prod,(1.0/count))); printf(,count/resum); return 0; }
1,117Averages/Pythagorean means
5c
wsxec
package main import "fmt" func main() { const ( target = 269696 modulus = 1000000 ) for n := 1; ; n++ {
1,116Babbage problem
0go
69m3p
int n=104;
1,116Babbage problem
7groovy
dztn3
typedef struct { double v; int c; } vcount; int cmp_dbl(const void *a, const void *b) { double x = *(const double*)a - *(const double*)b; return x < 0 ? -1 : x > 0; } int vc_cmp(const void *a, const void *b) { return ((const vcount*)b)->c - ((const vcount*)a)->c; } int get_mode(double* x, int len, vcount **list) { int i, j; vcount *vc; qsort(x, len, sizeof(double), cmp_dbl); for (i = 0, j = 1; i < len - 1; i++, j += (x[i] != x[i + 1])); *list = vc = malloc(sizeof(vcount) * j); vc[0].v = x[0]; vc[0].c = 1; for (i = j = 0; i < len - 1; i++, vc[j].c++) if (x[i] != x[i + 1]) vc[++j].v = x[i + 1]; qsort(vc, j + 1, sizeof(vcount), vc_cmp); for (i = 0; i <= j && vc[i].c == vc[0].c; i++); return i; } int main() { double values[] = { 1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 12, 12, 17 }; vcount *vc; int i, n_modes = get_mode(values, len, &vc); printf(, n_modes); for (i = 0; i < n_modes; i++) printf(, vc[i].v, vc[i].c); free(vc); return 0; }
1,118Averages/Mode
5c
cvc9c
findBabbageNumber :: Integer findBabbageNumber = head (filter ((269696 ==) . flip mod 1000000 . (^ 2)) [1 ..]) main :: IO () main = (putStrLn . unwords) (zipWith (++) (show <$> ([id, (^ 2)] <*> [findBabbageNumber])) [" ^ 2 equals", "!"])
1,116Babbage problem
8haskell
jbk7g
(use '[clojure.contrib.math:only (expt)]) (defn a-mean [coll] (/ (apply + coll) (count coll))) (defn g-mean [coll] (expt (apply * coll) (/ (count coll)))) (defn h-mean [coll] (/ (count coll) (apply + (map / coll)))) (let [numbers (range 1 11) a (a-mean numbers) g (g-mean numbers) h (h-mean numbers)] (println a ">=" g ">=" h) (>= a g h))
1,117Averages/Pythagorean means
6clojure
8no05
public class Test { public static void main(String[] args) {
1,116Babbage problem
9java
ug4vv
(defn modes [coll] (let [distrib (frequencies coll) [value freq] [first second] sorted (sort-by (comp - freq) distrib) maxfq (freq (first sorted))] (map value (take-while #(= maxfq (freq %)) sorted))))
1,118Averages/Mode
6clojure
5r5uz
null
1,116Babbage problem
10javascript
7khrd
void reverse(char *p) { size_t len = strlen(p); char *r = p + len - 1; while (p < r) { *p ^= *r; *r ^= *p; *p++ ^= *r--; } } void to_bt(int n, char *b) { static char d[] = { '0', '+', '-' }; static int v[] = { 0, 1, -1 }; char *ptr = b; *ptr = 0; while (n) { int r = n % 3; if (r < 0) { r += 3; } *ptr = d[r]; *(++ptr) = 0; n -= v[r]; n /= 3; } reverse(b); } int from_bt(const char *a) { int n = 0; while (*a != '\0') { n *= 3; if (*a == '+') { n++; } else if (*a == '-') { n--; } a++; } return n; } char last_char(char *ptr) { char c; if (ptr == NULL || *ptr == '\0') { return '\0'; } while (*ptr != '\0') { ptr++; } ptr--; c = *ptr; *ptr = 0; return c; } void add(const char *b1, const char *b2, char *out) { if (*b1 != '\0' && *b2 != '\0') { char c1[16]; char c2[16]; char ob1[16]; char ob2[16]; char d[3] = { 0, 0, 0 }; char L1, L2; strcpy(c1, b1); strcpy(c2, b2); L1 = last_char(c1); L2 = last_char(c2); if (L2 < L1) { L2 ^= L1; L1 ^= L2; L2 ^= L1; } if (L1 == '-') { if (L2 == '0') { d[0] = '-'; } if (L2 == '-') { d[0] = '+'; d[1] = '-'; } } if (L1 == '+') { if (L2 == '0') { d[0] = '+'; } if (L2 == '-') { d[0] = '0'; } if (L2 == '+') { d[0] = '-'; d[1] = '+'; } } if (L1 == '0') { if (L2 == '0') { d[0] = '0'; } } add(c1, &d[1], ob1); add(ob1, c2, ob2); strcpy(out, ob2); d[1] = 0; strcat(out, d); } else if (*b1 != '\0') { strcpy(out, b1); } else if (*b2 != '\0') { strcpy(out, b2); } else { *out = '\0'; } } void unary_minus(const char *b, char *out) { while (*b != '\0') { if (*b == '-') { *out++ = '+'; b++; } else if (*b == '+') { *out++ = '-'; b++; } else { *out++ = *b++; } } *out = '\0'; } void subtract(const char *b1, const char *b2, char *out) { char buf[16]; unary_minus(b2, buf); add(b1, buf, out); } void mult(const char *b1, const char *b2, char *out) { char r[16] = ; char t[16]; char c1[16]; char c2[16]; char *ptr = c2; strcpy(c1, b1); strcpy(c2, b2); reverse(c2); while (*ptr != '\0') { if (*ptr == '+') { add(r, c1, t); strcpy(r, t); } if (*ptr == '-') { subtract(r, c1, t); strcpy(r, t); } strcat(c1, ); ptr++; } ptr = r; while (*ptr == '0') { ptr++; } strcpy(out, ptr); } int main() { const char *a = ; char b[16]; const char *c = ; char t[16]; char d[16]; to_bt(-436, b); subtract(b, c, t); mult(a, t, d); printf(, a, from_bt(a)); printf(, b, from_bt(b)); printf(, c, from_bt(c)); printf(, d, from_bt(d)); return 0; }
1,119Balanced ternary
5c
lv9cy
fun main(args: Array<String>) { var number = 520L var square = 520 * 520L while (true) { val last6 = square.toString().takeLast(6) if (last6 == "269696") { println("The smallest number is $number whose square is $square") return } number += 2 square = number * number } }
1,116Babbage problem
11kotlin
92lmh
typedef struct { int hour, minute, second; } digitime; double timeToDegrees (digitime time) { return (360 * time.hour / 24.0 + 360 * time.minute / (24 * 60.0) + 360 * time.second / (24 * 3600.0)); } digitime timeFromDegrees (double angle) { digitime d; double totalSeconds = 24 * 60 * 60 * angle / 360; d.second = (int) totalSeconds % 60; d.minute = ((int) totalSeconds % 3600 - d.second) / 60; d.hour = (int) totalSeconds / 3600; return d; } double meanAngle (double *angles, int size) { double y_part = 0, x_part = 0; int i; for (i = 0; i < size; i++) { x_part += cos (angles[i] * M_PI / 180); y_part += sin (angles[i] * M_PI / 180); } return atan2 (y_part / size, x_part / size) * 180 / M_PI; } int main () { digitime *set, meanTime; int inputs, i; double *angleSet, angleMean; printf (); scanf (, &inputs); set = malloc (inputs * sizeof (digitime)); angleSet = malloc (inputs * sizeof (double)); printf (); for (i = 0; i < inputs; i++) { scanf (, &set[i].hour, &set[i].minute, &set[i].second); angleSet[i] = timeToDegrees (set[i]); } meanTime = timeFromDegrees (360 + meanAngle (angleSet, inputs)); printf (, meanTime.hour, meanTime.minute, meanTime.second); return 0; }
1,120Averages/Mean time of day
5c
z6dtx
null
1,116Babbage problem
1lua
cv292
template <class T> class AVLnode { public: T key; int balance; AVLnode *left, *right, *parent; AVLnode(T k, AVLnode *p) : key(k), balance(0), parent(p), left(NULL), right(NULL) {} ~AVLnode() { delete left; delete right; } }; template <class T> class AVLtree { public: AVLtree(void); ~AVLtree(void); bool insert(T key); void deleteKey(const T key); void printBalance(); private: AVLnode<T> *root; AVLnode<T>* rotateLeft ( AVLnode<T> *a ); AVLnode<T>* rotateRight ( AVLnode<T> *a ); AVLnode<T>* rotateLeftThenRight ( AVLnode<T> *n ); AVLnode<T>* rotateRightThenLeft ( AVLnode<T> *n ); void rebalance ( AVLnode<T> *n ); int height ( AVLnode<T> *n ); void setBalance ( AVLnode<T> *n ); void printBalance ( AVLnode<T> *n ); }; template <class T> void AVLtree<T>::rebalance(AVLnode<T> *n) { setBalance(n); if (n->balance == -2) { if (height(n->left->left) >= height(n->left->right)) n = rotateRight(n); else n = rotateLeftThenRight(n); } else if (n->balance == 2) { if (height(n->right->right) >= height(n->right->left)) n = rotateLeft(n); else n = rotateRightThenLeft(n); } if (n->parent != NULL) { rebalance(n->parent); } else { root = n; } } template <class T> AVLnode<T>* AVLtree<T>::rotateLeft(AVLnode<T> *a) { AVLnode<T> *b = a->right; b->parent = a->parent; a->right = b->left; if (a->right != NULL) a->right->parent = a; b->left = a; a->parent = b; if (b->parent != NULL) { if (b->parent->right == a) { b->parent->right = b; } else { b->parent->left = b; } } setBalance(a); setBalance(b); return b; } template <class T> AVLnode<T>* AVLtree<T>::rotateRight(AVLnode<T> *a) { AVLnode<T> *b = a->left; b->parent = a->parent; a->left = b->right; if (a->left != NULL) a->left->parent = a; b->right = a; a->parent = b; if (b->parent != NULL) { if (b->parent->right == a) { b->parent->right = b; } else { b->parent->left = b; } } setBalance(a); setBalance(b); return b; } template <class T> AVLnode<T>* AVLtree<T>::rotateLeftThenRight(AVLnode<T> *n) { n->left = rotateLeft(n->left); return rotateRight(n); } template <class T> AVLnode<T>* AVLtree<T>::rotateRightThenLeft(AVLnode<T> *n) { n->right = rotateRight(n->right); return rotateLeft(n); } template <class T> int AVLtree<T>::height(AVLnode<T> *n) { if (n == NULL) return -1; return 1 + std::max(height(n->left), height(n->right)); } template <class T> void AVLtree<T>::setBalance(AVLnode<T> *n) { n->balance = height(n->right) - height(n->left); } template <class T> void AVLtree<T>::printBalance(AVLnode<T> *n) { if (n != NULL) { printBalance(n->left); std::cout << n->balance << ; printBalance(n->right); } } template <class T> AVLtree<T>::AVLtree(void) : root(NULL) {} template <class T> AVLtree<T>::~AVLtree(void) { delete root; } template <class T> bool AVLtree<T>::insert(T key) { if (root == NULL) { root = new AVLnode<T>(key, NULL); } else { AVLnode<T> *n = root, *parent; while (true) { if (n->key == key) return false; parent = n; bool goLeft = n->key > key; n = goLeft ? n->left : n->right; if (n == NULL) { if (goLeft) { parent->left = new AVLnode<T>(key, parent); } else { parent->right = new AVLnode<T>(key, parent); } rebalance(parent); break; } } } return true; } template <class T> void AVLtree<T>::deleteKey(const T delKey) { if (root == NULL) return; AVLnode<T> *n = root, *parent = root, *delNode = NULL, *child = root; while (child != NULL) { parent = n; n = child; child = delKey >= n->key ? n->right : n->left; if (delKey == n->key) delNode = n; } if (delNode != NULL) { delNode->key = n->key; child = n->left != NULL ? n->left : n->right; if (root->key == delKey) { root = child; } else { if (parent->left == n) { parent->left = child; } else { parent->right = child; } rebalance(parent); } } } template <class T> void AVLtree<T>::printBalance() { printBalance(root); std::cout << std::endl; } int main(void) { AVLtree<int> t; std::cout << << std::endl; for (int i = 1; i <= 10; ++i) t.insert(i); std::cout << ; t.printBalance(); }
1,121AVL tree
5c
6mf32
double meanAngle (double *angles, int size) { double y_part = 0, x_part = 0; int i; for (i = 0; i < size; i++) { x_part += cos (angles[i] * M_PI / 180); y_part += sin (angles[i] * M_PI / 180); } return atan2 (y_part / size, x_part / size) * 180 / M_PI; } int main () { double angleSet1[] = { 350, 10 }; double angleSet2[] = { 90, 180, 270, 360}; double angleSet3[] = { 10, 20, 30}; printf (, meanAngle (angleSet1, 2)); printf (, meanAngle (angleSet2, 4)); printf (, meanAngle (angleSet3, 3)); return 0; }
1,122Averages/Mean angle
5c
lv6cy
double factorial(int n) { double f = 1; int i; for (i = 1; i <= n; i++) f *= i; return f; } double expected(int n) { double sum = 0; int i; for (i = 1; i <= n; i++) sum += factorial(n) / pow(n, i) / factorial(n - i); return sum; } int randint(int n) { int r, rmax = RAND_MAX / n * n; while ((r = rand()) >= rmax); return r / (RAND_MAX / n); } int test(int n, int times) { int i, count = 0; for (i = 0; i < times; i++) { int x = 1, bits = 0; while (!(bits & x)) { count++; bits |= x; x = 1 << randint(n); } } return count; } int main(void) { srand(time(0)); puts(); int n; for (n = 1; n <= MAX_N; n++) { int cnt = test(n, TIMES); double avg = (double)cnt / TIMES; double theory = expected(n); double diff = (avg / theory - 1) * 100; printf(, n, avg, theory, diff); } return 0; }
1,123Average loop length
5c
7hvrg
(defn mean-fn [k coll] (let [n (count coll) trig (get {:sin #(Math/sin %):cos #(Math/cos %)} k)] (* (/ 1 n) (reduce + (map trig coll))))) (defn mean-angle [degrees] (let [radians (map #(Math/toRadians %) degrees) a (mean-fn:sin radians) b (mean-fn:cos radians)] (Math/toDegrees (Math/atan2 a b))))
1,122Averages/Mean angle
6clojure
4rl5o
sub sma_generator { my $period = shift; my (@list, $sum); return sub { my $number = shift; push @list, $number; $sum += $number; $sum -= shift @list if @list > $period; return $sum / @list; } } my $sma = sma_generator(3); for (1, 2, 3, 2, 7) { printf "append $_ --> sma =%.2f (with period 3)\n", $sma->($_); }
1,115Averages/Simple moving average
2perl
4775d
package main import ( "fmt" "strings" )
1,119Balanced ternary
0go
xsewf
enum T { m('-', -1), z('0', 0), p('+', 1) final String symbol final int value private T(String symbol, int value) { this.symbol = symbol this.value = value } static T get(Object key) { switch (key) { case [m.value, m.symbol]: return m case [z.value, z.symbol]: return z case [p.value, p.symbol]: return p default: return null } } T negative() { T.get(-this.value) } String toString() { this.symbol } } class BalancedTernaryInteger { static final MINUS = new BalancedTernaryInteger(T.m) static final ZERO = new BalancedTernaryInteger(T.z) static final PLUS = new BalancedTernaryInteger(T.p) private static final LEADING_ZEROES = /^0+/ final String value BalancedTernaryInteger(String bt) { assert bt && bt.toSet().every { T.get(it) } value = bt ==~ LEADING_ZEROES ? T.z: bt.replaceAll(LEADING_ZEROES, ''); } BalancedTernaryInteger(BigInteger i) { this(i == 0 ? T.z.symbol: valueFromInt(i)); } BalancedTernaryInteger(T...tArray) { this(tArray.sum{ it.symbol }); } BalancedTernaryInteger(List<T> tList) { this(tList.sum{ it.symbol }); } private static String valueFromInt(BigInteger i) { assert i != null if (i < 0) return negate(valueFromInt(-i)) if (i == 0) return '' int bRem = (((i % 3) - 2) ?: -3) + 2 valueFromInt((i - bRem).intdiv(3)) + T.get(bRem) } private static String negate(String bt) { bt.collect{ T.get(it) }.inject('') { str, t -> str + (-t) } } private static final Map INITIAL_SUM_PARTS = [carry:T.z, sum:[]] private static final prepValueLen = { int len, String s -> s.padLeft(len + 1, T.z.symbol).collect{ T.get(it) } } private static final partCarrySum = { partialSum, carry, trit -> [carry: carry, sum: [trit] + partialSum] } private static final partSum = { parts, trits -> def carrySum = partCarrySum.curry(parts.sum) switch ((trits + parts.carry).sort()) { case [[T.m, T.m, T.m]]: return carrySum(T.m, T.z)
1,119Balanced ternary
7groovy
pakbo
(ns cyclelengths (:gen-class)) (defn factorial [n] " n! " (apply *' (range 1 (inc n)))) (defn pow [n i] " n^i" (apply *' (repeat i n))) (defn analytical [n] " Analytical Computation " (->>(range 1 (inc n)) (map #(/ (factorial n) (pow n %) (factorial (- n %)))) (reduce + 0))) (def TIMES 1000000) (defn single-test-cycle-length [n] " Single random test of cycle length " (loop [count 0 bits 0 x 1] (if (zero? (bit-and x bits)) (recur (inc count) (bit-or bits x) (bit-shift-left 1 (rand-int n))) count))) (defn avg-cycle-length [n times] " Average results of single tests of cycle lengths " (/ (reduce + (for [i (range times)] (single-test-cycle-length n))) times)) (println "\tAvg\t\tExp\t\tDiff") (doseq [q (range 1 21) :let [anal (double (analytical q)) avg (double (avg-cycle-length q TIMES)) diff (Math/abs (* 100 (- 1 (/ avg anal))))]] (println (format "%3d\t%.4f\t%.4f\t%.2f%%" q avg anal diff)))
1,123Average loop length
6clojure
parbd
data BalancedTernary = Bt [Int] zeroTrim a = if null s then [0] else s where s = fst $ foldl f ([],[]) a f (x,y) 0 = (x, y++[0]) f (x,y) z = (x++y++[z], []) btList (Bt a) = a instance Eq BalancedTernary where (==) a b = btList a == btList b btNormalize = listBt . _carry 0 where _carry c [] = if c == 0 then [] else [c] _carry c (a:as) = r:_carry cc as where (cc, r) = f $ (a+c) `quotRem` 3 where f (x, 2) = (x + 1, -1) f (x, -2) = (x - 1, 1) f x = x listBt = Bt . zeroTrim instance Show BalancedTernary where show = reverse . map (\d->case d of -1->'-'; 0->'0'; 1->'+') . btList strBt = Bt . zeroTrim.reverse.map (\c -> case c of '-' -> -1; '0' -> 0; '+' -> 1) intBt :: Integral a => a -> BalancedTernary intBt = fromIntegral . toInteger btInt = foldr (\a z -> a + 3 * z) 0 . btList listAdd a b = take (max (length a) (length b)) $ zipWith (+) (a++[0,0..]) (b++[0,0..]) instance Num BalancedTernary where negate = Bt . map negate . btList (+) x y = btNormalize $ listAdd (btList x) (btList y) (*) x y = btNormalize $ mul_ (btList x) (btList y) where mul_ _ [] = [] mul_ as b = foldr (\a z -> listAdd (map (a*) b) (0:z)) [] as signum (Bt a) = if a == [0] then 0 else Bt [last a] abs x = if signum x == Bt [-1] then negate x else x fromInteger = btNormalize . f where f 0 = [] f x = fromInteger (rem x 3): f (quot x 3) main = let (a,b,c) = (strBt "+-0++0+", intBt (-436), strBt "+-++-") r = a * (b - c) in do print $ map btInt [a,b,c] print $ r print $ btInt r
1,119Balanced ternary
8haskell
y9366
package main import "fmt" func main() { fmt.Println(mode([]int{2, 7, 1, 8, 2})) fmt.Println(mode([]int{2, 7, 1, 8, 2, 8})) } func mode(a []int) []int { m := make(map[int]int) for _, v := range a { m[v]++ } var mode []int var n int for k, v := range m { switch { case v < n: case v > n: n = v mode = append(mode[:0], k) default: mode = append(mode, k) } } return mode }
1,118Averages/Mode
0go
wsweg
typedef int bool; bool is_prime(int n) { int d = 5; if (n < 2) return FALSE; if (!(n % 2)) return n == 2; if (!(n % 3)) return n == 3; while (d *d <= n) { if (!(n % d)) return FALSE; d += 2; if (!(n % d)) return FALSE; d += 4; } return TRUE; } int count_prime_factors(int n) { int count = 0, f = 2; if (n == 1) return 0; if (is_prime(n)) return 1; while (TRUE) { if (!(n % f)) { count++; n /= f; if (n == 1) return count; if (is_prime(n)) f = n; } else if (f >= 3) f += 2; else f = 3; } } int main() { int i, n, count = 0; printf(, MAX); for (i = 1; i <= MAX; ++i) { n = count_prime_factors(i); if (is_prime(n)) { printf(, i); if (!(++count % 20)) printf(); } } printf(); return 0; }
1,124Attractive numbers
5c
fzsd3
def mode(Iterable col) { assert col def m = [:] col.each { m[it] = m[it] == null ? 1: m[it] + 1 } def keys = m.keySet().sort { -m[it] } keys.findAll { m[it] == m[keys[0]] } }
1,118Averages/Mode
7groovy
babky
package main import ( "errors" "fmt" "log" "math" "time" ) var inputs = []string{"23:00:17", "23:40:20", "00:12:45", "00:17:19"} func main() { tList := make([]time.Time, len(inputs)) const clockFmt = "15:04:05" var err error for i, s := range inputs { tList[i], err = time.Parse(clockFmt, s) if err != nil { log.Fatal(err) } } mean, err := meanTime(tList) if err != nil { log.Fatal(err) } fmt.Println(mean.Format(clockFmt)) } func meanTime(times []time.Time) (mean time.Time, err error) { if len(times) == 0 { err = errors.New("meanTime: no times specified") return } var ssum, csum float64 for _, t := range times { h, m, s := t.Clock() n := t.Nanosecond() fSec := (float64((h*60+m)*60+s) + float64(n)*1e-9) sin, cos := math.Sincos(fSec * math.Pi / (12 * 60 * 60)) ssum += sin csum += cos } if ssum == 0 && csum == 0 { err = errors.New("meanTime: mean undefined") return } _, dayFrac := math.Modf(1 + math.Atan2(ssum, csum)/(2*math.Pi)) return mean.Add(time.Duration(dayFrac * 24 * float64(time.Hour))), nil }
1,120Averages/Mean time of day
0go
kp7hz
package avl
1,121AVL tree
0go
pajbg
typedef struct floatList { float *list; int size; } *FloatList; int floatcmp( const void *a, const void *b) { if (*(const float *)a < *(const float *)b) return -1; else return *(const float *)a > *(const float *)b; } float median( FloatList fl ) { qsort( fl->list, fl->size, sizeof(float), floatcmp); return 0.5 * ( fl->list[fl->size/2] + fl->list[(fl->size-1)/2]); } int main() { static float floats1[] = { 5.1, 2.6, 6.2, 8.8, 4.6, 4.1 }; static struct floatList flist1 = { floats1, sizeof(floats1)/sizeof(float) }; static float floats2[] = { 5.1, 2.6, 8.8, 4.6, 4.1 }; static struct floatList flist2 = { floats2, sizeof(floats2)/sizeof(float) }; printf(, median(&flist1)); printf(, median(&flist2)); return 0; }
1,125Averages/Median
5c
0opst
import Prelude (foldr, maximum, (==), (+)) import Data.Map (insertWith', empty, filter, elems, keys) mode:: (Ord a) => [a] -> [a] mode xs = keys (filter (== maximum (elems counts)) counts) where counts = foldr (\x -> insertWith' (+) x 1) empty xs
1,118Averages/Mode
8haskell
6963k
import static java.lang.Math.* final format = 'HH:mm:ss', clock = PI / 12, millisPerHr = 3600*1000 final tzOffset = new Date(0).timezoneOffset / 60 def parseTime = { time -> (Date.parse(format, time).time / millisPerHr) - tzOffset } def formatTime = { time -> new Date((time + tzOffset) * millisPerHr as int).format(format) } def mean = { list, closure -> list.sum(closure)/list.size() } def meanTime = { ... timeStrings -> def times = timeStrings.collect(parseTime) formatTime(atan2( mean(times) { sin(it * clock) }, mean(times) { cos(it * clock) }) / clock) }
1,120Averages/Mean time of day
7groovy
g7u46
data Tree a = Leaf | Node Int (Tree a) a (Tree a) deriving (Show, Eq) foldTree :: Ord a => [a] -> Tree a foldTree = foldr insert Leaf height :: Tree a -> Int height Leaf = -1 height (Node h _ _ _) = h depth :: Tree a -> Tree a -> Int depth a b = succ (max (height a) (height b)) insert :: Ord a => a -> Tree a -> Tree a insert v Leaf = Node 1 Leaf v Leaf insert v t@(Node n left v_ right) | v_ < v = rotate $ Node n left v_ (insert v right) | v_ > v = rotate $ Node n (insert v left) v_ right | otherwise = t max_ :: Ord a => Tree a -> Maybe a max_ Leaf = Nothing max_ (Node _ _ v right) = case right of Leaf -> Just v _ -> max_ right delete :: Ord a => a -> Tree a -> Tree a delete _ Leaf = Leaf delete x (Node h left v right) | x == v = maybe left (rotate . (Node h left <*> (`delete` right))) (max_ right) | x > v = rotate $ Node h left v (delete x right) | x < v = rotate $ Node h (delete x left) v right rotate :: Tree a -> Tree a rotate Leaf = Leaf rotate (Node h (Node lh ll lv lr) v r) | lh - height r > 1 && height ll - height lr > 0 = Node lh ll lv (Node (depth r lr) lr v r) rotate (Node h l v (Node rh rl rv rr)) | rh - height l > 1 && height rr - height rl > 0 = Node rh (Node (depth l rl) l v rl) rv rr rotate (Node h (Node lh ll lv (Node rh rl rv rr)) v r) | lh - height r > 1 = Node h (Node (rh + 1) (Node (lh - 1) ll lv rl) rv rr) v r rotate (Node h l v (Node rh (Node lh ll lv lr) rv rr)) | rh - height l > 1 = Node h l v (Node (lh + 1) ll lv (Node (rh - 1) lr rv rr)) rotate (Node h l v r) = let (l_, r_) = (rotate l, rotate r) in Node (depth l_ r_) l_ v r_ draw :: Show a => Tree a -> String draw t = '\n': draw_ t 0 <> "\n" where draw_ Leaf _ = [] draw_ (Node h l v r) d = draw_ r (d + 1) <> node <> draw_ l (d + 1) where node = padding d <> show (v, h) <> "\n" padding n = replicate (n * 4) ' ' main :: IO () main = putStr $ draw $ foldTree [1 .. 31]
1,121AVL tree
8haskell
fzod1
public class BalancedTernary { public static void main(String[] args) { BTernary a=new BTernary("+-0++0+"); BTernary b=new BTernary(-436); BTernary c=new BTernary("+-++-"); System.out.println("a="+a.intValue()); System.out.println("b="+b.intValue()); System.out.println("c="+c.intValue()); System.out.println();
1,119Balanced ternary
9java
dtin9
use strict ; use warnings ; my $current = 0 ; while ( ($current ** 2 ) % 1000000 != 269696 ) { $current++ ; } print "The square of $current is " . ($current * $current) . "!\n" ;
1,116Babbage problem
2perl
wsqe6
pthread_mutex_t bucket_mutex[N_BUCKETS]; int buckets[N_BUCKETS]; pthread_t equalizer; pthread_t randomizer; void transfer_value(int from, int to, int howmuch) { bool swapped = false; if ( (from == to) || ( howmuch < 0 ) || (from < 0 ) || (to < 0) || (from >= N_BUCKETS) || (to >= N_BUCKETS) ) return; if ( from > to ) { int temp1 = from; from = to; to = temp1; swapped = true; howmuch = -howmuch; } pthread_mutex_lock(&bucket_mutex[from]); pthread_mutex_lock(&bucket_mutex[to]); if ( howmuch > buckets[from] && !swapped ) howmuch = buckets[from]; if ( -howmuch > buckets[to] && swapped ) howmuch = -buckets[to]; buckets[from] -= howmuch; buckets[to] += howmuch; pthread_mutex_unlock(&bucket_mutex[from]); pthread_mutex_unlock(&bucket_mutex[to]); } void print_buckets() { int i; int sum=0; for(i=0; i < N_BUCKETS; i++) pthread_mutex_lock(&bucket_mutex[i]); for(i=0; i < N_BUCKETS; i++) { printf(, buckets[i]); sum += buckets[i]; } printf(, sum); for(i=0; i < N_BUCKETS; i++) pthread_mutex_unlock(&bucket_mutex[i]); } void *equalizer_start(void *t) { for(;;) { int b1 = rand()%N_BUCKETS; int b2 = rand()%N_BUCKETS; int diff = buckets[b1] - buckets[b2]; if ( diff < 0 ) transfer_value(b2, b1, -diff/2); else transfer_value(b1, b2, diff/2); } return NULL; } void *randomizer_start(void *t) { for(;;) { int b1 = rand()%N_BUCKETS; int b2 = rand()%N_BUCKETS; int diff = rand()%(buckets[b1]+1); transfer_value(b1, b2, diff); } return NULL; } int main() { int i, total=0; for(i=0; i < N_BUCKETS; i++) pthread_mutex_init(&bucket_mutex[i], NULL); for(i=0; i < N_BUCKETS; i++) { buckets[i] = rand() % 100; total += buckets[i]; printf(, buckets[i]); } printf(, total); pthread_create(&equalizer, NULL, equalizer_start, NULL); pthread_create(&randomizer, NULL, randomizer_start, NULL); for(;;) { sleep(1); print_buckets(); } for(i=0; i < N_BUCKETS; i++) pthread_mutex_destroy(bucket_mutex+i); return EXIT_SUCCESS; }
1,126Atomic updates
5c
dtwnv
(defn update-map [base update] (merge base update)) (update-map {"name" "Rocket Skates" "price" "12.75" "color" "yellow"} {"price" "15.25" "color" "red" "year" "1974"})
1,127Associative array/Merging
6clojure
0oksj
import Data.Complex (cis, phase) import Data.List.Split (splitOn) import Text.Printf (printf) timeToRadians :: String -> Float timeToRadians time = let hours:minutes:seconds:_ = splitOn ":" time s = fromIntegral (read seconds :: Int) m = fromIntegral (read minutes :: Int) h = fromIntegral (read hours :: Int) in (2*pi)*(h+ (m + s/60.0 )/60.0 )/24.0 radiansToTime :: Float -> String radiansToTime r = let tau = pi*2 (_,fDay) = properFraction (r / tau) :: (Int, Float) fDayPositive = if fDay < 0 then 1.0+fDay else fDay (hours, fHours) = properFraction $ 24.0 * fDayPositive (minutes, fMinutes) = properFraction $ 60.0 * fHours seconds = 60.0 * fMinutes in printf "%0d" (hours::Int) ++ ":" ++ printf "%0d" (minutes::Int) ++ ":" ++ printf "%0.0f" (seconds::Float) meanAngle :: [Float] -> Float meanAngle = phase . sum . map cis main :: IO () main = putStrLn $ radiansToTime $ meanAngle $ map timeToRadians ["23:00:17", "23:40:20", "00:12:45", "00:17:19"]
1,120Averages/Mean time of day
8haskell
nf8ie
bool approxEquals(double value, double other, double epsilon) { return fabs(value - other) < epsilon; } void test(double a, double b) { double epsilon = 1e-18; printf(, a, b, approxEquals(a, b, epsilon)); } int main() { test(100000000000000.01, 100000000000000.011); test(100.01, 100.011); test(10000000000000.001 / 10000.0, 1000000000.0000001000); test(0.001, 0.0010000001); test(0.000000000000000000000101, 0.0); test(sqrt(2.0) * sqrt(2.0), 2.0); test(-sqrt(2.0) * sqrt(2.0), -2.0); test(3.14159265358979323846, 3.14159265358979324); return 0; }
1,128Approximate equality
5c
xsrwu
import java.util.*; public class Mode { public static <T> List<T> mode(List<? extends T> coll) { Map<T, Integer> seen = new HashMap<T, Integer>(); int max = 0; List<T> maxElems = new ArrayList<T>(); for (T value : coll) { if (seen.containsKey(value)) seen.put(value, seen.get(value) + 1); else seen.put(value, 1); if (seen.get(value) > max) { max = seen.get(value); maxElems.clear(); maxElems.add(value); } else if (seen.get(value) == max) { maxElems.add(value); } } return maxElems; } public static void main(String[] args) { System.out.println(mode(Arrays.asList(1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17)));
1,118Averages/Mode
9java
ntnih
main() { var base = { 'name': 'Rocket Skates', 'price': 12.75, 'color': 'yellow' }; var newData = { 'price': 15.25, 'color': 'red', 'year': 1974 }; var updated = Map.from( base )
1,127Associative array/Merging
18dart
hbljb
public class AVLtree { private Node root; private static class Node { private int key; private int balance; private int height; private Node left; private Node right; private Node parent; Node(int key, Node parent) { this.key = key; this.parent = parent; } } public boolean insert(int key) { if (root == null) { root = new Node(key, null); return true; } Node n = root; while (true) { if (n.key == key) return false; Node parent = n; boolean goLeft = n.key > key; n = goLeft ? n.left : n.right; if (n == null) { if (goLeft) { parent.left = new Node(key, parent); } else { parent.right = new Node(key, parent); } rebalance(parent); break; } } return true; } private void delete(Node node) { if (node.left == null && node.right == null) { if (node.parent == null) { root = null; } else { Node parent = node.parent; if (parent.left == node) { parent.left = null; } else { parent.right = null; } rebalance(parent); } return; } if (node.left != null) { Node child = node.left; while (child.right != null) child = child.right; node.key = child.key; delete(child); } else { Node child = node.right; while (child.left != null) child = child.left; node.key = child.key; delete(child); } } public void delete(int delKey) { if (root == null) return; Node child = root; while (child != null) { Node node = child; child = delKey >= node.key ? node.right : node.left; if (delKey == node.key) { delete(node); return; } } } private void rebalance(Node n) { setBalance(n); if (n.balance == -2) { if (height(n.left.left) >= height(n.left.right)) n = rotateRight(n); else n = rotateLeftThenRight(n); } else if (n.balance == 2) { if (height(n.right.right) >= height(n.right.left)) n = rotateLeft(n); else n = rotateRightThenLeft(n); } if (n.parent != null) { rebalance(n.parent); } else { root = n; } } private Node rotateLeft(Node a) { Node b = a.right; b.parent = a.parent; a.right = b.left; if (a.right != null) a.right.parent = a; b.left = a; a.parent = b; if (b.parent != null) { if (b.parent.right == a) { b.parent.right = b; } else { b.parent.left = b; } } setBalance(a, b); return b; } private Node rotateRight(Node a) { Node b = a.left; b.parent = a.parent; a.left = b.right; if (a.left != null) a.left.parent = a; b.right = a; a.parent = b; if (b.parent != null) { if (b.parent.right == a) { b.parent.right = b; } else { b.parent.left = b; } } setBalance(a, b); return b; } private Node rotateLeftThenRight(Node n) { n.left = rotateLeft(n.left); return rotateRight(n); } private Node rotateRightThenLeft(Node n) { n.right = rotateRight(n.right); return rotateLeft(n); } private int height(Node n) { if (n == null) return -1; return n.height; } private void setBalance(Node... nodes) { for (Node n : nodes) { reheight(n); n.balance = height(n.right) - height(n.left); } } public void printBalance() { printBalance(root); } private void printBalance(Node n) { if (n != null) { printBalance(n.left); System.out.printf("%s ", n.balance); printBalance(n.right); } } private void reheight(Node node) { if (node != null) { node.height = 1 + Math.max(height(node.left), height(node.right)); } } public static void main(String[] args) { AVLtree tree = new AVLtree(); System.out.println("Inserting values 1 to 10"); for (int i = 1; i < 10; i++) tree.insert(i); System.out.print("Printing balance: "); tree.printBalance(); } }
1,121AVL tree
9java
0owse
package main import ( "fmt" "math" "math/cmplx" ) func deg2rad(d float64) float64 { return d * math.Pi / 180 } func rad2deg(r float64) float64 { return r * 180 / math.Pi } func mean_angle(deg []float64) float64 { sum := 0i for _, x := range deg { sum += cmplx.Rect(1, deg2rad(x)) } return rad2deg(cmplx.Phase(sum)) } func main() { for _, angles := range [][]float64{ {350, 10}, {90, 180, 270, 360}, {10, 20, 30}, } { fmt.Printf("The mean angle of%v is:%f degrees\n", angles, mean_angle(angles)) } }
1,122Averages/Mean angle
0go
xspwf
(defn median [ns] (let [ns (sort ns) cnt (count ns) mid (bit-shift-right cnt 1)] (if (odd? cnt) (nth ns mid) (/ (+ (nth ns mid) (nth ns (dec mid))) 2))))
1,125Averages/Median
6clojure
dtxnb
null
1,119Balanced ternary
11kotlin
0oqsf
<?php for ( $i = 1 ; ($i * $i) % 1000000 !== 269696 ; $i++ ); echo $i, ' * ', $i, ' = ', ($i * $i), PHP_EOL;
1,116Babbage problem
12php
luvcj
int isBal(const char*s,int l){ signed c=0; while(l--) if(s[l]==']') ++c; else if(s[l]=='[') if(--c<0) break; return !c; } void shuffle(char*s,int h){ int x,t,i=h; while(i--){ t=s[x=rand()%h]; s[x]=s[i]; s[i]=t; } } void genSeq(char*s,int n){ if(n){ memset(s,'[',n); memset(s+n,']',n); shuffle(s,n*2); } s[n*2]=0; } void doSeq(int n){ char s[64]; const char *o=; genSeq(s,n); if(isBal(s,n*2)) o=; printf(,s,o); } int main(){ int n=0; while(n<9) doSeq(n++); return 0; }
1,129Balanced brackets
5c
y9s6f
(defn xfer [m from to amt] (let [{f-bal from t-bal to} m f-bal (- f-bal amt) t-bal (+ t-bal amt)] (if (or (neg? f-bal) (neg? t-bal)) (throw (IllegalArgumentException. "Call results in negative balance.")) (assoc m from f-bal to t-bal))))
1,126Atomic updates
6clojure
6m83q
function mode(ary) { var counter = {}; var mode = []; var max = 0; for (var i in ary) { if (!(ary[i] in counter)) counter[ary[i]] = 0; counter[ary[i]]++; if (counter[ary[i]] == max) mode.push(ary[i]); else if (counter[ary[i]] > max) { max = counter[ary[i]]; mode = [ary[i]]; } } return mode; } mode([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]);
1,118Averages/Mode
10javascript
3m3z0
package main import ( "fmt" "math" "math/rand" ) const nmax = 20 func main() { fmt.Println(" N average analytical (error)") fmt.Println("=== ========= ============ =========") for n := 1; n <= nmax; n++ { a := avg(n) b := ana(n) fmt.Printf("%3d %9.4f %12.4f (%6.2f%%)\n", n, a, b, math.Abs(a-b)/b*100) } } func avg(n int) float64 { const tests = 1e4 sum := 0 for t := 0; t < tests; t++ { var v [nmax]bool for x := 0; !v[x]; x = rand.Intn(n) { v[x] = true sum++ } } return float64(sum) / tests } func ana(n int) float64 { nn := float64(n) term := 1. sum := 1. for i := nn - 1; i >= 1; i-- { term *= i / nn sum += term } return sum }
1,123Average loop length
0go
dtsne
from collections import deque def simplemovingaverage(period): assert period == int(period) and period > 0, summ = n = 0.0 values = deque([0.0] * period) def sma(x): nonlocal summ, n values.append(x) summ += x - values.popleft() n = min(n+1, period) return summ / n return sma
1,115Averages/Simple moving average
3python
gjj4h
public class MeanTimeOfDay { static double meanAngle(double[] angles) { int len = angles.length; double sinSum = 0.0; for (int i = 0; i < len; i++) { sinSum += Math.sin(angles[i] * Math.PI / 180.0); } double cosSum = 0.0; for (int i = 0; i < len; i++) { cosSum += Math.cos(angles[i] * Math.PI / 180.0); } return Math.atan2(sinSum / len, cosSum / len) * 180.0 / Math.PI; } static int timeToSecs(String t) { int hours = Integer.parseInt(t.substring(0, 2)); int mins = Integer.parseInt(t.substring(3, 5)); int secs = Integer.parseInt(t.substring(6, 8)); return 3600 * hours + 60 * mins + secs; } static double timeToDegrees(String t) { return timeToSecs(t) / 240.0; } static String degreesToTime(double d) { if (d < 0.0) d += 360.0; int secs = (int)(d * 240.0); int hours = secs / 3600; int mins = secs % 3600; secs = mins % 60; mins /= 60; return String.format("%2d:%2d:%2d", hours, mins, secs); } public static void main(String[] args) { String[] tm = {"23:00:17", "23:40:20", "00:12:45", "00:17:19"}; double[] angles = new double[4]; for (int i = 0; i < 4; i++) angles[i] = timeToDegrees(tm[i]); double mean = meanAngle(angles); System.out.println("Average time is: " + degreesToTime(mean)); } }
1,120Averages/Mean time of day
9java
q0exa
function tree(less, val, more) { return { depth: 1+Math.max(less.depth, more.depth), less: less, val: val, more: more, }; } function node(val) { return tree({depth: 0}, val, {depth: 0}); } function insert(x,y) { if (0 == y.depth) return x; if (0 == x.depth) return y; if (1 == x.depth && 1 == y.depth) { switch (Math.sign(y.val)-x.val) { case -1: return tree(y, x.val, {depth: 0}); case 0: return y; case 1: return tree(x, y.val, {depth: 0}); } } switch (Math.sign(y.val-x.val)) { case -1: return balance(insert(x.less, y), x.val, x.more); case 0: return balance(insert(x.less, y.less), x.val, insert(x.more, y.more)); case 1: return balance(x.less. x.val, insert(x.more, y)); } } function balance(less,val,more) { if (2 > Math.abs(less.depth-more.depth)) return tree(less,val,more); if (more.depth > less.depth) { if (more.more.depth >= more.less.depth) {
1,121AVL tree
10javascript
dt8nu
import static java.lang.Math.* def meanAngle = { atan2( it.sum { sin(it * PI / 180) } / it.size(), it.sum { cos(it * PI / 180) } / it.size()) * 180 / PI }
1,122Averages/Mean angle
7groovy
pa7bo
import Data.Complex (cis, phase) meanAngle :: RealFloat c => [c] -> c meanAngle = (/ pi) . (* 180) . phase . sum . map (cis . (/ 180) . (* pi)) main :: IO () main = mapM_ (\angles -> putStrLn $ "The mean angle of " ++ show angles ++ " is: " ++ show (meanAngle angles) ++ " degrees") [[350, 10], [90, 180, 270, 360], [10, 20, 30]]
1,122Averages/Mean angle
8haskell
y9f66
int main(){ int a; assert(a == 42); return 0; }
1,130Assertions
5c
v5n2o
package main import "fmt" type assoc map[string]interface{} func merge(base, update assoc) assoc { result := make(assoc) for k, v := range base { result[k] = v } for k, v := range update { result[k] = v } return result } func main() { base := assoc{"name": "Rocket Skates", "price": 12.75, "color": "yellow"} update := assoc{"price": 15.25, "color": "red", "year": 1974} result := merge(base, update) fmt.Println(result) }
1,127Associative array/Merging
0go
9limt
data Item = Item { name :: Maybe String , price :: Maybe Float , color :: Maybe String , year :: Maybe Int } deriving (Show) itemFromMerge :: Item -> Item -> Item itemFromMerge (Item n p c y) (Item n1 p1 c1 y1) = Item (maybe n pure n1) (maybe p pure p1) (maybe c pure c1) (maybe y pure y1) main :: IO () main = print $ itemFromMerge (Item (Just "Rocket Skates") (Just 12.75) (Just "yellow") Nothing) (Item Nothing (Just 15.25) (Just "red") (Just 1974))
1,127Associative array/Merging
8haskell
b1vk2
import System.Random import qualified Data.Set as S import Text.Printf findRep :: (Random a, Integral a, RandomGen b) => a -> b -> (a, b) findRep n gen = findRep' (S.singleton 1) 1 gen where findRep' seen len gen' | S.member fx seen = (len, gen'') | otherwise = findRep' (S.insert fx seen) (len + 1) gen'' where (fx, gen'') = randomR (1, n) gen' statistical:: (Integral a, Random b, Integral b, RandomGen c, Fractional d) => a -> b -> c -> (d, c) statistical samples size gen = let (total, gen') = sar samples gen 0 in ((fromIntegral total) / (fromIntegral samples), gen') where sar 0 gen' acc = (acc, gen') sar samples' gen' acc = let (len, gen'') = findRep size gen' in sar (samples' - 1) gen'' (acc + len) factorial:: (Integral a) => a -> a factorial n = foldl (*) 1 [1..n] analytical:: (Integral a, Fractional b) => a -> b analytical n = sum [fromIntegral num / fromIntegral (factorial (n - i)) / fromIntegral (n ^ i) | i <- [1..n]] where num = factorial n test:: (Integral a, Random b, Integral b, PrintfArg b, RandomGen c) => a -> [b] -> c -> IO c test _ [] gen = return gen test samples (x:xs) gen = do let (st, gen') = statistical samples x gen an = analytical x err = abs (st - an) / st * 100.0 str = printf "%3d %9.4f %12.4f (%6.2f%%)\n" x (st :: Float) (an :: Float) (err :: Float) putStr str test samples xs gen' main:: IO () main = do putStrLn " N average analytical (error)" putStrLn "=== ========= ============ =========" let samples = 10000:: Integer range = [1..20]:: [Integer] _ <- test samples range $ mkStdGen 0 return ()
1,123Average loop length
8haskell
5g9ug