code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
Point = Struct.new(:x, :y) def distance(p1, p2) Math.hypot(p1.x - p2.x, p1.y - p2.y) end def closest_bruteforce(points) mindist, minpts = Float::MAX, [] points.combination(2) do |pi,pj| dist = distance(pi, pj) if dist < mindist mindist = dist minpts = [pi, pj] end end [mindist, minpts] end def closest_recursive(points) return closest_bruteforce(points) if points.length <= 3 xP = points.sort_by(&:x) mid = points.length / 2 xm = xP[mid].x dL, pairL = closest_recursive(xP[0,mid]) dR, pairR = closest_recursive(xP[mid..-1]) dmin, dpair = dL<dR? [dL, pairL]: [dR, pairR] yP = xP.find_all {|p| (xm - p.x).abs < dmin}.sort_by(&:y) closest, closestPair = dmin, dpair 0.upto(yP.length - 2) do |i| (i+1).upto(yP.length - 1) do |k| break if (yP[k].y - yP[i].y) >= dmin dist = distance(yP[i], yP[k]) if dist < closest closest = dist closestPair = [yP[i], yP[k]] end end end [closest, closestPair] end points = Array.new(100) {Point.new(rand, rand)} p ans1 = closest_bruteforce(points) p ans2 = closest_recursive(points) fail if ans1[0]!= ans2[0] require 'benchmark' points = Array.new(10000) {Point.new(rand, rand)} Benchmark.bm(12) do |x| x.report() {ans1 = closest_bruteforce(points)} x.report() {ans2 = closest_recursive(points)} end
1,036Closest-pair problem
14ruby
2gplw
use std::collections::HashMap; use std::io; use std::io::prelude::*; use std::io::BufReader; use std::net::{TcpListener, TcpStream}; use std::sync::{Arc, RwLock}; use std::thread; type Username = String;
1,051Chat server
15rust
esbaj
mul_inv <- function(a, b) { b0 <- b x0 <- 0L x1 <- 1L if (b == 1) return(1L) while(a > 1){ q <- as.integer(a/b) t <- b b <- a %% b a <- t t <- x0 x0 <- x1 - q*x0 x1 <- t } if (x1 < 0) x1 <- x1 + b0 return(x1) } chinese_remainder <- function(n, a) { len <- length(n) prod <- 1L sum <- 0L for (i in 1:len) prod <- prod * n[i] for (i in 1:len){ p <- as.integer(prod / n[i]) sum <- sum + a[i] * mul_inv(p, n[i]) * p } return(sum %% prod) } n <- c(3L, 5L, 7L) a <- c(2L, 3L, 2L) chinese_remainder(n, a)
1,047Chinese remainder theorem
13r
2gvlg
use strict; sub circles { my ($x1, $y1, $x2, $y2, $r) = @_; return "Radius is zero" if $r == 0; return "Coincident points gives infinite number of circles" if $x1 == $x2 and $y1 == $y2; my ($dx, $dy) = ($x2 - $x1, $y2 - $y1); my $q = sqrt($dx**2 + $dy**2); return "Separation of points greater than diameter" if $q > 2*$r; my ($x3, $y3) = (($x1 + $x2) / 2, ($y1 + $y2) / 2); my $d = sqrt($r**2-($q/2)**2); sprintf '(%.4f,%.4f) and (%.4f,%.4f)', $x3 - $d*$dy/$q, $y3 + $d*$dx/$q, $x3 + $d*$dy/$q, $y3 - $d*$dx/$q; } my @arr = ( [0.1234, 0.9876, 0.8765, 0.2345, 2.0], [0.0000, 2.0000, 0.0000, 0.0000, 1.0], [0.1234, 0.9876, 0.1234, 0.9876, 2.0], [0.1234, 0.9876, 0.8765, 0.2345, 0.5], [0.1234, 0.9876, 0.1234, 0.9876, 0.0] ); printf "(%.4f,%.4f) and (%.4f,%.4f) with radius%.1f:%s\n", @$_[0..4], circles @$_ for @arr;
1,046Circles of given radius through two points
2perl
u74vr
pinyin = { '' => 'ji', '' => 'y', '' => 'bng', '' => 'dng', '' => 'w', '' => 'j', '' => 'gng', '' => 'xn', '' => 'rn', '' => 'gi', '' => 'z', '' => 'chu', '' => 'yn', '' => 'mo', '' => 'chn', '' => 's', '' => 'w', '' => 'wi', '' => 'shn', '' => 'yu', '' => 'x', '' => 'hi' } celestial = %w( ) terrestrial = %w( ) animals = %w(Rat Ox Tiger Rabbit Dragon Snake Horse Goat Monkey Rooster Dog Pig) elements = %w(Wood Fire Earth Metal Water) aspects = %w(yang yin) BASE = 4 args = if!ARGV.empty? ARGV else [Time.new.year] end args.each do |arg| ce_year = Integer(arg) print if ARGV.length > 1 cycle_year = ce_year - BASE stem_number = cycle_year % 10 stem_han = celestial[stem_number] stem_pinyin = pinyin[stem_han] element_number = stem_number / 2 element = elements[element_number] branch_number = cycle_year % 12 branch_han = terrestrial[branch_number] branch_pinyin = pinyin[branch_han] animal = animals[branch_number] aspect_number = cycle_year % 2 aspect = aspects[aspect_number] index = cycle_year % 60 + 1 print stem_han, branch_han puts end
1,048Chinese zodiac
14ruby
l4lcl
t(chol(matrix(c(25, 15, -5, 15, 18, 0, -5, 0, 11), nrow=3, ncol=3))) t(chol(matrix(c(18, 22, 54, 42, 22, 70, 86, 62, 54, 86, 174, 134, 42, 62, 134, 106), nrow=4, ncol=4)))
1,042Cholesky decomposition
13r
z9cth
null
1,036Closest-pair problem
15rust
vr12t
fn chinese_zodiac(year: usize) -> String { static ANIMALS: [&str; 12] = [ "Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake", "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig", ]; static ASPECTS: [&str; 2] = ["Yang", "Yin"]; static ELEMENTS: [&str; 5] = ["Wood", "Fire", "Earth", "Metal", "Water"]; static STEMS: [char; 10] = [ '', '', '', '', '', '', '', '', '', '', ]; static BRANCHES: [char; 12] = [ '', '', '', '', '', '', '', '', '', '', '', '', ]; static S_NAMES: [&str; 10] = [ "ji", "y", "bng", "dng", "w", "j", "gng", "xn", "rn", "gi", ]; static B_NAMES: [&str; 12] = [ "z", "chu", "yn", "mo", "chn", "s", "w", "wi", "shn", "yu", "x", "hi", ]; let y = year - 4; let s = y% 10; let b = y% 12; let stem = STEMS[s]; let branch = BRANCHES[b]; let s_name = S_NAMES[s]; let b_name = B_NAMES[b]; let element = ELEMENTS[s / 2]; let animal = ANIMALS[b]; let aspect = ASPECTS[s% 2]; let cycle = y% 60 + 1; format!( "{} {}{} {:9} {:7} {:7} {:6} {:02}/60", year, stem, branch, format!("{}-{}", s_name, b_name), element, animal, aspect, cycle ) } fn main() { let years = [1935, 1938, 1968, 1972, 1976, 1984, 2017]; println!("Year Chinese Pinyin Element Animal Aspect Cycle"); println!("---- ------- --------- ------- ------- ------ -----"); for &year in &years { println!("{}", chinese_zodiac(year)); } }
1,048Chinese zodiac
15rust
2g2lt
object Zodiac extends App { val years = Seq(1935, 1938, 1968, 1972, 1976, 1984, 1985, 2017, 2018) private def animals = Seq("Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake", "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig") private def animalChars = Seq("", "", "", "", "", "", "", "", "", "", "", "") private def elements = Seq("Wood", "Fire", "Earth", "Metal", "Water") private def elementChars = Seq(Array("", "", "", "", ""), Array("", "", "", "", "")) private def getYY(year: Int) = if (year % 2 == 0) "yang" else "yin" for (year <- years) { println(year + " is the year of the " + elements(math.floor((year - 4) % 10 / 2).toInt) + " " + animals((year - 4) % 12) + " (" + getYY(year) + "). " + elementChars(year % 2)(math.floor((year - 4) % 10 / 2).toInt) + animalChars((year - 4) % 12)) } }
1,048Chinese zodiac
16scala
5j5ut
import java.io.File; public class FileExistsTest { public static boolean isFileExists(String filename) { boolean exists = new File(filename).exists(); return exists; } public static void test(String type, String filename) { System.out.println("The following " + type + " called " + filename + (isFileExists(filename) ? " exists." : " not exists.") ); } public static void main(String args[]) { test("file", "input.txt"); test("file", File.separator + "input.txt"); test("directory", "docs"); test("directory", File.separator + "docs" + File.separator); } }
1,053Check that file exists
9java
ka4hm
import argparse import random import shapely.geometry as geometry import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation def main(args): plt.style.use() fig = plt.figure() line, = plt.plot([], [], ) plt.xlim(0, 1) plt.ylim(0, 1) title = plt.title(title) fig.canvas.set_window_title(title) data = get_data(args.frames) line_ani = animation.FuncAnimation( fig=fig, func=update_line, frames=args.frames, fargs=(data, line), interval=args.interval, repeat=False ) plt.show() def get_data(n): leg = 1 triangle = get_triangle(leg) cur_point = gen_point_within_poly(triangle) data = [] for _ in range(n): data.append((cur_point.x, cur_point.y)) cur_point = next_point(triangle, cur_point) return data def get_triangle(n): ax = ay = 0.0 a = ax, ay bx = 0.5 * n by = 0.75 * (n ** 2) b = bx, by cx = n cy = 0.0 c = cx, cy triangle = geometry.Polygon([a, b, c]) return triangle def gen_point_within_poly(poly): minx, miny, maxx, maxy = poly.bounds while True: x = random.uniform(minx, maxx) y = random.uniform(miny, maxy) point = geometry.Point(x, y) if point.within(poly): return point def next_point(poly, point): vertices = poly.boundary.coords[:-1] random_vertex = geometry.Point(random.choice(vertices)) line = geometry.linestring.LineString([point, random_vertex]) return line.centroid def update_line(num, data, line): new_data = zip(*data[:num]) or [(), ()] line.set_data(new_data) return line, if __name__ == : arg_parser = argparse.ArgumentParser(description=) arg_parser.add_argument(, dest=, type=int, default=1000) arg_parser.add_argument(, dest=, type=int, default=10) main(arg_parser.parse_args())
1,052Chaos game
3python
ylf6q
def comb(m, n) (0...n).to_a.combination(m).to_a end comb(3, 5)
1,031Combinations
14ruby
4h85p
import scala.collection.mutable.ListBuffer import scala.util.Random object ClosestPair { case class Point(x: Double, y: Double){ def distance(p: Point) = math.hypot(x-p.x, y-p.y) override def toString = "(" + x + ", " + y + ")" } case class Pair(point1: Point, point2: Point) { val distance: Double = point1 distance point2 override def toString = { point1 + "-" + point2 + ": " + distance } } def sortByX(points: List[Point]) = { points.sortBy(point => point.x) } def sortByY(points: List[Point]) = { points.sortBy(point => point.y) } def divideAndConquer(points: List[Point]): Pair = { val pointsSortedByX = sortByX(points) val pointsSortedByY = sortByY(points) divideAndConquer(pointsSortedByX, pointsSortedByY) } def bruteForce(points: List[Point]): Pair = { val numPoints = points.size if (numPoints < 2) return null var pair = Pair(points(0), points(1)) if (numPoints > 2) { for (i <- 0 until numPoints - 1) { val point1 = points(i) for (j <- i + 1 until numPoints) { val point2 = points(j) val distance = point1 distance point2 if (distance < pair.distance) pair = Pair(point1, point2) } } } return pair } private def divideAndConquer(pointsSortedByX: List[Point], pointsSortedByY: List[Point]): Pair = { val numPoints = pointsSortedByX.size if(numPoints <= 3) { return bruteForce(pointsSortedByX) } val dividingIndex = numPoints >>> 1 val leftOfCenter = pointsSortedByX.slice(0, dividingIndex) val rightOfCenter = pointsSortedByX.slice(dividingIndex, numPoints) var tempList = leftOfCenter.map(x => x)
1,036Closest-pair problem
16scala
4hw50
var fso = new ActiveXObject("Scripting.FileSystemObject"); fso.FileExists('input.txt'); fso.FileExists('c:/input.txt'); fso.FolderExists('docs'); fso.FolderExists('c:/docs');
1,053Check that file exists
10javascript
eshao
pChaosGameS3 <- function(size, lim, clr, fn, ttl) { cat(" *** START:", date(), "size=",size, "lim=",lim, "clr=",clr, "\n"); sz1=floor(size/2); sz2=floor(sz1*sqrt(3)); xf=yf=v=0; M <- matrix(c(0), ncol=size, nrow=size, byrow=TRUE); x <- sample(1:size, 1, replace=FALSE); y <- sample(1:sz2, 1, replace=FALSE); pf=paste0(fn, ".png"); for (i in 1:lim) { v <- sample(0:3, 1, replace=FALSE); if(v==0) {x=x/2; y=y/2;} if(v==1) {x=sz1+(sz1-x)/2; y=sz2-(sz2-y)/2;} if(v==2) {x=size-(size-x)/2; y=y/2;} xf=floor(x); yf=floor(y); if(xf<1||xf>size||yf<1||yf>size) {next}; M[xf,yf]=1; } plotmat(M, fn, clr, ttl, 0, size); cat(" *** END:",date(),"\n"); } pChaosGameS3(600, 30000, "red", "SierpTriR1", "Sierpinski triangle")
1,052Chaos game
13r
tyofz
use strict; my @c = (); push @c, 10, 11, 12; push @c, 65; print join(" ",@c) . "\n"; my %h = (); $h{'one'} = 1; $h{'two'} = 2; foreach my $i ( keys %h ) { print $i . " -> " . $h{$i} . "\n"; }
1,037Collections
2perl
ke8hc
fn comb<T: std::fmt::Default>(arr: &[T], n: uint) { let mut incl_arr: ~[bool] = std::vec::from_elem(arr.len(), false); comb_intern(arr, n, incl_arr, 0); } fn comb_intern<T: std::fmt::Default>(arr: &[T], n: uint, incl_arr: &mut [bool], index: uint) { if (arr.len() < n + index) { return; } if (n == 0) { let mut it = arr.iter().zip(incl_arr.iter()).filter_map(|(val, incl)| if (*incl) { Some(val) } else { None } ); for val in it { print!("{} ", *val); } print("\n"); return; } incl_arr[index] = true; comb_intern(arr, n-1, incl_arr, index+1); incl_arr[index] = false; comb_intern(arr, n, incl_arr, index+1); } fn main() { let arr1 = ~[1, 2, 3, 4, 5]; comb(arr1, 3); let arr2 = ~["A", "B", "C", "D", "E"]; comb(arr2, 3); }
1,031Combinations
15rust
gko4o
def chinese_remainder(mods, remainders) max = mods.inject(:* ) series = remainders.zip( mods ).map{|r,m| r.step( max, m ).to_a } series.inject(:& ).first end p chinese_remainder([3,5,7], [2,3,2]) p chinese_remainder([10,4,9], [11,22,19])
1,047Chinese remainder theorem
14ruby
rb7gs
class MyClass: name2 = 2 def __init__(self): self.name1 = 0 def someMethod(self): self.name1 = 1 MyClass.name2 = 3 myclass = MyClass() class MyOtherClass: count = 0 def __init__(self, name, gender=, age=None): MyOtherClass.count += 1 self.name = name self.gender = gender if age is not None: self.age = age def __del__(self): MyOtherClass.count -= 1 person1 = MyOtherClass() print person1.name, person1.gender print person1.age person2 = MyOtherClass(, , 23) print person2.name, person2.gender, person2.age
1,038Classes
3python
fy2de
null
1,053Check that file exists
11kotlin
ghl4d
fmt.Println('a')
1,054Character codes
0go
7b2r2
require 'matrix' class Matrix def symmetric? return false if not square? (0 ... row_size).each do |i| (0 .. i).each do |j| return false if self[i,j]!= self[j,i] end end true end def cholesky_factor raise ArgumentError, unless symmetric? l = Array.new(row_size) {Array.new(row_size, 0)} (0 ... row_size).each do |k| (0 ... row_size).each do |i| if i == k sum = (0 .. k-1).inject(0.0) {|sum, j| sum + l[k][j] ** 2} val = Math.sqrt(self[k,k] - sum) l[k][k] = val elsif i > k sum = (0 .. k-1).inject(0.0) {|sum, j| sum + l[i][j] * l[k][j]} val = (self[k,i] - sum) / l[k][k] l[i][k] = val end end end Matrix[*l] end end puts Matrix[[25,15,-5],[15,18,0],[-5,0,11]].cholesky_factor puts Matrix[[18, 22, 54, 42], [22, 70, 86, 62], [54, 86, 174, 134], [42, 62, 134, 106]].cholesky_factor
1,042Cholesky decomposition
14ruby
c549k
implicit def toComb(m: Int) = new AnyRef { def comb(n: Int) = recurse(m, List.range(0, n)) private def recurse(m: Int, l: List[Int]): List[List[Int]] = (m, l) match { case (0, _) => List(Nil) case (_, Nil) => Nil case _ => (recurse(m - 1, l.tail) map (l.head :: _)) ::: recurse(m, l.tail) } }
1,031Combinations
16scala
j1d7i
fn egcd(a: i64, b: i64) -> (i64, i64, i64) { if a == 0 { (b, 0, 1) } else { let (g, x, y) = egcd(b% a, a); (g, y - (b / a) * x, x) } } fn mod_inv(x: i64, n: i64) -> Option<i64> { let (g, x, _) = egcd(x, n); if g == 1 { Some((x% n + n)% n) } else { None } } fn chinese_remainder(residues: &[i64], modulii: &[i64]) -> Option<i64> { let prod = modulii.iter().product::<i64>(); let mut sum = 0; for (&residue, &modulus) in residues.iter().zip(modulii) { let p = prod / modulus; sum += residue * mod_inv(p, modulus)? * p } Some(sum% prod) } fn main() { let modulii = [3,5,7]; let residues = [2,3,2]; match chinese_remainder(&residues, &modulii) { Some(sol) => println!("{}", sol), None => println!("modulii not pairwise coprime") } }
1,047Chinese remainder theorem
15rust
7pjrc
import scala.util.{Success, Try} object ChineseRemainderTheorem extends App { def chineseRemainder(n: List[Int], a: List[Int]): Option[Int] = { require(n.size == a.size) val prod = n.product def iter(n: List[Int], a: List[Int], sm: Int): Int = { def mulInv(a: Int, b: Int): Int = { def loop(a: Int, b: Int, x0: Int, x1: Int): Int = { if (a > 1) loop(b, a % b, x1 - (a / b) * x0, x0) else x1 } if (b == 1) 1 else { val x1 = loop(a, b, 0, 1) if (x1 < 0) x1 + b else x1 } } if (n.nonEmpty) { val p = prod / n.head iter(n.tail, a.tail, sm + a.head * mulInv(p, n.head) * p) } else sm } Try { iter(n, a, 0) % prod } match { case Success(v) => Some(v) case _ => None } } println(chineseRemainder(List(3, 5, 7), List(2, 3, 2))) println(chineseRemainder(List(11, 12, 13), List(10, 4, 12))) println(chineseRemainder(List(11, 22, 19), List(10, 4, 9))) }
1,047Chinese remainder theorem
16scala
kebhk
circS3 <- list(radius=5.5, centre=c(3, 4.2)) class(circS3) <- "circle" plot.circle <- function(x, ...) { t <- seq(0, 2*pi, length.out=200) plot(x$centre[1] + x$radius*cos(t), x$centre[2] + x$radius*sin(t), type="l", ...) } plot(circS3)
1,038Classes
13r
otm84
from collections import namedtuple from math import sqrt Pt = namedtuple('Pt', 'x, y') Circle = Cir = namedtuple('Circle', 'x, y, r') def circles_from_p1p2r(p1, p2, r): 'Following explanation at http: if r == 0.0: raise ValueError('radius of zero') (x1, y1), (x2, y2) = p1, p2 if p1 == p2: raise ValueError('coincident points gives infinite number of Circles') dx, dy = x2 - x1, y2 - y1 q = sqrt(dx**2 + dy**2) if q > 2.0*r: raise ValueError('separation of points > diameter') x3, y3 = (x1+x2)/2, (y1+y2)/2 d = sqrt(r**2-(q/2)**2) c1 = Cir(x = x3 - d*dy/q, y = y3 + d*dx/q, r = abs(r)) c2 = Cir(x = x3 + d*dy/q, y = y3 - d*dx/q, r = abs(r)) return c1, c2 if __name__ == '__main__': for p1, p2, r in [(Pt(0.1234, 0.9876), Pt(0.8765, 0.2345), 2.0), (Pt(0.0000, 2.0000), Pt(0.0000, 0.0000), 1.0), (Pt(0.1234, 0.9876), Pt(0.1234, 0.9876), 2.0), (Pt(0.1234, 0.9876), Pt(0.8765, 0.2345), 0.5), (Pt(0.1234, 0.9876), Pt(0.1234, 0.9876), 0.0)]: print('Through points:\n %r,\n %r\n and radius%f\nYou can construct the following circles:' % (p1, p2, r)) try: print(' %r\n %r\n'% circles_from_p1p2r(p1, p2, r)) except ValueError as v: print(' ERROR:%s\n'% (v.args[0],))
1,046Circles of given radius through two points
3python
5jgux
printf ("%d\n", ('a' as char) as int) printf ("%c\n", 97)
1,054Character codes
7groovy
uryv9
fn cholesky(mat: Vec<f64>, n: usize) -> Vec<f64> { let mut res = vec![0.0; mat.len()]; for i in 0..n { for j in 0..(i+1){ let mut s = 0.0; for k in 0..j { s += res[i * n + k] * res[j * n + k]; } res[i * n + j] = if i == j { (mat[i * n + i] - s).sqrt() } else { (1.0 / res[j * n + j] * (mat[i * n + j] - s)) }; } } res } fn show_matrix(matrix: Vec<f64>, n: usize){ for i in 0..n { for j in 0..n { print!("{:.4}\t", matrix[i * n + j]); } println!(""); } println!(""); } fn main(){ let dimension = 3 as usize; let m1 = vec![25.0, 15.0, -5.0, 15.0, 18.0, 0.0, -5.0, 0.0, 11.0]; let res1 = cholesky(m1, dimension); show_matrix(res1, dimension); let dimension = 4 as usize; let m2 = vec![18.0, 22.0, 54.0, 42.0, 22.0, 70.0, 86.0, 62.0, 54.0, 86.0, 174.0, 134.0, 42.0, 62.0, 134.0, 106.0]; let res2 = cholesky(m2, dimension); show_matrix(res2, dimension); }
1,042Cholesky decomposition
15rust
l4gcc
<?php $a = array(); array_push($a, 55, 10, 20); print_r($a); $a['one'] = 1; $a['two'] = 2; print_r($a); ?>
1,037Collections
12php
3c4zq
import Data.Char main = do print (ord 'a') print (chr 97) print (ord '') print (chr 960)
1,054Character codes
8haskell
8da0z
case class Matrix( val matrix:Array[Array[Double]] ) {
1,042Cholesky decomposition
16scala
u7jv8
CREATE TEMPORARY TABLE inputs(remainder INT, modulus INT); INSERT INTO inputs VALUES (2, 3), (3, 5), (2, 7); WITH recursive -- Multiply out the product of moduli multiplication(idx, product) AS ( SELECT 1, 1 UNION ALL SELECT multiplication.idx+1, multiplication.product * inputs.modulus FROM multiplication, inputs WHERE inputs.rowid = multiplication.idx ), -- Take the final value from the product table product(final_value) AS ( SELECT MAX(product) FROM multiplication ), -- Calculate the multiplicative inverse from each equation multiplicative_inverse(id, a, b, x, y) AS ( SELECT inputs.modulus, product.final_value / inputs.modulus, inputs.modulus, 0, 1 FROM inputs, product UNION ALL SELECT id, b, a%b, y - (a/b)*x, x FROM multiplicative_inverse WHERE a>0 ) -- Combine residues into final answer SELECT SUM( (y% inputs.modulus) * inputs.remainder * (product.final_value / inputs.modulus) )% product.final_value FROM multiplicative_inverse, product, inputs WHERE a=1 AND multiplicative_inverse.id = inputs.modulus;
1,047Chinese remainder theorem
19sql
1qapg
import Foundation struct Point { var x: Double var y: Double func distance(to p: Point) -> Double { let x = pow(p.x - self.x, 2) let y = pow(p.y - self.y, 2) return (x + y).squareRoot() } } extension Collection where Element == Point { func closestPair() -> (Point, Point)? { let (xP, xY) = (sorted(by: { $0.x < $1.x }), sorted(by: { $0.y < $1.y })) return Self.closestPair(xP, xY)?.1 } static func closestPair(_ xP: [Element], _ yP: [Element]) -> (Double, (Point, Point))? { guard xP.count > 3 else { return xP.closestPairBruteForce() } let half = xP.count / 2 let xl = Array(xP[..<half]) let xr = Array(xP[half...]) let xm = xl.last!.x let (yl, yr) = yP.reduce(into: ([Element](), [Element]()), {cur, el in if el.x > xm { cur.1.append(el) } else { cur.0.append(el) } }) guard let (distanceL, pairL) = closestPair(xl, yl) else { return nil } guard let (distanceR, pairR) = closestPair(xr, yr) else { return nil } let (dMin, pairMin) = distanceL > distanceR? (distanceR, pairR): (distanceL, pairL) let ys = yP.filter({ abs(xm - $0.x) < dMin }) var (closest, pairClosest) = (dMin, pairMin) for i in 0..<ys.count { let p1 = ys[i] for k in i+1..<ys.count { let p2 = ys[k] guard abs(p2.y - p1.y) < dMin else { break } let distance = abs(p1.distance(to: p2)) if distance < closest { (closest, pairClosest) = (distance, (p1, p2)) } } } return (closest, pairClosest) } func closestPairBruteForce() -> (Double, (Point, Point))? { guard count >= 2 else { return nil } var closestPoints = (self.first!, self[index(after: startIndex)]) var minDistance = abs(closestPoints.0.distance(to: closestPoints.1)) guard count!= 2 else { return (minDistance, closestPoints) } for i in 0..<count { for j in i+1..<count { let (iIndex, jIndex) = (index(startIndex, offsetBy: i), index(startIndex, offsetBy: j)) let (p1, p2) = (self[iIndex], self[jIndex]) let distance = abs(p1.distance(to: p2)) if distance < minDistance { minDistance = distance closestPoints = (p1, p2) } } } return (minDistance, closestPoints) } } var points = [Point]() for _ in 0..<10_000 { points.append(Point( x: .random(in: -10.0...10.0), y: .random(in: -10.0...10.0) )) } print(points.closestPair()!)
1,036Closest-pair problem
17swift
l4bc2
extern crate image; extern crate rand; use rand::prelude::*; use std::f32; fn main() { let max_iterations = 50_000; let img_side = 800; let tri_size = 400.0;
1,052Chaos game
15rust
cu39z
import Darwin func euclid(_ m:Int, _ n:Int) -> (Int,Int) { if m% n == 0 { return (0,1) } else { let rs = euclid(n% m, m) let r = rs.1 - rs.0 * (n / m) let s = rs.0 return (r,s) } } func gcd(_ m:Int, _ n:Int) -> Int { let rs = euclid(m, n) return m * rs.0 + n * rs.1 } func coprime(_ m:Int, _ n:Int) -> Bool { return gcd(m,n) == 1? true: false } coprime(14,26)
1,047Chinese remainder theorem
17swift
gkr49
import javax.swing._ import java.awt._ import java.awt.event.ActionEvent import scala.collection.mutable import scala.util.Random object ChaosGame extends App { SwingUtilities.invokeLater(() => new JFrame("Chaos Game") { class ChaosGame extends JPanel { private val (dim, margin)= (new Dimension(640, 640), 60) private val sizez: Int = dim.width - 2 * margin private val (stack, r) = (new mutable.Stack[ColoredPoint], new Random) private val points = Seq(new Point(dim.width / 2, margin), new Point(margin, sizez), new Point(margin + sizez, sizez) ) private val colors = Seq(Color.red, Color.green, Color.blue) override def paintComponent(gg: Graphics): Unit = { val g = gg.asInstanceOf[Graphics2D] def drawPoints(g: Graphics2D): Unit = { for (p <- stack) { g.setColor(colors(p.colorIndex)) g.fillOval(p.x, p.y, 1, 1) } } super.paintComponent(gg) g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) drawPoints(g) } private def addPoint(): Unit = { val colorIndex = r.nextInt(3) def halfwayPoint(a: Point, b: Point, idx: Int) = new ColoredPoint((a.x + b.x) / 2, (a.y + b.y) / 2, idx) stack.push(halfwayPoint(stack.top, points(colorIndex), colorIndex)) } class ColoredPoint(x: Int, y: Int, val colorIndex: Int) extends Point(x, y) stack.push(new ColoredPoint(-1, -1, 0)) new Timer(100, (_: ActionEvent) => { if (stack.size < 50000) { for (i <- 0 until 1000) addPoint() repaint() } }).start() setBackground(Color.white) setPreferredSize(dim) } add(new ChaosGame, BorderLayout.CENTER) pack() setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE) setLocationRelativeTo(null) setResizable(false) setVisible(true) } ) }
1,052Chaos game
16scala
vgm2s
class MyClass def initialize @instance_var = 0 end def add_1 @instance_var += 1 end end my_class = MyClass.new
1,038Classes
14ruby
z9utw
function output( s, b ) if b then print ( s, " does not exist." ) else print ( s, " does exist." ) end end output( "input.txt", io.open( "input.txt", "r" ) == nil ) output( "/input.txt", io.open( "/input.txt", "r" ) == nil ) output( "docs", io.open( "docs", "r" ) == nil ) output( "/docs", io.open( "/docs", "r" ) == nil )
1,053Check that file exists
1lua
rk2ga
struct MyClass { variable: i32,
1,038Classes
15rust
3c5z8
Pt = Struct.new(:x, :y) Circle = Struct.new(:x, :y, :r) def circles_from(pt1, pt2, r) raise ArgumentError, if pt1 == pt2 && r > 0 return [Circle.new(pt1.x, pt1.y, r)] if pt1 == pt2 && r == 0 dx, dy = pt2.x - pt1.x, pt2.y - pt1.y q = Math.hypot(dx, dy) raise ArgumentError, if q > 2.0*r x3, y3 = (pt1.x + pt2.x)/2.0, (pt1.y + pt2.y)/2.0 d = (r**2 - (q/2)**2)**0.5 [Circle.new(x3 - d*dy/q, y3 + d*dx/q, r), Circle.new(x3 + d*dy/q, y3 - d*dx/q, r)].uniq end ar = [[Pt.new(0.1234, 0.9876), Pt.new(0.8765, 0.2345), 2.0], [Pt.new(0.0000, 2.0000), Pt.new(0.0000, 0.0000), 1.0], [Pt.new(0.1234, 0.9876), Pt.new(0.1234, 0.9876), 2.0], [Pt.new(0.1234, 0.9876), Pt.new(0.8765, 0.2345), 0.5], [Pt.new(0.1234, 0.9876), Pt.new(0.1234, 0.9876), 0.0]] ar.each do |p1, p2, r| print begin circles = circles_from(p1, p2, r) puts circles.each{|c| puts } rescue ArgumentError => e puts e end puts end
1,046Circles of given radius through two points
14ruby
gk74q
class MyClass(val myMethod: Int) {
1,038Classes
16scala
mvryc
public class Foo { public static void main(String[] args) { System.out.println((int)'a');
1,054Character codes
9java
esja5
use std::fmt; #[derive(Clone,Copy)] struct Point { x: f64, y: f64 } fn distance (p1: Point, p2: Point) -> f64 { ((p1.x - p2.x).powi(2) + (p1.y - p2.y).powi(2)).sqrt() } impl fmt::Display for Point { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "({:.4}, {:.4})", self.x, self.y) } } fn describe_circle(p1: Point, p2: Point, r: f64) { let sep = distance(p1, p2); if sep == 0. { if r == 0. { println!("No circles can be drawn through {}", p1); } else { println!("Infinitely many circles can be drawn through {}", p1); } } else if sep == 2.0 * r { println!("Given points are opposite ends of a diameter of the circle with center ({:.4},{:.4}) and r {:.4}", (p1.x+p2.x) / 2.0, (p1.y+p2.y) / 2.0, r); } else if sep > 2.0 * r { println!("Given points are farther away from each other than a diameter of a circle with r {:.4}", r); } else { let mirror_dist = (r.powi(2) - (sep / 2.0).powi(2)).sqrt(); println!("Two circles are possible."); println!("Circle C1 with center ({:.4}, {:.4}), r {:.4} and Circle C2 with center ({:.4}, {:.4}), r {:.4}", ((p1.x + p2.x) / 2.0) + mirror_dist * (p1.y-p2.y)/sep, (p1.y+p2.y) / 2.0 + mirror_dist*(p2.x-p1.x)/sep, r, (p1.x+p2.x) / 2.0 - mirror_dist*(p1.y-p2.y)/sep, (p1.y+p2.y) / 2.0 - mirror_dist*(p2.x-p1.x)/sep, r); } } fn main() { let points: Vec<(Point, Point)> = vec![ (Point { x: 0.1234, y: 0.9876 }, Point { x: 0.8765, y: 0.2345 }), (Point { x: 0.0000, y: 2.0000 }, Point { x: 0.0000, y: 0.0000 }), (Point { x: 0.1234, y: 0.9876 }, Point { x: 0.1234, y: 0.9876 }), (Point { x: 0.1234, y: 0.9876 }, Point { x: 0.8765, y: 0.2345 }), (Point { x: 0.1234, y: 0.9876 }, Point { x: 0.1234, y: 0.9876 }) ]; let radii: Vec<f64> = vec![2.0, 1.0, 2.0, 0.5, 0.0]; for (p, r) in points.into_iter().zip(radii.into_iter()) { println!("\nPoints: ({}, {}), Radius: {:.4}", p.0, p.1, r); describe_circle(p.0, p.1, r); } }
1,046Circles of given radius through two points
15rust
rbjg5
console.log('a'.charCodeAt(0));
1,054Character codes
10javascript
0n1sz
func cholesky(matrix: [Double], n: Int) -> [Double] { var res = [Double](repeating: 0, count: matrix.count) for i in 0..<n { for j in 0..<i+1 { var s = 0.0 for k in 0..<j { s += res[i * n + k] * res[j * n + k] } if i == j { res[i * n + j] = (matrix[i * n + i] - s).squareRoot() } else { res[i * n + j] = (1.0 / res[j * n + j] * (matrix[i * n + j] - s)) } } } return res } func printMatrix(_ matrix: [Double], n: Int) { for i in 0..<n { for j in 0..<n { print(matrix[i * n + j], terminator: " ") } print() } } let res1 = cholesky( matrix: [25.0, 15.0, -5.0, 15.0, 18.0, 0.0, -5.0, 0.0, 11.0], n: 3 ) let res2 = cholesky( matrix: [18.0, 22.0, 54.0, 42.0, 22.0, 70.0, 86.0, 62.0, 54.0, 86.0, 174.0, 134.0, 42.0, 62.0, 134.0, 106.0], n: 4 ) printMatrix(res1, n: 3) print() printMatrix(res2, n: 4)
1,042Cholesky decomposition
17swift
9u5mj
collection = [0, '1'] x = collection[0] collection.append(2) collection.insert(0, '-1') y = collection[0] collection.extend([2,'3']) collection += [2,'3'] collection[2:6] len(collection) collection = (0, 1) collection[:] collection[-4:-1] collection[::2] collection= x = collection[::-1] collection[::2] == [::2] collection.__getitem__(slice(0,len(collection),2)) collection = {0: , 1: } collection['zero'] = 2 collection = set([0, '1'])
1,037Collections
3python
bwokr
import org.scalatest.FunSuite import math._ case class V2(x: Double, y: Double) { val distance = hypot(x, y) def /(other: V2) = V2((x+other.x) / 2.0, (y+other.y) / 2.0) def -(other: V2) = V2(x-other.x,y-other.y) override def equals(other: Any) = other match { case p: V2 => abs(x-p.x) < 0.0001 && abs(y-p.y) < 0.0001 case _ => false } override def toString = f"($x%.4f, $y%.4f)" } case class Circle(center: V2, radius: Double) class PointTest extends FunSuite { println(" p1 p2 r result") Seq( (V2(0.1234, 0.9876), V2(0.8765, 0.2345), 2.0, Seq(Circle(V2(1.8631, 1.9742), 2.0), Circle(V2(-0.8632, -0.7521), 2.0))), (V2(0.0000, 2.0000), V2(0.0000, 0.0000), 1.0, Seq(Circle(V2(0.0, 1.0), 1.0))), (V2(0.1234, 0.9876), V2(0.1234, 0.9876), 2.0, "coincident points yields infinite circles"), (V2(0.1234, 0.9876), V2(0.8765, 0.2345), 0.5, "radius is less then the distance between points"), (V2(0.1234, 0.9876), V2(0.1234, 0.9876), 0.0, "radius of zero yields no circles") ) foreach { v => print(s"${v._1} ${v._2} ${v._3}: ") circles(v._1, v._2, v._3) match { case Right(list) => println(list mkString ",") assert(list === v._4) case Left(error) => println(error) assert(error === v._4) } } def circles(p1: V2, p2: V2, radius: Double) = if (radius == 0.0) { Left("radius of zero yields no circles") } else if (p1 == p2) { Left("coincident points yields infinite circles") } else if (radius * 2 < (p1-p2).distance) { Left("radius is less then the distance between points") } else { Right(circlesThruPoints(p1, p2, radius)) } ensuring { result => result.isLeft || result.right.get.nonEmpty } def circlesThruPoints(p1: V2, p2: V2, radius: Double): Seq[Circle] = { val diff = p2 - p1 val d = pow(pow(radius, 2) - pow(diff.distance / 2, 2), 0.5) val mid = p1 / p2 Seq( Circle(V2(mid.x - d * diff.y / diff.distance, mid.y + d * diff.x / diff.distance), abs(radius)), Circle(V2(mid.x + d * diff.y / diff.distance, mid.y - d * diff.x / diff.distance), abs(radius))).distinct } }
1,046Circles of given radius through two points
16scala
habja
numeric(5) 1:10 c(1, 3, 6, 10, 7 + 8, sqrt(441))
1,037Collections
13r
7pqry
func addCombo(prevCombo: [Int], var pivotList: [Int]) -> [([Int], [Int])] { return (0..<pivotList.count) .map { _ -> ([Int], [Int]) in (prevCombo + [pivotList.removeAtIndex(0)], pivotList) } } func combosOfLength(n: Int, m: Int) -> [[Int]] { return [Int](1...m) .reduce([([Int](), [Int](0..<n))]) { (accum, _) in accum.flatMap(addCombo) }.map { $0.0 } } println(combosOfLength(5, 3))
1,031Combinations
17swift
5j0u8
fun main(args: Array<String>) { var c = 'a' var i = c.toInt() println("$c <-> $i") i += 2 c = i.toChar() println("$i <-> $c") }
1,054Character codes
11kotlin
ka5h3
class MyClass{
1,038Classes
17swift
tmvfl
import Foundation struct Point: Equatable { var x: Double var y: Double } struct Circle { var center: Point var radius: Double static func circleBetween( _ p1: Point, _ p2: Point, withRadius radius: Double ) -> (Circle, Circle?)? { func applyPoint(_ p1: Point, _ p2: Point, op: (Double, Double) -> Double) -> Point { return Point(x: op(p1.x, p2.x), y: op(p1.y, p2.y)) } func mul2(_ p: Point, mul: Double) -> Point { return Point(x: p.x * mul, y: p.y * mul) } func div2(_ p: Point, div: Double) -> Point { return Point(x: p.x / div, y: p.y / div) } func norm(_ p: Point) -> Point { return div2(p, div: (p.x * p.x + p.y * p.y).squareRoot()) } guard radius!= 0, p1!= p2 else { return nil } let diameter = 2 * radius let pq = applyPoint(p1, p2, op: -) let magPQ = (pq.x * pq.x + pq.y * pq.y).squareRoot() guard diameter >= magPQ else { return nil } let midpoint = div2(applyPoint(p1, p2, op: +), div: 2) let halfPQ = magPQ / 2 let magMidC = abs(radius * radius - halfPQ * halfPQ).squareRoot() let midC = mul2(norm(Point(x: -pq.y, y: pq.x)), mul: magMidC) let center1 = applyPoint(midpoint, midC, op: +) let center2 = applyPoint(midpoint, midC, op: -) if center1 == center2 { return (Circle(center: center1, radius: radius), nil) } else { return (Circle(center: center1, radius: radius), Circle(center: center2, radius: radius)) } } } let testCases = [ (Point(x: 0.1234, y: 0.9876), Point(x: 0.8765, y: 0.2345), 2.0), (Point(x: 0.0000, y: 2.0000), Point(x: 0.0000, y: 0.0000), 1.0), (Point(x: 0.1234, y: 0.9876), Point(x: 0.1234, y: 0.9876), 2.0), (Point(x: 0.1234, y: 0.9876), Point(x: 0.8765, y: 0.2345), 0.5), (Point(x: 0.1234, y: 0.9876), Point(x: 0.1234, y: 0.9876), 0.0) ] for testCase in testCases { switch Circle.circleBetween(testCase.0, testCase.1, withRadius: testCase.2) { case nil: print("No ans") case (let circle1, nil)?: print("One ans: \(circle1)") case (let circle1, let circle2?)?: print("Two ans: \(circle1) \(circle2)") } }
1,046Circles of given radius through two points
17swift
4hr5g
a = [] a[0] = 1 a[3] = a << 3.14 a = Array.new a = Array.new(3) a = Array.new(3, 0) a = Array.new(3){|i| i*2}
1,037Collections
14ruby
1qnpw
let a = [1u8,2,3,4,5];
1,037Collections
15rust
asd14
Windows PowerShell Copyright (C) 2012 Microsoft Corporation. All rights reserved. PS C:\Users\FransAdm> scala Welcome to Scala version 2.10.1 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_25). Type in expressions to have them evaluated. Type :help for more information. scala>
1,037Collections
16scala
xozwg
use File::Spec::Functions qw(catfile rootdir); print -e 'input.txt'; print -d 'docs'; print -e catfile rootdir, 'input.txt'; print -d catfile rootdir, 'docs';
1,053Check that file exists
2perl
nzqiw
print(string.byte("a"))
1,054Character codes
1lua
be4ka
if (file_exists('input.txt')) echo 'input.txt is here right by my side'; if (file_exists('docs' )) echo 'docs is here with me'; if (file_exists('/input.txt')) echo 'input.txt is over there in the root dir'; if (file_exists('/docs' )) echo 'docs is over there in the root dir';
1,053Check that file exists
12php
7bvrp
import os os.path.isfile() os.path.isfile() os.path.isdir() os.path.isdir()
1,053Check that file exists
3python
d3sn1
file.exists("input.txt") file.exists("/input.txt") file.exists("docs") file.exists("/docs") file.exists("input.txt", "/input.txt", "docs", "/docs")
1,053Check that file exists
13r
8de0x
File.file?() File.file?() File.directory?() File.directory?()
1,053Check that file exists
14ruby
ty8f2
use std::fs; fn main() { for file in ["input.txt", "docs", "/input.txt", "/docs"].iter() { match fs::metadata(file) { Ok(attr) => { if attr.is_dir() { println!("{} is a directory", file); }else { println!("{} is a file", file); } }, Err(_) => { println!("{} does not exist", file); } }; } }
1,053Check that file exists
15rust
zmoto
import java.nio.file.{ Files, FileSystems } object FileExistsTest extends App { val defaultFS = FileSystems.getDefault() val separator = defaultFS.getSeparator() def test(filename: String) { val path = defaultFS.getPath(filename) println(s"The following ${if (Files.isDirectory(path)) "directory" else "file"} called $filename" + (if (Files.exists(path)) " exists." else " not exists.")) }
1,053Check that file exists
16scala
yld63
use strict; use warnings; use utf8; binmode(STDOUT, ':utf8'); use Encode; use Unicode::UCD 'charinfo'; use List::AllUtils qw(zip natatime); for my $c (split //, 'A') { my $o = ord $c; my $utf8 = join '', map { sprintf "%x ", ord } split //, Encode::encode("utf8", $c); my $iterator = natatime 2, zip @{['Character', 'Character name', 'Ordinal(s)', 'Hex ordinal(s)', 'UTF-8', 'Round trip']}, @{[ $c, charinfo($o)->{'name'}, $o, sprintf("0x%x",$o), $utf8, chr $o, ]}; while ( my ($label, $value) = $iterator->() ) { printf "%14s:%s\n", $label, $value } print "\n"; }
1,054Character codes
2perl
39ozs
echo ord('a'), ; echo chr(97), ;
1,054Character codes
12php
pwgba
print ord('a') print chr(97)
1,054Character codes
3python
6ci3w
ascii <- as.integer(charToRaw("hello world")); ascii text <- rawToChar(as.raw(ascii)); text
1,054Character codes
13r
f6sdc
> .ord => 97 > 97.chr =>
1,054Character codes
14ruby
m2dyj
use std::char::from_u32; fn main() {
1,054Character codes
15rust
9vfmm
scala> 'a' toInt res2: Int = 97 scala> 97 toChar res3: Char = a scala> '\u0061' res4: Char = a scala> "\uD869\uDEA5" res5: String =
1,054Character codes
16scala
243lb
let c1: UnicodeScalar = "a" println(c1.value)
1,054Character codes
17swift
yln6e
typedef int bool; typedef enum { ENCRYPT, DECRYPT } cmode; const char *l_alphabet = ; const char *r_alphabet = ; void chao(const char *in, char *out, cmode mode, bool show_steps) { int i, j, index; char store; size_t len = strlen(in); char left[27], right[27], temp[27]; strcpy(left, l_alphabet); strcpy(right, r_alphabet); temp[26] = '\0'; for (i = 0; i < len; ++i ) { if (show_steps) printf(, left, right); if (mode == ENCRYPT) { index = strchr(right, in[i]) - right; out[i] = left[index]; } else { index = strchr(left, in[i]) - left; out[i] = right[index]; } if (i == len - 1) break; for (j = index; j < 26; ++j) temp[j - index] = left[j]; for (j = 0; j < index; ++j) temp[26 - index + j] = left[j]; store = temp[1]; for (j = 2; j < 14; ++j) temp[j - 1] = temp[j]; temp[13] = store; strcpy(left, temp); for (j = index; j < 26; ++j) temp[j - index] = right[j]; for (j = 0; j < index; ++j) temp[26 - index + j] = right[j]; store = temp[0]; for (j = 1; j < 26; ++j) temp[j - 1] = temp[j]; temp[25] = store; store = temp[2]; for (j = 3; j < 14; ++j) temp[j - 1] = temp[j]; temp[13] = store; strcpy(right, temp); } } int main() { const char *plain_text = ; char *cipher_text = malloc(strlen(plain_text) + 1); char *plain_text2 = malloc(strlen(plain_text) + 1); printf(, plain_text); printf( ); chao(plain_text, cipher_text, ENCRYPT, TRUE); printf(, cipher_text); chao(cipher_text, plain_text2, DECRYPT, FALSE); printf(, plain_text2); free(cipher_text); free(plain_text2); return 0; }
1,055Chaocipher
5c
es7av
const int N = 15; int main() { register int k, n; unsigned long long int num, den; int catalan; printf(); for (n=2; n<=N; ++n) { num = den = 1; for (k=2; k<=n; ++k) { num *= (n+k); den *= k; catalan = num /den; } printf(, catalan); } printf(); return 0; }
1,056Catalan numbers/Pascal's triangle
5c
x8jwu
package main import( "fmt" "strings" "unicode/utf8" ) type Mode int const( Encrypt Mode = iota Decrypt ) const( lAlphabet = "HXUCZVAMDSLKPEFJRIGTWOBNYQ" rAlphabet = "PTLNBQDEOYSFAVZKGJRIHWXUMC" ) func Chao(text string, mode Mode, showSteps bool) string { len := len(text) if utf8.RuneCountInString(text) != len { fmt.Println("Text contains non-ASCII characters") return "" } left := lAlphabet right := rAlphabet eText := make([]byte, len) temp := make([]byte, 26) for i := 0; i < len; i++ { if showSteps { fmt.Println(left, " ", right) } var index int if mode == Encrypt { index = strings.IndexByte(right, text[i]) eText[i] = left[index] } else { index = strings.IndexByte(left, text[i]) eText[i] = right[index] } if i == len - 1 { break }
1,055Chaocipher
0go
9vdmt
static const char *dog = ; static const char *Dog = ; static const char *DOG = ; int main() { printf(, dog, Dog, DOG); return 0; }
1,057Case-sensitivity of identifiers
5c
yl86f
class Chaocipher { private enum Mode { ENCRYPT, DECRYPT } private static final String L_ALPHABET = "HXUCZVAMDSLKPEFJRIGTWOBNYQ" private static final String R_ALPHABET = "PTLNBQDEOYSFAVZKGJRIHWXUMC" private static int indexOf(char[] a, char c) { for (int i = 0; i < a.length; ++i) { if (a[i] == c) { return i } } return -1 } private static String exec(String text, Mode mode) { return exec(text, mode, false) } private static String exec(String text, Mode mode, Boolean showSteps) { char[] left = L_ALPHABET.toCharArray() char[] right = R_ALPHABET.toCharArray() char[] eText = new char[text.length()] char[] temp = new char[26] for (int i = 0; i < text.length(); ++i) { if (showSteps) { println("${new String(left)} ${new String(right)}") } int index if (mode == Mode.ENCRYPT) { index = indexOf(right, text.charAt(i)) eText[i] = left[index] } else { index = indexOf(left, text.charAt(i)) eText[i] = right[index] } if (i == text.length() - 1) { break }
1,055Chaocipher
7groovy
zm0t5
user=> (let [dog "Benjamin" Dog "Samba" DOG "Bernie"] (format "The three dogs are named%s,%s and%s." dog Dog DOG)) "The three dogs are named Benjamin, Samba and Bernie."
1,057Case-sensitivity of identifiers
6clojure
24fl1
import Data.List (elemIndex) chao :: Eq a => [a] -> [a] -> Bool -> [a] -> [a] chao _ _ _ [] = [] chao l r plain (x: xs) = maybe [] go (elemIndex x src) where (src, dst) | plain = (l, r) | otherwise = (r, l) go n = dst !! n: chao (shifted 1 14 (rotated n l)) ((shifted 2 14 . shifted 0 26) (rotated n r)) plain xs rotated :: Int -> [a] -> [a] rotated n = take . length <*> drop n . cycle shifted :: Int -> Int -> [a] -> [a] shifted src dst s = concat [x, rotated 1 y, b] where (a, b) = splitAt dst s (x, y) = splitAt src a encode, decode :: Bool encode = False decode = True main :: IO () main = do let chaoWheels = chao "HXUCZVAMDSLKPEFJRIGTWOBNYQ" "PTLNBQDEOYSFAVZKGJRIHWXUMC" plainText = "WELLDONEISBETTERTHANWELLSAID" cipherText = chaoWheels encode plainText mapM_ print [ plainText, cipherText, chaoWheels decode cipherText ]
1,055Chaocipher
8haskell
be5k2
import java.util.Arrays; public class Chaocipher { private enum Mode { ENCRYPT, DECRYPT } private static final String L_ALPHABET = "HXUCZVAMDSLKPEFJRIGTWOBNYQ"; private static final String R_ALPHABET = "PTLNBQDEOYSFAVZKGJRIHWXUMC"; private static int indexOf(char[] a, char c) { for (int i = 0; i < a.length; ++i) { if (a[i] == c) { return i; } } return -1; } private static String exec(String text, Mode mode) { return exec(text, mode, false); } private static String exec(String text, Mode mode, Boolean showSteps) { char[] left = L_ALPHABET.toCharArray(); char[] right = R_ALPHABET.toCharArray(); char[] eText = new char[text.length()]; char[] temp = new char[26]; for (int i = 0; i < text.length(); ++i) { if (showSteps) { System.out.printf("%s %s\n", new String(left), new String(right)); } int index; if (mode == Mode.ENCRYPT) { index = indexOf(right, text.charAt(i)); eText[i] = left[index]; } else { index = indexOf(left, text.charAt(i)); eText[i] = right[index]; } if (i == text.length() - 1) { break; }
1,055Chaocipher
9java
gh94m
const L_ALPHABET = "HXUCZVAMDSLKPEFJRIGTWOBNYQ"; const R_ALPHABET = "PTLNBQDEOYSFAVZKGJRIHWXUMC"; const ENCRYPT = 0; const DECRYPT = 1; function setCharAt(str, index, chr) { if (index > str.length - 1) return str; return str.substr(0, index) + chr + str.substr(index + 1); } function chao(text, mode, show_steps) { var left = L_ALPHABET; var right = R_ALPHABET; var out = text; var temp = "01234567890123456789012345"; var i = 0; var index, j, store; if (show_steps) { console.log("The left and right alphabets after each permutation during encryption are:"); } while (i < text.length) { if (show_steps) { console.log(left + " " + right); } if (mode == ENCRYPT) { index = right.indexOf(text[i]); out = setCharAt(out, i, left[index]); } else { index = left.indexOf(text[i]); out = setCharAt(out, i, right[index]); } if (i == text.length - 1) { break; }
1,055Chaocipher
10javascript
kauhq
null
1,055Chaocipher
11kotlin
24zli
package main import "fmt" func main() { const n = 15 t := [n + 2]uint64{0, 1} for i := 1; i <= n; i++ { for j := i; j > 1; j-- { t[j] += t[j-1] } t[i+1] = t[i] for j := i + 1; j > 1; j-- { t[j] += t[j-1] } fmt.Printf("%2d:%d\n", i, t[i+1]-t[i]) } }
1,056Catalan numbers/Pascal's triangle
0go
l5fcw
null
1,055Chaocipher
1lua
vg32x
class Catalan { public static void main(String[] args) { BigInteger N = 15; BigInteger k,n,num,den; BigInteger catalan; print(1); for(n=2;n<=N;n++) { num = 1; den = 1; for(k=2;k<=n;k++) { num = num*(n+k); den = den*k; catalan = num/den; } print(" " + catalan); } } }
1,056Catalan numbers/Pascal's triangle
7groovy
6c83o
void cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){ int i,j; if(times==numSets){ printf(); for(i=0;i<times;i++){ printf(,currentSet[i]); } printf(); } else{ for(j=0;j<setLengths[times];j++){ currentSet[times] = sets[times][j]; cartesianProduct(sets,setLengths,currentSet,numSets,times+1); } } } void printSets(int** sets, int* setLengths, int numSets){ int i,j; printf(,numSets); for(i=0;i<numSets+1;i++){ printf(,i+1); for(j=0;j<setLengths[i];j++){ printf(,sets[i][j]); } } } void processInputString(char* str){ int **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0; char *token,*holder,*holderToken; for(i=0;str[i]!=00;i++) if(str[i]=='x') numSets++; if(numSets==0){ printf(,str); return; } currentSet = (int*)calloc(sizeof(int),numSets + 1); setLengths = (int*)calloc(sizeof(int),numSets + 1); sets = (int**)malloc((numSets + 1)*sizeof(int*)); token = strtok(str,); while(token!=NULL){ holder = (char*)malloc(strlen(token)*sizeof(char)); j = 0; for(i=0;token[i]!=00;i++){ if(token[i]>='0' && token[i]<='9') holder[j++] = token[i]; else if(token[i]==',') holder[j++] = ' '; } holder[j] = 00; setLength = 0; for(i=0;holder[i]!=00;i++) if(holder[i]==' ') setLength++; if(setLength==0 && strlen(holder)==0){ printf(); return; } setLengths[counter] = setLength+1; sets[counter] = (int*)malloc((1+setLength)*sizeof(int)); k = 0; start = 0; for(l=0;holder[l]!=00;l++){ if(holder[l+1]==' '||holder[l+1]==00){ holderToken = (char*)malloc((l+1-start)*sizeof(char)); strncpy(holderToken,holder + start,l+1-start); sets[counter][k++] = atoi(holderToken); start = l+2; } } counter++; token = strtok(NULL,); } printf(); cartesianProduct(sets,setLengths,currentSet,numSets + 1,0); printf(); } int main(int argC,char* argV[]) { if(argC!=2) printf(,argV[0]); else processInputString(argV[1]); return 0; }
1,058Cartesian product of two or more lists
5c
vgf2o
vertex face_point(face f) { int i; vertex v; if (!f->avg) { f->avg = vertex_new(); foreach(i, v, f->v) if (!i) f->avg->pos = v->pos; else vadd(f->avg->pos, v->pos); vdiv(f->avg->pos, len(f->v)); } return f->avg; } vertex edge_point(edge e) { int i; face f; if (!e->e_pt) { e->e_pt = vertex_new(); e->avg = e->v[0]->pos; vadd(e->avg, e->v[1]->pos); e->e_pt->pos = e->avg; if (!hole_edge(e)) { foreach (i, f, e->f) vadd(e->e_pt->pos, face_point(f)->pos); vdiv(e->e_pt->pos, 4); } else vdiv(e->e_pt->pos, 2); vdiv(e->avg, 2); } return e->e_pt; } vertex updated_point(vertex v) { int i, n = 0; edge e; face f; coord_t sum = {0, 0, 0}; if (v->v_new) return v->v_new; v->v_new = vertex_new(); if (hole_vertex(v)) { v->v_new->pos = v->pos; foreach(i, e, v->e) { if (!hole_edge(e)) continue; vadd(v->v_new->pos, edge_point(e)->pos); n++; } vdiv(v->v_new->pos, n + 1); } else { n = len(v->f); foreach(i, f, v->f) vadd(sum, face_point(f)->pos); foreach(i, e, v->e) vmadd(sum, edge_point(e)->pos, 2, sum); vdiv(sum, n); vmadd(sum, v->pos, n - 3, sum); vdiv(sum, n); v->v_new->pos = sum; } return v->v_new; } model catmull(model m) { int i, j, a, b, c, d; face f; vertex v, x; model nm = model_new(); foreach (i, f, m->f) { foreach(j, v, f->v) { _get_idx(a, updated_point(v)); _get_idx(b, edge_point(elem(f->e, (j + 1) % len(f->e)))); _get_idx(c, face_point(f)); _get_idx(d, edge_point(elem(f->e, j))); model_add_face(nm, 4, a, b, c, d); } } return nm; }
1,059Catmull–Clark subdivision surface
5c
urfv4
import System.Environment (getArgs) pascal :: [[Integer]] pascal = [1]: map (\row -> 1: zipWith (+) row (tail row) ++ [1]) pascal catalan :: [Integer] catalan = map (diff . uncurry drop) $ zip [0..] (alt pascal) where alt (x:_:zs) = x: alt zs diff (x:y:_) = x - y diff (x:_) = x main :: IO () main = do ns <- fmap (map read) getArgs :: IO [Int] mapM_ (print . flip take catalan) ns
1,056Catalan numbers/Pascal's triangle
8haskell
1x4ps
int main() { const int N = 2; int base = 10; int c1 = 0; int c2 = 0; int k; for (k = 1; k < pow(base, N); k++) { c1++; if (k % (base - 1) == (k * k) % (base - 1)) { c2++; printf(, k); } } printf(, c2, c1, 100.0 - 100.0 * c2 / c1); return 0; }
1,060Casting out nines
5c
ghz45
package main import ( "fmt" "sort" ) type ( Point [3]float64 Face []int Edge struct { pn1 int
1,059Catmull–Clark subdivision surface
0go
0njsk
typedef int (*intFn)(int, int); int reduce(intFn fn, int size, int *elms) { int i, val = *elms; for (i = 1; i < size; ++i) val = fn(val, elms[i]); return val; } int add(int a, int b) { return a + b; } int sub(int a, int b) { return a - b; } int mul(int a, int b) { return a * b; } int main(void) { int nums[] = {1, 2, 3, 4, 5}; printf(, reduce(add, 5, nums)); printf(, reduce(sub, 5, nums)); printf(, reduce(mul, 5, nums)); return 0; }
1,061Catamorphism
5c
24olo
import Data.Array import Data.Foldable (length, concat, sum) import Data.List (genericLength) import Data.Maybe (mapMaybe) import Prelude hiding (length, concat, sum) import qualified Data.Map.Strict as Map newtype VertexId = VertexId { getVertexId :: Int } deriving (Ix, Ord, Eq, Show) newtype EdgeId = EdgeId { getEdgeId :: Int } deriving (Ix, Ord, Eq, Show) newtype FaceId = FaceId { getFaceId :: Int } deriving (Ix, Ord, Eq, Show) data Vertex a = Vertex { vertexPoint :: a , vertexEdges :: [EdgeId] , vertexFaces :: [FaceId] } deriving Show data Edge = Edge { edgeVertexA :: VertexId , edgeVertexB :: VertexId , edgeFaces :: [FaceId] } deriving Show data Face = Face { faceVertices :: [VertexId] , faceEdges :: [EdgeId] } deriving Show type VertexArray a = Array VertexId (Vertex a) type EdgeArray = Array EdgeId Edge type FaceArray = Array FaceId Face data Mesh a = Mesh { meshVertices :: VertexArray a , meshEdges :: EdgeArray , meshFaces :: FaceArray } deriving Show data SimpleVertex a = SimpleVertex { sVertexPoint :: a } deriving Show data SimpleFace = SimpleFace { sFaceVertices :: [VertexId] } deriving Show type SimpleVertexArray a = Array VertexId (SimpleVertex a) type SimpleFaceArray = Array FaceId SimpleFace data SimpleMesh a = SimpleMesh { sMeshVertices :: SimpleVertexArray a , sMeshFaces :: SimpleFaceArray } deriving Show fmap1 :: Functor f => (t -> a -> b) -> (t -> f a) -> t -> f b fmap1 g h x = fmap (g x) (h x) aZipWith :: Ix i1 => (a -> b -> e) -> Array i1 a -> Array i b -> Array i1 e aZipWith f a b = listArray (bounds a) $ zipWith f (elems a) (elems b) average :: (Foldable f, Fractional a) => f a -> a average xs = (sum xs) / (fromIntegral $ length xs) newtype FacePoint a = FacePoint { getFacePoint :: a } deriving Show newtype EdgeCenterPoint a = EdgeCenterPoint { getEdgeCenterPoint :: a } deriving Show newtype EdgePoint a = EdgePoint { getEdgePoint :: a } deriving Show newtype VertexPoint a = VertexPoint { getVertexPoint :: a } deriving Show type FacePointArray a = Array FaceId (FacePoint a) type EdgePointArray a = Array EdgeId (EdgePoint a) type EdgeCenterPointArray a = Array EdgeId (EdgeCenterPoint a) type IsEdgeHoleArray = Array EdgeId Bool type VertexPointArray a = Array VertexId (VertexPoint a) facePoint :: Fractional a => Mesh a -> Face -> FacePoint a facePoint mesh = FacePoint . average . (fmap $ vertexPointById mesh) . faceVertices allFacePoints :: Fractional a => Mesh a -> FacePointArray a allFacePoints = fmap1 facePoint meshFaces vertexPointById :: Mesh a -> VertexId -> a vertexPointById mesh = vertexPoint . (meshVertices mesh !) edgeCenterPoint :: Fractional a => Mesh a -> Edge -> EdgeCenterPoint a edgeCenterPoint mesh (Edge ea eb _) = EdgeCenterPoint . average $ fmap (vertexPointById mesh) [ea, eb] allEdgeCenterPoints :: Fractional a => Mesh a -> EdgeCenterPointArray a allEdgeCenterPoints = fmap1 edgeCenterPoint meshEdges allIsEdgeHoles :: Mesh a -> IsEdgeHoleArray allIsEdgeHoles = fmap ((< 2) . length . edgeFaces) . meshEdges edgePoint :: Fractional a => Edge -> FacePointArray a -> EdgeCenterPoint a -> EdgePoint a edgePoint (Edge _ _ [_]) _ (EdgeCenterPoint ecp) = EdgePoint ecp edgePoint (Edge _ _ faceIds) facePoints (EdgeCenterPoint ecp) = EdgePoint $ average [ecp, average $ fmap (getFacePoint . (facePoints !)) faceIds] allEdgePoints :: Fractional a => Mesh a -> FacePointArray a -> EdgeCenterPointArray a -> EdgePointArray a allEdgePoints mesh fps ecps = aZipWith (\e ecp -> edgePoint e fps ecp) (meshEdges mesh) ecps vertexPoint':: Fractional a => Vertex a -> FacePointArray a -> EdgeCenterPointArray a -> IsEdgeHoleArray -> VertexPoint a vertexPoint' vertex facePoints ecps iehs | length faceIds == length edgeIds = VertexPoint newCoords | otherwise = VertexPoint avgHoleEcps where newCoords = (oldCoords * m1) + (avgFacePoints * m2) + (avgMidEdges * m3) oldCoords = vertexPoint vertex avgFacePoints = average $ fmap (getFacePoint . (facePoints !)) faceIds avgMidEdges = average $ fmap (getEdgeCenterPoint . (ecps !)) edgeIds m1 = (n - 3) / n m2 = 1 / n m3 = 2 / n n = genericLength faceIds faceIds = vertexFaces vertex edgeIds = vertexEdges vertex avgHoleEcps = average . (oldCoords:) . fmap (getEdgeCenterPoint . (ecps !)) $ filter (iehs !) edgeIds allVertexPoints :: Fractional a => Mesh a -> FacePointArray a -> EdgeCenterPointArray a -> IsEdgeHoleArray -> VertexPointArray a allVertexPoints mesh fps ecps iehs = fmap (\v -> vertexPoint' v fps ecps iehs) (meshVertices mesh) newFaces:: Face -> FaceId -> Int -> Int -> [SimpleFace] newFaces (Face vertexIds edgeIds) faceId epOffset vpOffset = take (genericLength vertexIds) $ zipWith3 newFace (cycle vertexIds) (cycle edgeIds) (drop 1 (cycle edgeIds)) where f = VertexId . (+ epOffset) . getEdgeId newFace vid epA epB = SimpleFace [ VertexId . (+ vpOffset) $ getVertexId vid , f epA , VertexId $ getFaceId faceId , f epB] subdivide:: Fractional a => SimpleMesh a -> SimpleMesh a subdivide simpleMesh = SimpleMesh combinedVertices (listArray (FaceId 0, FaceId (genericLength faces - 1)) faces) where mesh = makeComplexMesh simpleMesh fps = allFacePoints mesh ecps = allEdgeCenterPoints mesh eps = allEdgePoints mesh fps ecps iehs = allIsEdgeHoles mesh vps = allVertexPoints mesh fps ecps iehs edgePointOffset = length fps vertexPointOffset = edgePointOffset + length eps combinedVertices = listArray (VertexId 0, VertexId (vertexPointOffset + length vps - 1)) . fmap SimpleVertex $ concat [ fmap getFacePoint $ elems fps , fmap getEdgePoint $ elems eps , fmap getVertexPoint $ elems vps] faces = concat $ zipWith (\face fid -> newFaces face fid edgePointOffset vertexPointOffset) (elems $ meshFaces mesh) (fmap FaceId [0..]) makeComplexMesh:: forall a. SimpleMesh a -> Mesh a makeComplexMesh (SimpleMesh sVertices sFaces) = Mesh vertices edges faces where makeEdgesFromFace:: SimpleFace -> FaceId -> [Edge] makeEdgesFromFace (SimpleFace vertexIds) fid = take (genericLength vertexIds) $ zipWith (\a b -> Edge a b [fid]) verts (drop 1 verts) where verts = cycle vertexIds edgeKey:: VertexId -> VertexId -> (VertexId, VertexId) edgeKey a b = (min a b, max a b) sFacesList:: [SimpleFace] sFacesList = elems sFaces fids:: [FaceId] fids = fmap FaceId [0..] eids:: [EdgeId] eids = fmap EdgeId [0..] faceEdges:: [[Edge]] faceEdges = zipWith makeEdgesFromFace sFacesList fids edgeMap:: Map.Map (VertexId, VertexId) Edge edgeMap = Map.fromListWith (\(Edge a b fidsA) (Edge _ _ fidsB) -> Edge a b (fidsA ++ fidsB)) . fmap (\edge@(Edge a b _) -> (edgeKey a b, edge)) $ concat faceEdges edges:: EdgeArray edges = listArray (EdgeId 0, EdgeId $ (Map.size edgeMap) - 1) $ Map.elems edgeMap edgeIdMap:: Map.Map (VertexId, VertexId) EdgeId edgeIdMap = Map.fromList $ zipWith (\(Edge a b _) eid -> ((edgeKey a b), eid)) (elems edges) eids faceEdgeIds:: [[EdgeId]] faceEdgeIds = fmap (mapMaybe (\(Edge a b _) -> Map.lookup (edgeKey a b) edgeIdMap)) faceEdges faces:: FaceArray faces = listArray (FaceId 0, FaceId $ (length sFaces) - 1) $ zipWith (\(SimpleFace verts) edgeIds -> Face verts edgeIds) sFacesList faceEdgeIds vidsToFids:: Map.Map VertexId [FaceId] vidsToFids = Map.fromListWith (++) . concat $ zipWith (\(SimpleFace vertexIds) fid -> fmap (\vid -> (vid, [fid])) vertexIds) sFacesList fids vidsToEids:: Map.Map VertexId [EdgeId] vidsToEids = Map.fromListWith (++) . concat $ zipWith (\(Edge a b _) eid -> [(a, [eid]), (b, [eid])]) (elems edges) eids simpleToComplexVert:: SimpleVertex a -> VertexId -> Vertex a simpleToComplexVert (SimpleVertex point) vid = Vertex point (Map.findWithDefault [] vid vidsToEids) (Map.findWithDefault [] vid vidsToFids) vertices:: VertexArray a vertices = listArray (bounds sVertices) $ zipWith simpleToComplexVert (elems sVertices) (fmap VertexId [0..]) pShowSimpleMesh:: Show a => SimpleMesh a -> String pShowSimpleMesh (SimpleMesh vertices faces) = "Vertices:\n" ++ (arrShow vertices sVertexPoint) ++ "Faces:\n" ++ (arrShow faces (fmap getVertexId . sFaceVertices)) where arrShow a f = concatMap ((++ "\n") . show . (\(i, e) -> (i, f e))) . zip [0:: Int ..] $ elems a data Point a = Point a a a deriving (Show) instance Functor Point where fmap f (Point x y z) = Point (f x) (f y) (f z) zipPoint:: (a -> b -> c) -> Point a -> Point b -> Point c zipPoint f (Point x y z) (Point x' y' z') = Point (f x x') (f y y') (f z z') instance Num a => Num (Point a) where (+) = zipPoint (+) (-) = zipPoint (-) (*) = zipPoint (*) negate = fmap negate abs = fmap abs signum = fmap signum fromInteger i = let i' = fromInteger i in Point i' i' i' instance Fractional a => Fractional (Point a) where recip = fmap recip fromRational r = let r' = fromRational r in Point r' r' r' testCube:: SimpleMesh (Point Double) testCube = SimpleMesh vertices faces where vertices = listArray (VertexId 0, VertexId 7) $ fmap SimpleVertex [ Point (-1) (-1) (-1) , Point (-1) (-1) 1 , Point (-1) 1 (-1) , Point (-1) 1 1 , Point 1 (-1) (-1) , Point 1 (-1) 1 , Point 1 1 (-1) , Point 1 1 1] faces = listArray (FaceId 0, FaceId 5) $ fmap (SimpleFace . (fmap VertexId)) [ [0, 4, 5, 1] , [4, 6, 7, 5] , [6, 2, 3, 7] , [2, 0, 1, 3] , [1, 5, 7, 3] , [0, 2, 6, 4]] testCubeWithHole:: SimpleMesh (Point Double) testCubeWithHole = SimpleMesh (sMeshVertices testCube) (ixmap (FaceId 0, FaceId 4) id (sMeshFaces testCube)) testTriangle:: SimpleMesh (Point Double) testTriangle = SimpleMesh vertices faces where vertices = listArray (VertexId 0, VertexId 2) $ fmap SimpleVertex [ Point 0 0 0 , Point 0 0 1 , Point 0 1 0] faces = listArray (FaceId 0, FaceId 0) $ fmap (SimpleFace . (fmap VertexId)) [ [0, 1, 2]] main:: IO () main = putStr . pShowSimpleMesh $ subdivide testCube
1,059Catmull–Clark subdivision surface
8haskell
cuo94
(ns clojure.examples.product (:gen-class) (:require [clojure.pprint:as pp])) (defn cart [colls] "Compute the cartesian product of list of lists" (if (empty? colls) '(()) (for [more (cart (rest colls)) x (first colls)] (cons x more))))
1,058Cartesian product of two or more lists
6clojure
rkyg2
public class Test { public static void main(String[] args) { int N = 15; int[] t = new int[N + 2]; t[1] = 1; for (int i = 1; i <= N; i++) { for (int j = i; j > 1; j--) t[j] = t[j] + t[j - 1]; t[i + 1] = t[i]; for (int j = i + 1; j > 1; j--) t[j] = t[j] + t[j - 1]; System.out.printf("%d ", t[i + 1] - t[i]); } } }
1,056Catalan numbers/Pascal's triangle
9java
7bcrj
typedef struct { uint8_t magic[2]; } bmpfile_magic_t; typedef struct { uint32_t filesz; uint16_t creator1; uint16_t creator2; uint32_t bmp_offset; } bmpfile_header_t; typedef struct { uint32_t header_sz; int32_t width; int32_t height; uint16_t nplanes; uint16_t bitspp; uint32_t compress_type; uint32_t bmp_bytesz; int32_t hres; int32_t vres; uint32_t ncolors; uint32_t nimpcolors; } bitmap_info_header_t; typedef struct { uint8_t r; uint8_t g; uint8_t b; uint8_t nothing; } rgb_t; typedef short int pixel_t; pixel_t *load_bmp(const char *filename, bitmap_info_header_t *bitmapInfoHeader) { FILE *filePtr = fopen(filename, ); if (filePtr == NULL) { perror(); return NULL; } bmpfile_magic_t mag; if (fread(&mag, sizeof(bmpfile_magic_t), 1, filePtr) != 1) { fclose(filePtr); return NULL; } if (*((uint16_t*)mag.magic) != 0x4D42) { fprintf(stderr, , mag.magic[0], mag.magic[1]); fclose(filePtr); return NULL; } bmpfile_header_t bitmapFileHeader; if (fread(&bitmapFileHeader, sizeof(bmpfile_header_t), 1, filePtr) != 1) { fclose(filePtr); return NULL; } if (fread(bitmapInfoHeader, sizeof(bitmap_info_header_t), 1, filePtr) != 1) { fclose(filePtr); return NULL; } if (bitmapInfoHeader->compress_type != 0) fprintf(stderr, ); if (fseek(filePtr, bitmapFileHeader.bmp_offset, SEEK_SET)) { fclose(filePtr); return NULL; } pixel_t *bitmapImage = malloc(bitmapInfoHeader->bmp_bytesz * sizeof(pixel_t)); if (bitmapImage == NULL) { fclose(filePtr); return NULL; } size_t pad, count=0; unsigned char c; pad = 4*ceil(bitmapInfoHeader->bitspp*bitmapInfoHeader->width/32.) - bitmapInfoHeader->width; for(size_t i=0; i<bitmapInfoHeader->height; i++){ for(size_t j=0; j<bitmapInfoHeader->width; j++){ if (fread(&c, sizeof(unsigned char), 1, filePtr) != 1) { fclose(filePtr); return NULL; } bitmapImage[count++] = (pixel_t) c; } fseek(filePtr, pad, SEEK_CUR); } fclose(filePtr); return bitmapImage; } bool save_bmp(const char *filename, const bitmap_info_header_t *bmp_ih, const pixel_t *data) { FILE* filePtr = fopen(filename, ); if (filePtr == NULL) return true; bmpfile_magic_t mag = {{0x42, 0x4d}}; if (fwrite(&mag, sizeof(bmpfile_magic_t), 1, filePtr) != 1) { fclose(filePtr); return true; } const uint32_t offset = sizeof(bmpfile_magic_t) + sizeof(bmpfile_header_t) + sizeof(bitmap_info_header_t) + ((1U << bmp_ih->bitspp) * 4); const bmpfile_header_t bmp_fh = { .filesz = offset + bmp_ih->bmp_bytesz, .creator1 = 0, .creator2 = 0, .bmp_offset = offset }; if (fwrite(&bmp_fh, sizeof(bmpfile_header_t), 1, filePtr) != 1) { fclose(filePtr); return true; } if (fwrite(bmp_ih, sizeof(bitmap_info_header_t), 1, filePtr) != 1) { fclose(filePtr); return true; } for (size_t i = 0; i < (1U << bmp_ih->bitspp); i++) { const rgb_t color = {(uint8_t)i, (uint8_t)i, (uint8_t)i}; if (fwrite(&color, sizeof(rgb_t), 1, filePtr) != 1) { fclose(filePtr); return true; } } size_t pad = 4*ceil(bmp_ih->bitspp*bmp_ih->width/32.) - bmp_ih->width; unsigned char c; for(size_t i=0; i < bmp_ih->height; i++) { for(size_t j=0; j < bmp_ih->width; j++) { c = (unsigned char) data[j + bmp_ih->width*i]; if (fwrite(&c, sizeof(char), 1, filePtr) != 1) { fclose(filePtr); return true; } } c = 0; for(size_t j=0; j<pad; j++) if (fwrite(&c, sizeof(char), 1, filePtr) != 1) { fclose(filePtr); return true; } } fclose(filePtr); return false; } void convolution(const pixel_t *in, pixel_t *out, const float *kernel, const int nx, const int ny, const int kn, const bool normalize) { assert(kn % 2 == 1); assert(nx > kn && ny > kn); const int khalf = kn / 2; float min = FLT_MAX, max = -FLT_MAX; if (normalize) for (int m = khalf; m < nx - khalf; m++) for (int n = khalf; n < ny - khalf; n++) { float pixel = 0.0; size_t c = 0; for (int j = -khalf; j <= khalf; j++) for (int i = -khalf; i <= khalf; i++) { pixel += in[(n - j) * nx + m - i] * kernel[c]; c++; } if (pixel < min) min = pixel; if (pixel > max) max = pixel; } for (int m = khalf; m < nx - khalf; m++) for (int n = khalf; n < ny - khalf; n++) { float pixel = 0.0; size_t c = 0; for (int j = -khalf; j <= khalf; j++) for (int i = -khalf; i <= khalf; i++) { pixel += in[(n - j) * nx + m - i] * kernel[c]; c++; } if (normalize) pixel = MAX_BRIGHTNESS * (pixel - min) / (max - min); out[n * nx + m] = (pixel_t)pixel; } } void gaussian_filter(const pixel_t *in, pixel_t *out, const int nx, const int ny, const float sigma) { const int n = 2 * (int)(2 * sigma) + 3; const float mean = (float)floor(n / 2.0); float kernel[n * n]; fprintf(stderr, , n, sigma); size_t c = 0; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { kernel[c] = exp(-0.5 * (pow((i - mean) / sigma, 2.0) + pow((j - mean) / sigma, 2.0))) / (2 * M_PI * sigma * sigma); c++; } convolution(in, out, kernel, nx, ny, n, true); } pixel_t *canny_edge_detection(const pixel_t *in, const bitmap_info_header_t *bmp_ih, const int tmin, const int tmax, const float sigma) { const int nx = bmp_ih->width; const int ny = bmp_ih->height; pixel_t *G = calloc(nx * ny * sizeof(pixel_t), 1); pixel_t *after_Gx = calloc(nx * ny * sizeof(pixel_t), 1); pixel_t *after_Gy = calloc(nx * ny * sizeof(pixel_t), 1); pixel_t *nms = calloc(nx * ny * sizeof(pixel_t), 1); pixel_t *out = malloc(bmp_ih->bmp_bytesz * sizeof(pixel_t)); if (G == NULL || after_Gx == NULL || after_Gy == NULL || nms == NULL || out == NULL) { fprintf(stderr, ); exit(1); } gaussian_filter(in, out, nx, ny, sigma); const float Gx[] = {-1, 0, 1, -2, 0, 2, -1, 0, 1}; convolution(out, after_Gx, Gx, nx, ny, 3, false); const float Gy[] = { 1, 2, 1, 0, 0, 0, -1,-2,-1}; convolution(out, after_Gy, Gy, nx, ny, 3, false); for (int i = 1; i < nx - 1; i++) for (int j = 1; j < ny - 1; j++) { const int c = i + nx * j; G[c] = (pixel_t)hypot(after_Gx[c], after_Gy[c]); } for (int i = 1; i < nx - 1; i++) for (int j = 1; j < ny - 1; j++) { const int c = i + nx * j; const int nn = c - nx; const int ss = c + nx; const int ww = c + 1; const int ee = c - 1; const int nw = nn + 1; const int ne = nn - 1; const int sw = ss + 1; const int se = ss - 1; const float dir = (float)(fmod(atan2(after_Gy[c], after_Gx[c]) + M_PI, M_PI) / M_PI) * 8; if (((dir <= 1 || dir > 7) && G[c] > G[ee] && G[c] > G[ww]) || ((dir > 1 && dir <= 3) && G[c] > G[nw] && G[c] > G[se]) || ((dir > 3 && dir <= 5) && G[c] > G[nn] && G[c] > G[ss]) || ((dir > 5 && dir <= 7) && G[c] > G[ne] && G[c] > G[sw])) nms[c] = G[c]; else nms[c] = 0; } int *edges = (int*) after_Gy; memset(out, 0, sizeof(pixel_t) * nx * ny); memset(edges, 0, sizeof(pixel_t) * nx * ny); size_t c = 1; for (int j = 1; j < ny - 1; j++) for (int i = 1; i < nx - 1; i++) { if (nms[c] >= tmax && out[c] == 0) { out[c] = MAX_BRIGHTNESS; int nedges = 1; edges[0] = c; do { nedges--; const int t = edges[nedges]; int nbs[8]; nbs[0] = t - nx; nbs[1] = t + nx; nbs[2] = t + 1; nbs[3] = t - 1; nbs[4] = nbs[0] + 1; nbs[5] = nbs[0] - 1; nbs[6] = nbs[1] + 1; nbs[7] = nbs[1] - 1; for (int k = 0; k < 8; k++) if (nms[nbs[k]] >= tmin && out[nbs[k]] == 0) { out[nbs[k]] = MAX_BRIGHTNESS; edges[nedges] = nbs[k]; nedges++; } } while (nedges > 0); } c++; } free(after_Gx); free(after_Gy); free(G); free(nms); return out; } int main(const int argc, const char ** const argv) { if (argc < 2) { printf(, argv[0]); return 1; } static bitmap_info_header_t ih; const pixel_t *in_bitmap_data = load_bmp(argv[1], &ih); if (in_bitmap_data == NULL) { fprintf(stderr, ); return 1; } printf(, ih.width, ih.height, ih.bitspp); const pixel_t *out_bitmap_data = canny_edge_detection(in_bitmap_data, &ih, 45, 50, 1.0f); if (out_bitmap_data == NULL) { fprintf(stderr, ); return 1; } if (save_bmp(, &ih, out_bitmap_data)) { fprintf(stderr, ); return 1; } free((pixel_t*)in_bitmap_data); free((pixel_t*)out_bitmap_data); return 0; }
1,062Canny edge detector
5c
nzhi6
typedef struct cidr_tag { uint32_t address; unsigned int mask_length; } cidr_t; bool cidr_parse(const char* str, cidr_t* cidr) { int a, b, c, d, m; if (sscanf(str, , &a, &b, &c, &d, &m) != 5) return false; if (m < 1 || m > 32 || a < 0 || a > UINT8_MAX || b < 0 || b > UINT8_MAX || c < 0 || c > UINT8_MAX || d < 0 || d > UINT8_MAX) return false; uint32_t mask = ~((1 << (32 - m)) - 1); uint32_t address = (a << 24) + (b << 16) + (c << 8) + d; address &= mask; cidr->address = address; cidr->mask_length = m; return true; } void cidr_format(const cidr_t* cidr, char* str, size_t size) { uint32_t address = cidr->address; unsigned int d = address & UINT8_MAX; address >>= 8; unsigned int c = address & UINT8_MAX; address >>= 8; unsigned int b = address & UINT8_MAX; address >>= 8; unsigned int a = address & UINT8_MAX; snprintf(str, size, , a, b, c, d, cidr->mask_length); } int main(int argc, char** argv) { const char* tests[] = { , , , , , }; for (int i = 0; i < sizeof(tests)/sizeof(tests[0]); ++i) { cidr_t cidr; if (cidr_parse(tests[i], &cidr)) { char out[32]; cidr_format(&cidr, out, sizeof(out)); printf(, tests[i], out); } else { fprintf(stderr, , tests[i]); } } return 0; }
1,063Canonicalize CIDR
5c
jpz70
int is_prime(unsigned int n) { if (n <= 3) { return n > 1; } else if (!(n % 2) || !(n % 3)) { return 0; } else { unsigned int i; for (i = 5; i*i <= n; i += 6) if (!(n % i) || !(n % (i + 2))) return 0; return 1; } } void carmichael3(int p1) { if (!is_prime(p1)) return; int h3, d, p2, p3; for (h3 = 1; h3 < p1; ++h3) { for (d = 1; d < h3 + p1; ++d) { if ((h3 + p1)*(p1 - 1) % d == 0 && mod(-p1 * p1, h3) == d % h3) { p2 = 1 + ((p1 - 1) * (h3 + p1)/d); if (!is_prime(p2)) continue; p3 = 1 + (p1 * p2 / h3); if (!is_prime(p3) || (p2 * p3) % (p1 - 1) != 1) continue; printf(, p1, p2, p3); } } } } int main(void) { int p1; for (p1 = 2; p1 < 62; ++p1) carmichael3(p1); return 0; }
1,064Carmichael 3 strong pseudoprimes
5c
aq911
> (reduce * '(1 2 3 4 5)) 120 > (reduce + 100 '(1 2 3 4 5)) 115
1,061Catamorphism
6clojure
ght4f
sub init { @left = split '', 'HXUCZVAMDSLKPEFJRIGTWOBNYQ'; @right = split '', 'PTLNBQDEOYSFAVZKGJRIHWXUMC'; } sub encode { my($letter) = @_; my $index = index join('', @right), $letter; my $enc = $left[$index]; left_permute($index); right_permute($index); $enc } sub decode { my($letter) = @_; my $index = index join('', @left), $letter; my $dec = $right[$index]; left_permute($index); right_permute($index); $dec } sub right_permute { my($index) = @_; rotate(\@right, $index + 1); rotate(\@right, 1, 2, 13); } sub left_permute { my($index) = @_; rotate(\@left, $index); rotate(\@left, 1, 1, 13); } sub rotate { our @list; local *list = shift; my($n,$s,$e) = @_; @list = $s ? @list[0..$s-1, $s+$n..$e+$n-1, $s..$s+$n-1, $e+1..$ : @list[$n..$ } init; $e_msg .= encode($_) for split '', 'WELLDONEISBETTERTHANWELLSAID'; init; $d_msg .= decode($_) for split '', $e_msg; print "$e_msg\n"; print "$d_msg\n";
1,055Chaocipher
2perl
sibq3
var n = 15; for (var t = [0, 1], i = 1; i <= n; i++) { for (var j = i; j > 1; j--) t[j] += t[j - 1]; t[i + 1] = t[i]; for (var j = i + 1; j > 1; j--) t[j] += t[j - 1]; document.write(i == 1 ? '' : ', ', t[i + 1] - t[i]); }
1,056Catalan numbers/Pascal's triangle
10javascript
pw5b7