code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
powerMod :: (Integral a, Integral b) => a -> a -> b -> a powerMod m _ 0 = 1 powerMod m x n | n > 0 = f x_ (n - 1) x_ where x_ = x `rem` m f _ 0 y = y f a d y = g a d where g b i | even i = g (b * b `rem` m) (i `quot` 2) | otherwise = f b (i - 1) (b * y `rem` m) powerMod m _ _ = error "powerMod: negative exponent"
544Multiplicative order
8haskell
n7uie
import Control.Monad (join) import Data.List (unfoldr) isMunchausen :: Integer -> Bool isMunchausen = (==) <*> (sum . map (join (^)) . unfoldr digit) digit 0 = Nothing digit n = Just (r, q) where (q, r) = n `divMod` 10 main :: IO () main = print $ filter isMunchausen [1 .. 5000]
541Munchausen numbers
8haskell
py3bt
package main import ( "fmt" "math" "rcu" ) var maxDepth = 6 var maxBase = 36 var c = rcu.PrimeSieve(int(math.Pow(float64(maxBase), float64(maxDepth))), true) var digits = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" var maxStrings [][][]int var mostBases = -1 func maxSlice(a []int) int { max := 0 for _, e := range a { if e > max { max = e } } return max } func maxInt(a, b int) int { if a > b { return a } return b } func process(indices []int) { minBase := maxInt(2, maxSlice(indices)+1) if maxBase - minBase + 1 < mostBases { return
546Multi-base primes
0go
x23wf
isConsistent(List q, int n) { for (int i=0; i<n; i++) { if (q[i] == q[n]) { return false;
543N-queens problem
18dart
3pjzz
import java.math.BigInteger; import java.util.ArrayList; import java.util.List; public class MultiplicativeOrder { private static final BigInteger ONE = BigInteger.ONE; private static final BigInteger TWO = BigInteger.valueOf(2); private static final BigInteger THREE = BigInteger.valueOf(3); private static final BigInteger TEN = BigInteger.TEN; private static class PExp { BigInteger prime; long exp; PExp(BigInteger prime, long exp) { this.prime = prime; this.exp = exp; } } private static void moTest(BigInteger a, BigInteger n) { if (!n.isProbablePrime(20)) { System.out.println("Not computed. Modulus must be prime for this algorithm."); return; } if (a.bitLength() < 100) System.out.printf("ord(%s)", a); else System.out.print("ord([big])"); if (n.bitLength() < 100) System.out.printf(" mod%s ", n); else System.out.print(" mod [big] "); BigInteger mob = moBachShallit58(a, n, factor(n.subtract(ONE))); System.out.println("= " + mob); } private static BigInteger moBachShallit58(BigInteger a, BigInteger n, List<PExp> pf) { BigInteger n1 = n.subtract(ONE); BigInteger mo = ONE; for (PExp pe : pf) { BigInteger y = n1.divide(pe.prime.pow((int) pe.exp)); long o = 0; BigInteger x = a.modPow(y, n.abs()); while (x.compareTo(ONE) > 0) { x = x.modPow(pe.prime, n.abs()); o++; } BigInteger o1 = BigInteger.valueOf(o); o1 = pe.prime.pow(o1.intValue()); o1 = o1.divide(mo.gcd(o1)); mo = mo.multiply(o1); } return mo; } private static List<PExp> factor(BigInteger n) { List<PExp> pf = new ArrayList<>(); BigInteger nn = n; Long e = 0L; while (!nn.testBit(e.intValue())) e++; if (e > 0L) { nn = nn.shiftRight(e.intValue()); pf.add(new PExp(TWO, e)); } BigInteger s = sqrt(nn); BigInteger d = THREE; while (nn.compareTo(ONE) > 0) { if (d.compareTo(s) > 0) d = nn; e = 0L; while (true) { BigInteger[] qr = nn.divideAndRemainder(d); if (qr[1].bitLength() > 0) break; nn = qr[0]; e++; } if (e > 0L) { pf.add(new PExp(d, e)); s = sqrt(nn); } d = d.add(TWO); } return pf; } private static BigInteger sqrt(BigInteger n) { BigInteger b = n; while (true) { BigInteger a = b; b = n.divide(a).add(a).shiftRight(1); if (b.compareTo(a) >= 0) return a; } } public static void main(String[] args) { moTest(BigInteger.valueOf(37), BigInteger.valueOf(3343)); BigInteger b = TEN.pow(100).add(ONE); moTest(b, BigInteger.valueOf(7919)); b = TEN.pow(1000).add(ONE); moTest(b, BigInteger.valueOf(15485863)); b = TEN.pow(10000).subtract(ONE); moTest(b, BigInteger.valueOf(22801763489L)); moTest(BigInteger.valueOf(1511678068), BigInteger.valueOf(7379191741L)); moTest(BigInteger.valueOf(3047753288L), BigInteger.valueOf(2257683301L)); } }
544Multiplicative order
9java
qvmxa
public class Nth { public static String ordinalAbbrev(int n){ String ans = "th";
540N'th
9java
u80vv
class Integer def narcissistic? return false if negative? digs = self.digits m = digs.size digs.map{|d| d**m}.sum == self end end puts 0.step.lazy.select(&:narcissistic?).first(25)
536Narcissistic decimal number
14ruby
3pez7
null
544Multiplicative order
11kotlin
1mtpd
console.log(function () { var lstSuffix = 'th st nd rd th th th th th th'.split(' '), fnOrdinalForm = function (n) { return n.toString() + ( 11 <= n % 100 && 13 >= n % 100 ? "th" : lstSuffix[n % 10] ); }, range = function (m, n) { return Array.apply( null, Array(n - m + 1) ).map(function (x, i) { return m + i; }); }; return [[0, 25], [250, 265], [1000, 1025]].map(function (tpl) { return range.apply(null, tpl).map(fnOrdinalForm).join(' '); }).join('\n\n'); }());
540N'th
10javascript
7fdrd
fn is_narcissistic(x: u32) -> bool { let digits: Vec<u32> = x .to_string() .chars() .map(|c| c.to_digit(10).unwrap()) .collect(); digits .iter() .map(|d| d.pow(digits.len() as u32)) .sum::<u32>() == x } fn main() { let mut counter = 0; let mut i = 0; while counter < 25 { if is_narcissistic(i) { println!("{}", i); counter += 1; } i += 1; } }
536Narcissistic decimal number
15rust
61w3l
object NDN extends App { val narc: Int => Int = n => (n.toString map (_.asDigit) map (math.pow(_, n.toString.size)) sum) toInt val isNarc: Int => Boolean = i => i == narc(i) println((Iterator from 0 filter isNarc take 25 toList) mkString(" ")) }
536Narcissistic decimal number
16scala
9wsm5
public class Main { public static void main(String[] args) { for(int i = 0 ; i <= 5000 ; i++ ){ int val = String.valueOf(i).chars().map(x -> (int) Math.pow( x-48 ,x-48)).sum(); if( i == val){ System.out.println( i + " (munchausen)"); } } } }
541Munchausen numbers
9java
rdig0
extension String { func multiSplit(on seps: [String]) -> ([Substring], [(String, (start: String.Index, end: String.Index))]) { var matches = [Substring]() var matched = [(String, (String.Index, String.Index))]() var i = startIndex var lastMatch = startIndex main: while i!= endIndex { for sep in seps where self[i...].hasPrefix(sep) { if i > lastMatch { matches.append(self[lastMatch..<i]) } else { matches.append("") } lastMatch = index(i, offsetBy: sep.count) matched.append((sep, (i, lastMatch))) i = lastMatch continue main } i = index(i, offsetBy: 1) } if i > lastMatch { matches.append(self[lastMatch..<i]) } return (matches, matched) } } let (matches, matchedSeps) = "a!===b=!=c".multiSplit(on: ["==", "!=", "="]) print(matches, matchedSeps.map({ $0.0 }))
539Multisplit
17swift
rddgg
int a[10]; float b[3][2]; char c[4][5][6]; double d[6][7][8][9]; int e[][3]; float f[5][4][]; int *g; float **h; double **i[]; char **j[][5];
547Multi-dimensional array
5c
7fqrg
double w[] = { 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 }; double h[] = { 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 }; int main() { int n = sizeof(h)/sizeof(double); gsl_matrix *X = gsl_matrix_calloc(n, 3); gsl_vector *Y = gsl_vector_alloc(n); gsl_vector *beta = gsl_vector_alloc(3); for (int i = 0; i < n; i++) { gsl_vector_set(Y, i, w[i]); gsl_matrix_set(X, i, 0, 1); gsl_matrix_set(X, i, 1, h[i]); gsl_matrix_set(X, i, 2, h[i] * h[i]); } double chisq; gsl_matrix *cov = gsl_matrix_alloc(3, 3); gsl_multifit_linear_workspace * wspc = gsl_multifit_linear_alloc(n, 3); gsl_multifit_linear(X, Y, beta, cov, &chisq, wspc); printf(); for (int i = 0; i < 3; i++) printf(, gsl_vector_get(beta, i)); printf(); gsl_matrix_free(X); gsl_matrix_free(cov); gsl_vector_free(Y); gsl_vector_free(beta); gsl_multifit_linear_free(wspc); }
548Multiple regression
5c
fh2d3
extension BinaryInteger { @inlinable public var isNarcissistic: Bool { let digits = String(self).map({ Int(String($0))! }) let m = digits.count guard m!= 1 else { return true } return digits.map({ $0.power(m) }).reduce(0, +) == self } @inlinable public func power(_ n: Self) -> Self { return stride(from: 0, to: n, by: 1).lazy.map({_ in self }).reduce(1, *) } } let narcs = Array((0...).lazy.filter({ $0.isNarcissistic }).prefix(25)) print("First 25 narcissistic numbers are \(narcs)")
536Narcissistic decimal number
17swift
zbatu
for (let i of [...Array(5000).keys()] .filter(n => n == n.toString().split('') .reduce((a, b) => a+Math.pow(parseInt(b),parseInt(b)), 0))) console.log(i);
541Munchausen numbers
10javascript
b6zki
func nxm(n, m int) [][]int { d2 := make([][]int, n) for i := range d2 { d2[i] = make([]int, m) } return d2 }
545Multiple distinct objects
0go
pydbg
use strict; use warnings; use feature 'say'; use List::AllUtils <firstidx max>; use ntheory qw/fromdigits todigitstring primes/; my(%prime_base, %max_bases, $l); my $chars = 5; my $upto = fromdigits( '1' . 'Z' x $chars, 36); my @primes = @{primes( $upto )}; for my $base (2..36) { my $n = todigitstring($base-1, $base) x $chars; my $threshold = fromdigits($n, $base); my $i = firstidx { $_ > $threshold } @primes; map { push @{$prime_base{ todigitstring($primes[$_],$base) }}, $base } 0..$i-1; } $l = length and $max_bases{$l} = max( $ for my $m (1 .. $chars) { say "$m character strings that are prime in maximum bases: ", 1+$max_bases{$m}; for (sort grep { length($_) == $m } keys %prime_base) { my @bases = @{($prime_base{$_})[0]}; say "$_: " . join ' ', @bases if $max_bases{$m} eq $ } say '' }
546Multi-base primes
2perl
5oeu2
def createFoos1 = { n -> (0..<n).collect { new Foo() } }
545Multiple distinct objects
7groovy
7f0rz
replicateM n makeTheDistinctThing
545Multiple distinct objects
8haskell
fh5d1
use ntheory qw/znorder/; say znorder(54, 100001); use bigint; say znorder(11, 1 + 10**100);
544Multiplicative order
2perl
mekyz
from decimal import Decimal, getcontext def nthroot (n, A, precision): getcontext().prec = precision n = Decimal(n) x_0 = A / n x_1 = 1 while True: x_0, x_1 = x_1, (1 / n)*((n - 1)*x_0 + (A / (x_0 ** (n - 1)))) if x_0 == x_1: return x_1
531Nth root
3python
iraof
fun Int.ordinalAbbrev() = if (this % 100 / 10 == 1) "th" else when (this % 10) { 1 -> "st" 2 -> "nd" 3 -> "rd" else -> "th" } fun IntRange.ordinalAbbrev() = map { "$it" + it.ordinalAbbrev() }.joinToString(" ") fun main(args: Array<String>) { listOf((0..25), (250..265), (1000..1025)).forEach { println(it.ordinalAbbrev()) } }
540N'th
11kotlin
9wemh
Foo[] foos = new Foo[n];
545Multiple distinct objects
9java
059se
var a = new Array(n); for (var i = 0; i < n; i++) a[i] = new Foo();
545Multiple distinct objects
10javascript
djunu
bool is_prime(uint64_t n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (uint64_t p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += 2; if (n % p == 0) return false; } return true; } int main() { setlocale(LC_ALL, ); printf(); printf(); uint64_t m0 = 1, m1 = 1; for (uint64_t i = 0; i < 42; ++i) { uint64_t m = i > 1 ? (m1 * (2 * i + 1) + m0 * (3 * i - 3)) / (i + 2) : 1; printf(, i, m, is_prime(m) ? : ); m0 = m1; m1 = m; } }
549Motzkin numbers
5c
053st
int move_to_front(char *str,char c) { char *q,*p; int shift=0; p=(char *)malloc(strlen(str)+1); strcpy(p,str); q=strchr(p,c); shift=q-p; strncpy(str+1,p,shift); str[0]=c; free(p); return shift; } void decode(int* pass,int size,char *sym) { int i,index; char c; char table[]=; for(i=0;i<size;i++) { c=table[pass[i]]; index=move_to_front(table,c); if(pass[i]!=index) printf(); sym[i]=c; } sym[size]='\0'; } void encode(char *sym,int size,int *pass) { int i=0; char c; char table[]=; for(i=0;i<size;i++) { c=sym[i]; pass[i]=move_to_front(table,c); } } int check(char *sym,int size,int *pass) { int *pass2=malloc(sizeof(int)*size); char *sym2=malloc(sizeof(char)*size); int i,val=1; encode(sym,size,pass2); i=0; while(i<size && pass[i]==pass2[i])i++; if(i!=size)val=0; decode(pass,size,sym2); if(strcmp(sym,sym2)!=0)val=0; free(sym2); free(pass2); return val; } int main() { char sym[3][MAX_SIZE]={,,}; int pass[MAX_SIZE]={0}; int i,len,j; for(i=0;i<3;i++) { len=strlen(sym[i]); encode(sym[i],len,pass); printf(,sym[i]); for(j=0;j<len;j++) printf(,pass[j]); printf(); if(check(sym[i],len,pass)) printf(); else printf(); } return 0; }
550Move-to-front algorithm
5c
dj9nv
nthroot <- function(A, n, tol=sqrt(.Machine$double.eps)) { ifelse(A < 1, x0 <- A * n, x0 <- A / n) repeat { x1 <- ((n-1)*x0 + A / x0^(n-1))/n if(abs(x1 - x0) > tol) x0 <- x1 else break } x1 } nthroot(7131.5^10, 10) nthroot(7, 0.5)
531Nth root
13r
sukqy
null
541Munchausen numbers
11kotlin
v0q21
null
545Multiple distinct objects
11kotlin
ecza4
int main() { Display *d; Window inwin; Window inchildwin; int rootx, rooty; int childx, childy; Atom atom_type_prop; int actual_format; unsigned int mask; unsigned long n_items, bytes_after_ret; Window *props; d = XOpenDisplay(NULL); (void)XGetWindowProperty(d, DefaultRootWindow(d), XInternAtom(d, , True), 0, 1, False, AnyPropertyType, &atom_type_prop, &actual_format, &n_items, &bytes_after_ret, (unsigned char**)&props); XQueryPointer(d, props[0], &inwin, &inchildwin, &rootx, &rooty, &childx, &childy, &mask); printf(, childx, childy); XFree(props); (void)XCloseDisplay(d); return 0; }
551Mouse position
5c
ecoav
def gcd(a, b): while b != 0: a, b = b, a% b return a def lcm(a, b): return (a*b) / gcd(a, b) def isPrime(p): return (p > 1) and all(f == p for f,e in factored(p)) primeList = [2,3,5,7] def primes(): for p in primeList: yield p while 1: p += 2 while not isPrime(p): p += 2 primeList.append(p) yield p def factored( a): for p in primes(): j = 0 while a%p == 0: a /= p j += 1 if j > 0: yield (p,j) if a < p*p: break if a > 1: yield (a,1) def multOrdr1(a,(p,e) ): m = p**e t = (p-1)*(p**(e-1)) qs = [1,] for f in factored(t): qs = [ q * f[0]**j for j in range(1+f[1]) for q in qs ] qs.sort() for q in qs: if pow( a, q, m )==1: break return q def multOrder(a,m): assert gcd(a,m) == 1 mofs = (multOrdr1(a,r) for r in factored(m)) return reduce(lcm, mofs, 1) if __name__ == : print multOrder(37, 1000) b = 10**20-1 print multOrder(2, b) print multOrder(17,b) b = 100001 print multOrder(54,b) print pow( 54, multOrder(54,b),b) if any( (1==pow(54,r, b)) for r in range(1,multOrder(54,b))): print 'Exists a power r < 9090 where pow(54,r,b)==1' else: print 'Everything checks.'
544Multiplicative order
3python
9wbmf
null
545Multiple distinct objects
1lua
wl3ea
int multifact(int n, int deg){ return n <= deg ? n : n * multifact(n - deg, deg); } int multifact_i(int n, int deg){ int result = n; while (n >= deg + 1){ result *= (n - deg); n -= deg; } return result; } int main(void){ int i, j; for (i = 1; i <= HIGHEST_DEGREE; i++){ printf(, i); for (j = 1; j <= LARGEST_NUMBER; j++){ printf(, multifact(j, i)); } } }
552Multifactorial
5c
x2iwu
null
546Multi-base primes
15rust
7fsrc
function getSuffix (n) local lastTwo, lastOne = n % 100, n % 10 if lastTwo > 3 and lastTwo < 21 then return "th" end if lastOne == 1 then return "st" end if lastOne == 2 then return "nd" end if lastOne == 3 then return "rd" end return "th" end function Nth (n) return n .. "'" .. getSuffix(n) end for i = 0, 25 do print(Nth(i), Nth(i + 250), Nth(i + 1000)) end
540N'th
1lua
cxw92
(def lowercase (map char (range (int \a) (inc (int \z))))) (defn move-to-front [x xs] (cons x (remove #{x} xs))) (defn encode [text table & {:keys [acc]:or {acc []}}] (let [c (first text) idx (.indexOf table c)] (if (empty? text) acc (recur (drop 1 text) (move-to-front c table) {:acc (conj acc idx)})))) (defn decode [indices table & {:keys [acc]:or {acc []}}] (if (empty? indices) (apply str acc) (let [n (first indices) c (nth table n)] (recur (drop 1 indices) (move-to-front c table) {:acc (conj acc c)})))) (doseq [word ["broood" "bananaaa" "hiphophiphop"]] (let [encoded (encode word lowercase) decoded (decode encoded lowercase)] (println (format "%s encodes to%s which decodes back to%s." word encoded decoded))))
550Move-to-front algorithm
6clojure
61u3q
package main import "fmt" type md struct { dim []int ele []float64 } func newMD(dim ...int) *md { n := 1 for _, d := range dim { n *= d } return &md{append([]int{}, dim...), make([]float64, n)} } func (m *md) index(i ...int) (x int) { for d, dx := range m.dim { x = x*dx + i[d] } return } func (m *md) at(i ...int) float64 { return m.ele[m.index(i...)] } func (m *md) set(x float64, i ...int) { m.ele[m.index(i...)] = x } func (m *md) show(i ...int) { fmt.Printf("m%d =%g\n", i, m.at(i...)) } func main() { m := newMD(5, 4, 3, 2) m.show(4, 3, 2, 1) m.set(87, 4, 3, 2, 1) m.show(4, 3, 2, 1) for i := 0; i < m.dim[0]; i++ { for j := 0; j < m.dim[1]; j++ { for k := 0; k < m.dim[2]; k++ { for l := 0; l < m.dim[3]; l++ { x := m.index(i, j, k, l) m.set(float64(x)+.1, i, j, k, l) } } } } fmt.Println(m.ele[:10]) fmt.Println(m.ele[len(m.ele)-10:]) m.show(4, 3, 2, 1) }
547Multi-dimensional array
0go
dj2ne
(let [point (.. java.awt.MouseInfo getPointerInfo getLocation)] [(.getX point) (.getY point)])
551Mouse position
6clojure
05tsj
def nthroot(n, a, precision = 1e-5) x = Float(a) begin prev = x x = ((n - 1) * prev + a / (prev ** (n - 1))) / n end while (prev - x).abs > precision x end p nthroot(5,34)
531Nth root
14ruby
djwns
function isMunchausen (n) local sum, nStr, digit = 0, tostring(n) for pos = 1, #nStr do digit = tonumber(nStr:sub(pos, pos)) sum = sum + digit ^ digit end return sum == n end
541Munchausen numbers
1lua
u8svl
package main import ( "fmt" "rcu" ) func motzkin(n int) []int { m := make([]int, n+1) m[0] = 1 m[1] = 1 for i := 2; i <= n; i++ { m[i] = (m[i-1]*(2*i+1) + m[i-2]*(3*i-3)) / (i + 2) } return m } func main() { fmt.Println(" n M[n] Prime?") fmt.Println("-----------------------------------") m := motzkin(41) for i, e := range m { fmt.Printf("%2d %23s %t\n", i, rcu.Commatize(e), rcu.IsPrime(e)) } }
549Motzkin numbers
0go
u8bvt
public class MultiDimensionalArray { public static void main(String[] args) {
547Multi-dimensional array
9java
9wjmu
package main import ( "fmt" "github.com/gonum/matrix/mat64" ) func givens() (x, y *mat64.Dense) { height := []float64{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 := []float64{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} degree := 2 x = Vandermonde(height, degree) y = mat64.NewDense(len(weight), 1, weight) return } func Vandermonde(a []float64, degree int) *mat64.Dense { x := mat64.NewDense(len(a), degree+1, nil) for i := range a { for j, p := 0, 1.; j <= degree; j, p = j+1, p*a[i] { x.Set(i, j, p) } } return x } func main() { x, y := givens() fmt.Printf("%.4f\n", mat64.Formatted(mat64.QR(x).Solve(y))) }
548Multiple regression
0go
jtq7d
require 'prime' def powerMod(b, p, m) p.to_s(2).each_char.inject(1) do |result, bit| result = (result * result) % m bit=='1'? (result * b) % m: result end end def multOrder_(a, p, k) pk = p ** k t = (p - 1) * p ** (k - 1) r = 1 for q, e in t.prime_division x = powerMod(a, t / q**e, pk) while x!= 1 r *= q x = powerMod(x, q, pk) end end r end def multOrder(a, m) m.prime_division.inject(1) do |result, f| result.lcm(multOrder_(a, *f)) end end puts multOrder(37, 1000) b = 10**20-1 puts multOrder(2, b) puts multOrder(17,b) b = 100001 puts multOrder(54,b) puts powerMod(54, multOrder(54,b), b) if (1...multOrder(54,b)).any? {|r| powerMod(54, r, b) == 1} puts 'Exists a power r < 9090 where powerMod(54,r,b)==1' else puts 'Everything checks.' end
544Multiplicative order
14ruby
lq1cl
null
531Nth root
15rust
fhxd6
import Control.Monad.Memo (Memo, memo, startEvalMemo) import Math.NumberTheory.Primes.Testing (isPrime) import System.Environment (getArgs) import Text.Printf (printf) type I = Integer motzkin :: I -> Memo I I I motzkin 0 = return 1 motzkin 1 = return 1 motzkin n = do m1 <- memo motzkin (n-1) m2 <- memo motzkin (n-2) return $ ((2*n+1)*m1 + (3*n-3)*m2) `div` (n+2) motzkins :: I -> [I] motzkins = startEvalMemo . mapM motzkin . enumFromTo 0 printMotzkins :: I -> IO () printMotzkins n = mapM_ prnt $ zip [0 :: I ..] (motzkins n) where prnt (i, m) = printf "%2d%20d%s\n" i m $ prime m prime m = if isPrime m then "prime" else "" main :: IO () main = do [n] <- map read <$> getArgs printMotzkins n
549Motzkin numbers
8haskell
wlded
function array() { var dimensions= Array.prototype.slice.call(arguments); var N=1, rank= dimensions.length; for (var j= 0; j<rank; j++) N*= dimensions[j]; this.dimensions= dimensions; this.values= new Array(N); }
547Multi-dimensional array
10javascript
u81vb
import Numeric.LinearAlgebra import Numeric.LinearAlgebra.LAPACK m :: Matrix Double m = (3><3) [7.589183,1.703609,-4.477162, -4.597851,9.434889,-6.543450, 0.4588202,-6.115153,1.331191] v :: Matrix Double v = (3><1) [1.745005,-4.448092,-4.160842]
548Multiple regression
8haskell
ogm8p
(defn !! [m n] (->> (iterate #(- % m) n) (take-while pos?) (apply *))) (doseq [m (range 1 6)] (prn m (map #(!! m %) (range 1 11))))
552Multifactorial
6clojure
ogz8j
def nroot(n: Int, a: Double): Double = { @tailrec def rec(x0: Double) : Double = { val x1 = ((n - 1) * x0 + a/math.pow(x0, n-1))/n if (x0 <= x1) x0 else rec(x1) } rec(a) }
531Nth root
16scala
3p0zy
(Foo->new) x $n
545Multiple distinct objects
2perl
cxb9a
package main import "fmt" func F(n int) int { if n == 0 { return 1 } return n - M(F(n-1)) } func M(n int) int { if n == 0 { return 0 } return n - F(M(n-1)) } func main() { for i := 0; i < 20; i++ { fmt.Printf("%2d ", F(i)) } fmt.Println() for i := 0; i < 20; i++ { fmt.Printf("%2d ", M(i)) } fmt.Println() }
542Mutual recursion
0go
wlmeg
(defn bind [coll f] (apply vector (mapcat f coll))) (defn unit [val] (vector val)) (defn doubler [n] [(* 2 n)]) (def vecstr (comp vector str)) (bind (bind (vector 3 4 5) doubler) vecstr) (-> [3 4 5] (bind doubler) (bind vecstr))
553Monads/List monad
6clojure
2sgl1
null
547Multi-dimensional array
11kotlin
zb5ts
import java.util.Arrays; import java.util.Objects; public class MultipleRegression { public static void require(boolean condition, String message) { if (condition) { return; } throw new IllegalArgumentException(message); } public static class Matrix { private final double[][] data; private final int rowCount; private final int colCount; public Matrix(int rows, int cols) { require(rows > 0, "Need at least one row"); this.rowCount = rows; require(cols > 0, "Need at least one column"); this.colCount = cols; this.data = new double[rows][cols]; for (double[] row : this.data) { Arrays.fill(row, 0.0); } } public Matrix(double[][] source) { require(source.length > 0, "Need at least one row"); this.rowCount = source.length; require(source[0].length > 0, "Need at least one column"); this.colCount = source[0].length; this.data = new double[this.rowCount][this.colCount]; for (int i = 0; i < this.rowCount; i++) { set(i, source[i]); } } public double[] get(int row) { Objects.checkIndex(row, this.rowCount); return this.data[row]; } public void set(int row, double[] data) { Objects.checkIndex(row, this.rowCount); require(data.length == this.colCount, "The column in the row must match the number of columns in the matrix"); System.arraycopy(data, 0, this.data[row], 0, this.colCount); } public double get(int row, int col) { Objects.checkIndex(row, this.rowCount); Objects.checkIndex(col, this.colCount); return this.data[row][col]; } public void set(int row, int col, double value) { Objects.checkIndex(row, this.rowCount); Objects.checkIndex(col, this.colCount); this.data[row][col] = value; } @SuppressWarnings("UnnecessaryLocalVariable") public Matrix times(Matrix that) { var rc1 = this.rowCount; var cc1 = this.colCount; var rc2 = that.rowCount; var cc2 = that.colCount; require(cc1 == rc2, "Cannot multiply if the first columns does not equal the second rows"); var result = new Matrix(rc1, cc2); for (int i = 0; i < rc1; i++) { for (int j = 0; j < cc2; j++) { for (int k = 0; k < rc2; k++) { var prod = get(i, k) * that.get(k, j); result.set(i, j, result.get(i, j) + prod); } } } return result; } public Matrix transpose() { var rc = this.rowCount; var cc = this.colCount; var trans = new Matrix(cc, rc); for (int i = 0; i < cc; i++) { for (int j = 0; j < rc; j++) { trans.set(i, j, get(j, i)); } } return trans; } public void toReducedRowEchelonForm() { int lead = 0; var rc = this.rowCount; var cc = this.colCount; for (int r = 0; r < rc; r++) { if (cc <= lead) { return; } var i = r; while (get(i, lead) == 0.0) { i++; if (rc == i) { i = r; lead++; if (cc == lead) { return; } } } var temp = get(i); set(i, get(r)); set(r, temp); if (get(r, lead) != 0.0) { var div = get(r, lead); for (int j = 0; j < cc; j++) { set(r, j, get(r, j) / div); } } for (int k = 0; k < rc; k++) { if (k != r) { var mult = get(k, lead); for (int j = 0; j < cc; j++) { var prod = get(r, j) * mult; set(k, j, get(k, j) - prod); } } } lead++; } } public Matrix inverse() { require(this.rowCount == this.colCount, "Not a square matrix"); var len = this.rowCount; var aug = new Matrix(len, 2 * len); for (int i = 0; i < len; i++) { for (int j = 0; j < len; j++) { aug.set(i, j, get(i, j)); }
548Multiple regression
9java
wlfej
def f, m
542Mutual recursion
7groovy
b6tky
[Foo()] * n
545Multiple distinct objects
3python
lqpcv
use strict; use warnings; use ntheory qw( is_prime ); sub motzkin { my $N = shift; my @m = ( 0, 1, 1 ); for my $i ( 3 .. $N ) { $m[$i] = ($m[$i - 1] * (2 * $i - 1) + $m[$i - 2] * (3 * $i - 6)) / ($i + 1); } return splice @m, 1; } print " n M[n]\n"; my $count = 0; for ( motzkin(42) ) { printf "%3d%25s %s\n", $count++, s/\B(?=(\d\d\d)+$)/,/gr, is_prime($_) ? 'prime' : ''; }
549Motzkin numbers
2perl
n79iw
package main import ( "fmt" "math" ) type mwriter struct { value float64 log string } func (m mwriter) bind(f func(v float64) mwriter) mwriter { n := f(m.value) n.log = m.log + n.log return n } func unit(v float64, s string) mwriter { return mwriter{v, fmt.Sprintf(" %-17s:%g\n", s, v)} } func root(v float64) mwriter { return unit(math.Sqrt(v), "Took square root") } func addOne(v float64) mwriter { return unit(v+1, "Added one") } func half(v float64) mwriter { return unit(v/2, "Divided by two") } func main() { mw1 := unit(5, "Initial value") mw2 := mw1.bind(root).bind(addOne).bind(half) fmt.Println("The Golden Ratio is", mw2.value) fmt.Println("\nThis was derived as follows:-") fmt.Println(mw2.log) }
554Monads/Writer monad
0go
suiqa
null
547Multi-dimensional array
1lua
3p4zo
null
548Multiple regression
10javascript
84y0l
package main import ( "fmt" "github.com/go-vgo/robotgo" ) func isInside(x, y, w, h, mx, my int) bool { rx := x + w - 1 ry := y + h - 1 return mx >= x && mx <= rx && my >= y && my <= ry } func main() { name := "gedit"
551Mouse position
0go
9w4mt
f 0 = 1 f n | n > 0 = n - m (f $ n-1) m 0 = 0 m n | n > 0 = n - f (m $ n-1) main = do print $ map f [0..19] print $ map m [0..19]
542Mutual recursion
8haskell
61k3k
rep(foo(), n)
545Multiple distinct objects
13r
yaj6h
typedef enum type { INT, STRING } Type; typedef struct maybe { int i; char *s; Type t; _Bool is_something; } Maybe; void print_Maybe(Maybe *m) { if (m->t == INT) printf(, m->i); else if (m->t == STRING) printf(%s\, m->s); else printf(); } Maybe *return_maybe(void *data, Type t) { Maybe *m = malloc(sizeof(Maybe)); if (t == INT) { m->i = *(int *) data; m->s = NULL; m->t = INT; m->is_something = true; } else if (t == STRING) { m->i = 0; m->s = data; m->t = STRING; m->is_something = true; } else { m->i = 0; m->s = NULL; m->t = 0; m->is_something = false; } return m; } Maybe *bind_maybe(Maybe *m, Maybe *(*f)(void *)) { Maybe *n = malloc(sizeof(Maybe)); if (f(&(m->i))->is_something) { n->i = f(&(m->i))->i; n->s = f(&(m->i))->s; n->t = f(&(m->i))->t; n->is_something = true; } else { n->i = 0; n->s = NULL; n->t = 0; n->is_something = false; } return n; } Maybe *f_1(void *v) { Maybe *m = malloc(sizeof(Maybe)); m->i = (*(int *) v) * (*(int *) v); m->s = NULL; m->t = INT; m->is_something = true; return m; } Maybe *f_2(void *v) { Maybe *m = malloc(sizeof(Maybe)); m->i = 0; m->s = malloc(*(int *) v * sizeof(char) + 1); for (int i = 0; i < *(int *) v; i++) { m->s[i] = 'x'; } m->s[*(int *) v + 1] = '\0'; m->t = STRING; m->is_something = true; return m; } int main() { int i = 7; char *s = ; Maybe *m_1 = return_maybe(&i, INT); Maybe *m_2 = return_maybe(s, STRING); print_Maybe(m_1); print_Maybe(m_2); print_Maybe(bind_maybe(m_1, f_1)); print_Maybe(bind_maybe(m_1, f_2)); print_Maybe(bind_maybe(bind_maybe(m_1, f_1), f_2)); }
555Monads/Maybe monad
5c
u8gv4
package main import ( "bytes" "fmt" ) type symbolTable string func (symbols symbolTable) encode(s string) []byte { seq := make([]byte, len(s)) pad := []byte(symbols) for i, c := range []byte(s) { x := bytes.IndexByte(pad, c) seq[i] = byte(x) copy(pad[1:], pad[:x]) pad[0] = c } return seq } func (symbols symbolTable) decode(seq []byte) string { chars := make([]byte, len(seq)) pad := []byte(symbols) for i, x := range seq { c := pad[x] chars[i] = c copy(pad[1:], pad[:x]) pad[0] = c } return string(chars) } func main() { m := symbolTable("abcdefghijklmnopqrstuvwxyz") for _, s := range []string{"broood", "bananaaa", "hiphophiphop"} { enc := m.encode(s) dec := m.decode(enc) fmt.Println(s, enc, dec) if dec != s { panic("Whoops!") } } }
550Move-to-front algorithm
0go
7fer2
import Control.Monad.Trans.Writer import Control.Monad ((>=>)) loggingVersion :: (a -> b) -> c -> a -> Writer c b loggingVersion f log x = writer (f x, log) logRoot = loggingVersion sqrt "obtained square root, " logAddOne = loggingVersion (+1) "added 1, " logHalf = loggingVersion (/2) "divided by 2, " halfOfAddOneOfRoot = logRoot >=> logAddOne >=> logHalf main = print $ runWriter (halfOfAddOneOfRoot 5)
554Monads/Writer monad
8haskell
9wvmo
1.upto(5) { Thread.sleep(1000) def p = java.awt.MouseInfo.pointerInfo.location println "${it}: x=${p.@x} y=${p.@y}" }
551Mouse position
7groovy
zblt5
extension FloatingPoint where Self: ExpressibleByFloatLiteral { @inlinable public func power(_ e: Int) -> Self { var res = Self(1) for _ in 0..<e { res *= self } return res } @inlinable public func root(n: Int, epsilon: Self = 2.220446049250313e-16) -> Self { var d = Self(0) var res = Self(1) guard self!= 0 else { return 0 } guard n >= 1 else { return .nan } repeat { d = (self / res.power(n - 1) - res) / Self(n) res += d } while d >= epsilon * 10 || d <= -epsilon * 10 return res } } print(81.root(n: 4)) print(13.root(n: 5))
531Nth root
17swift
n7eil
[Foo.new] * n Array.new(n, Foo.new)
545Multiple distinct objects
14ruby
v0a2n
use std::rc::Rc; use std::cell::RefCell; fn main() { let size = 3;
545Multiple distinct objects
15rust
u8evj
for (i <- (0 until n)) yield new Foo()
545Multiple distinct objects
16scala
gnq4i
import Data.List (delete, elemIndex, mapAccumL) import Data.Maybe (fromJust) table :: String table = ['a' .. 'z'] encode :: String -> [Int] encode = let f t s = (s: delete s t, fromJust (elemIndex s t)) in snd . mapAccumL f table decode :: [Int] -> String decode = snd . mapAccumL f table where f t i = let s = (t !! i) in (s: delete s t, s) main :: IO () main = mapM_ print $ (,) <*> uncurry ((==) . fst) <$> ((,) <*> (decode . snd) <$> ((,) <*> encode <$> ["broood", "bananaaa", "hiphophiphop"]))
550Move-to-front algorithm
8haskell
8430z
(function () { 'use strict';
554Monads/Writer monad
10javascript
me2yv
package main import "fmt" type mlist struct{ value []int } func (m mlist) bind(f func(lst []int) mlist) mlist { return f(m.value) } func unit(lst []int) mlist { return mlist{lst} } func increment(lst []int) mlist { lst2 := make([]int, len(lst)) for i, v := range lst { lst2[i] = v + 1 } return unit(lst2) } func double(lst []int) mlist { lst2 := make([]int, len(lst)) for i, v := range lst { lst2[i] = 2 * v } return unit(lst2) } func main() { ml1 := unit([]int{3, 4, 5}) ml2 := ml1.bind(increment).bind(double) fmt.Printf("%v ->%v\n", ml1.value, ml2.value) }
553Monads/List monad
0go
1mqp5
null
548Multiple regression
11kotlin
b68kb
main() { int n=5,d=3; int z= fact(n,d); print('$n factorial of degree $d is $z'); for(var j=1;j<=5;j++) { print('first 10 numbers of degree $j:'); for(var i=1;i<=10;i++) { int z=fact(i,j); print('$z'); } print('\n'); } } int fact(int a,int b) { if(a<=b||a==0) return a; if(a>1) return a*fact((a-b),b); }
552Multifactorial
18dart
b6xk1
Point mouseLocation = MouseInfo.getPointerInfo().getLocation();
551Mouse position
9java
gnp4m
require motzkin = Enumerator.new do |y| m = [1,1] m.each{|m| y << m } 2.step do |i| m << (m.last*(2*i+1) + m[-2]*(3*i-3)) / (i+2) m.unshift y << m.last end end motzkin.take(42).each_with_index do |m, i| puts end
549Motzkin numbers
14ruby
tk2f2
null
549Motzkin numbers
15rust
zbvto
main = print $ [3,4,5] >>= (return . (+1)) >>= (return . (*2))
553Monads/List monad
8haskell
tkmf7
use feature 'say'; for $i (0..1) { for $j (0..2) { for $k (0..3) { $a[$i][$j][$k][$l] = [(0)x5]; } } } @b = ( [1, 2, 4, 8, 16, 32], [<Mon Tue Wed Thu Fri Sat Sun>], [sub{$_[0]+$_[1]}, sub{$_[0]-$_[1]}, sub{$_[0]*$_[1]}, sub{$_[0]/$_[1]}] ); say $b[0][5]; say $b[1][2]; say $b[2][0]->(40,2); $ $c[2][2] = 42; say $c[-1][-1]; my @d = <Mon Tue Ned Sat Fri Thu>; push @d, 'Sun'; $d[2] = 'Wed'; @d[3..5] = @d[reverse 3..5]; say "@d";
547Multi-dimensional array
2perl
b6ok4
document.addEventListener('mousemove', function(e){ var position = { x: e.clientX, y: e.clientY } }
551Mouse position
10javascript
k3xhq
use List::Util "sum"; for my $n (1..5000) { print "$n\n" if $n == sum( map { $_**$_ } split(//,$n) ); }
541Munchausen numbers
2perl
05vs4
class Foo { } var foos = [Foo]() for i in 0..<n { foos.append(Foo()) }
545Multiple distinct objects
17swift
2s1lj
import Foundation extension BinaryInteger { @inlinable public var isPrime: Bool { if self == 0 || self == 1 { return false } else if self == 2 { return true } let max = Self(ceil((Double(self).squareRoot()))) for i in stride(from: 2, through: max, by: 1) where self% i == 0 { return false } return true } } func motzkin(_ n: Int) -> [Int] { var m = Array(repeating: 0, count: n) m[0] = 1 m[1] = 1 for i in 2..<n { m[i] = (m[i - 1] * (2 * i + 1) + m[i - 2] * (3 * i - 3)) / (i + 2) } return m } let m = motzkin(42) for (i, n) in m.enumerated() { print("\(i): \(n) \(n.isPrime? "prime": "")") }
549Motzkin numbers
17swift
fhldk
(defn bind [val f] (if-let [v (:value val)] (f v) val)) (defn unit [val] {:value val}) (defn opt_add_3 [n] (unit (+ 3 n))) (defn opt_str [n] (unit (str n))) (bind (unit 4) opt_add_3) (bind (unit nil) opt_add_3) (bind (bind (unit 8) opt_add_3) opt_str) (bind (bind (unit nil) opt_add_3) opt_str)
555Monads/Maybe monad
6clojure
7fkr0
import java.util.LinkedList; import java.util.List; public class MTF{ public static List<Integer> encode(String msg, String symTable){ List<Integer> output = new LinkedList<Integer>(); StringBuilder s = new StringBuilder(symTable); for(char c: msg.toCharArray()){ int idx = s.indexOf("" + c); output.add(idx); s = s.deleteCharAt(idx).insert(0, c); } return output; } public static String decode(List<Integer> idxs, String symTable){ StringBuilder output = new StringBuilder(); StringBuilder s = new StringBuilder(symTable); for(int idx: idxs){ char c = s.charAt(idx); output = output.append(c); s = s.deleteCharAt(idx).insert(0, c); } return output.toString(); } private static void test(String toEncode, String symTable){ List<Integer> encoded = encode(toEncode, symTable); System.out.println(toEncode + ": " + encoded); String decoded = decode(encoded, symTable); System.out.println((toEncode.equals(decoded) ? "": "in") + "correctly decoded to " + decoded); } public static void main(String[] args){ String symTable = "abcdefghijklmnopqrstuvwxyz"; test("broood", symTable); test("bananaaa", symTable); test("hiphophiphop", symTable); } }
550Move-to-front algorithm
9java
ecia5
null
554Monads/Writer monad
11kotlin
ogf8z
Array.prototype.bind = function (func) { return this.map(func).reduce(function (acc, a) { return acc.concat(a); }); } Array.unit = function (elem) { return [elem]; } Array.lift = function (func) { return function (elem) { return Array.unit(func(elem)); }; } inc = function (n) { return n + 1; } doub = function (n) { return 2 * n; } listy_inc = Array.lift(inc); listy_doub = Array.lift(doub); [3,4,5].bind(listy_inc).bind(listy_doub);
553Monads/List monad
10javascript
fhydg
null
551Mouse position
11kotlin
2s7li
null
543N-queens problem
0go
x2mwf
var encodeMTF = function (word) { var init = {wordAsNumbers: [], charList: 'abcdefghijklmnopqrstuvwxyz'.split('')}; return word.split('').reduce(function (acc, char) { var charNum = acc.charList.indexOf(char);
550Move-to-front algorithm
10javascript
05zsz
package Writer; use strict; use warnings; sub new { my ($class, $value, $log) = @_; return bless [ $value => $log ], $class; } sub Bind { my ($self, $code) = @_; my ($value, $log) = @$self; my $n = $code->($value); return Writer->new( @$n[0], $log.@$n[1] ); } sub Unit { Writer->new($_[0], sprintf("%-17s:%.12f\n",$_[1],$_[0])) } sub root { Unit sqrt($_[0]), "Took square root" } sub addOne { Unit $_[0]+1, "Added one" } sub half { Unit $_[0]/2, "Divided by two" } print Unit(5, "Initial value")->Bind(\&root)->Bind(\&addOne)->Bind(\&half)->[1];
554Monads/Writer monad
2perl
gnh4e
null
553Monads/List monad
11kotlin
wl8ek
>>> from pprint import pprint as pp >>> from itertools import product >>> >>> def dict_as_mdarray(dimensions=(2, 3), init=0.0): ... return {indices: init for indices in product(*(range(i) for i in dimensions))} ... >>> >>> mdarray = dict_as_mdarray((2, 3, 4, 5)) >>> pp(mdarray) {(0, 0, 0, 0): 0.0, (0, 0, 0, 1): 0.0, (0, 0, 0, 2): 0.0, (0, 0, 0, 3): 0.0, (0, 0, 0, 4): 0.0, (0, 0, 1, 0): 0.0, ... (1, 2, 3, 0): 0.0, (1, 2, 3, 1): 0.0, (1, 2, 3, 2): 0.0, (1, 2, 3, 3): 0.0, (1, 2, 3, 4): 0.0} >>> mdarray[(0, 1, 2, 3)] 0.0 >>> mdarray[(0, 1, 2, 3)] = 6.78 >>> mdarray[(0, 1, 2, 3)] 6.78 >>> mdarray[(0, 1, 2, 3)] = 5.4321 >>> mdarray[(0, 1, 2, 3)] 5.4321 >>> pp(mdarray) {(0, 0, 0, 0): 0.0, (0, 0, 0, 1): 0.0, (0, 0, 0, 2): 0.0, ... (0, 1, 2, 2): 0.0, (0, 1, 2, 3): 5.4321, (0, 1, 2, 4): 0.0, ... (1, 2, 3, 3): 0.0, (1, 2, 3, 4): 0.0} >>>
547Multi-dimensional array
3python
pyibm
def listOrder = { a, b -> def k = [a.size(), b.size()].min() def i = (0..<k).find { a[it] != b[it] } (i != null) ? a[i] <=> b[i]: a.size() <=> b.size() } def orderedPermutations = { list -> def n = list.size() (0..<n).permutations().sort(listOrder) } def diagonalSafe = { list -> def n = list.size() n == 1 || (0..<(n-1)).every{ i -> ((i+1)..<n).every{ j -> !([list[i]+j-i, list[i]+i-j].contains(list[j])) } } } def queensDistinctSolutions = { n ->
543N-queens problem
7groovy
pytbo
<?php $pwr = array_fill(0, 10, 0); function isMunchhausen($n) { global $pwr; $sm = 0; $temp = $n; while ($temp) { $sm= $sm + $pwr[($temp % 10)]; $temp = (int)($temp / 10); } return $sm == $n; } for ($i = 0; $i < 10; $i++) { $pwr[$i] = pow((float)($i), (float)($i)); } for ($i = 1; $i < 5000 + 1; $i++) { if (isMunchhausen($i)) { echo $i . PHP_EOL; } }
541Munchausen numbers
12php
5o0us