code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
package dogs
import "fmt" | 1,057Case-sensitivity of identifiers
| 0go
| 1x5p5 |
def dog = "Benjamin", Dog = "Samba", DOG = "Bernie"
println (dog == DOG ? "There is one dog named ${dog}": "There are three dogs named ${dog}, ${Dog} and ${DOG}.") | 1,057Case-sensitivity of identifiers
| 7groovy
| jpc7o |
import Text.Printf
main = printf "The three dogs are named%s,%s and%s.\n" dog dOG dOg
where dog = "Benjamin"
dOG = "Samba"
dOg = "Bernie" | 1,057Case-sensitivity of identifiers
| 8haskell
| tyxf7 |
package main
import (
ed "github.com/Ernyoke/Imger/edgedetection"
"github.com/Ernyoke/Imger/imgio"
"log"
)
func main() {
img, err := imgio.ImreadRGBA("Valve_original_(1).png")
if err != nil {
log.Fatal("Could not read image", err)
}
cny, err := ed.CannyRGBA(img, 15, 45, 5)
if err != nil {
log.Fatal("Could not perform Canny Edge detection")
}
err = imgio.Imwrite(cny, "Valve_canny_(1).png")
if err != nil {
log.Fatal("Could not write Canny image to disk")
}
} | 1,062Canny edge detector
| 0go
| rktgm |
(ns example
(:gen-class))
(defn prime? [n]
" Prime number test (using Java) "
(.isProbablePrime (biginteger n) 16))
(defn carmichael [p1]
" Triplets of Carmichael primes, with first element prime p1 "
(if (prime? p1)
(into [] (for [h3 (range 2 p1)
:let [g (+ h3 p1)]
d (range 1 g)
:when (and (= (mod (* g (dec p1)) d) 0)
(= (mod (- (* p1 p1)) h3) (mod d h3)))
:let [p2 (inc (quot (* (dec p1) g) d))]
:when (prime? p2)
:let [p3 (inc (quot (* p1 p2) h3))]
:when (prime? p3)
:when (= (mod (* p2 p3) (dec p1)) 1)]
[p1 p2 p3]))))
(def numbers (mapcat carmichael (range 2 62)))
(println (count numbers) "Carmichael numbers found:")
(doseq [t numbers]
(println (format "%5d x%5d x%5d =%10d" (first t) (second t) (last t) (apply * t)))) | 1,064Carmichael 3 strong pseudoprimes
| 6clojure
| siuqr |
def main():
lalpha =
ralpha =
msg =
print(, lalpha)
print(, ralpha)
print(, msg)
print(, do_chao(msg, lalpha, ralpha, 1, 0), )
do_chao(msg, lalpha, ralpha, 1, 1)
def do_chao(msg, lalpha, ralpha, en=1, show=0):
msg = correct_case(msg)
out =
if show:
print(*54)
print(10* + + 21* + )
print(*54)
print(lalpha, ralpha, )
for L in msg:
if en:
lalpha, ralpha = rotate_wheels(lalpha, ralpha, L)
out += lalpha[0]
else:
ralpha, lalpha = rotate_wheels(ralpha, lalpha, L)
out += ralpha[0]
lalpha, ralpha = scramble_wheels(lalpha, ralpha)
if show:
print(lalpha, ralpha)
return out
def makealpha(key=):
alpha =
z = set()
key = [x.upper() for x in (key + alpha[::-1])
if not (x.upper() in z or z.add(x.upper()))]
return .join(key)
def correct_case(string):
return .join([s.upper() for s in string if s.isalpha()])
def permu(alp, num):
alp = alp[:num], alp[num:]
return .join(alp[::-1])
def rotate_wheels(lalph, ralph, key):
newin = ralph.index(key)
return permu(lalph, newin), permu(ralph, newin)
def scramble_wheels(lalph, ralph):
lalph = list(lalph)
lalph = .join([*lalph[0],
*lalph[2:14],
lalph[1],
*lalph[14:]])
ralph = list(ralph)
ralph = .join([*ralph[1:3],
*ralph[4:15],
ralph[3],
*ralph[15:],
ralph[0]])
return lalph, ralph
main() | 1,055Chaocipher
| 3python
| 0npsq |
null | 1,056Catalan numbers/Pascal's triangle
| 11kotlin
| ur3vc |
String dog = "Benjamin";
String Dog = "Samba"; | 1,057Case-sensitivity of identifiers
| 9java
| 8db06 |
function nextrow (t)
local ret = {}
t[0], t[#t + 1] = 0, 0
for i = 1, #t do ret[i] = t[i - 1] + t[i] end
return ret
end
function catalans (n)
local t, middle = {1}
for i = 1, n do
middle = math.ceil(#t / 2)
io.write(t[middle] - (t[middle + 1] or 0) .. " ")
t = nextrow(nextrow(t))
end
end
catalans(15) | 1,056Catalan numbers/Pascal's triangle
| 1lua
| 576u6 |
var dog = "Benjamin";
var Dog = "Samba";
var DOG = "Bernie";
document.write("The three dogs are named " + dog + ", " + Dog + ", and " + DOG + "."); | 1,057Case-sensitivity of identifiers
| 10javascript
| f6wdg |
typedef struct{
int x;
int (*funcPtr)(int);
}functionPair;
int factorial(int num){
if(num==0||num==1)
return 1;
else
return num*factorial(num-1);
}
int main(int argc,char** argv)
{
functionPair response;
if(argc!=2)
return printf(,argv[0]);
else{
response = (functionPair){.x = atoi(argv[1]),.funcPtr=&factorial};
printf(,response.x,response.funcPtr(response.x));
}
return 0;
} | 1,065Call an object method
| 5c
| itgo2 |
import java.awt.image.BufferedImage;
import java.util.Arrays;
public class CannyEdgeDetector { | 1,062Canny edge detector
| 9java
| aql1y |
package main
import (
"fmt"
"log"
"strconv"
"strings"
)
func check(err error) {
if err != nil {
log.Fatal(err)
}
} | 1,063Canonicalize CIDR
| 0go
| f6kd0 |
package main
import (
"fmt"
"log"
"strconv"
) | 1,060Casting out nines
| 0go
| itkog |
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np
import sys
def center_point(p1, p2):
cp = []
for i in range(3):
cp.append((p1[i]+p2[i])/2)
return cp
def sum_point(p1, p2):
sp = []
for i in range(3):
sp.append(p1[i]+p2[i])
return sp
def div_point(p, d):
sp = []
for i in range(3):
sp.append(p[i]/d)
return sp
def mul_point(p, m):
sp = []
for i in range(3):
sp.append(p[i]*m)
return sp
def get_face_points(input_points, input_faces):
NUM_DIMENSIONS = 3
face_points = []
for curr_face in input_faces:
face_point = [0.0, 0.0, 0.0]
for curr_point_index in curr_face:
curr_point = input_points[curr_point_index]
for i in range(NUM_DIMENSIONS):
face_point[i] += curr_point[i]
num_points = len(curr_face)
for i in range(NUM_DIMENSIONS):
face_point[i] /= num_points
face_points.append(face_point)
return face_points
def get_edges_faces(input_points, input_faces):
edges = []
for facenum in range(len(input_faces)):
face = input_faces[facenum]
num_points = len(face)
for pointindex in range(num_points):
if pointindex < num_points - 1:
pointnum_1 = face[pointindex]
pointnum_2 = face[pointindex+1]
else:
pointnum_1 = face[pointindex]
pointnum_2 = face[0]
if pointnum_1 > pointnum_2:
temp = pointnum_1
pointnum_1 = pointnum_2
pointnum_2 = temp
edges.append([pointnum_1, pointnum_2, facenum])
edges = sorted(edges)
num_edges = len(edges)
eindex = 0
merged_edges = []
while eindex < num_edges:
e1 = edges[eindex]
if eindex < num_edges - 1:
e2 = edges[eindex+1]
if e1[0] == e2[0] and e1[1] == e2[1]:
merged_edges.append([e1[0],e1[1],e1[2],e2[2]])
eindex += 2
else:
merged_edges.append([e1[0],e1[1],e1[2],None])
eindex += 1
else:
merged_edges.append([e1[0],e1[1],e1[2],None])
eindex += 1
edges_centers = []
for me in merged_edges:
p1 = input_points[me[0]]
p2 = input_points[me[1]]
cp = center_point(p1, p2)
edges_centers.append(me+[cp])
return edges_centers
def get_edge_points(input_points, edges_faces, face_points):
edge_points = []
for edge in edges_faces:
cp = edge[4]
fp1 = face_points[edge[2]]
if edge[3] == None:
fp2 = fp1
else:
fp2 = face_points[edge[3]]
cfp = center_point(fp1, fp2)
edge_point = center_point(cp, cfp)
edge_points.append(edge_point)
return edge_points
def get_avg_face_points(input_points, input_faces, face_points):
num_points = len(input_points)
temp_points = []
for pointnum in range(num_points):
temp_points.append([[0.0, 0.0, 0.0], 0])
for facenum in range(len(input_faces)):
fp = face_points[facenum]
for pointnum in input_faces[facenum]:
tp = temp_points[pointnum][0]
temp_points[pointnum][0] = sum_point(tp,fp)
temp_points[pointnum][1] += 1
avg_face_points = []
for tp in temp_points:
afp = div_point(tp[0], tp[1])
avg_face_points.append(afp)
return avg_face_points
def get_avg_mid_edges(input_points, edges_faces):
num_points = len(input_points)
temp_points = []
for pointnum in range(num_points):
temp_points.append([[0.0, 0.0, 0.0], 0])
for edge in edges_faces:
cp = edge[4]
for pointnum in [edge[0], edge[1]]:
tp = temp_points[pointnum][0]
temp_points[pointnum][0] = sum_point(tp,cp)
temp_points[pointnum][1] += 1
avg_mid_edges = []
for tp in temp_points:
ame = div_point(tp[0], tp[1])
avg_mid_edges.append(ame)
return avg_mid_edges
def get_points_faces(input_points, input_faces):
num_points = len(input_points)
points_faces = []
for pointnum in range(num_points):
points_faces.append(0)
for facenum in range(len(input_faces)):
for pointnum in input_faces[facenum]:
points_faces[pointnum] += 1
return points_faces
def get_new_points(input_points, points_faces, avg_face_points, avg_mid_edges):
new_points =[]
for pointnum in range(len(input_points)):
n = points_faces[pointnum]
m1 = (n - 3.0) / n
m2 = 1.0 / n
m3 = 2.0 / n
old_coords = input_points[pointnum]
p1 = mul_point(old_coords, m1)
afp = avg_face_points[pointnum]
p2 = mul_point(afp, m2)
ame = avg_mid_edges[pointnum]
p3 = mul_point(ame, m3)
p4 = sum_point(p1, p2)
new_coords = sum_point(p4, p3)
new_points.append(new_coords)
return new_points
def switch_nums(point_nums):
if point_nums[0] < point_nums[1]:
return point_nums
else:
return (point_nums[1], point_nums[0])
def cmc_subdiv(input_points, input_faces):
face_points = get_face_points(input_points, input_faces)
edges_faces = get_edges_faces(input_points, input_faces)
edge_points = get_edge_points(input_points, edges_faces, face_points)
avg_face_points = get_avg_face_points(input_points, input_faces, face_points)
avg_mid_edges = get_avg_mid_edges(input_points, edges_faces)
points_faces = get_points_faces(input_points, input_faces)
new_points = get_new_points(input_points, points_faces, avg_face_points, avg_mid_edges)
face_point_nums = []
next_pointnum = len(new_points)
for face_point in face_points:
new_points.append(face_point)
face_point_nums.append(next_pointnum)
next_pointnum += 1
edge_point_nums = dict()
for edgenum in range(len(edges_faces)):
pointnum_1 = edges_faces[edgenum][0]
pointnum_2 = edges_faces[edgenum][1]
edge_point = edge_points[edgenum]
new_points.append(edge_point)
edge_point_nums[(pointnum_1, pointnum_2)] = next_pointnum
next_pointnum += 1
new_faces =[]
for oldfacenum in range(len(input_faces)):
oldface = input_faces[oldfacenum]
if len(oldface) == 4:
a = oldface[0]
b = oldface[1]
c = oldface[2]
d = oldface[3]
face_point_abcd = face_point_nums[oldfacenum]
edge_point_ab = edge_point_nums[switch_nums((a, b))]
edge_point_da = edge_point_nums[switch_nums((d, a))]
edge_point_bc = edge_point_nums[switch_nums((b, c))]
edge_point_cd = edge_point_nums[switch_nums((c, d))]
new_faces.append((a, edge_point_ab, face_point_abcd, edge_point_da))
new_faces.append((b, edge_point_bc, face_point_abcd, edge_point_ab))
new_faces.append((c, edge_point_cd, face_point_abcd, edge_point_bc))
new_faces.append((d, edge_point_da, face_point_abcd, edge_point_cd))
return new_points, new_faces
def graph_output(output_points, output_faces):
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
for facenum in range(len(output_faces)):
curr_face = output_faces[facenum]
xcurr = []
ycurr = []
zcurr = []
for pointnum in range(len(curr_face)):
xcurr.append(output_points[curr_face[pointnum]][0])
ycurr.append(output_points[curr_face[pointnum]][1])
zcurr.append(output_points[curr_face[pointnum]][2])
xcurr.append(output_points[curr_face[0]][0])
ycurr.append(output_points[curr_face[0]][1])
zcurr.append(output_points[curr_face[0]][2])
ax.plot(xcurr,ycurr,zcurr,color='b')
plt.show()
input_points = [
[-1.0, 1.0, 1.0],
[-1.0, -1.0, 1.0],
[ 1.0, -1.0, 1.0],
[ 1.0, 1.0, 1.0],
[ 1.0, -1.0, -1.0],
[ 1.0, 1.0, -1.0],
[-1.0, -1.0, -1.0],
[-1.0, 1.0, -1.0]
]
input_faces = [
[0, 1, 2, 3],
[3, 2, 4, 5],
[5, 4, 6, 7],
[7, 0, 3, 5],
[7, 6, 1, 0],
[6, 1, 2, 4],
]
if len(sys.argv) != 2:
print()
sys.exit()
else:
iterations = int(sys.argv[1])
output_points, output_faces = input_points, input_faces
for i in range(iterations):
output_points, output_faces = cmc_subdiv(output_points, output_faces)
graph_output(output_points, output_faces) | 1,059Catmull–Clark subdivision surface
| 3python
| 7byrm |
txt =
@left = .chars
@right = .chars
def encrypt(char)
coded_char = @left[@right.index(char)]
@left.rotate!(@left.index(coded_char))
part = @left.slice!(1,13).rotate
@left.insert(1, *part)
@right.rotate!(@right.index(char)+1)
part = @right.slice!(2,12).rotate
@right.insert(2, *part)
@left[0]
end
puts txt.each_char.map{|c| encrypt(c) }.join | 1,055Chaocipher
| 14ruby
| ofa8v |
import Control.Monad (guard)
import Data.Bits ((.|.), (.&.), complement, shiftL, shiftR, zeroBits)
import Data.Maybe (listToMaybe)
import Data.Word (Word32, Word8)
import Text.ParserCombinators.ReadP (ReadP, char, readP_to_S)
import Text.Printf (printf)
import Text.Read.Lex (readDecP)
data CIDR = CIDR Word32 Word8
cidrRead :: String -> Maybe CIDR
cidrRead = listToMaybe . map fst . readP_to_S cidrP
cidrShow :: CIDR -> String
cidrShow (CIDR addr n) = let (a, b, c, d) = octetsFrom addr
in printf "%u.%u.%u.%u/%u" a b c d n
cidrP :: ReadP CIDR
cidrP = do a <- octetP <* char '.'
b <- octetP <* char '.'
c <- octetP <* char '.'
d <- octetP <* char '/'
n <- netBitsP
return $ CIDR (addrFrom a b c d .&. netmask n) n
where octetP = wordP 255
netBitsP = wordP 32
wordP :: Integral a => Integer -> ReadP a
wordP lim = do n <- readDecP
guard $ n <= lim
return $ fi n
octetsFrom :: Word32 -> (Word8, Word8, Word8, Word8)
octetsFrom addr = (oct addr 3, oct addr 2, oct addr 1, oct addr 0)
where oct w n = fi $ w `shiftR` (8*n) .&. 0xff
addrFrom :: Word8 -> Word8 -> Word8 -> Word8 -> Word32
addrFrom a b c d = 0 <<+ a <<+ b <<+ c <<+ d
where w <<+ o = w `shiftL` 8 .|. fi o
netmask :: Word8 -> Word32
netmask n = complement $ complement zeroBits `shiftR` fi n
fi :: (Integral a, Num b) => a -> b
fi = fromIntegral
test :: String -> IO ()
test str = do
let cidrStr = maybe "invalid CIDR string" cidrShow (cidrRead str)
printf "%-18s ->%s\n" str cidrStr
main :: IO ()
main = do
test "87.70.141.1/22"
test "36.18.154.103/12"
test "62.62.197.11/29"
test "67.137.119.181/4"
test "161.214.74.21/24"
test "184.232.176.184/18"
test "184.256.176.184/12"
test "184.232.176.184/33"
test "184.232.184/18" | 1,063Canonicalize CIDR
| 8haskell
| 4jn5s |
co9 n
| n <= 8 = n
| otherwise = co9 $ sum $ filter (/= 9) $ digits 10 n
task2 = filter (\n -> co9 n == co9 (n ^ 2)) [1 .. 100]
task3 k = filter (\n -> n `mod` k == n ^ 2 `mod` k) [1 .. 100] | 1,060Casting out nines
| 8haskell
| vgn2k |
pub struct Vector3 {pub x: f64, pub y: f64, pub z: f64, pub w: f64}
pub struct Triangle {pub r: [usize; 3], pub(crate) col: [f32; 4], pub(crate) p: [Vector3; 3], n: Vector3, pub t: [Vector2; 3]}
pub struct Mesh{pub v: Vec<Vector3>, pub f: Vec<Triangle>}
impl Triangle{
pub fn new() -> Triangle {return Triangle {r: [0, 0, 0], col: [0.0; 4], p: [Vector3::new(0.0, 0.0, 0.0), Vector3::new(0.0, 0.0, 0.0), Vector3::new(0.0, 0.0, 0.0)], n: Vector3::new(0.0, 0.0, 0.0), t: [Vector2::new(0.0, 0.0), Vector2::new(0.0, 0.0), Vector2::new(0.0, 0.0)]}}
pub fn copy(&self) -> Triangle {return Triangle {r: self.r.clone(), col: self.col, p: [self.p[0].copy(), self.p[1].copy(), self.p[2].copy()], n: self.n.copy(), t: [self.t[0].copy(), self.t[1].copy(), self.t[2].copy()]}}
}
impl Vector3 {
pub fn new(x: f64, y: f64, z: f64) -> Vector3 {return Vector3 {x, y, z, w: 1.0}}
pub fn normalize(&mut self) {
let l = (self.x * self.x + self.y * self.y + self.z * self.z).sqrt();
self.x /= l;
self.y /= l;
self.z /= l;
}
pub fn dot_product(v1: &Vector3, v2: &Vector3) -> f64 {return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z}
pub fn cross_product(v1: &Vector3, v2: &Vector3) -> Vector3 {return Vector3::new(v1.y * v2.z - v1.z * v2.y, v1.z * v2.x - v1.x * v2.z, v1.x * v2.y - v1.y * v2.x)}
pub fn intersect_plane(plane_n: &Vector3, plane_p: &Vector3, line_start: &Vector3, line_end: &Vector3, mut t: f64) -> Vector3 {
let mut p_n = plane_n.copy();
p_n.normalize();
let plane_d = -Vector3::dot_product(&p_n, plane_p);
let ad = Vector3::dot_product(line_start, &p_n);
let bd = Vector3::dot_product(line_end, &p_n);
t = (-plane_d - ad) / (bd - ad);
let line = line_end.copy() - line_start;
let line_i = line * t;
return line_start.copy() + &line_i;
}
pub fn copy(&self) -> Vector3 {return Vector3 {x: self.x, y: self.y, z: self.z, w: self.w}}
}
impl Mesh {
pub fn get_face_points(&self) -> Vec<Vector3> {
let mut face_points: Vec<Vector3> = Vec::new();
for curr_face in &self.f {
let mut face_point = Vector3::new(0.0, 0.0, 0.0);
for curr_point_index in curr_face.r {
let curr_point = &self.v[curr_point_index];
face_point += &curr_point
}
face_point /= curr_face.r.len() as f64;
face_points.push(face_point.copy());
}
return face_points;
}
pub fn get_edges_faces(&self) -> Vec<[f64; 7]> {
let mut edges: Vec<[usize; 3]> = Vec::new();
for face_num in 0..self.f.len() {
let face: Triangle = self.f[face_num].copy();
let num_points = face.p.len();
for point_index in 0..num_points {
let mut point_num_1 = 0;
let mut point_num_2 = 0;
if point_index < num_points - 1 {
point_num_1 = face.r[point_index];
point_num_2 = face.r[point_index + 1];
} else {
point_num_1 = face.r[point_index];
point_num_2 = face.r[0];
}
if point_num_1 > point_num_2 {
let temp = point_num_1;
point_num_1 = point_num_2;
point_num_2 = temp;
}
edges.push([point_num_1, point_num_2, face_num]);
}
}
edges.sort();
let num_edges = edges.len();
let mut index = 0;
let mut merged_edges: Vec<[f64; 4]> = Vec::new();
while index < num_edges {
let e1 = edges[index];
if index < num_edges - 1 {
let e2 = edges[index + 1];
if e1[0] == e2[0] && e1[1] == e2[1] {
merged_edges.push([e1[0] as f64, e1[1] as f64, e1[2] as f64, e2[2] as f64]);
index += 2;
} else {
merged_edges.push([e1[0] as f64, e1[1] as f64, e1[2] as f64, -1.0]);
index += 1;
}
} else {
merged_edges.push([e1[0] as f64, e1[1] as f64, e1[2] as f64, -1.0]);
index += 1
}
}
let mut edges_centers = Vec::new();
for me in merged_edges {
let p1 = self.v[me[0] as usize].copy();
let p2 = self.v[me[1] as usize].copy();
let cp: Vector3 = Mesh::center_point(&p1, &p2);
edges_centers.push([me[0] as f64, me[1] as f64, me[2] as f64, me[3] as f64, cp.x, cp.y, cp.z]);
}
return edges_centers;
}
pub fn get_edge_points(&self, edges_faces: &Vec<[f64; 7]>, face_points: &Vec<Vector3>) -> Vec<Vector3> {
let mut edge_points = Vec::new();
for edge in edges_faces {
let cp = Vector3::new(edge[4], edge[5], edge[6]);
let fp1: Vector3 = face_points[edge[2] as usize].copy();
let mut fp2: Vector3 = fp1.copy();
if edge[3]!= -1.0 { fp2 = face_points[edge[3] as usize].copy() };
let cfp = Mesh::center_point(&fp1, &fp2);
let edge_point = Mesh::center_point(&cp, &cfp);
edge_points.push(edge_point);
}
return edge_points
}
pub fn get_avg_face_points(&self, face_points: &Vec<Vector3>) -> Vec<Vector3> {
let num_points = self.v.len();
let mut temp_points = Vec::new();
let mut div: Vec<i32> = Vec::new();
for _ in 0..num_points {
temp_points.push(Vector3::new(0.0, 0.0, 0.0));
div.push(0)
};
for face_num in 0..self.f.len() {
let mut fp = face_points[face_num].copy();
for point_num in self.f[face_num].r {
let tp = temp_points[point_num].copy();
temp_points[point_num] = tp + &fp;
div[point_num] += 1;
}
}
let mut avg_face_points: Vec<Vector3> = Vec::new();
for i in 0..temp_points.len() {
let tp: Vector3 = temp_points[i].copy();
let t = tp / (div[i] as f64);
avg_face_points.push(t.copy());
}
return avg_face_points;
}
pub fn get_avg_mid_edges(&self, edges_faces: &Vec<[f64; 7]>) -> Vec<Vector3> {
let num_points = self.v.len();
let mut temp_points = Vec::new();
let mut div: Vec<i32> = Vec::new();
for point_num in 0..num_points{ temp_points.push(Vector3::new(0.0, 0.0, 0.0)); div.push(0)}
for edge in edges_faces {
let cp = Vector3::new(edge[4], edge[5], edge[6]);
for point_num in [edge[0] as usize, edge[1] as usize] {
let tp = temp_points[point_num].copy();
temp_points[point_num] = tp + &cp;
div[point_num] += 1
}
}
let mut avg_mid_edges: Vec<Vector3> = Vec::new();
for i in 0..temp_points.len(){
let ame: Vector3 = temp_points[i].copy() / (div[i] as f64);
avg_mid_edges.push(ame)}
return avg_mid_edges
}
pub fn get_points_faces(&self) -> Vec<i32> {
let num_points = self.v.len();
let mut points_faces: Vec<i32> = Vec::new();
for point_num in 0..num_points{points_faces.push(0)}
for face_num in 0..self.f.len() {
for point_num in self.f[face_num].r {
points_faces[point_num] += 1;
}
}
return points_faces
}
pub fn get_new_points(&self, points_faces: &Vec<i32>, avg_face_points: &Vec<Vector3>, avg_mid_edges: &Vec<Vector3>) -> Vec<Vector3> {
let mut new_points: Vec<Vector3> = Vec::new();
for point_num in 0..self.v.len() {
let n = points_faces[point_num] as f64;
let m1 = (n - 3.0) / n;
let m2 = 1.0 / n;
let m3 = 2.0 / n;
let old_coords = self.v[point_num].copy();
let p1 = old_coords * m1;
let afp = avg_face_points[point_num].copy();
let p2 = afp * m2;
let ame = avg_mid_edges[point_num].copy();
let p3 = ame * m3;
let p4 = p1 + &p2;
let new_coords = p4 + &p3;
new_points.push(new_coords);
}
return new_points;
}
pub fn switch_nums(point_nums: [f64; 2]) -> [f64; 2] {
return if point_nums[0] < point_nums[1] { point_nums } else {[point_nums[1], point_nums[0]]}
}
pub fn get_key(points: [f64; 2]) -> String {
return points[0].to_string() + ";" + &*points[1].to_string();
}
pub fn subdivide(&mut self) {
let face_points = self.get_face_points();
let edges_faces = self.get_edges_faces();
let edge_points = self.get_edge_points(&edges_faces, &face_points);
let avg_face_points = self.get_avg_face_points(&face_points);
let avg_mid_edges = self.get_avg_mid_edges(&edges_faces);
let points_faces = self.get_points_faces();
let mut new_points = self.get_new_points(&points_faces, &avg_face_points, &avg_mid_edges);
let mut face_point_nums = Vec::new();
let mut next_point_num = new_points.len();
for face_point in face_points {
new_points.push(face_point);
face_point_nums.push(next_point_num);
next_point_num += 1;
}
let mut edge_point_nums: HashMap<String, usize> = HashMap::new();
for edge_num in 0..edges_faces.len() {
let point_num_1 = edges_faces[edge_num][0];
let point_num_2 = edges_faces[edge_num][1];
let edge_point = edge_points[edge_num].copy();
new_points.push(edge_point);
edge_point_nums.insert(Mesh::get_key([point_num_1, point_num_2]), next_point_num);
next_point_num += 1;
}
let mut new_faces = Vec::new();
for old_face_num in 0..self.f.len() {
let old_face = self.f[old_face_num].copy();
let a = old_face.r[0] as f64;
let b = old_face.r[1] as f64;
let c = old_face.r[2] as f64;
let face_point_abc = face_point_nums[old_face_num];
let edge_point_ab = *edge_point_nums.get(&*Mesh::get_key(Mesh::switch_nums([a, b]))).unwrap();
let edge_point_bc = *edge_point_nums.get(&*Mesh::get_key(Mesh::switch_nums([b, c]))).unwrap();
let edge_point_ca = *edge_point_nums.get(&*Mesh::get_key(Mesh::switch_nums([c, a]))).unwrap();
new_faces.push([a, edge_point_ab as f64, face_point_abc as f64, edge_point_ca as f64]);
new_faces.push([b, edge_point_bc as f64, face_point_abc as f64, edge_point_ab as f64]);
new_faces.push([c, edge_point_ca as f64, face_point_abc as f64, edge_point_bc as f64]);
}
self.f = Vec::new();
for face_num in 0..new_faces.len() {
let curr_face = new_faces[face_num];
let mut t1: Triangle = Triangle::new();
let mut t2: Triangle = Triangle::new();
t1.p[0] = Vector3::new(new_points[curr_face[0] as usize].x, new_points[curr_face[0] as usize].y, new_points[curr_face[0] as usize].z);
t1.p[1] = Vector3::new(new_points[curr_face[1] as usize].x, new_points[curr_face[1] as usize].y, new_points[curr_face[1] as usize].z);
t1.p[2] = Vector3::new(new_points[curr_face[2] as usize].x, new_points[curr_face[2] as usize].y, new_points[curr_face[2] as usize].z);
t2.p[0] = Vector3::new(new_points[curr_face[2] as usize].x, new_points[curr_face[2] as usize].y, new_points[curr_face[2] as usize].z);
t2.p[1] = Vector3::new(new_points[curr_face[3] as usize].x, new_points[curr_face[3] as usize].y, new_points[curr_face[3] as usize].z);
t2.p[2] = Vector3::new(new_points[curr_face[0] as usize].x, new_points[curr_face[0] as usize].y, new_points[curr_face[0] as usize].z);
t1.r = [curr_face[0] as usize, curr_face[1] as usize, curr_face[2] as usize];
t2.r = [curr_face[2] as usize, curr_face[3] as usize, curr_face[0] as usize];
self.f.push(t1);
self.f.push(t2);
}
self.v = new_points;
}
} | 1,059Catmull–Clark subdivision surface
| 15rust
| kach5 |
const LEFT_ALPHABET_CT: &str = "HXUCZVAMDSLKPEFJRIGTWOBNYQ";
const RIGHT_ALPHABET_PT: &str = "PTLNBQDEOYSFAVZKGJRIHWXUMC";
const ZENITH: usize = 0;
const NADIR: usize = 12;
const SEQUENCE: &str = "WELLDONEISBETTERTHANWELLSAID";
fn cipher(letter: &char, left: &String, right: &String) -> (usize, char) {
let pos = right.find(*letter).unwrap();
let cipher = left.chars().nth(pos).unwrap();
(pos, cipher)
}
fn main() {
let mut left = LEFT_ALPHABET_CT.to_string();
let mut right = RIGHT_ALPHABET_PT.to_string();
let ciphertext = SEQUENCE.chars()
.map(|letter| {
let (pos, cipher_char) = cipher(&letter, &left, &right);
left = format!("{}{}", &left[pos..], &left[..pos]);
left = format!("{}{}{}{}", &left[ZENITH..1], &left[2..NADIR+2], &left[1..2], &left[NADIR+2..]);
if pos!= right.len() - 1 {
right = format!("{}{}", &right[pos + 1..], &right[..pos + 1]);
}
right = format!("{}{}{}{}", &right[ZENITH..2], &right[3..NADIR+2], &right[2..3], &right[NADIR+2..]);
cipher_char
})
.collect::<String>();
println!("Plaintext: {}", SEQUENCE);
println!("Ciphertext: {}", ciphertext);
} | 1,055Chaocipher
| 15rust
| iteod |
fun main(args: Array<String>) {
val dog = "Benjamin"
val Dog = "Samba"
val DOG = "Bernie"
println("The three dogs are named $dog, $Dog and $DOG")
} | 1,057Case-sensitivity of identifiers
| 11kotlin
| w0rek |
(Long/toHexString 15)
(System/currentTimeMillis)
(.equals 1 2)
(. 1 (equals 2)) | 1,065Call an object method
| 6clojure
| zmktj |
import java.text.MessageFormat;
import java.text.ParseException;
public class CanonicalizeCIDR {
public static void main(String[] args) {
for (String test : TESTS) {
try {
CIDR cidr = new CIDR(test);
System.out.printf("%-18s ->%s\n", test, cidr.toString());
} catch (Exception ex) {
System.err.printf("Error parsing '%s':%s\n", test, ex.getLocalizedMessage());
}
}
}
private static class CIDR {
private CIDR(int address, int maskLength) {
this.address = address;
this.maskLength = maskLength;
}
private CIDR(String str) throws Exception {
Object[] args = new MessageFormat(FORMAT).parse(str);
int address = 0;
for (int i = 0; i < 4; ++i) {
int a = ((Number)args[i]).intValue();
if (a < 0 || a > 255)
throw new Exception("Invalid IP address");
address <<= 8;
address += a;
}
int maskLength = ((Number)args[4]).intValue();
if (maskLength < 1 || maskLength > 32)
throw new Exception("Invalid mask length");
int mask = ~((1 << (32 - maskLength)) - 1);
this.address = address & mask;
this.maskLength = maskLength;
}
public String toString() {
int address = this.address;
int d = address & 0xFF;
address >>= 8;
int c = address & 0xFF;
address >>= 8;
int b = address & 0xFF;
address >>= 8;
int a = address & 0xFF;
Object[] args = { a, b, c, d, maskLength };
return new MessageFormat(FORMAT).format(args);
}
private int address;
private int maskLength;
private static final String FORMAT = "{0,number,integer}.{1,number,integer}.{2,number,integer}.{3,number,integer}/{4,number,integer}";
};
private static final String[] TESTS = {
"87.70.141.1/22",
"36.18.154.103/12",
"62.62.197.11/29",
"67.137.119.181/4",
"161.214.74.21/24",
"184.232.176.184/18"
};
} | 1,063Canonicalize CIDR
| 9java
| cuq9h |
dog = "Benjamin"
Dog = "Samba"
DOG = "Bernie"
print( "There are three dogs named "..dog..", "..Dog.." and "..DOG.."." ) | 1,057Case-sensitivity of identifiers
| 1lua
| x87wz |
int myopenimage(const char *in)
{
static int handle=0;
fprintf(stderr, , in);
return handle++;
}
int main()
{
void *imglib;
int (*extopenimage)(const char *);
int imghandle;
imglib = dlopen(, RTLD_LAZY);
if ( imglib != NULL ) {
*(void **)(&extopenimage) = dlsym(imglib, );
imghandle = extopenimage();
} else {
imghandle = myopenimage();
}
printf(, imghandle);
if (imglib != NULL ) dlclose(imglib);
return EXIT_SUCCESS;
} | 1,066Call a function in a shared library
| 5c
| vgq2o |
use strict;
use warnings;
use lib '/home/hkdtam/lib';
use Image::EdgeDetect;
my $detector = Image::EdgeDetect->new();
$detector->process('./input.jpg', './output.jpg') or die; | 1,062Canny edge detector
| 2perl
| zm1tb |
function RGBtoHSV($r, $g, $b) {
$r = $r/255.;
$g = $g/255.;
$b = $b/255.;
$cols = array( => $r, => $g, => $b);
asort($cols, SORT_NUMERIC);
$min = key(array_slice($cols, 1));
$max = key(array_slice($cols, -1));
if($cols[$min] == $cols[$max]) {
$h = 0;
} else {
if($max == ) {
$h = 60. * ( 0 + ( ($cols[]-$cols[]) / ($cols[$max]-$cols[$min]) ) );
} elseif ($max == ) {
$h = 60. * ( 2 + ( ($cols[]-$cols[]) / ($cols[$max]-$cols[$min]) ) );
} elseif ($max == ) {
$h = 60. * ( 4 + ( ($cols[]-$cols[]) / ($cols[$max]-$cols[$min]) ) );
}
if($h < 0) {
$h += 360;
}
}
if($cols[$max] == 0) {
$s = 0;
} else {
$s = ( ($cols[$max]-$cols[$min])/$cols[$max] );
$s = $s * 255;
}
$v = $cols[$max];
$v = $v * 255;
return(array($h, $s, $v));
}
$filename = ;
$dimensions = getimagesize($filename);
$w = $dimensions[0];
$h = $dimensions[1];
$im = imagecreatefrompng($filename);
for($hi=0; $hi < $h; $hi++) {
for($wi=0; $wi < $w; $wi++) {
$rgb = imagecolorat($im, $wi, $hi);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$hsv = RGBtoHSV($r, $g, $b);
$brgb = imagecolorat($im, $wi, $hi+1);
$br = ($brgb >> 16) & 0xFF;
$bg = ($brgb >> 8) & 0xFF;
$bb = $brgb & 0xFF;
$bhsv = RGBtoHSV($br, $bg, $bb);
if($hsv[2]-$bhsv[2] > 20) {
imagesetpixel($im, $wi, $hi, imagecolorallocate($im, 255, 0, 0));
}
else {
imagesetpixel($im, $wi, $hi, imagecolorallocate($im, 0, 0, 0));
}
}
}
header('Content-Type: image/jpeg');
imagepng($im);
imagedestroy($im); | 1,062Canny edge detector
| 12php
| bemk9 |
const canonicalize = s => { | 1,063Canonicalize CIDR
| 10javascript
| 57iur |
import java.util.*;
import java.util.stream.IntStream;
public class CastingOutNines {
public static void main(String[] args) {
System.out.println(castOut(16, 1, 255));
System.out.println(castOut(10, 1, 99));
System.out.println(castOut(17, 1, 288));
}
static List<Integer> castOut(int base, int start, int end) {
int[] ran = IntStream
.range(0, base - 1)
.filter(x -> x % (base - 1) == (x * x) % (base - 1))
.toArray();
int x = start / (base - 1);
List<Integer> result = new ArrayList<>();
while (true) {
for (int n : ran) {
int k = (base - 1) * x + n;
if (k < start)
continue;
if (k > end)
return result;
result.add(k);
}
x++;
}
}
} | 1,060Casting out nines
| 9java
| ylq6g |
package main
import "fmt"
type pair [2]int
func cart2(a, b []int) []pair {
p := make([]pair, len(a)*len(b))
i := 0
for _, a := range a {
for _, b := range b {
p[i] = pair{a, b}
i++
}
}
return p
}
func main() {
fmt.Println(cart2([]int{1, 2}, []int{3, 4}))
fmt.Println(cart2([]int{3, 4}, []int{1, 2}))
fmt.Println(cart2([]int{1, 2}, nil))
fmt.Println(cart2(nil, []int{1, 2}))
} | 1,058Cartesian product of two or more lists
| 0go
| sijqa |
char lines[HEIGHT][WIDTH];
void init() {
int i, j;
for (i = 0; i < HEIGHT; ++i) {
for (j = 0; j < WIDTH; ++j) lines[i][j] = '*';
}
}
void cantor(int start, int len, int index) {
int i, j, seg = len / 3;
if (seg == 0) return;
for (i = index; i < HEIGHT; ++i) {
for (j = start + seg; j < start + seg * 2; ++j) lines[i][j] = ' ';
}
cantor(start, seg, index + 1);
cantor(start + seg * 2, seg, index + 1);
}
void print() {
int i, j;
for (i = 0; i < HEIGHT; ++i) {
for (j = 0; j < WIDTH; ++j) printf(, lines[i][j]);
printf();
}
}
int main() {
init();
cantor(0, WIDTH, 1);
print();
return 0;
} | 1,067Cantor set
| 5c
| 9v1m1 |
function main(s, e, bs, pbs) {
bs = bs || 10;
pbs = pbs || 10
document.write('start:', toString(s), ' end:', toString(e),
' base:', bs, ' printBase:', pbs)
document.write('<br>castOutNine: ');
castOutNine()
document.write('<br>kaprekar: ');
kaprekar()
document.write('<br><br>')
function castOutNine() {
for (var n = s, k = 0, bsm1 = bs - 1; n <= e; n += 1)
if (n % bsm1 == (n * n) % bsm1) k += 1,
document.write(toString(n), ' ')
document.write('<br>trying ', k, ' numbers instead of ', n = e - s + 1,
' numbers saves ', (100 - k / n * 100)
.toFixed(3), '%')
}
function kaprekar() {
for (var n = s; n <= e; n += 1)
if (isKaprekar(n)) document.write(toString(n), ' ')
function isKaprekar(n) {
if (n < 1) return false
if (n == 1) return true
var s = (n * n)
.toString(bs)
for (var i = 1, e = s.length; i < e; i += 1) {
var a = parseInt(s.substr(0, i), bs)
var b = parseInt(s.substr(i), bs)
if (b && a + b == n) return true
}
return false
}
}
function toString(n) {
return n.toString(pbs)
.toUpperCase()
}
}
main(1, 10 * 10 - 1)
main(1, 16 * 16 - 1, 16)
main(1, 17 * 17 - 1, 17)
main(parseInt('10', 17), parseInt('gg', 17), 17, 17) | 1,060Casting out nines
| 10javascript
| 24ilr |
package main
import "fmt" | 1,064Carmichael 3 strong pseudoprimes
| 0go
| m2eyi |
class CartesianCategory {
static Iterable multiply(Iterable a, Iterable b) {
assert [a,b].every { it != null }
def (m,n) = [a.size(),b.size()]
(0..<(m*n)).inject([]) { prod, i -> prod << [a[i.intdiv(n)], b[i%n]].flatten() }
}
} | 1,058Cartesian product of two or more lists
| 7groovy
| aq51p |
import numpy as np
from scipy.ndimage.filters import convolve, gaussian_filter
from scipy.misc import imread, imshow
def CannyEdgeDetector(im, blur = 1, highThreshold = 91, lowThreshold = 31):
im = np.array(im, dtype=float)
im2 = gaussian_filter(im, blur)
im3h = convolve(im2,[[-1,0,1],[-2,0,2],[-1,0,1]])
im3v = convolve(im2,[[1,2,1],[0,0,0],[-1,-2,-1]])
grad = np.power(np.power(im3h, 2.0) + np.power(im3v, 2.0), 0.5)
theta = np.arctan2(im3v, im3h)
thetaQ = (np.round(theta * (5.0 / np.pi)) + 5)% 5
gradSup = grad.copy()
for r in range(im.shape[0]):
for c in range(im.shape[1]):
if r == 0 or r == im.shape[0]-1 or c == 0 or c == im.shape[1] - 1:
gradSup[r, c] = 0
continue
tq = thetaQ[r, c]% 4
if tq == 0:
if grad[r, c] <= grad[r, c-1] or grad[r, c] <= grad[r, c+1]:
gradSup[r, c] = 0
if tq == 1:
if grad[r, c] <= grad[r-1, c+1] or grad[r, c] <= grad[r+1, c-1]:
gradSup[r, c] = 0
if tq == 2:
if grad[r, c] <= grad[r-1, c] or grad[r, c] <= grad[r+1, c]:
gradSup[r, c] = 0
if tq == 3:
if grad[r, c] <= grad[r-1, c-1] or grad[r, c] <= grad[r+1, c+1]:
gradSup[r, c] = 0
strongEdges = (gradSup > highThreshold)
thresholdedEdges = np.array(strongEdges, dtype=np.uint8) + (gradSup > lowThreshold)
finalEdges = strongEdges.copy()
currentPixels = []
for r in range(1, im.shape[0]-1):
for c in range(1, im.shape[1]-1):
if thresholdedEdges[r, c] != 1:
continue
localPatch = thresholdedEdges[r-1:r+2,c-1:c+2]
patchMax = localPatch.max()
if patchMax == 2:
currentPixels.append((r, c))
finalEdges[r, c] = 1
while len(currentPixels) > 0:
newPix = []
for r, c in currentPixels:
for dr in range(-1, 2):
for dc in range(-1, 2):
if dr == 0 and dc == 0: continue
r2 = r+dr
c2 = c+dc
if thresholdedEdges[r2, c2] == 1 and finalEdges[r2, c2] == 0:
newPix.append((r2, c2))
finalEdges[r2, c2] = 1
currentPixels = newPix
return finalEdges
if __name__==:
im = imread(, mode=)
finalEdges = CannyEdgeDetector(im)
imshow(finalEdges) | 1,062Canny edge detector
| 3python
| 39azc |
use v5.16;
use Socket qw(inet_aton inet_ntoa);
if (!@ARGV) {
chomp(@ARGV = <>);
}
for (@ARGV) {
my ($dotted, $size) = split m
my $binary = sprintf "%032b", unpack('N', inet_aton $dotted);
substr($binary, $size) = 0 x (32 - $size);
$dotted = inet_ntoa(pack 'B32', $binary);
say "$dotted/$size";
} | 1,063Canonicalize CIDR
| 2perl
| pwmb0 |
#!/usr/bin/runhaskell
import Data.Numbers.Primes
import Control.Monad (guard)
carmichaels = do
p <- takeWhile (<= 61) primes
h3 <- [2..(p-1)]
let g = h3 + p
d <- [1..(g-1)]
guard $ (g * (p - 1)) `mod` d == 0 && (-1 * p * p) `mod` h3 == d `mod` h3
let q = 1 + (((p - 1) * g) `div` d)
guard $ isPrime q
let r = 1 + ((p * q) `div` h3)
guard $ isPrime r && (q * r) `mod` (p - 1) == 1
return (p, q, r)
main = putStr $ unlines $ map show carmichaels | 1,064Carmichael 3 strong pseudoprimes
| 8haskell
| ka3h0 |
use constant N => 15;
my @t = (0, 1);
for(my $i = 1; $i <= N; $i++) {
for(my $j = $i; $j > 1; $j--) { $t[$j] += $t[$j-1] }
$t[$i+1] = $t[$i];
for(my $j = $i+1; $j>1; $j--) { $t[$j] += $t[$j-1] }
print $t[$i+1] - $t[$i], " ";
} | 1,056Catalan numbers/Pascal's triangle
| 2perl
| 8dp0w |
cartProd :: [a] -> [b] -> [(a, b)]
cartProd xs ys =
[ (x, y)
| x <- xs
, y <- ys ] | 1,058Cartesian product of two or more lists
| 8haskell
| 9vomo |
int add(int num1, int num2) {
return num1 + num2;
} | 1,066Call a function in a shared library
| 18dart
| ylp65 |
null | 1,060Casting out nines
| 11kotlin
| f61do |
typedef unsigned long long ull;
ull binomial(ull m, ull n)
{
ull r = 1, d = m - n;
if (d > n) { n = d; d = m - n; }
while (m > n) {
r *= m--;
while (d > 1 && ! (r%d) ) r /= d--;
}
return r;
}
ull catalan1(int n) {
return binomial(2 * n, n) / (1 + n);
}
ull catalan2(int n) {
int i;
ull r = !n;
for (i = 0; i < n; i++)
r += catalan2(i) * catalan2(n - 1 - i);
return r;
}
ull catalan3(int n)
{
return n ? 2 * (2 * n - 1) * catalan3(n - 1) / (1 + n) : 1;
}
int main(void)
{
int i;
puts();
for (i = 0; i < 16; i++) {
printf(, i,
catalan1(i), catalan2(i), catalan3(i));
}
return 0;
} | 1,068Catalan numbers
| 5c
| m2bys |
import sys
from socket import inet_aton, inet_ntoa
from struct import pack, unpack
args = sys.argv[1:]
if len(args) == 0:
args = sys.stdin.readlines()
for cidr in args:
dotted, size_str = cidr.split('/')
size = int(size_str)
numeric = unpack('!I', inet_aton(dotted))[0]
binary = f'{numeric:
prefix = binary[:size + 2]
canon_binary = prefix + '0' * (32 - size)
canon_numeric = int(canon_binary, 2)
canon_dotted = inet_ntoa(pack('!I',
(canon_numeric)))
print(f'{canon_dotted}/{size}') | 1,063Canonicalize CIDR
| 3python
| 1x9pc |
local N = 2
local base = 10
local c1 = 0
local c2 = 0
for k = 1, math.pow(base, N) - 1 do
c1 = c1 + 1
if k % (base - 1) == (k * k) % (base - 1) then
c2 = c2 + 1
io.write(k .. ' ')
end
end
print()
print(string.format("Trying%d numbers instead of%d numbers saves%f%%", c2, c1, 100.0 - 100.0 * c2 / c1)) | 1,060Casting out nines
| 1lua
| tyafn |
>>> n = 15
>>> t = [0] * (n + 2)
>>> t[1] = 1
>>> for i in range(1, n + 1):
for j in range(i, 1, -1): t[j] += t[j - 1]
t[i + 1] = t[i]
for j in range(i + 1, 1, -1): t[j] += t[j - 1]
print(t[i+1] - t[i], end=' ')
1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845
>>> | 1,056Catalan numbers/Pascal's triangle
| 3python
| of181 |
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Optional.of;
import static java.util.stream.Collectors.toList;
import java.util.List;
public class CartesianProduct {
public List<?> product(List<?>... a) {
if (a.length >= 2) {
List<?> product = a[0];
for (int i = 1; i < a.length; i++) {
product = product(product, a[i]);
}
return product;
}
return emptyList();
}
private <A, B> List<?> product(List<A> a, List<B> b) {
return of(a.stream()
.map(e1 -> of(b.stream().map(e2 -> asList(e1, e2)).collect(toList())).orElse(emptyList()))
.flatMap(List::stream)
.collect(toList())).orElse(emptyList());
}
} | 1,058Cartesian product of two or more lists
| 9java
| tywf9 |
type Foo int | 1,065Call an object method
| 0go
| ghi4n |
public class Test {
static int mod(int n, int m) {
return ((n % m) + m) % m;
}
static boolean isPrime(int n) {
if (n == 2 || n == 3)
return true;
else if (n < 2 || n % 2 == 0 || n % 3 == 0)
return false;
for (int div = 5, inc = 2; Math.pow(div, 2) <= n;
div += inc, inc = 6 - inc)
if (n % div == 0)
return false;
return true;
}
public static void main(String[] args) {
for (int p = 2; p < 62; p++) {
if (!isPrime(p))
continue;
for (int h3 = 2; h3 < p; h3++) {
int g = h3 + p;
for (int d = 1; d < g; d++) {
if ((g * (p - 1)) % d != 0 || mod(-p * p, h3) != d % h3)
continue;
int q = 1 + (p - 1) * g / d;
if (!isPrime(q))
continue;
int r = 1 + (p * q / h3);
if (!isPrime(r) || (q * r) % (p - 1) != 1)
continue;
System.out.printf("%d x%d x%d%n", p, q, r);
}
}
}
}
} | 1,064Carmichael 3 strong pseudoprimes
| 9java
| 4ji58 |
package main
import (
"fmt"
)
func main() {
n := []int{1, 2, 3, 4, 5}
fmt.Println(reduce(add, n))
fmt.Println(reduce(sub, n))
fmt.Println(reduce(mul, n))
}
func add(a int, b int) int { return a + b }
func sub(a int, b int) int { return a - b }
func mul(a int, b int) int { return a * b }
func reduce(rf func(int, int) int, m []int) int {
r := m[0]
for _, v := range m[1:] {
r = rf(r, v)
}
return r
} | 1,061Catamorphism
| 0go
| qo4xz |
(() => { | 1,058Cartesian product of two or more lists
| 10javascript
| m28yv |
data Obj = Obj { field :: Int, method :: Int -> Int }
mkAdder :: Int -> Obj
mkAdder x = Obj x (+x)
instanse Show Obj where
show o = "Obj " ++ show (field o) | 1,065Call an object method
| 8haskell
| sivqk |
ClassWithStaticMethod.staticMethodName(argument1, argument2); | 1,065Call an object method
| 9java
| 1xyp2 |
#include <stdio.h>
int openimage(const char *s)
{
static int handle = 100;
fprintf(stderr, "opening%s\n", s);
return handle++;
} | 1,066Call a function in a shared library
| 0go
| si2qa |
#!/usr/bin/env stack
import Control.Exception ( try )
import Foreign ( FunPtr, allocaBytes )
import Foreign.C
( CSize(..), CString, withCAStringLen, peekCAStringLen )
import System.Info ( os )
import System.IO.Error ( ioeGetErrorString )
import System.IO.Unsafe ( unsafePerformIO )
import System.Posix.DynamicLinker
( RTLDFlags(RTLD_LAZY), dlsym, dlopen )
dlSuffix :: String
dlSuffix = if os == "darwin" then ".dylib" else ".so"
type RevFun = CString -> CString -> CSize -> IO ()
foreign import ccall "dynamic"
mkFun :: FunPtr RevFun -> RevFun
callRevFun :: RevFun -> String -> String
callRevFun f s = unsafePerformIO $ withCAStringLen s $ \(cs, len) -> do
allocaBytes len $ \buf -> do
f buf cs (fromIntegral len)
peekCAStringLen (buf, len)
getReverse :: IO (String -> String)
getReverse = do
lib <- dlopen ("libcrypto" ++ dlSuffix) [RTLD_LAZY]
fun <- dlsym lib "BUF_reverse"
return $ callRevFun $ mkFun fun
main = do
x <- try getReverse
let (msg, rev) =
case x of
Left e -> (ioeGetErrorString e ++ "; using fallback", reverse)
Right f -> ("Using BUF_reverse from OpenSSL", f)
putStrLn msg
putStrLn $ rev "a man a plan a canal panama" | 1,066Call a function in a shared library
| 8haskell
| 9vamo |
package main
import (
"fmt"
"math"
"math/big"
"strconv"
"strings"
)
func calkinWilf(n int) []*big.Rat {
cw := make([]*big.Rat, n+1)
cw[0] = big.NewRat(1, 1)
one := big.NewRat(1, 1)
two := big.NewRat(2, 1)
for i := 1; i < n; i++ {
t := new(big.Rat).Set(cw[i-1])
f, _ := t.Float64()
f = math.Floor(f)
t.SetFloat64(f)
t.Mul(t, two)
t.Sub(t, cw[i-1])
t.Add(t, one)
t.Inv(t)
cw[i] = new(big.Rat).Set(t)
}
return cw
}
func toContinued(r *big.Rat) []int {
a := r.Num().Int64()
b := r.Denom().Int64()
var res []int
for {
res = append(res, int(a/b))
t := a % b
a, b = b, t
if a == 1 {
break
}
}
le := len(res)
if le%2 == 0 { | 1,069Calkin-Wilf sequence
| 0go
| of28q |
if ARGV.length == 0 then
ARGV = $stdin.readlines.map(&:chomp)
end
ARGV.each do |cidr|
dotted, size_str = cidr.split('/')
size = size_str.to_i
binary = dotted.split('.').map { |o| % o }.join
binary[size .. -1] = '0' * (32 - size)
canon = binary.chars.each_slice(8).map { |a| a.join.to_i(2) }.join('.')
puts
end | 1,063Canonicalize CIDR
| 14ruby
| eslax |
use std::net::Ipv4Addr;
fn canonical_cidr(cidr: &str) -> Result<String, &str> {
let mut split = cidr.splitn(2, '/');
if let (Some(addr), Some(mask)) = (split.next(), split.next()) {
let addr = addr.parse::<Ipv4Addr>().map(u32::from).map_err(|_| cidr)?;
let mask = mask.parse::<u8>().map_err(|_| cidr)?;
let bitmask = 0xff_ff_ff_ffu32 << (32 - mask);
let addr = Ipv4Addr::from(addr & bitmask);
Ok(format!("{}/{}", addr, mask))
} else {
Err(cidr)
}
}
#[cfg(test)]
mod tests {
#[test]
fn valid() {
[
("87.70.141.1/22", "87.70.140.0/22"),
("36.18.154.103/12", "36.16.0.0/12"),
("62.62.197.11/29", "62.62.197.8/29"),
("67.137.119.181/4", "64.0.0.0/4"),
("161.214.74.21/24", "161.214.74.0/24"),
("184.232.176.184/18", "184.232.128.0/18"),
]
.iter()
.cloned()
.for_each(|(input, expected)| {
assert_eq!(expected, super::canonical_cidr(input).unwrap());
});
}
}
fn main() {
println!("{}", canonical_cidr("127.1.2.3/24").unwrap());
} | 1,063Canonicalize CIDR
| 15rust
| w02e4 |
fun Int.isPrime(): Boolean {
return when {
this == 2 -> true
this <= 1 || this % 2 == 0 -> false
else -> {
val max = Math.sqrt(toDouble()).toInt()
(3..max step 2)
.filter { this % it == 0 }
.forEach { return false }
true
}
}
}
fun mod(n: Int, m: Int) = ((n % m) + m) % m
fun main(args: Array<String>) {
for (p1 in 3..61) {
if (p1.isPrime()) {
for (h3 in 2 until p1) {
val g = h3 + p1
for (d in 1 until g) {
if ((g * (p1 - 1)) % d == 0 && mod(-p1 * p1, h3) == d % h3) {
val q = 1 + (p1 - 1) * g / d
if (q.isPrime()) {
val r = 1 + (p1 * q / h3)
if (r.isPrime() && (q * r) % (p1 - 1) == 1) {
println("$p1 x $q x $r")
}
}
}
}
}
}
}
} | 1,064Carmichael 3 strong pseudoprimes
| 11kotlin
| l5qcp |
def vector1 = [1,2,3,4,5,6,7]
def vector2 = [7,6,5,4,3,2,1]
def map1 = [a:1, b:2, c:3, d:4]
println vector1.inject { acc, val -> acc + val } | 1,061Catamorphism
| 7groovy
| 1xlp6 |
(def ! (memoize #(apply * (range 1 (inc %)))))
(defn catalan-numbers-direct []
(map #(/ (! (* 2 %))
(* (! (inc %)) (! %))) (range)))
(def catalan-numbers-recursive
#(->> [1 1]
(iterate (fn [[c n]]
[(* 2 (dec (* 2 n)) (/ (inc n)) c) (inc n)]) ,)
(map first ,)))
user> (take 15 (catalan-numbers-direct))
(1 1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440)
user> (take 15 (catalan-numbers-recursive))
(1 1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440) | 1,068Catalan numbers
| 6clojure
| vgw2f |
x.y() | 1,065Call an object method
| 10javascript
| qo2x8 |
import java.util.Collections;
import java.util.Random;
public class TrySort {
static boolean useC;
static {
try {
System.loadLibrary("TrySort");
useC = true;
} catch(UnsatisfiedLinkError e) {
useC = false;
}
}
static native void sortInC(int[] ary);
static class IntList extends java.util.AbstractList<Integer> {
int[] ary;
IntList(int[] ary) { this.ary = ary; }
public Integer get(int i) { return ary[i]; }
public Integer set(int i, Integer j) {
Integer o = ary[i]; ary[i] = j; return o;
}
public int size() { return ary.length; }
}
static class ReverseAbsCmp
implements java.util.Comparator<Integer>
{
public int compare(Integer pa, Integer pb) {
int a = pa > 0 ? -pa : pa;
int b = pb > 0 ? -pb : pb;
return a < b ? -1 : a > b ? 1 : 0;
}
}
static void sortInJava(int[] ary) {
Collections.sort(new IntList(ary), new ReverseAbsCmp());
}
public static void main(String[] args) {
int[] ary = new int[1000000];
Random rng = new Random();
for (int i = 0; i < ary.length; i++)
ary[i] = rng.nextInt();
if (useC) {
System.out.print("Sorting in C... ");
sortInC(ary);
} else {
System.out.print
("Missing library for C! Sorting in Java... ");
sortInJava(ary);
}
for (int i = 0; i < ary.length - 1; i++) {
int a = ary[i];
int b = ary[i + 1];
if ((a > 0 ? -a : a) > (b > 0 ? -b : b)) {
System.out.println("*BUG IN SORT*");
System.exit(1);
}
}
System.out.println("ok");
}
} | 1,066Call a function in a shared library
| 9java
| tyjf9 |
import Control.Monad (forM_)
import Data.Bool (bool)
import Data.List.NonEmpty (NonEmpty, fromList, toList, unfoldr)
import Text.Printf (printf)
calkinWilfs :: [Rational]
calkinWilfs = iterate (recip . succ . ((-) =<< (2 *) . fromIntegral . floor)) 1
calkinWilfIdx :: Rational -> Integer
calkinWilfIdx = rld . cfo
cfo :: Rational -> NonEmpty Int
cfo = oddLen . cf
cf :: Rational -> NonEmpty Int
cf = unfoldr step
where
step r =
case properFraction r of
(n, 1) -> (succ n, Nothing)
(n, 0) -> (n, Nothing)
(n, f) -> (n, Just (recip f))
oddLen :: NonEmpty Int -> NonEmpty Int
oddLen = fromList . go . toList
where
go [x, y] = [x, pred y, 1]
go (x:y:zs) = x: y: go zs
go xs = xs
rld :: NonEmpty Int -> Integer
rld = snd . foldr step (True, 0)
where
step i (b, n) =
let p = 2 ^ i
in (not b, n * p + bool 0 (pred p) b)
main :: IO ()
main = do
forM_ (take 20 $ zip [1 :: Int ..] calkinWilfs) $
\(i, r) -> printf "%2d %s\n" i (show r)
let r = 83116 / 51639
printf
"\n%s is at index%d of the Calkin-Wilf sequence.\n"
(show r)
(calkinWilfIdx r) | 1,069Calkin-Wilf sequence
| 8haskell
| 24all |
local function isprime(n)
if n < 2 then return false end
if n % 2 == 0 then return n==2 end
if n % 3 == 0 then return n==3 end
local f, limit = 5, math.sqrt(n)
while (f <= limit) do
if n % f == 0 then return false end; f=f+2
if n % f == 0 then return false end; f=f+4
end
return true
end
local function carmichael3(p)
local list = {}
if not isprime(p) then return list end
for h = 2, p-1 do
for d = 1, h+p-1 do
if ((h + p) * (p - 1)) % d == 0 and (-p * p) % h == (d % h) then
local q = 1 + math.floor((p - 1) * (h + p) / d)
if isprime(q) then
local r = 1 + math.floor(p * q / h)
if isprime(r) and (q * r) % (p - 1) == 1 then
list[#list+1] = { p=p, q=q, r=r }
end
end
end
end
end
return list
end
local found = 0
for p = 2, 61 do
local list = carmichael3(p)
found = found + #list
table.sort(list, function(a,b) return (a.p<b.p) or (a.p==b.p and a.q<b.q) or (a.p==b.p and a.q==b.q and a.r<b.r) end)
for k,v in ipairs(list) do
print(string.format("%.f %.f %.f =%.f", v.p, v.q, v.r, v.p*v.q*v.r))
end
end
print(found.." found.") | 1,064Carmichael 3 strong pseudoprimes
| 1lua
| 24sl3 |
main :: IO ()
main =
putStrLn . unlines $
[ show . foldr (+) 0
, show . foldr (*) 1
, foldr ((++) . show) ""
] <*>
[[1 .. 10]] | 1,061Catamorphism
| 8haskell
| m2qyf |
class MyClass {
fun instanceMethod(s: String) = println(s)
companion object {
fun staticMethod(s: String) = println(s)
}
}
fun main(args: Array<String>) {
val mc = MyClass()
mc.instanceMethod("Hello instance world!")
MyClass.staticMethod("Hello static world!")
} | 1,065Call an object method
| 11kotlin
| jpf7r |
int main(int argc,char** argv) {
int arg1 = atoi(argv[1]), arg2 = atoi(argv[2]), sum, diff, product, quotient, remainder ;
__asm__ ( : (sum) : (arg1) , (arg2) );
__asm__ ( : (diff) : (arg1) , (arg2) );
__asm__ ( : (product) : (arg1) , (arg2) );
__asm__ (
: (quotient), (remainder) : (arg1), (arg2) );
printf( , arg1, arg2, sum );
printf( , arg1, arg2, diff );
printf( , arg1, arg2, product );
printf( , arg1, arg2, quotient );
printf( , arg1, arg2, remainder );
return 0 ;
} | 1,070Call a foreign-language function
| 5c
| 57wuk |
sub co9 {
my $n = shift;
return $n if $n < 10;
my $sum = 0; $sum += $_ for split(//,$n);
co9($sum);
}
sub showadd {
my($n,$m) = @_;
print "( $n [",co9($n),"] + $m [",co9($m),"] ) [",co9(co9($n)+co9($m)),"]",
" = ", $n+$m," [",co9($n+$m),"]\n";
}
sub co9filter {
my $base = shift;
die unless $base >= 2;
my($beg, $end, $basem1) = (1, $base*$base-1, $base-1);
my @list = grep { $_ % $basem1 == $_*$_ % $basem1 } $beg .. $end;
($end, scalar(@list), @list);
}
print "Part 1: Create a simple filter and demonstrate using simple example.\n";
showadd(6395, 1259);
print "\nPart 2: Use this to filter a range with co9(k) == co9(k^2).\n";
print join(" ", grep { co9($_) == co9($_*$_) } 1..99), "\n";
print "\nPart 3: Use efficient method on range.\n";
for my $base (10, 17) {
my($N, $n, @l) = co9filter($base);
printf "[@l]\nIn base%d, trying%d numbers instead of%d saves%.4f%%\n\n",
$base, $n, $N, 100-($n/$N)*100;
} | 1,060Casting out nines
| 2perl
| h1mjl |
def catalan(num)
t = [0, 1]
(1..num).map do |i|
i.downto(1){|j| t[j] += t[j-1]}
t[i+1] = t[i]
(i+1).downto(1) {|j| t[j] += t[j-1]}
t[i+1] - t[i]
end
end
p catalan(15) | 1,056Catalan numbers/Pascal's triangle
| 14ruby
| nzeit |
null | 1,058Cartesian product of two or more lists
| 11kotlin
| ofb8z |
#include <stdio.h>
int openimage(const char *s)
{
static int handle = 100;
fprintf(stderr, "opening%s\n", s);
return handle++;
} | 1,066Call a function in a shared library
| 11kotlin
| of58z |
(JNIDemo/callStrdup "Hello World!") | 1,070Call a foreign-language function
| 6clojure
| jp87m |
import java.util.stream.Stream;
public class ReduceTask {
public static void main(String[] args) {
System.out.println(Stream.of(1, 2, 3, 4, 5).mapToInt(i -> i).sum());
System.out.println(Stream.of(1, 2, 3, 4, 5).reduce(1, (a, b) -> a * b));
}
} | 1,061Catamorphism
| 9java
| f6pdv |
fn main()
{let n=15usize;
let mut t= [0; 17];
t[1]=1;
let mut j:usize;
for i in 1..n+1
{
j=i;
loop{
if j==1{
break;
}
t[j]=t[j] + t[j-1];
j=j-1;
}
t[i+1]= t[i];
j=i+1;
loop{
if j==1{
break;
}
t[j]=t[j] + t[j-1];
j=j-1;
}
print!("{} ", t[i+1]-t[i]);
}
} | 1,056Catalan numbers/Pascal's triangle
| 15rust
| d3wny |
def catalan(n: Int): Int =
if (n <= 1) 1
else (0 until n).map(i => catalan(i) * catalan(n - i - 1)).sum
(1 to 15).map(catalan(_)) | 1,056Catalan numbers/Pascal's triangle
| 16scala
| zmstr |
$dog='Benjamin';
$Dog='Samba';
$DOG='Bernie';
print "The three dogs are named $dog, $Dog, and $DOG \n" | 1,057Case-sensitivity of identifiers
| 2perl
| l5dc5 |
local object = { name = "foo", func = function (self) print(self.name) end }
object:func() | 1,065Call an object method
| 1lua
| h1tj8 |
alien = require("alien")
msgbox = alien.User32.MessageBoxA
msgbox:types({ ret='long', abi='stdcall', 'long', 'string', 'string', 'long' })
retval = msgbox(0, 'Please press Yes, No or Cancel', 'The Title', 3)
print(retval) | 1,066Call a function in a shared library
| 1lua
| it4ot |
package main
import "fmt"
const (
width = 81
height = 5
)
var lines [height][width]byte
func init() {
for i := 0; i < height; i++ {
for j := 0; j < width; j++ {
lines[i][j] = '*'
}
}
}
func cantor(start, len, index int) {
seg := len / 3
if seg == 0 {
return
}
for i := index; i < height; i++ {
for j := start + seg; j < start + 2 * seg; j++ {
lines[i][j] = ' '
}
}
cantor(start, seg, index + 1)
cantor(start + seg * 2, seg, index + 1)
}
func main() {
cantor(0, width, 1)
for _, line := range lines {
fmt.Println(string(line[:]))
}
} | 1,067Cantor set
| 0go
| esya6 |
use ntheory qw/forprimes is_prime vecprod/;
forprimes { my $p = $_;
for my $h3 (2 .. $p-1) {
my $ph3 = $p + $h3;
for my $d (1 .. $ph3-1) {
next if ((-$p*$p) % $h3) != ($d % $h3);
next if (($p-1)*$ph3) % $d;
my $q = 1 + ($p-1)*$ph3 / $d;
next unless is_prime($q);
my $r = 1 + ($p*$q-1) / $h3;
next unless is_prime($r);
next unless ($q*$r) % ($p-1) == 1;
printf "%2d x%5d x%5d =%s\n",$p,$q,$r,vecprod($p,$q,$r);
}
}
} 3,61; | 1,064Carmichael 3 strong pseudoprimes
| 2perl
| qovx6 |
var nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
function add(a, b) {
return a + b;
}
var summation = nums.reduce(add);
function mul(a, b) {
return a * b;
}
var product = nums.reduce(mul, 1);
var concatenation = nums.reduce(add, "");
console.log(summation, product, concatenation); | 1,061Catamorphism
| 10javascript
| ylx6r |
local pk,upk = table.pack, table.unpack
local getn = function(t)return #t end
local const = function(k)return function(e) return k end end
local function attachIdx(f) | 1,058Cartesian product of two or more lists
| 1lua
| itpot |
class App {
private static final int WIDTH = 81
private static final int HEIGHT = 5
private static char[][] lines
static {
lines = new char[HEIGHT][WIDTH]
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
lines[i][j] = '*'
}
}
}
private static void cantor(int start, int len, int index) {
int seg = (int) (len / 3)
if (seg == 0) return
for (int i = index; i < HEIGHT; i++) {
for (int j = start + seg; j < start + seg * 2; j++) {
lines[i][j] = ' '
}
}
cantor(start, seg, index + 1)
cantor(start + seg * 2, seg, index + 1)
}
static void main(String[] args) {
cantor(0, WIDTH, 1)
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
System.out.print(lines[i][j])
}
System.out.println()
}
}
} | 1,067Cantor set
| 7groovy
| kafh7 |
use strict;
use warnings;
use feature qw(say state);
use ntheory 'fromdigits';
use List::Lazy 'lazy_list';
use Math::AnyNum ':overload';
my $calkin_wilf = lazy_list { state @cw = 1; push @cw, 1 / ( (2 * int $cw[0]) + 1 - $cw[0] ); shift @cw };
sub r2cf {
my($num, $den) = @_;
my($n, @cf);
my $f = sub { return unless $den;
my $q = int($num/$den);
($num, $den) = ($den, $num - $q*$den);
$q;
};
push @cf, $n while defined($n = $f->());
reverse @cf;
}
sub r2cw {
my($num, $den) = @_;
my $bits;
my @f = r2cf($num, $den);
$bits .= ($_%2 ? 0 : 1) x $f[$_] for 0..$
fromdigits($bits, 2);
}
say 'First twenty terms of the Calkin-Wilf sequence:';
printf "%s ", $calkin_wilf->next() for 1..20;
say "\n\n83116/51639 is at index: " . r2cw(83116,51639); | 1,069Calkin-Wilf sequence
| 2perl
| jpo7f |
def CastOut(Base=10, Start=1, End=999999):
ran = [y for y in range(Base-1) if y%(Base-1) == (y*y)%(Base-1)]
x,y = divmod(Start, Base-1)
while True:
for n in ran:
k = (Base-1)*x + n
if k < Start:
continue
if k > End:
return
yield k
x += 1
for V in CastOut(Base=16,Start=1,End=255):
print(V, end=' ') | 1,060Casting out nines
| 3python
| ka9hf |
cantor :: [(Bool, Int)] -> [(Bool, Int)]
cantor = concatMap go
where
go (bln, n)
| bln && 1 < n =
let m = quot n 3
in [(True, m), (False, m), (True, m)]
| otherwise = [(bln, n)]
main :: IO ()
main = putStrLn $ cantorLines 5
cantorLines :: Int -> String
cantorLines n =
unlines $
showCantor
<$> take n (iterate cantor [(True, 3 ^ pred n)])
showCantor :: [(Bool, Int)] -> String
showCantor = concatMap $ uncurry (flip replicate . c)
where
c True = '*'
c False = ' ' | 1,067Cantor set
| 8haskell
| 39hzj |
fun main(args: Array<String>) {
val a = intArrayOf(1, 2, 3, 4, 5)
println("Array : ${a.joinToString(", ")}")
println("Sum : ${a.reduce { x, y -> x + y }}")
println("Difference : ${a.reduce { x, y -> x - y }}")
println("Product : ${a.reduce { x, y -> x * y }}")
println("Minimum : ${a.reduce { x, y -> if (x < y) x else y }}")
println("Maximum : ${a.reduce { x, y -> if (x > y) x else y }}")
} | 1,061Catamorphism
| 11kotlin
| 8d70q |
>>> dog = 'Benjamin'; Dog = 'Samba'; DOG = 'Bernie'
>>> print ('The three dogs are named ',dog,', ',Dog,', and ',DOG)
The three dogs are named Benjamin , Samba , and Bernie
>>> | 1,057Case-sensitivity of identifiers
| 3python
| 24flz |
dog <- 'Benjamin'
Dog <- 'Samba'
DOG <- 'Bernie'
cat('The three dogs are named ')
cat(dog)
cat(', ')
cat(Dog)
cat(' and ')
cat(DOG)
cat('.\n') | 1,057Case-sensitivity of identifiers
| 13r
| m2oy4 |
const char STX = '\002', ETX = '\003';
int compareStrings(const void *a, const void *b) {
char *aa = *(char **)a;
char *bb = *(char **)b;
return strcmp(aa, bb);
}
int bwt(const char *s, char r[]) {
int i, len = strlen(s) + 2;
char *ss, *str;
char **table;
if (strchr(s, STX) || strchr(s, ETX)) return 1;
ss = calloc(len + 1, sizeof(char));
sprintf(ss, , STX, s, ETX);
table = malloc(len * sizeof(const char *));
for (i = 0; i < len; ++i) {
str = calloc(len + 1, sizeof(char));
strcpy(str, ss + i);
if (i > 0) strncat(str, ss, i);
table[i] = str;
}
qsort(table, len, sizeof(const char *), compareStrings);
for(i = 0; i < len; ++i) {
r[i] = table[i][len - 1];
free(table[i]);
}
free(table);
free(ss);
return 0;
}
void ibwt(const char *r, char s[]) {
int i, j, len = strlen(r);
char **table = malloc(len * sizeof(const char *));
for (i = 0; i < len; ++i) table[i] = calloc(len + 1, sizeof(char));
for (i = 0; i < len; ++i) {
for (j = 0; j < len; ++j) {
memmove(table[j] + 1, table[j], len);
table[j][0] = r[j];
}
qsort(table, len, sizeof(const char *), compareStrings);
}
for (i = 0; i < len; ++i) {
if (table[i][len - 1] == ETX) {
strncpy(s, table[i] + 1, len - 2);
break;
}
}
for (i = 0; i < len; ++i) free(table[i]);
free(table);
}
void makePrintable(const char *s, char t[]) {
strcpy(t, s);
for ( ; *t != '\0'; ++t) {
if (*t == STX) *t = '^';
else if (*t == ETX) *t = '|';
}
}
int main() {
int i, res, len;
char *tests[6], *t, *r, *s;
tests[0] = ;
tests[1] = ;
tests[2] = ;
tests[3] = ;
tests[4] = ,
tests[5] = ;
for (i = 0; i < 6; ++i) {
len = strlen(tests[i]);
t = calloc(len + 1, sizeof(char));
makePrintable(tests[i], t);
printf(, t);
printf();
r = calloc(len + 3, sizeof(char));
res = bwt(tests[i], r);
if (res == 1) {
printf();
}
else {
makePrintable(r, t);
printf(, t);
}
s = calloc(len + 1, sizeof(char));
ibwt(r, s);
makePrintable(s, t);
printf(, t);
free(t);
free(r);
free(s);
}
return 0;
} | 1,071Burrows–Wheeler transform
| 5c
| qo6xc |
public class App {
private static final int WIDTH = 81;
private static final int HEIGHT = 5;
private static char[][] lines;
static {
lines = new char[HEIGHT][WIDTH];
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
lines[i][j] = '*';
}
}
}
private static void cantor(int start, int len, int index) {
int seg = len / 3;
if (seg == 0) return;
for (int i = index; i < HEIGHT; i++) {
for (int j = start + seg; j < start + seg * 2; j++) {
lines[i][j] = ' ';
}
}
cantor(start, seg, index + 1);
cantor(start + seg * 2, seg, index + 1);
}
public static void main(String[] args) {
cantor(0, WIDTH, 1);
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
System.out.print(lines[i][j]);
}
System.out.println();
}
}
} | 1,067Cantor set
| 9java
| it5os |
from fractions import Fraction
from math import floor
from itertools import islice, groupby
def cw():
a = Fraction(1)
while True:
yield a
a = 1 / (2 * floor(a) + 1 - a)
def r2cf(rational):
num, den = rational.numerator, rational.denominator
while den:
num, (digit, den) = den, divmod(num, den)
yield digit
def get_term_num(rational):
ans, dig, pwr = 0, 1, 0
for n in r2cf(rational):
for _ in range(n):
ans |= dig << pwr
pwr += 1
dig ^= 1
return ans
if __name__ == '__main__':
print('TERMS 1..20: ', ', '.join(str(x) for x in islice(cw(), 20)))
x = Fraction(83116, 51639)
print(f) | 1,069Calkin-Wilf sequence
| 3python
| h1ijw |
class Isprime():
'''
Extensible sieve of Eratosthenes
>>> isprime.check(11)
True
>>> isprime.multiples
{2, 4, 6, 8, 9, 10}
>>> isprime.primes
[2, 3, 5, 7, 11]
>>> isprime(13)
True
>>> isprime.multiples
{2, 4, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 18, 20, 21, 22}
>>> isprime.primes
[2, 3, 5, 7, 11, 13, 17, 19]
>>> isprime.nmax
22
>>>
'''
multiples = {2}
primes = [2]
nmax = 2
def __init__(self, nmax):
if nmax > self.nmax:
self.check(nmax)
def check(self, n):
if type(n) == float:
if not n.is_integer(): return False
n = int(n)
multiples = self.multiples
if n <= self.nmax:
return n not in multiples
else:
primes, nmax = self.primes, self.nmax
newmax = max(nmax*2, n)
for p in primes:
multiples.update(range(p*((nmax + p + 1)
for i in range(nmax+1, newmax+1):
if i not in multiples:
primes.append(i)
multiples.update(range(i*2, newmax+1, i))
self.nmax = newmax
return n not in multiples
__call__ = check
def carmichael(p1):
ans = []
if isprime(p1):
for h3 in range(2, p1):
g = h3 + p1
for d in range(1, g):
if (g * (p1 - 1))% d == 0 and (-p1 * p1)% h3 == d% h3:
p2 = 1 + ((p1 - 1)* g
if isprime(p2):
p3 = 1 + (p1 * p2
if isprime(p3):
if (p2 * p3)% (p1 - 1) == 1:
ans += [tuple(sorted((p1, p2, p3)))]
return ans
isprime = Isprime(2)
ans = sorted(sum((carmichael(n) for n in range(62) if isprime(n)), []))
print(',\n'.join(repr(ans[i:i+5])[1:-1] for i in range(0, len(ans)+1, 5))) | 1,064Carmichael 3 strong pseudoprimes
| 3python
| siuq9 |
MyClass->classMethod($someParameter);
my $foo = 'MyClass';
$foo->classMethod($someParameter);
$myInstance->method($someParameter);
$myInstance->anotherMethod;
MyClass::classMethod('MyClass', $someParameter);
MyClass::method($myInstance, $someParameter); | 1,065Call an object method
| 2perl
| tyhfg |
use Inline
C => "DATA",
ENABLE => "AUTOWRAP",
LIBS => "-lm";
print 4*atan(1) . "\n";
__DATA__
__C__
double atan(double x); | 1,066Call a function in a shared library
| 2perl
| gho4e |
int main(int argc, char* argv[])
{
double e;
puts(
);
e = exp(1);
printf(, e);
int n = 8192;
e = 1.0 + 1.0 / n;
for (int i = 0; i < 13; i++)
e *= e;
printf(, e);
const int N = 1000;
double a[1000];
a[0] = 1.0;
for (int i = 1; i < N; i++)
{
a[i] = a[i-1] / i;
}
e = 1.;
for (int i = N - 1; i > 0; i--)
e += a[i];
printf(, e);
return 0;
} | 1,072Calculating the value of e
| 5c
| 394za |
(() => {
"use strict"; | 1,067Cantor set
| 10javascript
| zmjt2 |
N = 2
base = 10
c1 = 0
c2 = 0
for k in 1 .. (base ** N) - 1
c1 = c1 + 1
if k % (base - 1) == (k * k) % (base - 1) then
c2 = c2 + 1
print % [k]
end
end
puts
print % [c2, c1, 100.0 - 100.0 * c2 / c1] | 1,060Casting out nines
| 14ruby
| pwlbh |
table.unpack = table.unpack or unpack | 1,061Catamorphism
| 1lua
| ofj8h |
module FiveDogs
dog =
dOg =
doG =
Dog =
DOG =
names = [dog, dOg, doG, Dog, DOG]
names.uniq!
puts % [names.length, names.join()]
puts
puts % local_variables.join()
puts % constants.join()
end | 1,057Case-sensitivity of identifiers
| 14ruby
| urzvz |
Subsets and Splits