code stringlengths 1 46.1k ⌀ | label class label 1.18k
classes | domain_label class label 21
classes | index stringlengths 4 5 |
|---|---|---|---|
import java.util.HashMap;
import java.util.Map;
public class MutualRecursion {
public static void main(final String args[]) {
int max = 20;
System.out.printf("First%d values of the Female sequence: %n", max);
for (int i = 0; i < max; i++) {
System.out.printf(" f(%d) =%d%n", i,... | 542Mutual recursion | 9java | n74ih |
use strict;
use feature 'say';
use Data::Monad::List;
my @cartesian = [(
list_flat_map_multi { scalar_list(join '', @_) }
scalar_list(0..1),
scalar_list(0..1),
scalar_list(0..1)
)->scalars];
say join "\n", @{shift @cartesian};
say '';
my @triples = [(
list_flat_map_multi { scalar_li... | 553Monads/List monad | 2perl | lq4c5 |
use strict;
use warnings;
use Statistics::Regression;
my @y = (52.21, 53.12, 54.48, 55.84, 57.20, 58.57, 59.93, 61.29, 63.11, 64.47, 66.28, 68.10, 69.92, 72.19, 74.46);
my @x = ( 1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63, 1.65, 1.68, 1.70, 1.73, 1.75, 1.78, 1.80, 1.83);
my @model = ('const', 'X', 'X**2... | 548Multiple regression | 2perl | 61436 |
import Control.Monad
import Data.List
queens :: Int -> [[Int]]
queens n = map fst $ foldM oneMoreQueen ([],[1..n]) [1..n] where
oneMoreQueen (y,d) _ = [(x:y, delete x d) | x <- d, safe x] where
safe x = and [x /= c + n && x /= c - n | (n,c) <- zip [1..] y]
printSolution y = d... | 543N-queens problem | 8haskell | yak66 |
function f(num) {
return (num === 0) ? 1 : num - m(f(num - 1));
}
function m(num) {
return (num === 0) ? 0 : num - f(m(num - 1));
}
function range(m, n) {
return Array.apply(null, Array(n - m + 1)).map(
function (x, i) { return m + i; }
);
}
var a = range(0, 19); | 542Mutual recursion | 10javascript | 3phz0 |
package main
import (
"fmt"
"strconv"
)
type maybe struct{ value *int }
func (m maybe) bind(f func(p *int) maybe) maybe {
return f(m.value)
}
func unit(p *int) maybe {
return maybe{p}
}
func decrement(p *int) maybe {
if p == nil {
return unit(nil)
} else {
q := *p - 1
... | 555Monads/Maybe monad | 0go | 05isk |
null | 550Move-to-front algorithm | 11kotlin | k3qh3 |
class WriterMonad {
private $value;
private $logs;
private function __construct($value, array $logs = []) {
$this->value = $value;
$this->logs = $logs;
}
public static function unit($value, string $log): WriterMonad {
return new WriterMonad($value, []);
}
public function bind(callable $mapper): Wri... | 554Monads/Writer monad | 12php | n7zig |
from __future__ import annotations
from itertools import chain
from typing import Any
from typing import Callable
from typing import Iterable
from typing import List
from typing import TypeVar
T = TypeVar()
class MList(List[T]):
@classmethod
def unit(cls, value: Iterable[T]) -> MList[T]:
return cls... | 553Monads/List monad | 3python | 2sglz |
main = do print $ Just 3 >>= (return . (*2)) >>= (return . (+1))
print $ Nothing >>= (return . (*2)) >>= (return . (+1)) | 555Monads/Maybe monad | 8haskell | cxv94 |
null | 550Move-to-front algorithm | 1lua | b6ska |
int mul_inv(int a, int b)
{
int b0 = b, t, q;
int x0 = 0, x1 = 1;
if (b == 1) return 1;
while (a > 1) {
q = a / b;
t = b, b = a % b, a = t;
t = x0, x0 = x1 - q * x0, x1 = t;
}
if (x1 < 0) x1 += b0;
return x1;
}
int main(void) {
printf(, mul_inv(42, 2017));
return 0;
} | 556Modular inverse | 5c | gn745 |
from __future__ import annotations
import functools
import math
import os
from typing import Any
from typing import Callable
from typing import Generic
from typing import List
from typing import TypeVar
from typing import Union
T = TypeVar()
class Writer(Generic[T]):
def __init__(self, value: Union[T, Writer[... | 554Monads/Writer monad | 3python | rdkgq |
import numpy as np
height = [1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63,
1.65, 1.68, 1.70, 1.73, 1.75, 1.78, 1.80, 1.83]
weight = [52.21, 53.12, 54.48, 55.84, 57.20, 58.57, 59.93,
61.29, 63.11, 64.47, 66.28, 68.10, 69.92, 72.19, 74.46]
X = np.mat(height**np.arange(3)[:, None])
y = np.mat(weight)
print(y * X.T ... | 548Multiple regression | 3python | yag6q |
use 5.10.0;
my %irregulars = ( 1 => 'st',
2 => 'nd',
3 => 'rd',
11 => 'th',
12 => 'th',
13 => 'th');
sub nth
{
my $n = shift;
$n .
($irregulars{$n % 100} // $irregulars{$n % 10} // 'th');
}
sub range { join ' ', ma... | 540N'th | 2perl | wlce6 |
(function () {
'use strict'; | 555Monads/Maybe monad | 10javascript | 9w2ml |
class Array
def bind(f)
flat_map(&f)
end
def self.unit(*args)
args
end
def self.lift(f)
-> e { self.unit(f[e]) }
end
end
inc = -> n { n + 1 }
str = -> n { n.to_s }
listy_inc = Array.lift(inc)
listy_str = Array.lift(str)
Array.unit(3,4,5).bind(listy_inc).bind(listy_str)
doub = -> n... | 553Monads/List monad | 14ruby | u87vz |
object MultiDimensionalArray extends App { | 547Multi-dimensional array | 16scala | qv3xw |
x <- c(1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63, 1.65, 1.68, 1.70, 1.73, 1.75, 1.78, 1.80, 1.83)
y <- c(52.21, 53.12, 54.48, 55.84, 57.20, 58.57, 59.93, 61.29, 63.11, 64.47, 66.28, 68.10, 69.92, 72.19, 74.46)
lm( y ~ x + I(x^2)) | 548Multiple regression | 13r | tkvfz |
package main
import "fmt"
func multiFactorial(n, k int) int {
r := 1
for ; n > 1; n -= k {
r *= n
}
return r
}
func main() {
for k := 1; k <= 5; k++ {
fmt.Print("degree ", k, ":")
for n := 1; n <= 10; n++ {
fmt.Print(" ", multiFactorial(n, k))
}
... | 552Multifactorial | 0go | lqgcw |
null | 555Monads/Maybe monad | 11kotlin | irfo4 |
double pi(double tolerance)
{
double x, y, val, error;
unsigned long sampled = 0, hit = 0, i;
do {
for (i = 1000000; i; i--, sampled++) {
x = rand() / (RAND_MAX + 1.0);
y = rand() / (RAND_MAX + 1.0);
if (x * x + y * y < 1) hit ++;
}
val = (double) hit / sampled;
error = sqrt(val * (1 - val) / s... | 557Monte Carlo methods | 5c | 2svlo |
mulfac :: (Num a, Enum a) => a -> [a]
mulfac k = 1: s
where
s = [1 .. k] <> zipWith (*) s [k + 1 ..]
mulfac1 :: (Num a, Enum a) => a -> a -> a
mulfac1 k n = product [n, n - k .. 1]
main :: IO ()
main =
mapM_
(print . take 10 . tail . mulfac)
[1 .. 5] | 552Multifactorial | 8haskell | 1msps |
function nth($num) {
$os = ;
if ($num % 100 <= 10 or $num % 100 > 20) {
switch ($num % 10) {
case 1:
$os = ;
break;
case 2:
$os = ;
break;
case 3:
$os = ;
break;
}
}
return $num . $os;
}
foreach ([[0,25], [250,265], [1000,1025]] as $i) ... | 540N'th | 12php | lqxcj |
null | 542Mutual recursion | 11kotlin | sulq7 |
null | 555Monads/Maybe monad | 1lua | n7ti8 |
alpha2morse() {
local -A alpha_assoc=( [A]='.-' [B]='-...' [C]='-.-.' [D]='-..' [E]='.' \
[F]='..-.' [G]='--.' [H]='....' [I]='..' [J]='.---' \
[K]='-.-' [L]='.-..' [M]='--' [N]='-.' [O]='---' \
[P]='.--.' [Q]='--.-' [R]='.-.' [S]='...' [T]='-' \
[U]='..-' [V]='...-'... | 558Morse code | 4bash | ogo8a |
(ns test-p.core
(:require [clojure.math.numeric-tower :as math]))
(defn extended-gcd
"The extended Euclidean algorithm--using Clojure code from RosettaCode for Extended Eucliean
(see http://en.wikipedia.orwiki/Extended_Euclidean_algorithm)
Returns a list containing the GCD and the Bzout coefficients
correspo... | 556Modular inverse | 6clojure | k3phs |
require 'matrix'
def regression_coefficients y, x
y = Matrix.column_vector y.map { |i| i.to_f }
x = Matrix.columns x.map { |xi| xi.map { |i| i.to_f }}
(x.t * x).inverse * x.t * y
end | 548Multiple regression | 14ruby | 9w7mz |
public class NQueens {
private static int[] b = new int[8];
private static int s = 0;
static boolean unsafe(int y) {
int x = b[y];
for (int i = 1; i <= y; i++) {
int t = b[y - i];
if (t == x ||
t == x - i ||
t == x + i) {
return true;
}
}
return fal... | 543N-queens problem | 9java | dj4n9 |
use strict;
use warnings;
use Data::Monad::Maybe;
sub safeReciprocal { ( $_[0] == 0 ) ? nothing : just( 1 / $_[0] ) }
sub safeRoot { ( $_[0] < 0 ) ? nothing : just( sqrt( $_[0] ) ) }
sub safeLog { ( $_[0] <= 0 ) ? nothing : just( log ( $_[0] ) ) }
print join(' ', map {
my $safeLogRootReciproca... | 555Monads/Maybe monad | 2perl | rdhgd |
use strict;
use warnings;
sub encode {
my ($str) = @_;
my $table = join '', 'a' .. 'z';
map {
$table =~ s/(.*?)$_/$_$1/ or die;
length($1);
} split //, $str;
}
sub decode {
my $table = join '', 'a' .. 'z';
join "", map {
$table =~ s/(.{$_})(.)/$2$1/ or die;
$2;
} @_;
}
for my $test ( qw(broood bananaaa... | 550Move-to-front algorithm | 2perl | 3pvzs |
use SDL;
use SDL::Events;
use SDLx::App;
my $app = SDLx::App->new;
$app->add_event_handler( sub {
my $event = shift;
if( $event->type == SDL_MOUSEMOTION ) {
printf( "x=%d y=%d\n", $event->motion_x, $event->motion_y );
$app->stop
}
} );
$app->run; | 551Mouse position | 2perl | sufq3 |
function queenPuzzle(rows, columns) {
if (rows <= 0) {
return [[]];
} else {
return addQueen(rows - 1, columns);
}
}
function addQueen(newRow, columns, prevSolution) {
var newSolutions = [];
var prev = queenPuzzle(newRow, columns);
for (var i = 0; i < prev.length; i++) {
... | 543N-queens problem | 10javascript | 61h38 |
from __future__ import annotations
from typing import Any
from typing import Callable
from typing import Generic
from typing import Optional
from typing import TypeVar
from typing import Union
T = TypeVar()
class Maybe(Generic[T]):
def __init__(self, value: Union[Optional[T], Maybe[T]] = None):
if isin... | 555Monads/Maybe monad | 3python | 7fkrm |
(defn calc-pi [iterations]
(loop [x (rand) y (rand) in 0 total 1]
(if (< total iterations)
(recur (rand) (rand) (if (<= (+ (* x x) (* y y)) 1) (inc in) in) (inc total))
(double (* (/ in total) 4)))))
(doseq [x (take 5 (iterate #(* 10 %) 10))] (println (str (format "% 8d" x) ": " (calc-pi x)))) | 557Monte Carlo methods | 6clojure | gnr4f |
for i in range(5000):
if i == sum(int(x) ** int(x) for x in str(i)):
print(i) | 541Munchausen numbers | 3python | 84u0o |
<?php
function symbolTable() {
$symbol = array();
for ($c = ord('a') ; $c <= ord('z') ; $c++) {
$symbol[$c - ord('a')] = chr($c);
}
return $symbol;
}
function mtfEncode($original, $symbol) {
$encoded = array();
for ($i = 0 ; $i < strlen($original) ; $i++) {
$char = $original[$i... | 550Move-to-front algorithm | 12php | py0ba |
char
dih[50],dah[50],medium[30],word[30],
*dd[2] = {dih,dah};
const char
*ascii = $@13311131313111113133111111113333131311333133313313313131111311311131333113313333113333313333113331113311113111113111133111333113333113131333113311331113333131313331131313313133131311133311131313131113131313111131133131311311... | 558Morse code | 5c | n7ni6 |
int main(void){
unsigned i, j, k, choice, winsbyswitch=0, door[3];
srand(time(NULL));
for(i=0; i<GAMES; i++){
door[0] = (!(rand()%2)) ? 1: 0;
if(door[0]) door[1]=door[2]=0; ... | 559Monty Hall problem | 5c | jfr70 |
public class MultiFact {
private static long multiFact(long n, int deg){
long ans = 1;
for(long i = n; i > 0; i -= deg){
ans *= i;
}
return ans;
}
public static void main(String[] args){
for(int deg = 1; deg <= 5; deg++){
System.out.print("degree " + deg + ":");
for(long n = 1; n <= 10; n++){
... | 552Multifactorial | 9java | 7f1rj |
import Tkinter as tk
def showxy(event):
xm, ym = event.x, event.y
str1 = % (xm, ym)
root.title(str1)
x,y, delta = 100, 100, 10
frame.config(bg='red'
if abs(xm - x) < delta and abs(ym - y) < delta
else 'yellow')
root = tk.Tk()
frame = tk.Frame(root, bg= '... | 551Mouse position | 3python | 05tsq |
class Maybe
def initialize(value)
@value = value
end
def map
if @value.nil?
self
else
Maybe.new(yield @value)
end
end
end
Maybe.new(3).map { |n| 2*n }.map { |n| n+1 }
Maybe.new(nil).map { |n| 2*n }.map { |n| n+1 }
Maybe.new(3).map { |n| nil }.map { |n| n+1 }
class Maybe
c... | 555Monads/Maybe monad | 14ruby | hzpjx |
import 'dart:async';
import 'dart:html';
import 'dart:math' show Random; | 557Monte Carlo methods | 18dart | 61y34 |
function multifact(n, deg){
var result = n;
while (n >= deg + 1){
result *= (n - deg);
n -= deg;
}
return result;
} | 552Multifactorial | 10javascript | pyqb7 |
null | 543N-queens problem | 11kotlin | 05lsf |
fun multifactorial(n: Long, d: Int) : Long {
val r = n % d
return (1..n).filter { it % d == r } .reduce { i, p -> i * p }
}
fun main(args: Array<String>) {
val m = 5
val r = 1..10L
for (d in 1..m) {
print("%${m}s:".format( "!".repeat(d)))
r.forEach { print(" " + multifactorial(it, d... | 552Multifactorial | 11kotlin | u8jvc |
Shoes.app(:title => , :width => 400, :height => 400) do
@position = para , :size => 12, :margin => 10
motion do |x, y|
@position.text =
end
end | 551Mouse position | 14ruby | og38v |
null | 551Mouse position | 15rust | ir6od |
import java.awt.MouseInfo
object MousePosition extends App {
val mouseLocation = MouseInfo.getPointerInfo.getLocation
println (mouseLocation)
} | 551Mouse position | 16scala | fh9d4 |
_suffix = ['th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th']
def nth(n):
return % (n, _suffix[n%10] if n% 100 <= 10 or n% 100 > 20 else 'th')
if __name__ == '__main__':
for j in range(0,1001, 250):
print(' '.join(nth(i) for i in list(range(j, j+25)))) | 540N'th | 3python | x2lwr |
function m(n) return n > 0 and n - f(m(n-1)) or 0 end
function f(n) return n > 0 and n - m(f(n-1)) or 1 end | 542Mutual recursion | 1lua | 052sd |
(import [javax.sound.sampled AudioFormat AudioSystem SourceDataLine])
(defn play [sample-rate bs]
(let [af (AudioFormat. sample-rate 8 1 true true)]
(doto (AudioSystem/getSourceDataLine af)
(.open af sample-rate)
.start
(.write bs 0 (count bs))
.drain
.close)))
(defn note [hz sampl... | 558Morse code | 6clojure | 3p3zr |
from __future__ import print_function
from string import ascii_lowercase
SYMBOLTABLE = list(ascii_lowercase)
def move2front_encode(strng, symboltable):
sequence, pad = [], symboltable[::]
for char in strng:
indx = pad.index(char)
sequence.append(indx)
pad = [pad.pop(indx)] + pad
re... | 550Move-to-front algorithm | 3python | 61u3w |
(ns monty-hall-problem
(:use [clojure.contrib.seq:only (shuffle)]))
(defn play-game [staying]
(let [doors (shuffle [:goat:goat:car])
choice (rand-int 3)
[a b] (filter #(not= choice %) (range 3))
alternative (if (=:goat (nth doors a)) b a)]
(=:car (nth doors (if staying choice alternativ... | 559Monty Hall problem | 6clojure | 1ybpy |
function multiFact (n, degree)
local fact = 1
for i = n, 2, -degree do
fact = fact * i
end
return fact
end
print("Degree\t|\tMultifactorials 1 to 10")
print(string.rep("-", 52))
for d = 1, 5 do
io.write(" " .. d, "\t| ")
for n = 1, 10 do
io.write(multiFact(n, d) .. " ")
end
... | 552Multifactorial | 1lua | 5ohu6 |
nth <- function(n)
{
if (length(n) > 1) return(sapply(n, nth))
mod <- function(m, n) ifelse(!(m%%n), n, m%%n)
suffices <- c("th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th")
if (n %% 100 <= 10 || n %% 100 > 20)
suffix <- suffices[mod(n+1, 10)]
else
suffix <- 'th'
paste(n, "'", suffix,... | 540N'th | 13r | 1mypn |
class Integer
def munchausen?
self.digits.map{|d| d**d}.sum == self
end
end
puts (1..5000).select(&:munchausen?) | 541Munchausen numbers | 14ruby | ir4oh |
N = 8 | 543N-queens problem | 1lua | 8420e |
fn main() {
let mut solutions = Vec::new();
for num in 1..5_000 {
let power_sum = num.to_string()
.chars()
.map(|c| {
let digit = c.to_digit(10).unwrap();
(digit as f64).powi(digit as i32) as usize
})
.sum::<usize>();
... | 541Munchausen numbers | 15rust | n7gi4 |
object Munch {
def main(args: Array[String]): Unit = {
import scala.math.pow
(1 to 5000).foreach {
i => if (i == (i.toString.toCharArray.map(d => pow(d.asDigit,d.asDigit))).sum)
println( i + " (munchausen)")
}
}
} | 541Munchausen numbers | 16scala | tkjfb |
int main(void)
{
int i, j, n = 12;
for (j = 1; j <= n; j++) printf(, j, j != n ? ' ' : '\n');
for (j = 0; j <= n; j++) printf(j != n ? : );
for (i = 1; i <= n; i++) {
for (j = 1; j <= n; j++)
printf(j < i ? : , i * j);
printf(, i);
}
return 0;
} | 560Multiplication tables | 5c | amb11 |
module MoveToFront
ABC = (..).to_a.freeze
def self.encode(str)
ar = ABC.dup
str.chars.each_with_object([]) do |char, memo|
memo << (i = ar.index(char))
ar = m2f(ar,i)
end
end
def self.decode(indices)
ar = ABC.dup
indices.each_with_object() do |i, str|
str << ar[i]
... | 550Move-to-front algorithm | 14ruby | me4yj |
package main
import (
"fmt"
"math/big"
)
func main() {
a := big.NewInt(42)
m := big.NewInt(2017)
k := new(big.Int).ModInverse(a, m)
fmt.Println(k)
} | 556Modular inverse | 0go | irdog |
import Foundation
func isMnchhausen(_ n: Int) -> Bool {
let nums = String(n).map(String.init).compactMap(Int.init)
return Int(nums.map({ pow(Double($0), Double($0)) }).reduce(0, +)) == n
}
for i in 1...5000 where isMnchhausen(i) {
print(i)
} | 541Munchausen numbers | 17swift | og58k |
package main
import (
"fmt"
"math"
"math/rand"
"time"
)
func getPi(numThrows int) float64 {
inCircle := 0
for i := 0; i < numThrows; i++ { | 557Monte Carlo methods | 0go | qvsxz |
fn main() {
let examples = vec!["broood", "bananaaa", "hiphophiphop"];
for example in examples {
let encoded = encode(example);
let decoded = decode(&encoded);
println!(
"{} encodes to {:?} decodes to {}",
example, encoded, decoded
);
}
}
fn get_symbo... | 550Move-to-front algorithm | 15rust | 9wgmm |
package rosetta
import scala.annotation.tailrec
object MoveToFront {
private val R = 256
private def symbolTable = (0 until R).map(_.toChar).mkString
def encode(s: String): List[Int] = {
encode(s, symbolTable)
}
def encode(s: String, symTable: String): List[Int] = {
val table = symTab... | 550Move-to-front algorithm | 16scala | 2sjlb |
int rand(int max) => (Math.random()*max).toInt();
class Game {
int _prize;
int _open;
int _chosen;
Game() {
_prize=rand(3);
_open=null;
_chosen=null;
}
void choose(int door) {
_chosen=door;
}
void reveal() {
if(_prize==_chosen) {
int toopen=rand(2);
if (toopen>=_prize... | 559Monty Hall problem | 18dart | u02vs |
modInv :: Int -> Int -> Maybe Int
modInv a m
| 1 == g = Just (mkPos i)
| otherwise = Nothing
where
(i, _, g) = gcdExt a m
mkPos x
| x < 0 = x + m
| otherwise = x
gcdExt :: Int -> Int -> (Int, Int, Int)
gcdExt a 0 = (1, 0, a)
gcdExt a b =
let (q, r) = a `quotRem` b
(s, t, g) = gcdE... | 556Modular inverse | 8haskell | v052k |
import Control.Monad
import System.Random
getPi throws = do
results <- replicateM throws one_trial
return (4 * fromIntegral (sum results) / fromIntegral throws)
where
one_trial = do
rand_x <- randomRIO (-1, 1)
rand_y <- randomRIO (-1, 1)
let dist :: Double
dist = sqrt (rand_x * ra... | 557Monte Carlo methods | 8haskell | me9yf |
{
my @cache;
use bigint;
sub mfact {
my ($s, $n) = @_;
return 1 if $n <= 0;
$cache[$s][$n] //= $n * mfact($s, $n - $s);
}
}
for my $s (1 .. 10) {
print "step=$s: ";
print join(" ", map(mfact($s, $_), 1 .. 10)), "\n";
} | 552Multifactorial | 2perl | 84t0w |
class Integer
def ordinalize
num = self.abs
ordinal = if (11..13).include?(num % 100)
else
case num % 10
when 1;
when 2;
when 3;
else
end
end
end
end
[(0..25),(250..265),(1000..1025)].each{|r| puts r.map(&:ordinalize).join(); puts} | 540N'th | 14ruby | suvqw |
var str="broood"
var number:[Int]=[1,17,15,0,0,5] | 550Move-to-front algorithm | 17swift | ya56e |
System.out.println(BigInteger.valueOf(42).modInverse(BigInteger.valueOf(2017))); | 556Modular inverse | 9java | ya96g |
(let [size 12
trange (range 1 (inc size))
fmt-width (+ (.length (str (* size size))) 1)
fmt-str (partial format (str "%" fmt-width "s"))
fmt-dec (partial format (str "% " fmt-width "d"))]
(doseq [s (cons
(apply str (fmt-str " ") (map #(fmt-dec %) trange))
(for [i tra... | 560Multiplication tables | 6clojure | svwqr |
fn nth(num: isize) -> String {
format!("{}{}", num, match (num% 10, num% 100) {
(1, 11) | (2, 12) | (3, 13) => "th",
(1, _) => "st",
(2, _) => "nd",
(3, _) => "rd",
_ => "th",
})
}
fn main() {
let ranges = [(0, 26), (250, 266), (1000, 1026)];
for &(s, e) in &rang... | 540N'th | 15rust | 05usl |
public class MC {
public static void main(String[] args) {
System.out.println(getPi(10000));
System.out.println(getPi(100000));
System.out.println(getPi(1000000));
System.out.println(getPi(10000000));
System.out.println(getPi(100000000));
}
public static double getPi(int numThrows){
int inCircle= 0;
f... | 557Monte Carlo methods | 9java | fhtdv |
var modInverse = function(a, b) {
a %= b;
for (var x = 1; x < b; x++) {
if ((a*x)%b == 1) {
return x;
}
}
} | 556Modular inverse | 10javascript | 2sulr |
object Nth extends App {
def abbrevNumber(i: Int) = print(s"$i${ordinalAbbrev(i)} ")
def ordinalAbbrev(n: Int) = {
val ans = "th" | 540N'th | 16scala | irgox |
function mcpi(n) {
var x, y, m = 0;
for (var i = 0; i < n; i += 1) {
x = Math.random();
y = Math.random();
if (x * x + y * y < 1) {
m += 1;
}
}
return 4 * m / n;
}
console.log(mcpi(1000));
console.log(mcpi(10000));
console.log(mcpi(100000));
console.log(mc... | 557Monte Carlo methods | 10javascript | yam6r |
null | 556Modular inverse | 11kotlin | fhzdo |
>>> from functools import reduce
>>> from operator import mul
>>> def mfac(n, m): return reduce(mul, range(n, 0, -m))
>>> for m in range(1, 11): print(% (m, [mfac(n, m) for n in range(1, 11)]))
1: [1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]
2: [1, 2, 3, 8, 15, 48, 105, 384, 945, 3840]
3: [1, 2, 3, 4, 10,... | 552Multifactorial | 3python | ogz81 |
null | 557Monte Carlo methods | 11kotlin | 84o0q |
null | 558Morse code | 0go | rdrgm |
multifactorial=function(x,n){
if(x<=n+1){
return(x)
}else{
return(x*multifactorial(x-n,n))
}
} | 552Multifactorial | 13r | qvnxs |
import System.IO
import MorseCode
import MorsePlaySox
main = do
hSetBuffering stdin NoBuffering
text <- getContents
play $ toMorse text | 558Morse code | 8haskell | 050s7 |
SELECT level card,
to_char(to_date(level,'j'),'fmjth') ord
FROM dual
CONNECT BY level <= 15;
SELECT to_char(to_date(5373485,'j'),'fmjth')
FROM dual; | 540N'th | 19sql | fhjdi |
function MonteCarlo ( n_throws )
math.randomseed( os.time() )
n_inside = 0
for i = 1, n_throws do
if math.random()^2 + math.random()^2 <= 1.0 then
n_inside = n_inside + 1
end
end
return 4 * n_inside / n_throws
end
print( MonteCarlo( 10000 ) )
print( MonteCarlo( 100000 ) ... | 557Monte Carlo methods | 1lua | ogi8h |
import java.util.*;
public class MorseCode {
final static String[][] code = {
{"A", ".- "}, {"B", "-... "}, {"C", "-.-. "}, {"D", "-.. "},
{"E", ". "}, {"F", "..-. "}, {"G", "--. "}, {"H", ".... "},
{"I", ".. "}, {"J", ".--- "}, {"K", "-.- "}, {"L", ".-.. ... | 558Morse code | 9java | a9a1y |
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
games := 100000
r := rand.New(rand.NewSource(time.Now().UnixNano()))
var switcherWins, keeperWins, shown int
for i := 0; i < games; i++ {
doors := []int{0, 0, 0}
doors[r.Intn(3)] = 1 | 559Monty Hall problem | 0go | fjnd0 |
def multifact(n, d)
n.step(1, -d).inject(:* )
end
(1..5).each {|d| puts \t} | 552Multifactorial | 14ruby | n76it |
var globalAudioContext = new webkitAudioContext();
function morsecode(text, unit, freq) {
'use strict'; | 558Morse code | 10javascript | susqz |
import System.Random (StdGen, getStdGen, randomR)
trials :: Int
trials = 10000
data Door = Car | Goat deriving Eq
play :: Bool -> StdGen -> (Door, StdGen)
play switch g = (prize, new_g)
where (n, new_g) = randomR (0, 2) g
d1 = [Car, Goat, Goat] !! n
prize = case switch of
False -> d1
... | 559Monty Hall problem | 8haskell | 4ou5s |
use bigint; say 42->bmodinv(2017);
use Math::ModInt qw/mod/; say mod(42, 2017)->inverse->residue;
use Math::Pari qw/PARI lift/; say lift PARI "Mod(1/42,2017)";
use Math::GMP qw/:constant/; say 42->bmodinv(2017);
use ntheory qw/invmod/; say invmod(42, 2017); | 556Modular inverse | 2perl | hzbjl |
fn multifactorial(n: i32, deg: i32) -> i32 {
if n < 1 {
1
} else {
n * multifactorial(n - deg, deg)
}
}
fn main() {
for i in 1..6 {
for j in 1..11 {
print!("{} ", multifactorial(j, i));
}
println!("");
}
} | 552Multifactorial | 15rust | djyny |
func addSuffix(n:Int) -> String {
if n% 100 / 10 == 1 {
return "th"
}
switch n% 10 {
case 1:
return "st"
case 2:
return "nd"
case 3:
return "rd"
default:
return "th"
}
}
for i in 0...25 {
print("\(i)\(addSuffix(i)) ")
}
println()
for i in 250... | 540N'th | 17swift | qv2xg |
def multiFact(n : BigInt, degree : BigInt) = (n to 1 by -degree).product
for{
degree <- 1 to 5
str = (1 to 10).map(n => multiFact(n, degree)).mkString(" ")
} println(s"Degree $degree: $str") | 552Multifactorial | 16scala | zbctr |
import javax.sound.sampled.AudioFormat
import javax.sound.sampled.AudioSystem
val morseCode = hashMapOf(
'a' to ".-", 'b' to "-...", 'c' to "-.-.",
'd' to "-..", 'e' to ".", 'f' to "..-.",
'g' to "--.", 'h' to "....", 'i' to "..",
'j' to ".---", 'k' to "-.-", 'l' to ".-..",
'm' ... | 558Morse code | 11kotlin | hzhj3 |
<?php
function invmod($a,$n){
if ($n < 0) $n = -$n;
if ($a < 0) $a = $n - (-$a % $n);
$t = 0; $nt = 1; $r = $n; $nr = $a % $n;
while ($nr != 0) {
$quot= intval($r/$nr);
$tmp = $nt; $nt = $t - $quot*$nt; $t = $tmp;
$tmp = $nr; $nr = $r - $quot*$nr; $r = $tmp;
}
if ($r > 1) return -1;
if ($... | 556Modular inverse | 12php | zb6t1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.