code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
func dot(v1: [Double], v2: [Double]) -> Double {
return reduce(lazy(zip(v1, v2)).map(*), 0, +)
}
println(dot([1, 3, -5], [4, -2, -1])) | 938Dot product
| 17swift
| 4ph5g |
DECLARE @s VARCHAR(10)
SET @s = '1234.56'
print isnumeric(@s) --prints 1 if numeric, 0 if not.
IF isnumeric(@s)=1 BEGIN print 'Numeric' END
ELSE print 'Non-numeric' | 956Determine if a string is numeric
| 19sql
| zlat4 |
func isNumeric(a: String) -> Bool {
return Double(a)!= nil
} | 956Determine if a string is numeric
| 17swift
| 0trs6 |
package main
import (
"fmt"
"math/big"
"rcu"
)
func main() {
count := 0
limit := 25
n := int64(17)
repunit := big.NewInt(1111111111111111)
t := new(big.Int)
zero := new(big.Int)
eleven := big.NewInt(11)
hundred := big.NewInt(100)
var deceptive []int64
for count < limit {
if !rcu.IsPrime(int(n)) && n%3 != 0 && n%5 != 0 {
bn := big.NewInt(n)
if t.Rem(repunit, bn).Cmp(zero) == 0 {
deceptive = append(deceptive, n)
count++
}
}
n += 2
repunit.Mul(repunit, hundred)
repunit.Add(repunit, eleven)
}
fmt.Println("The first", limit, "deceptive numbers are:")
fmt.Println(deceptive)
} | 959Deceptive numbers
| 0go
| eoca6 |
use strict;
use warnings;
use Math::AnyNum qw(imod is_prime);
my($x,@D) = 2;
while ($x++) {
push @D, $x if 1 == $x%2 and !is_prime $x and 0 == imod(1x($x-1),$x);
last if 25 == @D
}
print "@D\n"; | 959Deceptive numbers
| 2perl
| vj020 |
null | 959Deceptive numbers
| 15rust
| gpn4o |
typedef struct{
int a;
}layer1;
typedef struct{
layer1 l1;
float b,c;
}layer2;
typedef struct{
layer2 l2;
layer1 l1;
int d,e;
}layer3;
void showCake(layer3 cake){
printf(,cake.d);
printf(,cake.e);
printf(,cake.l1.a);
printf(,cake.l2.b);
printf(,cake.l2.l1.a);
}
int main()
{
layer3 cake1,cake2;
cake1.d = 1;
cake1.e = 2;
cake1.l1.a = 3;
cake1.l2.b = 4;
cake1.l2.l1.a = 5;
printf();
showCake(cake1);
cake2 = cake1;
cake2.l2.b += cake2.l2.l1.a;
printf();
showCake(cake2);
return 0;
} | 960Deepcopy
| 5c
| m5ays |
package main
import "fmt" | 960Deepcopy
| 0go
| a8m1f |
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class DeepCopy {
public static void main(String[] args) {
Person p1 = new Person("Clark", "Kent", new Address("1 World Center", "Metropolis", "NY", "010101"));
Person p2 = p1;
System.out.printf("Demonstrate shallow copy. Both are the same object.%n");
System.out.printf("Person p1 =%s%n", p1);
System.out.printf("Person p2 =%s%n", p2);
System.out.printf("Set city on person 2. City on both objects is changed.%n");
p2.getAddress().setCity("New York");
System.out.printf("Person p1 =%s%n", p1);
System.out.printf("Person p2 =%s%n", p2);
p1 = new Person("Clark", "Kent", new Address("1 World Center", "Metropolis", "NY", "010101"));
p2 = new Person(p1);
System.out.printf("%nDemonstrate copy constructor. Object p2 is a deep copy of p1.%n");
System.out.printf("Person p1 =%s%n", p1);
System.out.printf("Person p2 =%s%n", p2);
System.out.printf("Set city on person 2. City on objects is different.%n");
p2.getAddress().setCity("New York");
System.out.printf("Person p1 =%s%n", p1);
System.out.printf("Person p2 =%s%n", p2);
p2 = (Person) deepCopy(p1);
System.out.printf("%nDemonstrate serialization. Object p2 is a deep copy of p1.%n");
System.out.printf("Person p1 =%s%n", p1);
System.out.printf("Person p2 =%s%n", p2);
System.out.printf("Set city on person 2. City on objects is different.%n");
p2.getAddress().setCity("New York");
System.out.printf("Person p1 =%s%n", p1);
System.out.printf("Person p2 =%s%n", p2);
p2 = (Person) p1.clone();
System.out.printf("%nDemonstrate cloning. Object p2 is a deep copy of p1.%n");
System.out.printf("Person p1 =%s%n", p1);
System.out.printf("Person p2 =%s%n", p2);
System.out.printf("Set city on person 2. City on objects is different.%n");
p2.getAddress().setCity("New York");
System.out.printf("Person p1 =%s%n", p1);
System.out.printf("Person p2 =%s%n", p2);
}
private static Object deepCopy(Object object) {
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ObjectOutputStream outputStrm = new ObjectOutputStream(outputStream);
outputStrm.writeObject(object);
ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
ObjectInputStream objInputStream = new ObjectInputStream(inputStream);
return objInputStream.readObject();
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static class Address implements Serializable, Cloneable {
private static final long serialVersionUID = -7073778041809445593L;
private String street;
private String city;
private String state;
private String postalCode;
public String getStreet() {
return street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public String getPostalCode() {
return postalCode;
}
@Override
public String toString() {
return "[street=" + street + ", city=" + city + ", state=" + state + ", code=" + postalCode + "]";
}
public Address(String s, String c, String st, String p) {
street = s;
city = c;
state = st;
postalCode = p;
} | 960Deepcopy
| 9java
| o348d |
var deepcopy = function(o){
return JSON.parse(JSON.stringify(src));
};
var src = {foo:0,bar:[0,1]};
print(JSON.stringify(src));
var dst = deepcopy(src);
print(JSON.stringify(src)); | 960Deepcopy
| 10javascript
| tchfm |
null | 960Deepcopy
| 11kotlin
| xnlws |
double PI;
typedef double complex cplx;
void _fft(cplx buf[], cplx out[], int n, int step)
{
if (step < n) {
_fft(out, buf, n, step * 2);
_fft(out + step, buf + step, n, step * 2);
for (int i = 0; i < n; i += 2 * step) {
cplx t = cexp(-I * PI * i / n) * out[i + step];
buf[i / 2] = out[i] + t;
buf[(i + n)/2] = out[i] - t;
}
}
}
void fft(cplx buf[], int n)
{
cplx out[n];
for (int i = 0; i < n; i++) out[i] = buf[i];
_fft(buf, out, n, 1);
}
cplx *pad_two(double g[], int len, int *ns)
{
int n = 1;
if (*ns) n = *ns;
else while (n < len) n *= 2;
cplx *buf = calloc(sizeof(cplx), n);
for (int i = 0; i < len; i++) buf[i] = g[i];
*ns = n;
return buf;
}
void deconv(double g[], int lg, double f[], int lf, double out[]) {
int ns = 0;
cplx *g2 = pad_two(g, lg, &ns);
cplx *f2 = pad_two(f, lf, &ns);
fft(g2, ns);
fft(f2, ns);
cplx h[ns];
for (int i = 0; i < ns; i++) h[i] = g2[i] / f2[i];
fft(h, ns);
for (int i = 0; i >= lf - lg; i--)
out[-i] = h[(i + ns) % ns]/32;
free(g2);
free(f2);
}
int main()
{
PI = atan2(1,1) * 4;
double g[] = {24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7};
double f[] = { -3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1 };
double h[] = { -8,-9,-3,-1,-6,7 };
int lg = sizeof(g)/sizeof(double);
int lf = sizeof(f)/sizeof(double);
int lh = sizeof(h)/sizeof(double);
double h2[lh];
double f2[lf];
printf();
for (int i = 0; i < lf; i++) printf(, f[i]);
printf();
printf();
deconv(g, lg, h, lh, f2);
for (int i = 0; i < lf; i++) printf(, f2[i]);
printf();
printf();
for (int i = 0; i < lh; i++) printf(, h[i]);
printf();
printf();
deconv(g, lg, f, lf, h2);
for (int i = 0; i < lh; i++) printf(, h2[i]);
printf();
} | 961Deconvolution/1D
| 5c
| 4b85t |
function _deepcopy(o, tables)
if type(o) ~= 'table' then
return o
end
if tables[o] ~= nil then
return tables[o]
end
local new_o = {}
tables[o] = new_o
for k, v in next, o, nil do
local new_k = _deepcopy(k, tables)
local new_v = _deepcopy(v, tables)
new_o[new_k] = new_v
end
return new_o
end
function deepcopy(o)
return _deepcopy(o, {})
end | 960Deepcopy
| 1lua
| qd2x0 |
package main
import "fmt"
func main() {
h := []float64{-8, -9, -3, -1, -6, 7}
f := []float64{-3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1}
g := []float64{24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96,
96, 31, 55, 36, 29, -43, -7}
fmt.Println(h)
fmt.Println(deconv(g, f))
fmt.Println(f)
fmt.Println(deconv(g, h))
}
func deconv(g, f []float64) []float64 {
h := make([]float64, len(g)-len(f)+1)
for n := range h {
h[n] = g[n]
var lower int
if n >= len(f) {
lower = n - len(f) + 1
}
for i := lower; i < n; i++ {
h[n] -= h[i] * f[n-i]
}
h[n] /= f[0]
}
return h
} | 961Deconvolution/1D
| 0go
| o358q |
use strict;
use warnings;
use Storable;
use Data::Dumper;
my $src = { foo => 0, bar => [0, 1] };
$src->{baz} = $src;
my $dst = Storable::dclone($src);
print Dumper($src);
print Dumper($dst); | 960Deepcopy
| 2perl
| 27qlf |
deconv1d :: [Double] -> [Double] -> [Double]
deconv1d xs ys = takeWhile (/= 0) $ deconv xs ys
where
[] `deconv` _ = []
(0:xs) `deconv` (0:ys) = xs `deconv` ys
(x:xs) `deconv` (y:ys) =
let q = x / y
in q: zipWith (-) xs (scale q ys ++ repeat 0) `deconv` (y: ys)
scale :: Double -> [Double] -> [Double]
scale = map . (*)
h, f, g :: [Double]
h = [-8, -9, -3, -1, -6, 7]
f = [-3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1]
g =
[ 24
, 75
, 71
, -34
, 3
, 22
, -45
, 23
, 245
, 25
, 52
, 25
, -67
, -96
, 96
, 31
, 55
, 36
, 29
, -43
, -7
]
main :: IO ()
main = print $ (h == deconv1d g f) && (f == deconv1d g h) | 961Deconvolution/1D
| 8haskell
| 27xll |
<?php
class Foo
{
public function __clone()
{
$this->child = clone $this->child;
}
}
$object = new Foo;
$object->some_value = 1;
$object->child = new stdClass;
$object->child->some_value = 1;
$deepcopy = clone $object;
$deepcopy->some_value++;
$deepcopy->child->some_value++;
echo ,
;
?> | 960Deepcopy
| 12php
| sfvqs |
import java.util.Arrays;
public class Deconvolution1D {
public static int[] deconv(int[] g, int[] f) {
int[] h = new int[g.length - f.length + 1];
for (int n = 0; n < h.length; n++) {
h[n] = g[n];
int lower = Math.max(n - f.length + 1, 0);
for (int i = lower; i < n; i++)
h[n] -= h[i] * f[n - i];
h[n] /= f[0];
}
return h;
}
public static void main(String[] args) {
int[] h = { -8, -9, -3, -1, -6, 7 };
int[] f = { -3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1 };
int[] g = { 24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96,
96, 31, 55, 36, 29, -43, -7 };
StringBuilder sb = new StringBuilder();
sb.append("h = " + Arrays.toString(h) + "\n");
sb.append("deconv(g, f) = " + Arrays.toString(deconv(g, f)) + "\n");
sb.append("f = " + Arrays.toString(f) + "\n");
sb.append("deconv(g, h) = " + Arrays.toString(deconv(g, h)) + "\n");
System.out.println(sb.toString());
}
} | 961Deconvolution/1D
| 9java
| 6vb3z |
import copy
deepcopy_of_obj = copy.deepcopy(obj) | 960Deepcopy
| 3python
| vjs29 |
(defn tinyint [^long value]
(if (<= 1 value 10)
(proxy [Number] []
(doubleValue [] value)
(longValue [] value))
(throw (ArithmeticException. "integer overflow")))) | 962Define a primitive data type
| 6clojure
| jen7m |
null | 961Deconvolution/1D
| 11kotlin
| dmrnz |
function deconvolve(f, g)
local h = setmetatable({}, {__index = function(self, n)
if n == 1 then self[1] = g[1] / f[1]
else
self[n] = g[n]
for i = 1, n - 1 do
self[n] = self[n] - self[i] * (f[n - i + 1] or 0)
end
self[n] = self[n] / f[1]
end
return self[n]
end})
local _ = h[#g - #f + 1]
return setmetatable(h, nil)
end | 961Deconvolution/1D
| 1lua
| f97dp |
orig = { :num => 1, :ary => [2, 3] }
orig[:cycle] = orig
copy = Marshal.load(Marshal.dump orig)
orig[:ary] << 4
orig[:rng] = (5..6)
p orig
p copy
p [(orig.equal? orig[:cycle]),
(copy.equal? copy[:cycle]),
(not orig.equal? copy)] | 960Deepcopy
| 14ruby
| 5k8uj |
null | 960Deepcopy
| 15rust
| 4bo5u |
const char *shades = ;
double light[3] = { -50, 0, 50 };
void normalize(double * v)
{
double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);
v[0] /= len; v[1] /= len; v[2] /= len;
}
double dot(double *x, double *y)
{
double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];
return d < 0 ? -d : 0;
}
typedef struct { double cx, cy, cz, r; } sphere_t;
sphere_t pos = { 20, 20, 0, 20 }, neg = { 1, 1, -6, 20 };
int hit_sphere(sphere_t *sph, double x, double y, double *z1, double *z2)
{
double zsq;
x -= sph->cx;
y -= sph->cy;
zsq = sph->r * sph->r - (x * x + y * y);
if (zsq < 0) return 0;
zsq = sqrt(zsq);
*z1 = sph->cz - zsq;
*z2 = sph->cz + zsq;
return 1;
}
void draw_sphere(double k, double ambient)
{
int i, j, intensity, hit_result;
double b;
double vec[3], x, y, zb1, zb2, zs1, zs2;
for (i = floor(pos.cy - pos.r); i <= ceil(pos.cy + pos.r); i++) {
y = i + .5;
for (j = floor(pos.cx - 2 * pos.r); j <= ceil(pos.cx + 2 * pos.r); j++) {
x = (j - pos.cx) / 2. + .5 + pos.cx;
if (!hit_sphere(&pos, x, y, &zb1, &zb2))
hit_result = 0;
else if (!hit_sphere(&neg, x, y, &zs1, &zs2))
hit_result = 1;
else if (zs1 > zb1) hit_result = 1;
else if (zs2 > zb2) hit_result = 0;
else if (zs2 > zb1) hit_result = 2;
else hit_result = 1;
switch(hit_result) {
case 0:
putchar('+');
continue;
case 1:
vec[0] = x - pos.cx;
vec[1] = y - pos.cy;
vec[2] = zb1 - pos.cz;
break;
default:
vec[0] = neg.cx - x;
vec[1] = neg.cy - y;
vec[2] = neg.cz - zs2;
}
normalize(vec);
b = pow(dot(light, vec), k) + ambient;
intensity = (1 - b) * (sizeof(shades) - 1);
if (intensity < 0) intensity = 0;
if (intensity >= sizeof(shades) - 1)
intensity = sizeof(shades) - 2;
putchar(shades[intensity]);
}
putchar('\n');
}
}
int main()
{
double ang = 0;
while (1) {
printf();
light[1] = cos(ang * 2);
light[2] = cos(ang);
light[0] = sin(ang);
normalize(light);
ang += .05;
draw_sphere(2, .3);
usleep(100000);
}
return 0;
} | 963Death Star
| 5c
| qd9xc |
use Math::Cartesian::Product;
sub deconvolve {
our @g; local *g = shift;
our @f; local *f = shift;
my(@m,@d);
my $h = 1 + @g - @f;
push @m, [(0) x $h, $g[$_]] for 0..$
for my $j (0..$h-1) {
for my $k (0..$
$m[$j + $k][$j] = $f[$k]
}
}
rref(\@m);
push @d, @{ $m[$_] }[$h] for 0..$h-1;
@d;
}
sub convolve {
our @f; local *f = shift;
our @h; local *h = shift;
my @i;
for my $x (cartesian {@_} [0..$
push @i, @$x[0]+@$x[1];
}
my $cnt = 0;
my @g = (0) x (@f + @h - 1);
for my $x (cartesian {@_} [@f], [@h]) {
$g[$i[$cnt++]] += @$x[0]*@$x[1];
}
@g;
}
sub rref {
our @m; local *m = shift;
@m or return;
my ($lead, $rows, $cols) = (0, scalar(@m), scalar(@{$m[0]}));
foreach my $r (0 .. $rows - 1) {
$lead < $cols or return;
my $i = $r;
until ($m[$i][$lead])
{++$i == $rows or next;
$i = $r;
++$lead == $cols and return;}
@m[$i, $r] = @m[$r, $i];
my $lv = $m[$r][$lead];
$_ /= $lv foreach @{ $m[$r] };
my @mr = @{ $m[$r] };
foreach my $i (0 .. $rows - 1)
{$i == $r and next;
($lv, my $n) = ($m[$i][$lead], -1);
$_ -= $lv * $mr[++$n] foreach @{ $m[$i] };}
++$lead;}
}
my @h = qw<-8 -9 -3 -1 -6 7>;
my @f = qw<-3 -6 -1 8 -6 3 -1 -9 -9 3 -2 5 2 -2 -7 -1>;
print ' conv(f,h) = g = ' . join(' ', my @g = convolve(\@f, \@h)) . "\n";
print 'deconv(g,f) = h = ' . join(' ', deconvolve(\@g, \@f)) . "\n";
print 'deconv(g,h) = f = ' . join(' ', deconvolve(\@g, \@h)) . "\n"; | 961Deconvolution/1D
| 2perl
| jed7f |
def ToReducedRowEchelonForm( M ):
if not M: return
lead = 0
rowCount = len(M)
columnCount = len(M[0])
for r in range(rowCount):
if lead >= columnCount:
return
i = r
while M[i][lead] == 0:
i += 1
if i == rowCount:
i = r
lead += 1
if columnCount == lead:
return
M[i],M[r] = M[r],M[i]
lv = M[r][lead]
M[r] = [ mrx / lv for mrx in M[r]]
for i in range(rowCount):
if i != r:
lv = M[i][lead]
M[i] = [ iv - lv*rv for rv,iv in zip(M[r],M[i])]
lead += 1
return M
def pmtx(mtx):
print ('\n'.join(''.join('%4s'% col for col in row) for row in mtx))
def convolve(f, h):
g = [0] * (len(f) + len(h) - 1)
for hindex, hval in enumerate(h):
for findex, fval in enumerate(f):
g[hindex + findex] += fval * hval
return g
def deconvolve(g, f):
lenh = len(g) - len(f) + 1
mtx = [[0 for x in range(lenh+1)] for y in g]
for hindex in range(lenh):
for findex, fval in enumerate(f):
gindex = hindex + findex
mtx[gindex][hindex] = fval
for gindex, gval in enumerate(g):
mtx[gindex][lenh] = gval
ToReducedRowEchelonForm( mtx )
return [mtx[i][lenh] for i in range(lenh)]
if __name__ == '__main__':
h = [-8,-9,-3,-1,-6,7]
f = [-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1]
g = [24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7]
assert convolve(f,h) == g
assert deconvolve(g, f) == h | 961Deconvolution/1D
| 3python
| hwfjw |
wchar_t s_suits[] = L, s_nums[] = L;
static int seed = 1;
int rnd(void) { return (seed = (seed * 214013 + 2531011) & RMAX32) >> 16; }
void srnd(int x) { seed = x; }
void show(const int *c)
{
int i;
for (i = 0; i < 52; c++) {
printf(, 32 - (1 + *c) % 4 / 2,
s_suits[*c % 4], s_nums[*c / 4]);
if (!(++i % 8) || i == 52) putchar('\n');
}
}
void deal(int s, int *t)
{
int i, j;
srnd(s);
for (i = 0; i < 52; i++) t[i] = 51 - i;
for (i = 0; i < 51; i++) {
j = 51 - rnd() % (52 - i);
s = t[i], t[i] = t[j], t[j] = s;
}
}
int main(int c, char **v)
{
int s, card[52];
if (c < 2 || (s = atoi(v[1])) <= 0) s = 11982;
setlocale(LC_ALL, );
deal(s, card);
printf(, s);
show(card);
return 0;
} | 964Deal cards for FreeCell
| 5c
| 327za |
conv <- function(a, b) {
p <- length(a)
q <- length(b)
n <- p + q - 1
r <- nextn(n, f=2)
y <- fft(fft(c(a, rep(0, r-p))) * fft(c(b, rep(0, r-q))), inverse=TRUE)/r
y[1:n]
}
deconv <- function(a, b) {
p <- length(a)
q <- length(b)
n <- p - q + 1
r <- nextn(max(p, q), f=2)
y <- fft(fft(c(a, rep(0, r-p))) / fft(c(b, rep(0, r-q))), inverse=TRUE)/r
return(y[1:n])
} | 961Deconvolution/1D
| 13r
| gpo47 |
double PI;
typedef double complex cplx;
void _fft(cplx buf[], cplx out[], int n, int step)
{
if (step < n) {
_fft(out, buf, n, step * 2);
_fft(out + step, buf + step, n, step * 2);
for (int i = 0; i < n; i += 2 * step) {
cplx t = cexp(-I * PI * i / n) * out[i + step];
buf[i / 2] = out[i] + t;
buf[(i + n)/2] = out[i] - t;
}
}
}
void fft(cplx buf[], int n)
{
cplx out[n];
for (int i = 0; i < n; i++) out[i] = buf[i];
_fft(buf, out, n, 1);
}
cplx *pad_two(double g[], int len, int *ns)
{
int n = 1;
if (*ns) n = *ns;
else while (n < len) n *= 2;
cplx *buf = calloc(sizeof(cplx), n);
for (int i = 0; i < len; i++) buf[i] = g[i];
*ns = n;
return buf;
}
void deconv(double g[], int lg, double f[], int lf, double out[], int row_len) {
int ns = 0;
cplx *g2 = pad_two(g, lg, &ns);
cplx *f2 = pad_two(f, lf, &ns);
fft(g2, ns);
fft(f2, ns);
cplx h[ns];
for (int i = 0; i < ns; i++) h[i] = g2[i] / f2[i];
fft(h, ns);
for (int i = 0; i < ns; i++) {
if (cabs(creal(h[i])) < 1e-10)
h[i] = 0;
}
for (int i = 0; i > lf - lg - row_len; i--)
out[-i] = h[(i + ns) % ns]/32;
free(g2);
free(f2);
}
double* unpack2(void *m, int rows, int len, int to_len)
{
double *buf = calloc(sizeof(double), rows * to_len);
for (int i = 0; i < rows; i++)
for (int j = 0; j < len; j++)
buf[i * to_len + j] = ((double(*)[len])m)[i][j];
return buf;
}
void pack2(double * buf, int rows, int from_len, int to_len, void *out)
{
for (int i = 0; i < rows; i++)
for (int j = 0; j < to_len; j++)
((double(*)[to_len])out)[i][j] = buf[i * from_len + j] / 4;
}
void deconv2(void *g, int row_g, int col_g, void *f, int row_f, int col_f, void *out) {
double *g2 = unpack2(g, row_g, col_g, col_g);
double *f2 = unpack2(f, row_f, col_f, col_g);
double ff[(row_g - row_f + 1) * col_g];
deconv(g2, row_g * col_g, f2, row_f * col_g, ff, col_g);
pack2(ff, row_g - row_f + 1, col_g, col_g - col_f + 1, out);
free(g2);
free(f2);
}
double* unpack3(void *m, int x, int y, int z, int to_y, int to_z)
{
double *buf = calloc(sizeof(double), x * to_y * to_z);
for (int i = 0; i < x; i++)
for (int j = 0; j < y; j++) {
for (int k = 0; k < z; k++)
buf[(i * to_y + j) * to_z + k] =
((double(*)[y][z])m)[i][j][k];
}
return buf;
}
void pack3(double * buf, int x, int y, int z, int to_y, int to_z, void *out)
{
for (int i = 0; i < x; i++)
for (int j = 0; j < to_y; j++)
for (int k = 0; k < to_z; k++)
((double(*)[to_y][to_z])out)[i][j][k] =
buf[(i * y + j) * z + k] / 4;
}
void deconv3(void *g, int gx, int gy, int gz, void *f, int fx, int fy, int fz, void *out) {
double *g2 = unpack3(g, gx, gy, gz, gy, gz);
double *f2 = unpack3(f, fx, fy, fz, gy, gz);
double ff[(gx - fx + 1) * gy * gz];
deconv(g2, gx * gy * gz, f2, fx * gy * gz, ff, gy * gz);
pack3(ff, gx - fx + 1, gy, gz, gy - fy + 1, gz - fz + 1, out);
free(g2);
free(f2);
}
int main()
{
PI = atan2(1,1) * 4;
double h[2][3][4] = {
{{-6, -8, -5, 9}, {-7, 9, -6, -8}, { 2, -7, 9, 8}},
{{ 7, 4, 4, -6}, { 9, 9, 4, -4}, {-3, 7, -2, -3}}
};
int hx = 2, hy = 3, hz = 4;
double f[3][2][3] = { {{-9, 5, -8}, { 3, 5, 1}},
{{-1, -7, 2}, {-5, -6, 6}},
{{ 8, 5, 8}, {-2, -6, -4}} };
int fx = 3, fy = 2, fz = 3;
double g[4][4][6] = {
{ { 54, 42, 53, -42, 85, -72}, { 45,-170, 94, -36, 48, 73},
{-39, 65,-112, -16, -78, -72}, { 6, -11, -6, 62, 49, 8} },
{ {-57, 49, -23, 52, -135, 66},{-23, 127, -58, -5, -118, 64},
{ 87, -16, 121, 23, -41, -12},{-19, 29, 35,-148, -11, 45} },
{ {-55, -147, -146, -31, 55, 60},{-88, -45, -28, 46, -26,-144},
{-12, -107, -34, 150, 249, 66},{ 11, -15, -34, 27, -78, -50} },
{ { 56, 67, 108, 4, 2,-48},{ 58, 67, 89, 32, 32, -8},
{-42, -31,-103, -30,-23, -8},{ 6, 4, -26, -10, 26, 12}
}
};
int gx = 4, gy = 4, gz = 6;
double h2[gx - fx + 1][gy - fy + 1][gz - fz + 1];
deconv3(g, gx, gy, gz, f, fx, fy, fz, h2);
printf();
for (int i = 0; i < gx - fx + 1; i++) {
for (int j = 0; j < gy - fy + 1; j++) {
for (int k = 0; k < gz - fz + 1; k++)
printf(, h2[i][j][k]);
printf();
}
if (i < gx - fx) printf();
}
double f2[gx - hx + 1][gy - hy + 1][gz - hz + 1];
deconv3(g, gx, gy, gz, h, hx, hy, hz, f2);
printf();
for (int i = 0; i < gx - hx + 1; i++) {
for (int j = 0; j < gy - hy + 1; j++) {
for (int k = 0; k < gz - hz + 1; k++)
printf(, f2[i][j][k]);
printf();
}
if (i < gx - hx) printf();
}
} | 965Deconvolution/2D+
| 5c
| r1sg7 |
package main
import (
"fmt"
"image"
"image/color"
"image/png"
"math"
"os"
)
type vector [3]float64
func (v *vector) normalize() {
invLen := 1 / math.Sqrt(dot(v, v))
v[0] *= invLen
v[1] *= invLen
v[2] *= invLen
}
func dot(x, y *vector) float64 {
return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]
}
type sphere struct {
cx, cy, cz int
r int
}
func (s *sphere) hit(x, y int) (z1, z2 float64, hit bool) {
x -= s.cx
y -= s.cy
if zsq := s.r*s.r - (x*x + y*y); zsq >= 0 {
zsqrt := math.Sqrt(float64(zsq))
return float64(s.cz) - zsqrt, float64(s.cz) + zsqrt, true
}
return 0, 0, false
}
func deathStar(pos, neg *sphere, k, amb float64, dir *vector) *image.Gray {
w, h := pos.r*4, pos.r*3
bounds := image.Rect(pos.cx-w/2, pos.cy-h/2, pos.cx+w/2, pos.cy+h/2)
img := image.NewGray(bounds)
vec := new(vector)
for y, yMax := pos.cy-pos.r, pos.cy+pos.r; y <= yMax; y++ {
for x, xMax := pos.cx-pos.r, pos.cx+pos.r; x <= xMax; x++ {
zb1, zb2, hit := pos.hit(x, y)
if !hit {
continue
}
zs1, zs2, hit := neg.hit(x, y)
if hit {
if zs1 > zb1 {
hit = false
} else if zs2 > zb2 {
continue
}
}
if hit {
vec[0] = float64(neg.cx - x)
vec[1] = float64(neg.cy - y)
vec[2] = float64(neg.cz) - zs2
} else {
vec[0] = float64(x - pos.cx)
vec[1] = float64(y - pos.cy)
vec[2] = zb1 - float64(pos.cz)
}
vec.normalize()
s := dot(dir, vec)
if s < 0 {
s = 0
}
lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)
if lum < 0 {
lum = 0
} else if lum > 255 {
lum = 255
}
img.SetGray(x, y, color.Gray{uint8(lum)})
}
}
return img
}
func main() {
dir := &vector{20, -40, -10}
dir.normalize()
pos := &sphere{0, 0, 0, 120}
neg := &sphere{-90, -90, -30, 100}
img := deathStar(pos, neg, 1.5, .2, dir)
f, err := os.Create("dstar.png")
if err != nil {
fmt.Println(err)
return
}
if err = png.Encode(f, img); err != nil {
fmt.Println(err)
}
if err = f.Close(); err != nil {
fmt.Println(err)
}
} | 963Death Star
| 0go
| 27el7 |
package main
import (
"bytes"
"fmt"
"strconv"
"strings"
)
const digits = "0123456789"
func deBruijn(k, n int) string {
alphabet := digits[0:k]
a := make([]byte, k*n)
var seq []byte
var db func(int, int) | 966de Bruijn sequences
| 0go
| 5keul |
import Data.List (genericLength)
shades = ".:!*oe%#&@"
n = genericLength shades
dot a b = sum $ zipWith (*) a b
normalize x = (/ sqrt (x `dot` x)) <$> x
deathStar r k amb = unlines $
[ [ if x*x + y*y <= r*r
then let vec = normalize $ normal x y
b = (light `dot` vec) ** k + amb
intensity = (1 - b)*(n - 1)
in shades !! round ((0 `max` intensity) `min` n)
else ' '
| y <- map (/2.12) [- 2*r - 0.5 .. 2*r + 0.5] ]
| x <- [ - r - 0.5 .. r + 0.5] ]
where
light = normalize [-30,-30,-50]
normal x y
| (x+r)**2 + (y+r)**2 <= r**2 = [x+r, y+r, sph2 x y]
| otherwise = [x, y, sph1 x y]
sph1 x y = sqrt (r*r - x*x - y*y)
sph2 x y = r - sqrt (r*r - (x+r)**2 - (y+r)**2) | 963Death Star
| 8haskell
| a831g |
package main
import (
"fmt"
"math"
"math/cmplx"
)
func fft(buf []complex128, n int) {
out := make([]complex128, n)
copy(out, buf)
fft2(buf, out, n, 1)
}
func fft2(buf, out []complex128, n, step int) {
if step < n {
fft2(out, buf, n, step*2)
fft2(out[step:], buf[step:], n, step*2)
for j := 0; j < n; j += 2 * step {
fj, fn := float64(j), float64(n)
t := cmplx.Exp(-1i*complex(math.Pi, 0)*complex(fj, 0)/complex(fn, 0)) * out[j+step]
buf[j/2] = out[j] + t
buf[(j+n)/2] = out[j] - t
}
}
}
func padTwo(g []float64, le int, ns *int) []complex128 {
n := 1
if *ns != 0 {
n = *ns
} else {
for n < le {
n *= 2
}
}
buf := make([]complex128, n)
for i := 0; i < le; i++ {
buf[i] = complex(g[i], 0)
}
*ns = n
return buf
}
func deconv(g []float64, lg int, f []float64, lf int, out []float64, rowLe int) {
ns := 0
g2 := padTwo(g, lg, &ns)
f2 := padTwo(f, lf, &ns)
fft(g2, ns)
fft(f2, ns)
h := make([]complex128, ns)
for i := 0; i < ns; i++ {
h[i] = g2[i] / f2[i]
}
fft(h, ns)
for i := 0; i < ns; i++ {
if math.Abs(real(h[i])) < 1e-10 {
h[i] = 0
}
}
for i := 0; i > lf-lg-rowLe; i-- {
out[-i] = real(h[(i+ns)%ns] / 32)
}
}
func unpack2(m [][]float64, rows, le, toLe int) []float64 {
buf := make([]float64, rows*toLe)
for i := 0; i < rows; i++ {
for j := 0; j < le; j++ {
buf[i*toLe+j] = m[i][j]
}
}
return buf
}
func pack2(buf []float64, rows, fromLe, toLe int, out [][]float64) {
for i := 0; i < rows; i++ {
for j := 0; j < toLe; j++ {
out[i][j] = buf[i*fromLe+j] / 4
}
}
}
func deconv2(g [][]float64, rowG, colG int, f [][]float64, rowF, colF int, out [][]float64) {
g2 := unpack2(g, rowG, colG, colG)
f2 := unpack2(f, rowF, colF, colG)
ff := make([]float64, (rowG-rowF+1)*colG)
deconv(g2, rowG*colG, f2, rowF*colG, ff, colG)
pack2(ff, rowG-rowF+1, colG, colG-colF+1, out)
}
func unpack3(m [][][]float64, x, y, z, toY, toZ int) []float64 {
buf := make([]float64, x*toY*toZ)
for i := 0; i < x; i++ {
for j := 0; j < y; j++ {
for k := 0; k < z; k++ {
buf[(i*toY+j)*toZ+k] = m[i][j][k]
}
}
}
return buf
}
func pack3(buf []float64, x, y, z, toY, toZ int, out [][][]float64) {
for i := 0; i < x; i++ {
for j := 0; j < toY; j++ {
for k := 0; k < toZ; k++ {
out[i][j][k] = buf[(i*y+j)*z+k] / 4
}
}
}
}
func deconv3(g [][][]float64, gx, gy, gz int, f [][][]float64, fx, fy, fz int, out [][][]float64) {
g2 := unpack3(g, gx, gy, gz, gy, gz)
f2 := unpack3(f, fx, fy, fz, gy, gz)
ff := make([]float64, (gx-fx+1)*gy*gz)
deconv(g2, gx*gy*gz, f2, fx*gy*gz, ff, gy*gz)
pack3(ff, gx-fx+1, gy, gz, gy-fy+1, gz-fz+1, out)
}
func main() {
f := [][][]float64{
{{-9, 5, -8}, {3, 5, 1}},
{{-1, -7, 2}, {-5, -6, 6}},
{{8, 5, 8}, {-2, -6, -4}},
}
fx, fy, fz := len(f), len(f[0]), len(f[0][0])
g := [][][]float64{
{{54, 42, 53, -42, 85, -72}, {45, -170, 94, -36, 48, 73},
{-39, 65, -112, -16, -78, -72}, {6, -11, -6, 62, 49, 8}},
{{-57, 49, -23, 52, -135, 66}, {-23, 127, -58, -5, -118, 64},
{87, -16, 121, 23, -41, -12}, {-19, 29, 35, -148, -11, 45}},
{{-55, -147, -146, -31, 55, 60}, {-88, -45, -28, 46, -26, -144},
{-12, -107, -34, 150, 249, 66}, {11, -15, -34, 27, -78, -50}},
{{56, 67, 108, 4, 2, -48}, {58, 67, 89, 32, 32, -8},
{-42, -31, -103, -30, -23, -8}, {6, 4, -26, -10, 26, 12},
},
}
gx, gy, gz := len(g), len(g[0]), len(g[0][0])
h := [][][]float64{
{{-6, -8, -5, 9}, {-7, 9, -6, -8}, {2, -7, 9, 8}},
{{7, 4, 4, -6}, {9, 9, 4, -4}, {-3, 7, -2, -3}},
}
hx, hy, hz := gx-fx+1, gy-fy+1, gz-fz+1
h2 := make([][][]float64, hx)
for i := 0; i < hx; i++ {
h2[i] = make([][]float64, hy)
for j := 0; j < hy; j++ {
h2[i][j] = make([]float64, hz)
}
}
deconv3(g, gx, gy, gz, f, fx, fy, fz, h2)
fmt.Println("deconv3(g, f):\n")
for i := 0; i < hx; i++ {
for j := 0; j < hy; j++ {
for k := 0; k < hz; k++ {
fmt.Printf("% .10g ", h2[i][j][k])
}
fmt.Println()
}
if i < hx-1 {
fmt.Println()
}
}
kx, ky, kz := gx-hx+1, gy-hy+1, gz-hz+1
f2 := make([][][]float64, kx)
for i := 0; i < kx; i++ {
f2[i] = make([][]float64, ky)
for j := 0; j < ky; j++ {
f2[i][j] = make([]float64, kz)
}
}
deconv3(g, gx, gy, gz, h, hx, hy, hz, f2)
fmt.Println("\ndeconv(g, h):\n")
for i := 0; i < kx; i++ {
for j := 0; j < ky; j++ {
for k := 0; k < kz; k++ {
fmt.Printf("% .10g ", f2[i][j][k])
}
fmt.Println()
}
if i < kx-1 {
fmt.Println()
}
}
} | 965Deconvolution/2D+
| 0go
| nyvi1 |
(def deck (into [] (for [rank "A23456789TJQK" suit "CDHS"] (str rank suit))))
(defn lcg [seed]
(map #(bit-shift-right % 16)
(rest (iterate #(mod (+ (* % 214013) 2531011) (bit-shift-left 1 31)) seed))))
(defn gen [seed]
(map (fn [rnd rng] (into [] [(mod rnd rng) (dec rng)]))
(lcg seed) (range 52 0 -1)))
(defn xchg [v [src dst]] (assoc v dst (v src) src (v dst)))
(defn show [seed] (map #(println %) (partition 8 8 ""
(reverse (reduce xchg deck (gen seed))))))
(show 1) | 964Deal cards for FreeCell
| 6clojure
| cgp9b |
import java.util.function.BiConsumer
class DeBruijn {
interface Recursable<T, U> {
void apply(T t, U u, Recursable<T, U> r);
}
static <T, U> BiConsumer<T, U> recurse(Recursable<T, U> f) {
return { t, u -> f.apply(t, u, f) }
}
private static String deBruijn(int k, int n) {
byte[] a = new byte[k * n]
Arrays.fill(a, (byte) 0)
List<Byte> seq = new ArrayList<>()
BiConsumer<Integer, Integer> db = recurse({ int t, int p, f ->
if (t > n) {
if (n % p == 0) {
for (int i = 1; i < p + 1; ++i) {
seq.add(a[i])
}
}
} else {
a[t] = a[t - p]
f.apply(t + 1, p, f)
int j = a[t - p] + 1
while (j < k) {
a[t] = (byte) (j & 0xFF)
f.apply(t + 1, t, f)
j++
}
}
})
db.accept(1, 1)
StringBuilder sb = new StringBuilder()
for (Byte i: seq) {
sb.append("0123456789".charAt(i))
}
sb.append(sb.subSequence(0, n - 1))
return sb.toString()
}
private static boolean allDigits(String s) {
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i)
if (!Character.isDigit(c)) {
return false
}
}
return true
}
private static void validate(String db) {
int le = db.length()
int[] found = new int[10_000]
Arrays.fill(found, 0)
List<String> errs = new ArrayList<>() | 966de Bruijn sequences
| 7groovy
| cgk9i |
package main
import "fmt"
type TinyInt int
func NewTinyInt(i int) TinyInt {
if i < 1 {
i = 1
} else if i > 10 {
i = 10
}
return TinyInt(i)
}
func (t1 TinyInt) Add(t2 TinyInt) TinyInt {
return NewTinyInt(int(t1) + int(t2))
}
func (t1 TinyInt) Sub(t2 TinyInt) TinyInt {
return NewTinyInt(int(t1) - int(t2))
}
func (t1 TinyInt) Mul(t2 TinyInt) TinyInt {
return NewTinyInt(int(t1) * int(t2))
}
func (t1 TinyInt) Div(t2 TinyInt) TinyInt {
return NewTinyInt(int(t1) / int(t2))
}
func (t1 TinyInt) Rem(t2 TinyInt) TinyInt {
return NewTinyInt(int(t1) % int(t2))
}
func (t TinyInt) Inc() TinyInt {
return t.Add(TinyInt(1))
}
func (t TinyInt) Dec() TinyInt {
return t.Sub(TinyInt(1))
}
func main() {
t1 := NewTinyInt(6)
t2 := NewTinyInt(3)
fmt.Println("t1 =", t1)
fmt.Println("t2 =", t2)
fmt.Println("t1 + t2 =", t1.Add(t2))
fmt.Println("t1 - t2 =", t1.Sub(t2))
fmt.Println("t1 * t2 =", t1.Mul(t2))
fmt.Println("t1 / t2 =", t1.Div(t2))
fmt.Println("t1% t2 =", t1.Rem(t2))
fmt.Println("t1 + 1 =", t1.Inc())
fmt.Println("t1 - 1 =", t1.Dec())
} | 962Define a primitive data type
| 0go
| 8zv0g |
object Deconvolution1D extends App {
val (h, f) = (Array(-8, -9, -3, -1, -6, 7), Array(-3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1))
val g = Array(24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96, 96, 31, 55, 36, 29, -43, -7)
val sb = new StringBuilder
private def deconv(g: Array[Int], f: Array[Int]) = {
val h = Array.ofDim[Int](g.length - f.length + 1)
for (n <- h.indices) {
h(n) = g(n)
for (i <- math.max(n - f.length + 1, 0) until n) h(n) -= h(i) * f(n - i)
h(n) /= f(0)
}
h
}
sb.append(s"h = ${h.mkString("[", ", ", "]")}\n")
.append(s"deconv(g, f) = ${deconv(g, f).mkString("[", ", ", "]")}\n")
.append(s"f = ${f.mkString("[", ", ", "]")}\n")
.append(s"deconv(g, h) = ${deconv(g, h).mkString("[", ", ", "]")}")
println(sb.result())
} | 961Deconvolution/1D
| 16scala
| eomab |
import Data.List
import Data.Map ((!))
import qualified Data.Map as M
cycleForm :: [Int] -> [[Int]]
cycleForm p = unfoldr getCycle $ M.fromList $ zip [0..] p
where
getCycle p
| M.null p = Nothing
| otherwise =
let Just ((x,y), m) = M.minViewWithKey p
c = if x == y then [] else takeWhile (/= x) (iterate (m !) y)
in Just (c ++ [x], foldr M.delete m c)
lyndonWords :: Ord a => [a] -> Int -> [[a]]
lyndonWords s n = map (ref !!) <$> cycleForm perm
where
ref = concat $ replicate (length s ^ (n - 1)) s
perm = s >>= (`elemIndices` ref)
deBruijn :: Ord a => [a] -> Int -> [a]
deBruijn s n = let lw = concat $ lyndonWords n s
in lw ++ take (n-1) lw | 966de Bruijn sequences
| 8haskell
| xn3w4 |
data Check a b = Check { unCheck :: b } deriving (Eq, Ord)
class Checked a b where
check :: b -> Check a b
lift f x = f (unCheck x)
liftc f x = check $ f (unCheck x)
lift2 f x y = f (unCheck x) (unCheck y)
lift2c f x y = check $ f (unCheck x) (unCheck y)
lift2p f x y = (check u, check v) where (u,v) = f (unCheck x) (unCheck y)
instance Show b => Show (Check a b) where
show (Check x) = show x
showsPrec p (Check x) = showsPrec p x
instance (Enum b, Checked a b) => Enum (Check a b) where
succ = liftc succ
pred = liftc pred
toEnum = check . toEnum
fromEnum = lift fromEnum
instance (Num b, Checked a b) => Num (Check a b) where
(+) = lift2c (+)
(-) = lift2c (-)
(*) = lift2c (*)
negate = liftc negate
abs = liftc abs
signum = liftc signum
fromInteger = check . fromInteger
instance (Real b, Checked a b) => Real (Check a b) where
toRational = lift toRational
instance (Integral b, Checked a b) => Integral (Check a b) where
quot = lift2c quot
rem = lift2c rem
div = lift2c div
mod = lift2c mod
quotRem = lift2p quotRem
divMod = lift2p divMod
toInteger = lift toInteger | 962Define a primitive data type
| 8haskell
| lrech |
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.geometry.Point3D;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.shape.MeshView;
import javafx.scene.shape.TriangleMesh;
import javafx.scene.transform.Rotate;
import javafx.stage.Stage;
public class DeathStar extends Application {
private static final int DIVISION = 200; | 963Death Star
| 9java
| jei7c |
func deconv(g: [Double], f: [Double]) -> [Double] {
let fs = f.count
var ret = [Double](repeating: 0, count: g.count - fs + 1)
for n in 0..<ret.count {
ret[n] = g[n]
let lower = n >= fs? n - fs + 1: 0
for i in lower..<n {
ret[n] -= ret[i] * f[n - i]
}
ret[n] /= f[0]
}
return ret
}
let h = [-8.0, -9.0, -3.0, -1.0, -6.0, 7.0]
let f = [-3.0, -6.0, -1.0, 8.0, -6.0, 3.0, -1.0, -9.0,
-9.0, 3.0, -2.0, 5.0, 2.0, -2.0, -7.0, -1.0]
let g = [24.0, 75.0, 71.0, -34.0, 3.0, 22.0, -45.0,
23.0, 245.0, 25.0, 52.0, 25.0, -67.0, -96.0,
96.0, 31.0, 55.0, 36.0, 29.0, -43.0, -7.0]
print("\(h.map({ Int($0) }))")
print("\(deconv(g: g, f: f).map({ Int($0) }))\n")
print("\(f.map({ Int($0) }))")
print("\(deconv(g: g, f: h).map({ Int($0) }))") | 961Deconvolution/1D
| 17swift
| kxthx |
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.BiConsumer;
public class DeBruijn {
public interface Recursable<T, U> {
void apply(T t, U u, Recursable<T, U> r);
}
public static <T, U> BiConsumer<T, U> recurse(Recursable<T, U> f) {
return (t, u) -> f.apply(t, u, f);
}
private static String deBruijn(int k, int n) {
byte[] a = new byte[k * n];
Arrays.fill(a, (byte) 0);
List<Byte> seq = new ArrayList<>();
BiConsumer<Integer, Integer> db = recurse((t, p, f) -> {
if (t > n) {
if (n % p == 0) {
for (int i = 1; i < p + 1; ++i) {
seq.add(a[i]);
}
}
} else {
a[t] = a[t - p];
f.apply(t + 1, p, f);
int j = a[t - p] + 1;
while (j < k) {
a[t] = (byte) (j & 0xFF);
f.apply(t + 1, t, f);
j++;
}
}
});
db.accept(1, 1);
StringBuilder sb = new StringBuilder();
for (Byte i : seq) {
sb.append("0123456789".charAt(i));
}
sb.append(sb.subSequence(0, n - 1));
return sb.toString();
}
private static boolean allDigits(String s) {
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
if (!Character.isDigit(c)) {
return false;
}
}
return true;
}
private static void validate(String db) {
int le = db.length();
int[] found = new int[10_000];
Arrays.fill(found, 0);
List<String> errs = new ArrayList<>(); | 966de Bruijn sequences
| 9java
| bqik3 |
<!DOCTYPE html>
<html>
<body style="margin:0">
<canvas id="myCanvas" width="250" height="250" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d"); | 963Death Star
| 10javascript
| 10zp7 |
const val digits = "0123456789"
fun deBruijn(k: Int, n: Int): String {
val alphabet = digits.substring(0, k)
val a = ByteArray(k * n)
val seq = mutableListOf<Byte>()
fun db(t: Int, p: Int) {
if (t > n) {
if (n % p == 0) {
seq.addAll(a.sliceArray(1..p).asList())
}
} else {
a[t] = a[t - p]
db(t + 1, p)
var j = a[t - p] + 1
while (j < k) {
a[t] = j.toByte()
db(t + 1, t)
j++
}
}
}
db(1, 1)
val buf = StringBuilder()
for (i in seq) {
buf.append(alphabet[i.toInt()])
}
val b = buf.toString()
return b + b.subSequence(0, n - 1)
}
fun allDigits(s: String): Boolean {
for (c in s) {
if (c < '0' || '9' < c) {
return false
}
}
return true
}
fun validate(db: String) {
val le = db.length
val found = MutableList(10_000) { 0 }
val errs = mutableListOf<String>() | 966de Bruijn sequences
| 11kotlin
| r1qgo |
class BoundedIntOutOfBoundsException extends Exception
{
public BoundedIntOutOfBoundsException(int v, int l, int u) {
super("value " + v + " is out of bounds [" + l + "," + u + "]");
}
}
class BoundedInt {
private int value;
private int lower;
private int upper;
public BoundedInt(int l, int u) {
lower = Math.min(l, u);
upper = Math.max(l, u);
}
private boolean checkBounds(int v) {
return (v >= this.lower) && (v <= this.upper);
}
public void assign(BoundedInt i) throws BoundedIntOutOfBoundsException {{
assign(i.value()); | 962Define a primitive data type
| 9java
| 32hzg |
function tprint(tbl)
for i,v in pairs(tbl) do
print(v)
end
end
function deBruijn(k, n)
local a = {}
for i=1, k*n do
table.insert(a, 0)
end
local seq = {}
function db(t, p)
if t > n then
if n % p == 0 then
for i=1, p do
table.insert(seq, a[i + 1])
end
end
else
a[t + 1] = a[t - p + 1]
db(t + 1, p)
local j = a[t - p + 1] + 1
while j < k do
a[t + 1] = j % 256
db(t + 1, t)
j = j + 1
end
end
end
db(1, 1)
local buf = ""
for i,v in pairs(seq) do
buf = buf .. tostring(v)
end
return buf .. buf:sub(1, n - 1)
end
function allDigits(s)
return s:match('[0-9]+') == s
end
function validate(db)
local le = string.len(db)
local found = {}
local errs = {}
for i=1, 10000 do
table.insert(found, 0)
end | 966de Bruijn sequences
| 1lua
| 7asru |
function Num(n){
n = Math.floor(n);
if(isNaN(n))
throw new TypeError("Not a Number");
if(n < 1 || n > 10)
throw new TypeError("Out of range");
this._value = n;
}
Num.prototype.valueOf = function() { return this._value; }
Num.prototype.toString = function () { return this._value.toString();}
var w = new Num(3), x = new Num(4);
WScript.Echo(w + x); | 962Define a primitive data type
| 10javascript
| cga9j |
function V3(x,y,z) return {x=x,y=y,z=z} end
function dot(v,w) return v.x*w.x + v.y*w.y + v.z*w.z end
function norm(v) local m=math.sqrt(dot(v,v)) return V3(v.x/m, v.y/m, v.z/m) end
function clamp(n,lo,hi) return math.floor(math.min(math.max(lo,n),hi)) end
function hittest(s, x, y)
local z = s.r^2 - (x-s.x)^2 - (y-s.y)^2
if z >= 0 then
z = math.sqrt(z)
return true, s.z-z, s.z+z
end
return false, 0, 0
end
function deathstar(pos, neg, sun, k, amb)
shades = {[0]=" ",".",":","!","*","o","e","&","#","%","@"}
for y = pos.x-pos.r-0.5, pos.x+pos.r+0.5 do
for x = pos.x-pos.r-0.5, pos.x+pos.r+0.5, 0.5 do
local hitpos, pz1, pz2 = hittest(pos, x, y)
local result, hitneg, nz1, nz2 = 0
if hitpos then
hitneg, nz1, nz2 = hittest(neg, x, y)
if not hitneg or nz1 > pz1 then result = 1
elseif nz2 > pz2 then result = 0
elseif nz2 > pz1 then result = 2
else result = 1
end
end
local shade = 0
if result > 0 then
if result == 1 then
shade = clamp((1-dot(sun, norm(V3(x-pos.x, y-pos.y, pz1-pos.z)))^k+amb) * #shades, 1, #shades)
else
shade = clamp((1-dot(sun, norm(V3(neg.x-x, neg.y-y, neg.z-nz2)))^k+amb) * #shades, 1, #shades)
end
end
io.write(shades[shade])
end
io.write("\n")
end
end
deathstar({x=20, y=20, z=0, r=20}, {x=10, y=10, z=-15, r=10}, norm(V3(-2,1,3)), 2, 0.1) | 963Death Star
| 1lua
| 4bs5c |
use feature 'say';
use ntheory qw/forsetproduct/;
sub deconvolve_N {
our @g; local *g = shift;
our @f; local *f = shift;
my @df = shape(@f);
my @dg = shape(@g);
my @hsize;
push @hsize, $dg[$_] - $df[$_] + 1 for 0..$
my @toSolve = map { [row(\@g, \@f, \@hsize, $_)] } coords(shape(@g));
rref( \@toSolve );
my @h;
my $n = 0;
for (coords(@hsize)) {
my($k,$j,$i) = split ' ', $_;
$h[$i][$j][$k] = $toSolve[$n++][-1];
}
@h;
}
sub row {
our @g; local *g = shift;
our @f; local *f = shift;
our @hsize; local *hsize = shift;
my @gc = reverse split ' ', shift;
my @row;
my @fdim = shape(@f);
for (coords(@hsize)) {
my @hc = reverse split ' ', $_;
my @fc;
for my $i (0..$
my $window = $gc[$i] - $hc[$i];
push(@fc, $window), next if 0 <= $window && $window < $fdim[$i];
}
push @row, $
}
push @row, $g [$gc[0]] [$gc[1]] [$gc[2]];
return @row;
}
sub rref {
our @m; local *m = shift;
@m or return;
my ($lead, $rows, $cols) = (0, scalar(@m), scalar(@{$m[0]}));
foreach my $r (0 .. $rows - 1) {
$lead < $cols or return;
my $i = $r;
until ($m[$i][$lead])
{++$i == $rows or next;
$i = $r;
++$lead == $cols and return;}
@m[$i, $r] = @m[$r, $i];
my $lv = $m[$r][$lead];
$_ /= $lv foreach @{ $m[$r] };
my @mr = @{ $m[$r] };
foreach my $i (0 .. $rows - 1)
{$i == $r and next;
($lv, my $n) = ($m[$i][$lead], -1);
$_ -= $lv * $mr[++$n] foreach @{ $m[$i] };}
++$lead;}
}
sub coords {
my(@dimensions) = reverse @_;
my(@ranges,@coords);
push @ranges, [0..$_-1] for @dimensions;
forsetproduct { push @coords, "@_" } @ranges;
@coords;
}
sub shape {
my(@dim);
push @dim, scalar @_;
push @dim, shape(@{$_[0]}) if 'ARRAY' eq ref $_[0];
@dim;
}
sub pretty_print {
my($i, @a) = @_;
if ('ARRAY' eq ref $a[0]) {
say ' 'x$i, '[';
pretty_print($i+2, @$_) for @a;
say ' 'x$i, ']', $i ? ',' : '';
} else {
say ' 'x$i, '[', sprintf("@{['%5s'x@a]}",@a), ']', $i ? ',' : '';
}
}
my @f = (
[
[ -9, 5, -8 ],
[ 3, 5, 1 ],
],
[
[ -1, -7, 2 ],
[ -5, -6, 6 ],
],
[
[ 8, 5, 8 ],
[ -2, -6, -4 ],
]
);
my @g = (
[
[ 54, 42, 53, -42, 85, -72 ],
[ 45,-170, 94, -36, 48, 73 ],
[ -39, 65,-112, -16, -78, -72 ],
[ 6, -11, -6, 62, 49, 8 ],
],
[
[ -57, 49, -23, 52,-135, 66 ],
[ -23, 127, -58, -5,-118, 64 ],
[ 87, -16, 121, 23, -41, -12 ],
[ -19, 29, 35,-148, -11, 45 ],
],
[
[ -55,-147,-146, -31, 55, 60 ],
[ -88, -45, -28, 46, -26,-144 ],
[ -12,-107, -34, 150, 249, 66 ],
[ 11, -15, -34, 27, -78, -50 ],
],
[
[ 56, 67, 108, 4, 2, -48 ],
[ 58, 67, 89, 32, 32, -8 ],
[ -42, -31,-103, -30, -23, -8 ],
[ 6, 4, -26, -10, 26, 12 ],
]
);
my @h = deconvolve_N( \@g, \@f );
my @ff = deconvolve_N( \@g, \@h );
my $d = scalar shape(@g);
print "${d}D arrays:\n";
print "h =\n";
pretty_print(0,@h);
print "\nff =\n";
pretty_print(0,@ff); | 965Deconvolution/2D+
| 2perl
| kxihc |
null | 962Define a primitive data type
| 11kotlin
| ny4ij |
import numpy
import pprint
h = [
[[-6, -8, -5, 9], [-7, 9, -6, -8], [2, -7, 9, 8]],
[[7, 4, 4, -6], [9, 9, 4, -4], [-3, 7, -2, -3]]]
f = [
[[-9, 5, -8], [3, 5, 1]],
[[-1, -7, 2], [-5, -6, 6]],
[[8, 5, 8],[-2, -6, -4]]]
g = [
[
[54, 42, 53, -42, 85, -72],
[45, -170, 94, -36, 48, 73],
[-39, 65, -112, -16, -78, -72],
[6, -11, -6, 62, 49, 8]],
[
[-57, 49, -23, 52, -135, 66],
[-23, 127, -58, -5, -118, 64],
[87, -16, 121, 23, -41, -12],
[-19, 29, 35, -148, -11, 45]],
[
[-55, -147, -146, -31, 55, 60],
[-88, -45, -28, 46, -26, -144],
[-12, -107, -34, 150, 249, 66],
[11, -15, -34, 27, -78, -50]],
[
[56, 67, 108, 4, 2, -48],
[58, 67, 89, 32, 32, -8],
[-42, -31, -103, -30, -23, -8],
[6, 4, -26, -10, 26, 12]]]
def trim_zero_empty(x):
if len(x) > 0:
if type(x[0]) != numpy.ndarray:
return list(numpy.trim_zeros(x))
else:
new_x = []
for l in x:
tl = trim_zero_empty(l)
if len(tl) > 0:
new_x.append(tl)
return new_x
else:
return x
def deconv(a, b):
ffta = numpy.fft.fftn(a)
ashape = numpy.shape(a)
fftb = numpy.fft.fftn(b,ashape)
fftquotient = ffta / fftb
c = numpy.fft.ifftn(fftquotient)
trimmedc = numpy.around(numpy.real(c),decimals=6)
cleanc = trim_zero_empty(trimmedc)
return cleanc
print()
pprint.pprint(deconv(g,h))
print()
print()
pprint.pprint(deconv(g,f)) | 965Deconvolution/2D+
| 3python
| bqnkr |
use strict;
use warnings;
use feature 'say';
my $seq;
for my $x (0..99) {
my $a = sprintf '%02d', $x;
next if substr($a,1,1) < substr($a,0,1);
$seq .= (substr($a,0,1) == substr($a,1,1)) ? substr($a,0,1) : $a;
for ($a+1 .. 99) {
next if substr(sprintf('%02d', $_), 1,1) <= substr($a,0,1);
$seq .= sprintf "%s%02d", $a, $_;
}
}
$seq .= '000';
sub check {
my($seq) = @_;
my %chk;
for (0.. -1 + length $seq) { $chk{substr($seq, $_, 4)}++ }
say 'Missing: ' . join ' ', grep { ! $chk{ sprintf('%04d',$_) } } 0..9999;
say 'Extra: ' . join ' ', sort grep { $chk{$_} > 1 } keys %chk;
}
my $n = 130;
say "de Bruijn sequence length: " . length $seq;
say "\nFirst $n characters:\n" . substr($seq, 0, $n );
say "\nLast $n characters:\n" . substr($seq, -$n, $n);
say "\nIncorrect 4 digit PINs in this sequence:";
check $seq;
say "\nIncorrect 4 digit PINs in the reversed sequence:";
check(reverse $seq);
say "\nReplacing the 4444th digit, '@{[substr($seq,4443,1)]}', with '5'";
substr $seq, 4443, 1, 5;
say "Incorrect 4 digit PINs in the revised sequence:";
check $seq; | 966de Bruijn sequences
| 2perl
| dmvnw |
BI = { | 962Define a primitive data type
| 1lua
| dmgnq |
use strict;
sub sq {
my $s = 0;
$s += $_ ** 2 for @_;
$s;
}
sub hit {
my ($sph, $x, $y) = @_;
$x -= $sph->[0];
$y -= $sph->[1];
my $z = sq($sph->[3]) - sq($x, $y);
return if $z < 0;
$z = sqrt $z;
return $sph->[2] - $z, $sph->[2] + $z;
}
sub normalize {
my $v = shift;
my $n = sqrt sq(@$v);
$_ /= $n for @$v;
$v;
}
sub dot {
my ($x, $y) = @_;
my $s = $x->[0] * $y->[0] + $x->[1] * $y->[1] + $x->[2] * $y->[2];
$s > 0 ? $s : 0;
}
my $pos = [ 120, 120, 0, 120 ];
my $neg = [ -77, -33, -100, 190 ];
my $light = normalize([ -12, 13, -10 ]);
sub draw {
my ($k, $amb) = @_;
binmode STDOUT, ":raw";
print "P5\n", $pos->[0] * 2 + 3, " ", $pos->[1] * 2 + 3, "\n255\n";
for my $y (($pos->[1] - $pos->[3] - 1) .. ($pos->[1] + $pos->[3] + 1)) {
my @row = ();
for my $x (($pos->[0] - $pos->[3] - 1) .. ($pos->[0] + $pos->[3] + 1)) {
my ($hit, @hs) = 0;
my @h = hit($pos, $x, $y);
if (!@h) { $hit = 0 }
elsif (!(@hs = hit($neg, $x, $y))) { $hit = 1 }
elsif ($hs[0] > $h[0]) { $hit = 1 }
elsif ($hs[1] > $h[0]) { $hit = $hs[1] > $h[1] ? 0 : 2 }
else { $hit = 1 }
my ($val, $v);
if ($hit == 0) { $val = 0 }
elsif ($hit == 1) {
$v = [ $x - $pos->[0],
$y - $pos->[1],
$h[0] - $pos->[2] ];
} else {
$v = [ $neg->[0] - $x,
$neg->[1] - $y,
$neg->[2] - $hs[1] ];
}
if ($v) {
normalize($v);
$val = int((dot($v, $light) ** $k + $amb) * 255);
$val = ($val > 255) ? 255 : ($val < 0) ? 0 : $val;
}
push @row, $val;
}
print pack("C*", @row);
}
}
draw(2, 0.2); | 963Death Star
| 2perl
| o3v8x |
def de_bruijn(k, n):
try:
_ = int(k)
alphabet = list(map(str, range(k)))
except (ValueError, TypeError):
alphabet = k
k = len(k)
a = [0] * k * n
sequence = []
def db(t, p):
if t > n:
if n% p == 0:
sequence.extend(a[1:p + 1])
else:
a[t] = a[t - p]
db(t + 1, p)
for j in range(a[t - p] + 1, k):
a[t] = j
db(t + 1, t)
db(1, 1)
return .join(alphabet[i] for i in sequence)
def validate(db):
dbwithwrap = db+db[0:3]
digits = '0123456789'
errorstrings = []
for d1 in digits:
for d2 in digits:
for d3 in digits:
for d4 in digits:
teststring = d1+d2+d3+d4
if teststring not in dbwithwrap:
errorstrings.append(teststring)
if len(errorstrings) > 0:
print(+str(len(errorstrings))+)
for e in errorstrings:
print(+e+)
else:
print()
db = de_bruijn(10, 4)
print()
print(, str(len(db)))
print()
print(+db[0:130])
print()
print(+db[-130:])
print()
print()
validate(db)
dbreversed = db[::-1]
print()
print()
validate(dbreversed)
dboverlaid = db[0:4443]+'.'+db[4444:]
print()
print()
validate(dboverlaid) | 966de Bruijn sequences
| 3python
| f9ude |
import sys, math, collections
Sphere = collections.namedtuple(, )
V3 = collections.namedtuple(, )
def normalize((x, y, z)):
len = math.sqrt(x**2 + y**2 + z**2)
return V3(x / len, y / len, z / len)
def dot(v1, v2):
d = v1.x*v2.x + v1.y*v2.y + v1.z*v2.z
return -d if d < 0 else 0.0
def hit_sphere(sph, x0, y0):
x = x0 - sph.cx
y = y0 - sph.cy
zsq = sph.r ** 2 - (x ** 2 + y ** 2)
if zsq < 0:
return (False, 0, 0)
szsq = math.sqrt(zsq)
return (True, sph.cz - szsq, sph.cz + szsq)
def draw_sphere(k, ambient, light):
shades =
pos = Sphere(20.0, 20.0, 0.0, 20.0)
neg = Sphere(1.0, 1.0, -6.0, 20.0)
for i in xrange(int(math.floor(pos.cy - pos.r)),
int(math.ceil(pos.cy + pos.r) + 1)):
y = i + 0.5
for j in xrange(int(math.floor(pos.cx - 2 * pos.r)),
int(math.ceil(pos.cx + 2 * pos.r) + 1)):
x = (j - pos.cx) / 2.0 + 0.5 + pos.cx
(h, zb1, zb2) = hit_sphere(pos, x, y)
if not h:
hit_result = 0
else:
(h, zs1, zs2) = hit_sphere(neg, x, y)
if not h:
hit_result = 1
elif zs1 > zb1:
hit_result = 1
elif zs2 > zb2:
hit_result = 0
elif zs2 > zb1:
hit_result = 2
else:
hit_result = 1
if hit_result == 0:
sys.stdout.write(' ')
continue
elif hit_result == 1:
vec = V3(x - pos.cx, y - pos.cy, zb1 - pos.cz)
elif hit_result == 2:
vec = V3(neg.cx-x, neg.cy-y, neg.cz-zs2)
vec = normalize(vec)
b = dot(light, vec) ** k + ambient
intensity = int((1 - b) * len(shades))
intensity = min(len(shades), max(0, intensity))
sys.stdout.write(shades[intensity])
print
light = normalize(V3(-50, 30, 50))
draw_sphere(2, 0.5, light) | 963Death Star
| 3python
| i6uof |
package main
import (
"fmt"
"math"
"math/rand"
"os"
"strconv"
"time"
)
const sSuits = "CDHS"
const sNums = "A23456789TJQK"
const rMax32 = math.MaxInt32
var seed = 1
func rnd() int {
seed = (seed*214013 + 2531011) & rMax32
return seed >> 16
}
func deal(s int) []int {
seed = s
t := make([]int, 52)
for i := 0; i < 52; i++ {
t[i] = 51 - i
}
for i := 0; i < 51; i++ {
j := 51 - rnd()%(52-i)
t[i], t[j] = t[j], t[i]
}
return t
}
func show(cs []int) {
for i, c := range cs {
fmt.Printf("%c%c", sNums[c/4], sSuits[c%4])
if (i+1)%8 == 0 || i+1 == len(cs) {
fmt.Println()
}
}
}
func main() {
var game int
switch len(os.Args) {
case 1:
rand.Seed(time.Now().UnixNano())
game = 1 + rand.Intn(32000)
case 2:
var err error
game, err = strconv.Atoi(os.Args[1])
if err == nil && game >= 1 && game <= 32000 {
break
}
fallthrough
default:
fmt.Println("usage: deal [game]")
fmt.Println(" where game is a number in the range 1 to 32000")
return
}
fmt.Printf("\nGame #%d\n", game)
show(deal(game))
} | 964Deal cards for FreeCell
| 0go
| bqdkh |
class FreeCell{
int seed
List<String> createDeck(){
List<String> suits = ['','','','']
List<String> values = ['A','2','3','4','5','6','7','8','9','10','J','Q','K']
return [suits,values].combinations{suit,value -> "$suit$value"}
}
int random() {
seed = (214013 * seed + 2531011) & Integer.MAX_VALUE
return seed >> 16
}
List<String> shuffledDeck(List<String> cards) {
List<String> deck = cards.clone()
(deck.size() - 1..1).each{index ->
int r = random() % (index + 1)
deck.swap(r, index)
}
return deck
}
List<String> dealGame(int seed = 1){
this.seed= seed
List<String> cards = shuffledDeck(createDeck())
(1..cards.size()).each{ number->
print "${cards.pop()}\t"
if(number % 8 == 0) println('')
}
println('\n')
}
}
def freecell = new FreeCell()
freecell.dealGame()
freecell.dealGame(617) | 964Deal cards for FreeCell
| 7groovy
| r10gh |
import Data.Int
import Data.Bits
import Data.List
import Data.Array.ST
import Control.Monad
import Control.Monad.ST
import System.Environment
srnd :: Int32 -> [Int]
srnd = map (fromIntegral . flip shiftR 16) .
tail . iterate (\x -> (x * 214013 + 2531011) .&. maxBound)
deal :: Int32 -> [String]
deal s = runST (do
ar <- newListArray (0,51) $ sequence ["A23456789TJQK", "CDHS"]
:: ST s (STArray s Int String)
forM (zip [52,51..1] rnd) $ \(n, r) -> do
let j = r `mod` n
vj <- readArray ar j
vn <- readArray ar (n - 1)
writeArray ar j vn
return vj)
where rnd = srnd s
showCards :: [String] -> IO ()
showCards = mapM_ (putStrLn . unwords) .
takeWhile (not . null) .
unfoldr (Just . splitAt 8)
main :: IO ()
main = do
args <- getArgs
let s = read (head args) :: Int32
putStrLn $ "Deal " ++ show s ++ ":"
let cards = deal s
showCards cards | 964Deal cards for FreeCell
| 8haskell
| dm5n4 |
def deBruijn(k, n)
alphabet =
@a = Array.new(k * n, 0)
@seq = []
def db(k, n, t, p)
if t > n then
if n % p == 0 then
temp = @a[1 .. p]
@seq.concat temp
end
else
@a[t] = @a[t - p]
db(k, n, t + 1, p)
j = @a[t - p] + 1
while j < k do
@a[t] = j
db(k, n, t + 1, t)
j = j + 1
end
end
end
db(k, n, 1, 1)
buf =
for i in @seq
buf <<= alphabet[i]
end
return buf + buf[0 .. n-2]
end
def validate(db)
le = db.length
found = Array.new(10000, 0)
errs = []
for i in 0 .. le-4
s = db[i .. i+3]
if s.scan(/\D/).empty? then
found[s.to_i] += 1
end
end
for i in 0 .. found.length - 1
if found[i] == 0 then
errs <<= ( % [i])
elsif found[i] > 1 then
errs <<= ( % [i, found[i]])
end
end
if errs.length == 0 then
print
else
pl = (errs.length == 1)? :
print , errs.length, , pl,
for err in errs
print err,
end
end
end
db = deBruijn(10, 4)
print , db.length,
print , db[0 .. 129],
print , db[-130 .. db.length],
print
validate(db)
print
db[4443] = '.'
print
validate(db) | 966de Bruijn sequences
| 14ruby
| zl4tw |
package One_To_Ten;
use Carp qw(croak);
use Tie::Scalar qw();
use base qw(Tie::StdScalar);
sub STORE {
my $self = shift;
my $val = int shift;
croak 'out of bounds' if $val < 1 or $val > 10;
$$self = $val;
};
package main;
tie my $t, 'One_To_Ten';
$t = 3;
$t = 5.2;
$t = -2;
$t = 11;
$t = 'xyzzy'; | 962Define a primitive data type
| 2perl
| 7airh |
package main
import (
"fmt"
"rcu"
"strconv"
"strings"
)
func findFirst(list []int) (int, int) {
for i, n := range list {
if n > 1e7 {
return n, i
}
}
return -1, -1
}
func reverse(s string) string {
chars := []rune(s)
for i, j := 0, len(chars)-1; i < j; i, j = i+1, j-1 {
chars[i], chars[j] = chars[j], chars[i]
}
return string(chars)
}
func main() {
ranges := [][2]int{
{0, 0}, {101, 909}, {11011, 99099}, {1110111, 9990999}, {111101111, 119101111},
}
var cyclops []int
for _, r := range ranges {
numDigits := len(fmt.Sprint(r[0]))
center := numDigits / 2
for i := r[0]; i <= r[1]; i++ {
digits := rcu.Digits(i, 10)
if digits[center] == 0 {
count := 0
for _, d := range digits {
if d == 0 {
count++
}
}
if count == 1 {
cyclops = append(cyclops, i)
}
}
}
}
fmt.Println("The first 50 cyclops numbers are:")
for i, n := range cyclops[0:50] {
fmt.Printf("%6s ", rcu.Commatize(n))
if (i+1)%10 == 0 {
fmt.Println()
}
}
n, i := findFirst(cyclops)
ns, is := rcu.Commatize(n), rcu.Commatize(i)
fmt.Printf("\nFirst such number > 10 million is%s at zero-based index%s\n", ns, is)
var primes []int
for _, n := range cyclops {
if rcu.IsPrime(n) {
primes = append(primes, n)
}
}
fmt.Println("\n\nThe first 50 prime cyclops numbers are:")
for i, n := range primes[0:50] {
fmt.Printf("%6s ", rcu.Commatize(n))
if (i+1)%10 == 0 {
fmt.Println()
}
}
n, i = findFirst(primes)
ns, is = rcu.Commatize(n), rcu.Commatize(i)
fmt.Printf("\nFirst such number > 10 million is%s at zero-based index%s\n", ns, is)
var bpcyclops []int
var ppcyclops []int
for _, p := range primes {
ps := fmt.Sprint(p)
split := strings.Split(ps, "0")
noMiddle, _ := strconv.Atoi(split[0] + split[1])
if rcu.IsPrime(noMiddle) {
bpcyclops = append(bpcyclops, p)
}
if ps == reverse(ps) {
ppcyclops = append(ppcyclops, p)
}
}
fmt.Println("\n\nThe first 50 blind prime cyclops numbers are:")
for i, n := range bpcyclops[0:50] {
fmt.Printf("%6s ", rcu.Commatize(n))
if (i+1)%10 == 0 {
fmt.Println()
}
}
n, i = findFirst(bpcyclops)
ns, is = rcu.Commatize(n), rcu.Commatize(i)
fmt.Printf("\nFirst such number > 10 million is%s at zero-based index%s\n", ns, is)
fmt.Println("\n\nThe first 50 palindromic prime cyclops numbers are:\n")
for i, n := range ppcyclops[0:50] {
fmt.Printf("%9s ", rcu.Commatize(n))
if (i+1)%8 == 0 {
fmt.Println()
}
}
n, i = findFirst(ppcyclops)
ns, is = rcu.Commatize(n), rcu.Commatize(i)
fmt.Printf("\n\nFirst such number > 10 million is%s at zero-based index%s\n", ns, is)
} | 967Cyclops numbers
| 0go
| vjp2m |
import java.util.Arrays;
public class Shuffler {
private int seed;
private String[] deck = {
"AC", "AD", "AH", "AS",
"2C", "2D", "2H", "2S",
"3C", "3D", "3H", "3S",
"4C", "4D", "4H", "4S",
"5C", "5D", "5H", "5S",
"6C", "6D", "6H", "6S",
"7C", "7D", "7H", "7S",
"8C", "8D", "8H", "8S",
"9C", "9D", "9H", "9S",
"TC", "TD", "TH", "TS",
"JC", "JD", "JH", "JS",
"QC", "QD", "QH", "QS",
"KC", "KD", "KH", "KS",
};
private int random() {
seed = (214013 * seed + 2531011) & Integer.MAX_VALUE;
return seed >> 16;
} | 964Deal cards for FreeCell
| 9java
| sf9q0 |
typedef unsigned char byte;
byte *grid = 0;
int w, h, len;
unsigned long long cnt;
static int next[4], dir[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};
void walk(int y, int x)
{
int i, t;
if (!y || y == h || !x || x == w) {
cnt += 2;
return;
}
t = y * (w + 1) + x;
grid[t]++, grid[len - t]++;
for (i = 0; i < 4; i++)
if (!grid[t + next[i]])
walk(y + dir[i][0], x + dir[i][1]);
grid[t]--, grid[len - t]--;
}
unsigned long long solve(int hh, int ww, int recur)
{
int t, cx, cy, x;
h = hh, w = ww;
if (h & 1) t = w, w = h, h = t;
if (h & 1) return 0;
if (w == 1) return 1;
if (w == 2) return h;
if (h == 2) return w;
cy = h / 2, cx = w / 2;
len = (h + 1) * (w + 1);
grid = realloc(grid, len);
memset(grid, 0, len--);
next[0] = -1;
next[1] = -w - 1;
next[2] = 1;
next[3] = w + 1;
if (recur) cnt = 0;
for (x = cx + 1; x < w; x++) {
t = cy * (w + 1) + x;
grid[t] = 1;
grid[len - t] = 1;
walk(cy - 1, x);
}
cnt++;
if (h == w)
cnt *= 2;
else if (!(w & 1) && recur)
solve(w, h, 0);
return cnt;
}
int main()
{
int y, x;
for (y = 1; y <= 10; y++)
for (x = 1; x <= y; x++)
if (!(x & 1) || !(y & 1))
printf(, y, x, solve(y, x, 1));
return 0;
} | 968Cut a rectangle
| 5c
| o3m80 |
import Control.Monad (replicateM)
import Data.Numbers.Primes (isPrime)
cyclops :: [Integer]
cyclops = [0 ..] >>= flankingDigits
where
flankingDigits 0 = [0]
flankingDigits n =
fmap
(\s -> read s :: Integer)
( (fmap ((<>) . (<> "0")) >>= (<*>))
(replicateM n ['1' .. '9'])
)
blindPrime :: Integer -> Bool
blindPrime n =
let s = show n
m = quot (length s) 2
in isPrime $
(\s -> read s :: Integer)
(take m s <> drop (succ m) s)
palindromic :: Integer -> Bool
palindromic = ((==) =<< reverse) . show
main :: IO ()
main =
(putStrLn . unlines)
[ "First 50 Cyclops numbers A134808:",
unwords (show <$> take 50 cyclops),
"",
"First 50 Cyclops primes A134809:",
unwords $ take 50 [show n | n <- cyclops, isPrime n],
"",
"First 50 blind prime Cyclops numbers A329737:",
unwords $
take
50
[show n | n <- cyclops, isPrime n, blindPrime n],
"",
"First 50 prime palindromic cyclops numbers A136098:",
unwords $
take
50
[show n | n <- cyclops, isPrime n, palindromic n]
] | 967Cyclops numbers
| 8haskell
| eofai |
"use strict";
Class('MSRand', {
has: {
seed: { is: rw, },
},
methods: {
rand: function() {
this.setSeed((this.getSeed() * 214013 + 2531011) & 0x7FFFFFFF);
return ((this.getSeed() >> 16) & 0x7fff);
},
max_rand: function(mymax) {
return this.rand() % mymax;
},
shuffle: function(deck) {
if (deck.length) {
var i = deck.length;
while (--i) {
var j = this.max_rand(i+1);
var tmp = deck[i];
deck[i] = deck[j];
deck[j] = tmp;
}
}
return deck;
},
},
});
function deal_ms_fc_board(seed) {
var randomizer = new MSRand({ seed: seed });
var num_cols = 8;
var _perl_range = function(start, end) {
var ret = [];
for (var i = start; i <= end; i++) {
ret.push(i);
}
return ret;
};
var columns = _perl_range(0, num_cols-1).map(function () { return []; });
var deck = _perl_range(0, 4*13-1);
randomizer.shuffle(deck);
deck = deck.reverse()
for (var i = 0; i < 52; i++) {
columns[i % num_cols].push(deck[i]);
}
var render_card = function (card) {
var suit = (card % 4);
var rank = Math.floor(card / 4);
return "A23456789TJQK".charAt(rank) + "CDHS".charAt(suit);
}
var render_column = function(col) {
return ": " + col.map(render_card).join(" ") + "\n";
}
return columns.map(render_column).join("");
} | 964Deal cards for FreeCell
| 10javascript
| nyuiy |
null | 964Deal cards for FreeCell
| 11kotlin
| a8z13 |
>>> class num(int):
def __init__(self, b):
if 1 <= b <= 10:
return int.__init__(self+0)
else:
raise ValueError,% b
>>> x = num(3)
>>> x = num(11)
Traceback (most recent call last):
File , line 1, in <module>
x = num(11)
File , line 6, in __init__
raise ValueError,% b
ValueError: Value 11 should be >=0 and <= 10
>>> x
3
>>> type(x)
<class '__main__.num'>
>>> | 962Define a primitive data type
| 3python
| jen7p |
deck = {}
rank = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K"}
suit = {"C", "D", "H", "S"}
two31, state = bit32.lshift(1, 31), 0
function rng()
state = (214013 * state + 2531011) % two31
return bit32.rshift(state, 16)
end
function initdeck()
for i, r in ipairs(rank) do
for j, s in ipairs(suit) do
table.insert(deck, r .. s)
end
end
end
function deal(num)
initdeck()
state = num
print("Game #" .. num)
repeat
choice = rng(num) % #deck + 1
deck[choice], deck[#deck] = deck[#deck], deck[choice]
io.write(" " .. deck[#deck])
if (#deck % 8 == 5) then
print()
end
deck[#deck] = nil
until #deck == 0
print()
end
deal(1)
deal(617) | 964Deal cards for FreeCell
| 1lua
| eo3ac |
package main
import (
"fmt"
"math/big"
)
func main() {
zero := big.NewInt(0)
one := big.NewInt(1)
for k := int64(2); k <= 10; k += 2 {
bk := big.NewInt(k)
fmt.Println("The first 50 Curzon numbers using a base of", k, ":")
count := 0
n := int64(1)
pow := big.NewInt(k)
z := new(big.Int)
var curzon50 []int64
for {
z.Add(pow, one)
d := k*n + 1
bd := big.NewInt(d)
if z.Rem(z, bd).Cmp(zero) == 0 {
if count < 50 {
curzon50 = append(curzon50, n)
}
count++
if count == 50 {
for i := 0; i < len(curzon50); i++ {
fmt.Printf("%4d ", curzon50[i])
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Print("\nOne thousandth: ")
}
if count == 1000 {
fmt.Println(n)
break
}
}
n++
pow.Mul(pow, bk)
}
fmt.Println()
}
} | 969Curzon numbers
| 0go
| yu464 |
use strict;
use warnings;
use feature 'say';
use ntheory 'is_prime';
use List::AllUtils 'firstidx';
sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }
my @cyclops = 0;
for my $exp (0..3) {
my @oom = grep { ! /0/ } 10**$exp .. 10**($exp+1)-1;
for my $l (@oom) {
for my $r (@oom) {
push @cyclops, $l . '0' . $r;
}
}
}
my @prime_cyclops = grep { is_prime $_ } @cyclops;
my @prime_blind = grep { is_prime $_ =~ s/0//r } @prime_cyclops;
my @prime_palindr = grep { $_ eq reverse $_ } @prime_cyclops;
my $upto = 50;
my $over = 10_000_000;
for (
['', @cyclops],
['prime', @prime_cyclops],
['blind prime', @prime_blind],
['palindromic prime', @prime_palindr]) {
my($text,@values) = @$_;
my $i = firstidx { $_ > $over } @values;
say "First $upto $text cyclops numbers:\n" .
(sprintf "@{['%8d' x $upto]}", @values[0..$upto-1]) =~ s/(.{80})/$1\n/gr;
printf "First $text number >%s:%s at (zero based) index:%s\n\n", map { comma($_) } $over, $values[$i], $i;
} | 967Cyclops numbers
| 2perl
| i6co3 |
int main()
{
struct tm ts;
time_t t;
const char *d = ;
strptime(d, , &ts);
t = mktime(&ts);
t += 12*60*60;
printf(, ctime(&t));
return EXIT_SUCCESS;
} | 970Date manipulation
| 5c
| tclf4 |
Some object-oriented languages won't let you subclass the data types
like integers. Other languages implement those data types as classes, so you
can subclass them, no questions asked. Ruby implements numbers as classes
(Integer, with its concrete subclasses Fixnum and Bignum), and you can subclass
those classes. If you try, though, you'll quickly discover that your subclasses
are useless: they don't have constructors.
Ruby jealously guards the creation of new Integer objects. This way it ensures
that, for instance, there can be only one Fixnum instance for a given number
The easiest way to delegate all methods is to create a class that's nearly empty
and define a method_missing method. | 962Define a primitive data type
| 14ruby
| kxfhg |
use std::convert::TryFrom;
mod test_mod {
use std::convert::TryFrom;
use std::fmt; | 962Define a primitive data type
| 15rust
| bqtkx |
class TinyInt(val int: Byte) {
import TinyInt._
require(int >= lower && int <= upper, "TinyInt out of bounds.")
override def toString = int.toString
}
object TinyInt {
val (lower, upper) = (1, 10)
def apply(i: Byte) = new TinyInt(i)
}
val test = (TinyInt.lower to TinyInt.upper).map(n => TinyInt(n.toByte)) | 962Define a primitive data type
| 16scala
| a861n |
int wday(int year, int month, int day)
{
int adjustment, mm, yy;
adjustment = (14 - month) / 12;
mm = month + 12 * adjustment - 2;
yy = year - adjustment;
return (day + (13 * mm - 1) / 5 +
yy + yy / 4 - yy / 100 + yy / 400) % 7;
}
int main()
{
int y;
for (y = 2008; y <= 2121; y++) {
if (wday(y, 12, 25) == 0) printf(, y);
}
return 0;
} | 971Day of the week
| 5c
| 277lo |
use strict;
use warnings;
use Math::AnyNum 'ipow';
sub curzon {
my($base,$cnt) = @_;
my($n,@C) = 0;
while (++$n) {
push @C, $n if 0 == (ipow($base,$n) + 1) % ($base * $n + 1);
return @C if $cnt == @C;
}
}
my $upto = 50;
for my $k (<2 4 6 8 10>) {
my @C = curzon($k,1000);
print "First $upto Curzon numbers using a base of $k:\n" .
(sprintf "@{['%5d' x $upto]}", @C[0..$upto-1]) =~ s/(.{125})/$1\n/gr;
print "Thousandth: $C[-1]\n\n";
} | 969Curzon numbers
| 2perl
| xnfw8 |
null | 969Curzon numbers
| 15rust
| 8z607 |
package main
import "fmt"
var grid []byte
var w, h, last int
var cnt int
var next [4]int
var dir = [4][2]int{{0, -1}, {-1, 0}, {0, 1}, {1, 0}}
func walk(y, x int) {
if y == 0 || y == h || x == 0 || x == w {
cnt += 2
return
}
t := y*(w+1) + x
grid[t]++
grid[last-t]++
for i, d := range dir {
if grid[t+next[i]] == 0 {
walk(y+d[0], x+d[1])
}
}
grid[t]--
grid[last-t]--
}
func solve(hh, ww, recur int) int {
h = hh
w = ww
if h&1 != 0 {
h, w = w, h
}
switch {
case h&1 == 1:
return 0
case w == 1:
return 1
case w == 2:
return h
case h == 2:
return w
}
cy := h / 2
cx := w / 2
grid = make([]byte, (h+1)*(w+1))
last = len(grid) - 1
next[0] = -1
next[1] = -w - 1
next[2] = 1
next[3] = w + 1
if recur != 0 {
cnt = 0
}
for x := cx + 1; x < w; x++ {
t := cy*(w+1) + x
grid[t] = 1
grid[last-t] = 1
walk(cy-1, x)
}
cnt++
if h == w {
cnt *= 2
} else if w&1 == 0 && recur != 0 {
solve(w, h, 0)
}
return cnt
}
func main() {
for y := 1; y <= 10; y++ {
for x := 1; x <= y; x++ {
if x&1 == 0 || y&1 == 0 {
fmt.Printf("%d x%d:%d\n", y, x, solve(y, x, 1))
}
}
}
} | 968Cut a rectangle
| 0go
| 4ba52 |
(import java.util.Date
java.text.SimpleDateFormat)
(defn time+12 [s]
(let [sdf (SimpleDateFormat. "MMMM d yyyy h:mma zzz")]
(-> (.parse sdf s)
(.getTime ,)
(+ , 43200000)
long
(Date. ,)
(->> , (.format sdf ,))))) | 970Date manipulation
| 6clojure
| m54yq |
struct SmallInt {
var value: Int
init(value: Int) {
guard value >= 1 && value <= 10 else {
fatalError("SmallInts must be in the range [1, 10]")
}
self.value = value
}
static func +(_ lhs: SmallInt, _ rhs: SmallInt) -> SmallInt { SmallInt(value: lhs.value + rhs.value) }
static func -(_ lhs: SmallInt, _ rhs: SmallInt) -> SmallInt { SmallInt(value: lhs.value - rhs.value) }
static func *(_ lhs: SmallInt, _ rhs: SmallInt) -> SmallInt { SmallInt(value: lhs.value * rhs.value) }
static func /(_ lhs: SmallInt, _ rhs: SmallInt) -> SmallInt { SmallInt(value: lhs.value / rhs.value) }
}
extension SmallInt: ExpressibleByIntegerLiteral {
public init(integerLiteral value: Int) { self.init(value: value) }
}
extension SmallInt: CustomStringConvertible {
public var description: String { "\(value)" }
}
let a: SmallInt = 1
let b: SmallInt = 9
let c: SmallInt = 10
let d: SmallInt = 2
print(a + b)
print(c - b)
print(a * c)
print(c / d)
print(a + c) | 962Define a primitive data type
| 17swift
| hwdj0 |
class CutRectangle {
private static int[][] dirs = [[0, -1], [-1, 0], [0, 1], [1, 0]]
static void main(String[] args) {
cutRectangle(2, 2)
cutRectangle(4, 3)
}
static void cutRectangle(int w, int h) {
if (w % 2 == 1 && h % 2 == 1) {
return
}
int[][] grid = new int[h][w]
Stack<Integer> stack = new Stack<>()
int half = (int) ((w * h) / 2)
long bits = (long) Math.pow(2, half) - 1
for (; bits > 0; bits -= 2) {
for (int i = 0; i < half; i++) {
int r = (int) (i / w)
int c = i % w
grid[r][c] = (bits & (1 << i)) != 0 ? 1: 0
grid[h - r - 1][w - c - 1] = 1 - grid[r][c]
}
stack.push(0)
grid[0][0] = 2
int count = 1
while (!stack.empty()) {
int pos = stack.pop()
int r = (int) (pos / w)
int c = pos % w
for (int[] dir: dirs) {
int nextR = r + dir[0]
int nextC = c + dir[1]
if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {
if (grid[nextR][nextC] == 1) {
stack.push(nextR * w + nextC)
grid[nextR][nextC] = 2
count++
}
}
}
}
if (count == half) {
printResult(grid)
}
}
}
static void printResult(int[][] arr) {
for (int[] a: arr) {
println(Arrays.toString(a))
}
println()
}
} | 968Cut a rectangle
| 7groovy
| lrhc1 |
require 'prime'
NONZEROS = %w(1 2 3 4 5 6 7 8 9)
cyclopes = Enumerator.new do |y|
(0..).each do |n|
NONZEROS.repeated_permutation(n) do |lside|
NONZEROS.repeated_permutation(n) do |rside|
y << (lside.join + + rside.join).to_i
end
end
end
end
prime_cyclopes = Enumerator.new {|y| cyclopes.each {|c| y << c if c.prime?} }
blind_prime_cyclopes = Enumerator.new {|y| prime_cyclopes.each {|c| y << c if c.to_s.delete().to_i.prime?} }
palindromic_prime_cyclopes = Enumerator.new {|y| prime_cyclopes.each {|c| y << c if c.to_s == c.to_s.reverse} }
n, m = 50, 10_000_000
[, , , ].zip(
[cyclopes, prime_cyclopes, blind_prime_cyclopes, palindromic_prime_cyclopes]).each do |name, enum|
cycl, idx = enum.each_with_index.detect{|n, i| n > m}
puts ,
end | 967Cyclops numbers
| 14ruby
| f9vdr |
use strict;
use warnings;
use utf8;
sub deal {
my $s = shift;
my $rnd = sub {
return (($s = ($s * 214013 + 2531011) & 0x7fffffff) >> 16 );
};
my @d;
for my $b (split "", "A23456789TJQK") {
push @d, map("$_$b", qw/ /);
}
for my $idx (reverse 0 .. $
my $r = $rnd->() % ($idx + 1);
@d[$r, $idx] = @d[$idx, $r];
}
return [reverse @d];
}
my $hand_idx = shift(@ARGV) // 11_982;
my $cards = deal($hand_idx);
my $num_cards_in_height = 8;
my $string = '';
while (@$cards)
{
$string .= join(' ', splice(@$cards, 0, 8)) . "\n";
}
binmode STDOUT, ':encoding(utf-8)';
print "Hand $hand_idx\n";
print $string; | 964Deal cards for FreeCell
| 2perl
| 94bmn |
(import '(java.util GregorianCalendar))
(defn yuletide [start end]
(filter #(= (. (new GregorianCalendar %
(. GregorianCalendar DECEMBER) 25) get (. GregorianCalendar DAY_OF_WEEK))
(. GregorianCalendar SUNDAY)) (range start (inc end))))
(yuletide 2008 2121) | 971Day of the week
| 6clojure
| gpp4f |
import qualified Data.Vector.Unboxed.Mutable as V
import Data.STRef
import Control.Monad (forM_, when)
import Control.Monad.ST
dir :: [(Int, Int)]
dir = [(1, 0), (-1, 0), (0, -1), (0, 1)]
data Env = Env { w, h, len, count, ret :: !Int, next :: ![Int] }
cutIt :: STRef s Env -> ST s ()
cutIt env = do
e <- readSTRef env
when (odd $ h e) $ modifySTRef env $ \en -> en { h = w e,
w = h e }
e <- readSTRef env
if odd (h e)
then modifySTRef env $ \en -> en { ret = 0 }
else
if w e == 1
then modifySTRef env $ \en -> en { ret = 1 }
else do
let blen = (h e + 1) * (w e + 1) - 1
t = (h e `div` 2) * (w e + 1) + (w e `div` 2)
modifySTRef env $ \en -> en { len = blen,
count = 0,
next = [ w e + 1, (negate $ w e) - 1, -1, 1] }
grid <- V.replicate (blen + 1) False
case odd (w e) of
True -> do
V.write grid t True
V.write grid (t + 1) True
walk grid (h e `div` 2) (w e `div` 2 - 1)
e1 <- readSTRef env
let res1 = count e1
modifySTRef env $ \en -> en { count = 0 }
walk grid (h e `div` 2 - 1) (w e `div` 2)
modifySTRef env $ \en -> en { ret = res1 +
(count en * 2) }
False -> do
V.write grid t True
walk grid (h e `div` 2) (w e `div` 2 - 1)
e2 <- readSTRef env
let count2 = count e2
if h e == w e
then modifySTRef env $ \en -> en { ret =
count2 * 2 }
else do
walk grid (h e `div` 2 - 1)
(w e `div` 2)
modifySTRef env $ \en -> en { ret =
count en }
where
walk grid y x = do
e <- readSTRef env
if y <= 0 || y >= h e || x <= 0 || x >= w e
then modifySTRef env $ \en -> en { count = count en + 1 }
else do
let t = y * (w e + 1) + x
V.write grid t True
V.write grid (len e - t) True
forM_ (zip (next e) [0..3]) $ \(n, d) -> do
g <- V.read grid (t + n)
when (not g) $
walk grid (y + fst (dir !! d)) (x + snd (dir !! d))
V.write grid t False
V.write grid (len e - t) False
cut :: (Int, Int) -> Int
cut (x, y) = runST $ do
env <- newSTRef $ Env { w = y, h = x, len = 0, count = 0, ret = 0, next = [] }
cutIt env
result <- readSTRef env
return $ ret result
main :: IO ()
main = do
mapM_ (\(x, y) -> when (even (x * y)) (putStrLn $
show x ++ " x " ++ show y ++ ": " ++ show (cut (x, y))))
[ (x, y) | x <- [1..10], y <- [1..x] ] | 968Cut a rectangle
| 8haskell
| qdzx9 |
package main
import (
"fmt"
"log"
"math"
"sort"
"strings"
)
const (
algo = 2
maxAllFactors = 100000
)
func iabs(i int) int {
if i < 0 {
return -i
}
return i
}
type term struct{ coef, exp int }
func (t term) mul(t2 term) term {
return term{t.coef * t2.coef, t.exp + t2.exp}
}
func (t term) add(t2 term) term {
if t.exp != t2.exp {
log.Fatal("exponents unequal in term.add method")
}
return term{t.coef + t2.coef, t.exp}
}
func (t term) negate() term { return term{-t.coef, t.exp} }
func (t term) String() string {
switch {
case t.coef == 0:
return "0"
case t.exp == 0:
return fmt.Sprintf("%d", t.coef)
case t.coef == 1:
if t.exp == 1 {
return "x"
} else {
return fmt.Sprintf("x^%d", t.exp)
}
case t.exp == 1:
return fmt.Sprintf("%dx", t.coef)
}
return fmt.Sprintf("%dx^%d", t.coef, t.exp)
}
type poly struct{ terms []term } | 972Cyclotomic polynomial
| 0go
| 6v23p |
class FreeCell_Deal {
protected $deck = array(
'AC', 'AD', 'AH', 'AS', '2C', '2D', '2H', '2S', '3C', '3D', '3H', '3S',
'4C', '4D', '4H', '4S', '5C', '5D', '5H', '5S', '6C', '6D', '6H', '6S',
'7C', '7D', '7H', '7S', '8C', '8D', '8H', '8S', '9C', '9D', '9H', '9S',
'TC', 'TD', 'TH', 'TS', 'JC', 'JD', 'JH', 'JS', 'QC', 'QD', 'QH', 'QS',
'KC', 'KD', 'KH', 'KS'
);
protected $game;
protected $state;
public $deal = array();
function __construct( $game ) {
$this->game = max( min( $game, 32000 ), 1 );
$this->state = $this->game;
while ( ! empty( $this->deck ) ) {
$i = $this->lcg_rnd() % count( $this->deck );
$this->deal[] = $this->deck[ $i ];
$this->deck[ $i ] = end( $this->deck );
array_pop( $this->deck );
}
}
protected function lcg_rnd() {
return ( $this->state = ( $this->state * 214013 + 2531011 ) % 2147483648 ) >> 16;
}
function print( $cols = 8 ) {
echo str_pad( . $this->game . , $cols * 3 - 1, '=', STR_PAD_BOTH ), PHP_EOL;
foreach ( array_chunk( $this->deal, $cols ) as $row ) {
echo implode( , $row ), PHP_EOL;
}
echo PHP_EOL;
}
}
$tests = array( 1, 617, 11982 );
foreach ( $tests as $game_num ) {
$deal = new FreeCell_Deal( $game_num );
$deal->print();
} | 964Deal cards for FreeCell
| 12php
| wi6ep |
int cusipCheck(char str[10]){
int sum=0,i,v;
for(i=0;i<8;i++){
if(str[i]>='0'&&str[i]<='9')
v = str[i]-'0';
else if(str[i]>='A'&&str[i]<='Z')
v = (str[i] - 'A' + 10);
else if(str[i]=='*')
v = 36;
else if(str[i]=='@')
v = 37;
else if(str[i]=='
v = 38;
if(i%2!=0)
v*=2;
sum += ((int)(v/10) + v%10);
}
return ((10 - (sum%10))%10);
}
int main(int argC,char* argV[])
{
char cusipStr[10];
int i,numLines;
if(argC==1)
printf(,argV[0]);
else{
FILE* fp = fopen(argV[1],);
fscanf(fp,,&numLines);
printf();
printf();
for(i=0;i<numLines;i++){
fscanf(fp,,cusipStr);
printf(,cusipStr,(cusipCheck(cusipStr)==(cusipStr[8]-'0'))?:);
}
fclose(fp);
}
return 0;
} | 973CUSIP
| 5c
| wi8ec |
bool damm(unsigned char *input, size_t length) {
static const unsigned char table[10][10] = {
{0, 3, 1, 7, 5, 9, 8, 6, 4, 2},
{7, 0, 9, 2, 1, 5, 4, 8, 6, 3},
{4, 2, 0, 6, 8, 7, 1, 3, 5, 9},
{1, 7, 5, 0, 9, 8, 3, 4, 2, 6},
{6, 1, 2, 3, 0, 4, 5, 9, 7, 8},
{3, 6, 7, 4, 2, 0, 9, 5, 8, 1},
{5, 8, 6, 9, 7, 2, 0, 1, 3, 4},
{8, 9, 4, 5, 3, 6, 2, 0, 1, 7},
{9, 4, 3, 8, 6, 1, 7, 2, 0, 5},
{2, 5, 8, 1, 4, 3, 6, 7, 9, 0},
};
unsigned char interim = 0;
for (size_t i = 0; i < length; i++) {
interim = table[interim][input[i]];
}
return interim == 0;
}
int main() {
unsigned char input[4] = {5, 7, 2, 4};
puts(damm(input, 4) ? : );
return 0;
} | 974Damm algorithm
| 5c
| cgu9c |
import Data.List
import Data.Numbers.Primes (primeFactors)
negateVar p = zipWith (*) p $ reverse $ take (length p) $ cycle [1,-1]
lift p 1 = p
lift p n = intercalate (replicate (n-1) 0) (pure <$> p)
shortDiv :: [Integer] -> [Integer] -> [Integer]
shortDiv p1 (_:p2) = unfoldr go (length p1 - length p2, p1)
where
go (0, _) = Nothing
go (i, h:t) = Just (h, (i-1, zipWith (+) (map (h *) ker) t))
ker = negate <$> p2 ++ repeat 0
primePowerFactors = sortOn fst . map (\x-> (head x, length x)) . group . primeFactors
cyclotomics :: [[Integer]]
cyclotomics = cyclotomic <$> [0..]
cyclotomic :: Int -> [Integer]
cyclotomic 0 = [0]
cyclotomic 1 = [1, -1]
cyclotomic 2 = [1, 1]
cyclotomic n = case primePowerFactors n of
[(2,h)] -> 1: replicate (2 ^ (h-1) - 1) 0 ++ [1]
[(p,1)] -> replicate n 1
[(p,m)] -> lift (cyclotomics !! p) (p^(m-1))
[(2,1),(p,1)] -> take (n `div` 2) $ cycle [1,-1]
(2,1):_ -> negateVar $ cyclotomics !! (n `div` 2)
(p, m):ps -> let cm = cyclotomics !! (n `div` (p ^ m))
in lift (lift cm p `shortDiv` cm) (p^(m-1)) | 972Cyclotomic polynomial
| 8haskell
| jea7g |
import java.util.*;
public class CutRectangle {
private static int[][] dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};
public static void main(String[] args) {
cutRectangle(2, 2);
cutRectangle(4, 3);
}
static void cutRectangle(int w, int h) {
if (w % 2 == 1 && h % 2 == 1)
return;
int[][] grid = new int[h][w];
Stack<Integer> stack = new Stack<>();
int half = (w * h) / 2;
long bits = (long) Math.pow(2, half) - 1;
for (; bits > 0; bits -= 2) {
for (int i = 0; i < half; i++) {
int r = i / w;
int c = i % w;
grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;
grid[h - r - 1][w - c - 1] = 1 - grid[r][c];
}
stack.push(0);
grid[0][0] = 2;
int count = 1;
while (!stack.empty()) {
int pos = stack.pop();
int r = pos / w;
int c = pos % w;
for (int[] dir : dirs) {
int nextR = r + dir[0];
int nextC = c + dir[1];
if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {
if (grid[nextR][nextC] == 1) {
stack.push(nextR * w + nextC);
grid[nextR][nextC] = 2;
count++;
}
}
}
}
if (count == half) {
printResult(grid);
}
}
}
static void printResult(int[][] arr) {
for (int[] a : arr)
System.out.println(Arrays.toString(a));
System.out.println();
}
} | 968Cut a rectangle
| 9java
| psob3 |
long int factorial(int n){
if(n>1)
return n*factorial(n-1);
return 1;
}
long int sumOfFactorials(int num,...){
va_list vaList;
long int sum = 0;
va_start(vaList,num);
while(num--)
sum += factorial(va_arg(vaList,int));
va_end(vaList);
return sum;
}
int main()
{
printf(,sumOfFactorials(5,1,2,3,4,5));
printf(,sumOfFactorials(3,3,4,5));
printf(,sumOfFactorials(3,1,2,3));
return 0;
} | 975Currying
| 5c
| lrucy |
def randomGenerator(seed=1):
max_int32 = (1 << 31) - 1
seed = seed & max_int32
while True:
seed = (seed * 214013 + 2531011) & max_int32
yield seed >> 16
def deal(seed):
nc = 52
cards = list(range(nc - 1, -1, -1))
rnd = randomGenerator(seed)
for i, r in zip(range(nc), rnd):
j = (nc - 1) - r% (nc - i)
cards[i], cards[j] = cards[j], cards[i]
return cards
def show(cards):
l = [[int(c/4)] + [c%4] for c in cards]
for i in range(0, len(cards), 8):
print(.join(l[i: i+8]))
if __name__ == '__main__':
from sys import argv
seed = int(argv[1]) if len(argv) == 2 else 11982
print(.format(seed))
deck = deal(seed)
show(deck) | 964Deal cards for FreeCell
| 3python
| cgp9q |
package main
import (
"fmt"
big "github.com/ncw/gmp"
)
func cullen(n uint) *big.Int {
one := big.NewInt(1)
bn := big.NewInt(int64(n))
res := new(big.Int).Lsh(one, n)
res.Mul(res, bn)
return res.Add(res, one)
}
func woodall(n uint) *big.Int {
res := cullen(n)
return res.Sub(res, big.NewInt(2))
}
func main() {
fmt.Println("First 20 Cullen numbers (n * 2^n + 1):")
for n := uint(1); n <= 20; n++ {
fmt.Printf("%d ", cullen(n))
}
fmt.Println("\n\nFirst 20 Woodall numbers (n * 2^n - 1):")
for n := uint(1); n <= 20; n++ {
fmt.Printf("%d ", woodall(n))
}
fmt.Println("\n\nFirst 5 Cullen primes (in terms of n):")
count := 0
for n := uint(1); count < 5; n++ {
cn := cullen(n)
if cn.ProbablyPrime(15) {
fmt.Printf("%d ", n)
count++
}
}
fmt.Println("\n\nFirst 12 Woodall primes (in terms of n):")
count = 0
for n := uint(1); count < 12; n++ {
cn := woodall(n)
if cn.ProbablyPrime(15) {
fmt.Printf("%d ", n)
count++
}
}
fmt.Println()
} | 976Cullen and Woodall numbers
| 0go
| kxphz |
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class CyclotomicPolynomial {
@SuppressWarnings("unused")
private static int divisions = 0;
private static int algorithm = 2;
public static void main(String[] args) throws Exception {
System.out.println("Task 1: cyclotomic polynomials for n <= 30:");
for ( int i = 1 ; i <= 30 ; i++ ) {
Polynomial p = cyclotomicPolynomial(i);
System.out.printf("CP[%d] =%s%n", i, p);
}
System.out.println("Task 2: Smallest cyclotomic polynomial with n or -n as a coefficient:");
int n = 0;
for ( int i = 1 ; i <= 10 ; i++ ) {
while ( true ) {
n++;
Polynomial cyclo = cyclotomicPolynomial(n);
if ( cyclo.hasCoefficientAbs(i) ) {
System.out.printf("CP[%d] has coefficient with magnitude =%d%n", n, i);
n--;
break;
}
}
}
}
private static final Map<Integer, Polynomial> COMPUTED = new HashMap<>();
private static Polynomial cyclotomicPolynomial(int n) {
if ( COMPUTED.containsKey(n) ) {
return COMPUTED.get(n);
} | 972Cyclotomic polynomial
| 9java
| uhjvv |
null | 968Cut a rectangle
| 11kotlin
| 7axr4 |
library(gmp)
rand_MS <- function(n = 1, seed = 1) {
a <- as.bigz(214013)
c <- as.bigz(2531011)
m <- as.bigz(2^31)
x <- rep(as.bigz(0), n)
x[1] <- (a * as.bigz(seed) + c)%% m
i <- 1
while (i < n) {
x[i+1] <- (a * x[i] + c)%% m
i <- i + 1
}
as.integer(x / 2^16)
}
dealFreeCell <- function(seedNum) {
deck <- paste(rep(c("A",2,3,4,5,6,7,8,9,10,"J","Q","K"), each = 4), c("C","D","H","S"), sep = "")
cards = rand_MS(52,seedNum)
for (i in 52:1) {
cardToPick <- (cards[53-i]%% i)+1
deck[c(cardToPick,i)] <- deck[c(i, cardToPick)]
}
deck <- rev(deck)
deal = matrix(c(deck,NA,NA,NA,NA),ncol = 8, byrow = TRUE)
print(paste("Hand numer:",seedNum), quote = FALSE)
print(deal, quote = FALSE, na.print = "")
} | 964Deal cards for FreeCell
| 13r
| 6vj3e |
(defn- char->value
"convert the given char c to a value used to calculate the cusip check sum"
[c]
(let [int-char (int c)]
(cond
(and (>= int-char (int \0)) (<= int-char (int \9))) (- int-char 48)
(and (>= int-char (int \A)) (<= int-char (int \Z))) (- int-char 55)
(= c \*) 36
(= c \@) 37
(= c \#) 38
:else nil)))
(defn- calc-sum
"Calculate cusip sum. nil is returned for an invalid cusip."
[cusip]
(reduce
(fn [sum [i c]]
(if-let [v (char->value c)]
(let [v (if (= (mod i 2) 1) (* v 2) v)]
(+ sum (int (+ (/ v 10) (mod v 10)))))
(reduced nil)))
0
(map-indexed vector (subs cusip 0 8))))
(defn calc-cusip-checksum
"Given a valid 8 or 9 digit cusip, return the 9th checksum digit"
[cusip]
(when (>= (count cusip) 8)
(let [sum (calc-sum cusip)]
(when sum
(mod (- 10 (mod sum 10)) 10)))))
(defn is-valid-cusip9?
"predicate validating a 9 digit cusip."
[cusip9]
(when-let [checksum (and (= (count cusip9) 9)
(calc-cusip-checksum cusip9))]
(= (- (int (nth cusip9 8)) 48)
checksum)))
(defn rosetta-output
"show some nice output for the Rosetta Wiki"
[]
(doseq [cusip ["037833100" "17275R102" "38259P508" "594918104" "68389X106" "68389X105" "EXTRACRD8"
"EXTRACRD9" "BADCUSIP!" "683&9X106" "68389x105" "683$9X106" "68389}105" "87264ABE4"]]
(println cusip (if (is-valid-cusip9? cusip) "valid" "invalid")))) | 973CUSIP
| 6clojure
| 8zf05 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.