code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
use strict;
use warnings;
use feature 'say';
use enum qw(False True);
use List::Util <max uniqint product>;
use Algorithm::Combinatorics qw(combinations permutations);
sub table { my $t = shift() * (my $c = 1 + length max @_); ( sprintf( ('%'.$c.'d')x@_, @_) ) =~ s/.{1,$t}\K/\n/gr }
sub is_colorful {
my($n) = @_;
return True if 0 <= $n and $n <= 9;
return False if $n =~ /0|1/ or $n < 0;
my @digits = split '', $n;
return False unless @digits == uniqint @digits;
my @p;
for my $w (0 .. @digits) {
push @p, map { product @digits[$_ .. $_+$w] } 0 .. @digits-$w-1;
return False unless @p == uniqint @p
}
True
}
say "Colorful numbers less than 100:\n" . table 10, grep { is_colorful $_ } 0..100;
my $largest = 98765432;
1 while not is_colorful --$largest;
say "Largest magnitude colorful number: $largest\n";
my $total= 10;
map { is_colorful(join '', @$_) and $total++ } map { permutations $_ } combinations [2..9], $_ for 2..8;
say "Total colorful numbers: $total"; | 1,025Colorful numbers
| 2perl
| 4ht5d |
package main
import (
"github.com/fogleman/gg"
"log"
"os/exec"
"runtime"
)
var palette = [8]string{
"000000", | 1,026Colour pinstripe/Printer
| 0go
| rbzgm |
from turtle import *
from PIL import Image
import time
import subprocess
colors = [, , , , , , , ]
screen = getscreen()
inch_width = 11.0
inch_height = 8.5
pixels_per_inch = 100
pix_width = int(inch_width*pixels_per_inch)
pix_height = int(inch_height*pixels_per_inch)
screen.setup (width=pix_width, height=pix_height, startx=0, starty=0)
screen.screensize(pix_width,pix_height)
left_edge = -screen.window_width()
right_edge = screen.window_width()
bottom_edge = -screen.window_height()
top_edge = screen.window_height()
screen.delay(0)
screen.tracer(5)
for inch in range(int(inch_width)-1):
line_width = inch + 1
pensize(line_width)
colornum = 0
min_x = left_edge + (inch * pixels_per_inch)
max_x = left_edge + ((inch+1) * pixels_per_inch)
for y in range(bottom_edge,top_edge,line_width):
penup()
pencolor(colors[colornum])
colornum = (colornum + 1)% len(colors)
setposition(min_x,y)
pendown()
setposition(max_x,y)
screen.getcanvas().postscript(file=)
im = Image.open()
im.save()
subprocess.run([, , ]) | 1,026Colour pinstripe/Printer
| 3python
| 3cezc |
void
get_pixel_color (Display *d, int x, int y, XColor *color)
{
XImage *image;
image = XGetImage (d, RootWindow (d, DefaultScreen (d)), x, y, 1, 1, AllPlanes, XYPixmap);
color->pixel = XGetPixel (image, 0, 0);
XFree (image);
XQueryColor (d, DefaultColormap(d, DefaultScreen (d)), color);
}
XColor c;
get_pixel_color (display, 30, 40, &c);
printf (, c.red, c.green, c.blue); | 1,027Color of a screen pixel
| 5c
| j1370 |
-- save these lines in a file called
-- setupworld.sql
-- turn off feedback for cleaner display
SET feedback off
-- 3 x 3 world
-- alive has coordinates of living cells
DROP TABLE alive;
CREATE TABLE alive (x NUMBER,y NUMBER);
-- three alive up the middle
-- *
-- *
-- *
INSERT INTO alive VALUES (2,1);
INSERT INTO alive VALUES (2,2);
INSERT INTO alive VALUES (2,3);
commit;
-- save these lines in a file called
newgeneration.SQL
-- adjact contains one row for each pair of
-- coordinates that is adjacent to a living cell
DROP TABLE adjacent;
CREATE TABLE adjacent (x NUMBER,y NUMBER);
-- add row for each of the 8 adjacent squares
INSERT INTO adjacent SELECT x-1,y-1 FROM alive;
INSERT INTO adjacent SELECT x-1,y FROM alive;
INSERT INTO adjacent SELECT x-1,y+1 FROM alive;
INSERT INTO adjacent SELECT x,y-1 FROM alive;
INSERT INTO adjacent SELECT x,y+1 FROM alive;
INSERT INTO adjacent SELECT x+1,y-1 FROM alive;
INSERT INTO adjacent SELECT x+1,y FROM alive;
INSERT INTO adjacent SELECT x+1,y+1 FROM alive;
commit;
-- delete rows for squares that are outside the world
DELETE FROM adjacent WHERE x<1 OR y<1 OR x>3 OR y>3;
commit;
-- table counts is the number of live cells
-- adjacent to that point
DROP TABLE counts;
CREATE TABLE counts AS
SELECT x,y,COUNT(*) n
FROM adjacent a
GROUP BY x,y;
-- C N new C
-- 1 0,1 -> 0
-- 1 4,5,6,7,8 -> 0
-- 1 2,3 -> 1
-- 0 3 -> 1
-- 0 0,1,2,4,5,6,7,8 -> 0
-- delete the ones who die
DELETE FROM alive a
WHERE
((a.x,a.y) NOT IN (SELECT x,y FROM counts)) OR
((SELECT c.n FROM counts c WHERE a.x=c.x AND a.y=c.y) IN
(1,4,5,6,7,8));
-- insert the ones that are born
INSERT INTO alive a
SELECT x,y FROM counts c
WHERE c.n=3 AND
((c.x,c.y) NOT IN (SELECT x,y FROM alive));
commit;
-- create output table
DROP TABLE output;
CREATE TABLE output AS
SELECT rownum y,' ' x1,' ' x2,' ' x3
FROM dba_tables WHERE rownum < 4;
UPDATE output SET x1='*'
WHERE (1,y) IN
(SELECT x,y FROM alive);
UPDATE output SET x2='*'
WHERE (2,y) IN
(SELECT x,y FROM alive);
UPDATE output SET x3='*'
WHERE (3,y) IN
(SELECT x,y FROM alive);
commit
-- output configuration
SELECT x1||x2||x3 WLD
FROM output
ORDER BY y DESC; | 1,014Conway's Game of Life
| 19sql
| 1qbpg |
struct Cell: Hashable {
var x: Int
var y: Int
}
struct Colony {
private var height: Int
private var width: Int
private var cells: Set<Cell>
init(cells: Set<Cell>, height: Int, width: Int) {
self.cells = cells
self.height = height
self.width = width
}
private func neighborCounts() -> [Cell: Int] {
var counts = [Cell: Int]()
for cell in cells.flatMap(Colony.neighbors(for:)) {
counts[cell, default: 0] += 1
}
return counts
}
private static func neighbors(for cell: Cell) -> [Cell] {
return [
Cell(x: cell.x - 1, y: cell.y - 1),
Cell(x: cell.x, y: cell.y - 1),
Cell(x: cell.x + 1, y: cell.y - 1),
Cell(x: cell.x - 1, y: cell.y),
Cell(x: cell.x + 1, y: cell.y),
Cell(x: cell.x - 1, y: cell.y + 1),
Cell(x: cell.x, y: cell.y + 1),
Cell(x: cell.x + 1, y: cell.y + 1),
]
}
func printColony() {
for y in 0..<height {
for x in 0..<width {
let char = cells.contains(Cell(x: x, y: y))? "0": "."
print("\(char) ", terminator: "")
}
print()
}
}
mutating func run(iterations: Int) {
print("(0)")
printColony()
print()
for i in 1...iterations {
print("(\(i))")
runGeneration()
printColony()
print()
}
}
private mutating func runGeneration() {
cells = Set(neighborCounts().compactMap({keyValue in
switch (keyValue.value, cells.contains(keyValue.key)) {
case (2, true), (3, _):
return keyValue.key
case _:
return nil
}
}))
}
}
let blinker = [Cell(x: 1, y: 0), Cell(x: 1, y: 1), Cell(x: 1, y: 2)] as Set
var col = Colony(cells: blinker, height: 3, width: 3)
print("Blinker: ")
col.run(iterations: 3)
let glider = [
Cell(x: 1, y: 0),
Cell(x: 2, y: 1),
Cell(x: 0, y: 2),
Cell(x: 1, y: 2),
Cell(x: 2, y: 2)
] as Set
col = Colony(cells: glider, height: 8, width: 8)
print("Glider: ")
col.run(iterations: 20) | 1,014Conway's Game of Life
| 17swift
| gk549 |
(defn get-color-at [x y]
(.getPixelColor (java.awt.Robot.) x y)) | 1,027Color of a screen pixel
| 6clojure
| 1qcpy |
package main
import (
"github.com/fogleman/gg"
"math"
)
const tau = 2 * math.Pi
func hsb2rgb(hue, sat, bri float64) (r, g, b int) {
u := int(bri*255 + 0.5)
if sat == 0 {
r, g, b = u, u, u
} else {
h := (hue - math.Floor(hue)) * 6
f := h - math.Floor(h)
p := int(bri*(1-sat)*255 + 0.5)
q := int(bri*(1-sat*f)*255 + 0.5)
t := int(bri*(1-sat*(1-f))*255 + 0.5)
switch int(h) {
case 0:
r, g, b = u, t, p
case 1:
r, g, b = q, u, p
case 2:
r, g, b = p, u, t
case 3:
r, g, b = p, q, u
case 4:
r, g, b = t, p, u
case 5:
r, g, b = u, p, q
}
}
return
}
func colorWheel(dc *gg.Context) {
width, height := dc.Width(), dc.Height()
centerX, centerY := width/2, height/2
radius := centerX
if centerY < radius {
radius = centerY
}
for y := 0; y < height; y++ {
dy := float64(y - centerY)
for x := 0; x < width; x++ {
dx := float64(x - centerX)
dist := math.Sqrt(dx*dx + dy*dy)
if dist <= float64(radius) {
theta := math.Atan2(dy, dx)
hue := (theta + math.Pi) / tau
r, g, b := hsb2rgb(hue, 1, 1)
dc.SetRGB255(r, g, b)
dc.SetPixel(x, y)
}
}
}
}
func main() {
const width, height = 480, 480
dc := gg.NewContext(width, height)
dc.SetRGB(1, 1, 1) | 1,028Color wheel
| 0go
| mvwyi |
import java.awt.*;
import javax.swing.*;
public class ColorWheel {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ColorWheelFrame frame = new ColorWheelFrame();
frame.setVisible(true);
}
});
}
private static class ColorWheelFrame extends JFrame {
private ColorWheelFrame() {
super("Color Wheel");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().add(new ColorWheelPanel());
pack();
}
}
private static class ColorWheelPanel extends JComponent {
private ColorWheelPanel() {
setPreferredSize(new Dimension(400, 400));
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
int w = getWidth();
int h = getHeight();
int margin = 10;
int radius = (Math.min(w, h) - 2 * margin)/2;
int cx = w/2;
int cy = h/2;
float[] dist = {0.F, 1.0F};
g2.setColor(Color.BLACK);
g2.fillRect(0, 0, w, h);
for (int angle = 0; angle < 360; ++angle) {
Color color = hsvToRgb(angle, 1.0, 1.0);
Color[] colors = {Color.WHITE, color};
RadialGradientPaint paint = new RadialGradientPaint(cx, cy,
radius, dist, colors);
g2.setPaint(paint);
g2.fillArc(cx - radius, cy - radius, radius*2, radius*2,
angle, 1);
}
}
}
private static Color hsvToRgb(int h, double s, double v) {
double hp = h/60.0;
double c = s * v;
double x = c * (1 - Math.abs(hp % 2.0 - 1));
double m = v - c;
double r = 0, g = 0, b = 0;
if (hp <= 1) {
r = c;
g = x;
} else if (hp <= 2) {
r = x;
g = c;
} else if (hp <= 3) {
g = c;
b = x;
} else if (hp <= 4) {
g = x;
b = c;
} else if (hp <= 5) {
r = x;
b = c;
} else {
r = c;
b = x;
}
r += m;
g += m;
b += m;
return new Color((int)(r * 255), (int)(g * 255), (int)(b * 255));
}
} | 1,028Color wheel
| 9java
| 4hn58 |
null | 1,023Conditional structures
| 1lua
| n31i8 |
int main()
{
int d=DETECT,m,maxX,maxY,x,y,colour=0,increment=1;
initgraph(&d,&m,);
maxX = getmaxx();
maxY = getmaxy();
for(y=0;y<maxY;y+=maxY/sections)
{
for(x=0;x<maxX;x+=increment)
{
setfillstyle(SOLID_FILL,(colour++)%16);
bar(x,y,x+increment,y+maxY/sections);
}
increment++;
colour = 0;
}
getch();
closegraph();
return 0;
} | 1,029Colour pinstripe/Display
| 5c
| izro2 |
package main
import (
"fmt"
"github.com/go-vgo/robotgo"
)
func main() { | 1,027Color of a screen pixel
| 0go
| fybd0 |
null | 1,028Color wheel
| 11kotlin
| l4scp |
typedef struct oct_node_t oct_node_t, *oct_node;
struct oct_node_t{
uint64_t r, g, b;
int count, heap_idx;
oct_node kids[8], parent;
unsigned char n_kids, kid_idx, flags, depth;
};
inline int cmp_node(oct_node a, oct_node b)
{
if (a->n_kids < b->n_kids) return -1;
if (a->n_kids > b->n_kids) return 1;
int ac = a->count * (1 + a->kid_idx) >> a->depth;
int bc = b->count * (1 + b->kid_idx) >> b->depth;
return ac < bc ? -1 : ac > bc;
}
oct_node node_insert(oct_node root, unsigned char *pix)
{
unsigned char i, bit, depth = 0;
for (bit = 1 << 7; ++depth < OCT_DEPTH; bit >>= 1) {
i = !!(pix[1] & bit) * 4 + !!(pix[0] & bit) * 2 + !!(pix[2] & bit);
if (!root->kids[i])
root->kids[i] = node_new(i, depth, root);
root = root->kids[i];
}
root->r += pix[0];
root->g += pix[1];
root->b += pix[2];
root->count++;
return root;
}
oct_node node_fold(oct_node p)
{
if (p->n_kids) abort();
oct_node q = p->parent;
q->count += p->count;
q->r += p->r;
q->g += p->g;
q->b += p->b;
q->n_kids --;
q->kids[p->kid_idx] = 0;
return q;
}
void color_replace(oct_node root, unsigned char *pix)
{
unsigned char i, bit;
for (bit = 1 << 7; bit; bit >>= 1) {
i = !!(pix[1] & bit) * 4 + !!(pix[0] & bit) * 2 + !!(pix[2] & bit);
if (!root->kids[i]) break;
root = root->kids[i];
}
pix[0] = root->r;
pix[1] = root->g;
pix[2] = root->b;
}
void color_quant(image im, int n_colors)
{
int i;
unsigned char *pix = im->pix;
node_heap heap = { 0, 0, 0 };
oct_node root = node_new(0, 0, 0), got;
for (i = 0; i < im->w * im->h; i++, pix += 3)
heap_add(&heap, node_insert(root, pix));
while (heap.n > n_colors + 1)
heap_add(&heap, node_fold(pop_heap(&heap)));
double c;
for (i = 1; i < heap.n; i++) {
got = heap.buf[i];
c = got->count;
got->r = got->r / c + .5;
got->g = got->g / c + .5;
got->b = got->b / c + .5;
printf(,
i, got->r, got->g, got->b, got->count);
}
for (i = 0, pix = im->pix; i < im->w * im->h; i++, pix += 3)
color_replace(root, pix);
node_free();
free(heap.buf);
} | 1,030Color quantization
| 5c
| vrs2o |
import java.awt.Robot
class GetPixelColor {
static void main(args) {
println getColorAt(args[0] as Integer, args[1] as Integer)
}
static getColorAt(x, y) {
new Robot().getPixelColor(x, y)
}
} | 1,027Color of a screen pixel
| 7groovy
| 8fr0b |
local function hsv_to_rgb (h, s, v) | 1,028Color wheel
| 1lua
| 2g0l3 |
public static Color getColorAt(int x, int y){
return new Robot().getPixelColor(x, y);
} | 1,027Color of a screen pixel
| 9java
| c5s9h |
import java.awt.*
fun getMouseColor(): Color {
val location = MouseInfo.getPointerInfo().location
return getColorAt(location.x, location.y)
}
fun getColorAt(x: Int, y: Int): Color {
return Robot().getPixelColor(x, y)
} | 1,027Color of a screen pixel
| 11kotlin
| 3caz5 |
use Imager;
use Math::Complex qw(cplx i pi);
my ($width, $height) = (300, 300);
my $center = cplx($width/2, $height/2);
my $img = Imager->new(xsize => $width,
ysize => $height);
foreach my $y (0 .. $height - 1) {
foreach my $x (0 .. $width - 1) {
my $vec = $center - $x - $y * i;
my $mag = 2 * abs($vec) / $width;
my $dir = (pi + atan2($vec->Re, $vec->Im)) / (2 * pi);
$img->setpixel(x => $x, y => $y,
color => {hsv => [360 * $dir, $mag, $mag < 1 ? 1 : 0]});
}
}
$img->write(file => 'color_wheel.png'); | 1,028Color wheel
| 2perl
| qiux6 |
package main
import (
"container/heap"
"image"
"image/color"
"image/png"
"log"
"math"
"os"
"sort"
)
func main() {
f, err := os.Open("Quantum_frog.png")
if err != nil {
log.Fatal(err)
}
img, err := png.Decode(f)
if ec := f.Close(); err != nil {
log.Fatal(err)
} else if ec != nil {
log.Fatal(ec)
}
fq, err := os.Create("frog16.png")
if err != nil {
log.Fatal(err)
}
if err = png.Encode(fq, quant(img, 16)); err != nil {
log.Fatal(err)
}
} | 1,030Color quantization
| 0go
| snvqa |
package main
import "github.com/fogleman/gg"
var palette = [8]string{
"000000", | 1,029Colour pinstripe/Display
| 0go
| gkn4n |
import qualified Data.ByteString.Lazy as BS
import qualified Data.Foldable as Fold
import qualified Data.List as List
import Data.Ord
import qualified Data.Sequence as Seq
import Data.Word
import System.Environment
import Codec.Picture
import Codec.Picture.Types
type Accessor = PixelRGB8 -> Pixel8
red, blue, green :: Accessor
red (PixelRGB8 r _ _) = r
green (PixelRGB8 _ g _) = g
blue (PixelRGB8 _ _ b) = b
getPixels :: Pixel a => Image a -> [a]
getPixels image =
[pixelAt image x y
| x <- [0..(imageWidth image - 1)]
, y <- [0..(imageHeight image - 1)]]
extents :: [PixelRGB8] -> (PixelRGB8, PixelRGB8)
extents pixels = (extent minimum, extent maximum)
where
bound f g = f $ map g pixels
extent f = PixelRGB8 (bound f red) (bound f green) (bound f blue)
average :: [PixelRGB8] -> PixelRGB8
average pixels = PixelRGB8 (avg red) (avg green) (avg blue)
where
len = toInteger $ length pixels
avg c = fromIntegral $ (sum $ map (toInteger . c) pixels) `div` len
compwise :: (Word8 -> Word8 -> Word8) -> PixelRGB8 -> PixelRGB8 -> PixelRGB8
compwise f (PixelRGB8 ra ga ba) (PixelRGB8 rb gb bb) =
PixelRGB8 (f ra rb) (f ga gb) (f ba bb)
diffPixel :: PixelRGB8 -> PixelRGB8 -> PixelRGB8
diffPixel = compwise (\x y -> max x y - min x y)
distPixel :: PixelRGB8 -> PixelRGB8 -> Integer
distPixel x y = (rr ^ 2) + (gg ^ 2) + (bb ^ 2)
where
PixelRGB8 r g b = diffPixel x y
rr = toInteger r
gg = toInteger g
bb = toInteger b
longestAccessor :: (PixelRGB8, PixelRGB8) -> Accessor
longestAccessor (l, h) =
snd $ Fold.maximumBy (comparing fst) $ zip [r, g, b] [red, green, blue]
where
PixelRGB8 r g b = diffPixel h l
nearestIdx :: PixelRGB8 -> [PixelRGB8] -> Int
nearestIdx pixel px = ans
where
Just ans = List.findIndex (== near) px
near = List.foldl1 comp px
comp a b = if distPixel a pixel <= distPixel b pixel then a else b
meanSplit :: [PixelRGB8] -> Accessor -> ([PixelRGB8], [PixelRGB8])
meanSplit l f = List.splitAt index sorted
where
sorted = List.sortBy (comparing f) l
index = nearestIdx (average l) sorted
meanCutQuant :: Image PixelRGB8 -> Int -> (Image Pixel8, Palette)
meanCutQuant image numRegions = (indexmap, palette)
where
extentsP p = (p, extents p)
regions = map (\(p, e) -> (average p, e))
$ search $ Seq.singleton $ extentsP $ getPixels image
palette = snd $ generateFoldImage (\(x:xs) _ _ -> (xs, x))
(map fst regions) numRegions 1
indexmap = pixelMap
(\pixel -> fromIntegral $ nearestIdx pixel $ map fst regions)
image
search queue =
case Seq.viewl queue of
(pixels, extent) Seq.:< queueB ->
let (left, right) = meanSplit pixels $ longestAccessor extent
queueC = Fold.foldl (Seq.|>) queueB $ map extentsP [left, right]
in if Seq.length queueC >= numRegions
then List.take numRegions $ Fold.toList queueC
else search queueC
Seq.EmptyL -> error "Queue should never be empty."
quantizeIO :: FilePath -> FilePath -> Int -> IO ()
quantizeIO path outpath numRegions = do
dynimage <- readImage path
case dynimage of
Left err -> putStrLn err
Right (ImageRGB8 image) -> doImage image
Right (ImageRGBA8 image) -> doImage (pixelMap dropTransparency image)
_ -> putStrLn "Expecting RGB8 or RGBA8 image"
where
doImage image = do
let (indexmap, palette) = meanCutQuant image numRegions
case encodePalettedPng palette indexmap of
Left err -> putStrLn err
Right bstring -> BS.writeFile outpath bstring
main :: IO ()
main = do
args <- getArgs
prog <- getProgName
case args of
[path, outpath] -> quantizeIO path outpath 16
_ -> putStrLn $ "Usage: " ++ prog ++ " <image-file> <out-file.png>" | 1,030Color quantization
| 8haskell
| 9uemo |
import java.awt.*;
import static java.awt.Color.*;
import javax.swing.*;
public class ColourPinstripeDisplay extends JPanel {
final static Color[] palette = {black, red, green, blue, magenta,cyan,
yellow, white};
final int bands = 4;
public ColourPinstripeDisplay() {
setPreferredSize(new Dimension(900, 600));
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
int h = getHeight();
for (int b = 1; b <= bands; b++) {
for (int x = 0, colIndex = 0; x < getWidth(); x += b, colIndex++) {
g.setColor(palette[colIndex % palette.length]);
g.fillRect(x, (b - 1) * (h / bands), x + b, b * (h / bands));
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("ColourPinstripeDisplay");
f.add(new ColourPinstripeDisplay(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
} | 1,029Colour pinstripe/Display
| 9java
| 1qmp2 |
use strict;
use warnings;
use GD;
my $file = '/tmp/one-pixel-screen-capture.png';
system "screencapture -R 123,456,1,1 $file";
my $image = GD::Image->newFromPng($file);
my $index = $image->getPixel(0,0);
my($red,$green,$blue) = $image->rgb($index);
print "RGB: $red, $green, $blue\n";
unlink $file; | 1,027Color of a screen pixel
| 2perl
| px9b0 |
from PIL import Image
import colorsys
import math
if __name__ == :
im = Image.new(, (300,300))
radius = min(im.size)/2.0
cx, cy = im.size[0]/2, im.size[1]/2
pix = im.load()
for x in range(im.width):
for y in range(im.height):
rx = x - cx
ry = y - cy
s = (rx ** 2.0 + ry ** 2.0) ** 0.5 / radius
if s <= 1.0:
h = ((math.atan2(ry, rx) / math.pi) + 1.0) / 2.0
rgb = colorsys.hsv_to_rgb(h, s, 1.0)
pix[x,y] = tuple([int(round(c*255.0)) for c in rgb])
im.show() | 1,028Color wheel
| 3python
| sn5q9 |
null | 1,029Colour pinstripe/Display
| 11kotlin
| j1t7r |
$img = imagegrabscreen();
$color = imagecolorat($im, 10, 50);
imagedestroy($im); | 1,027Color of a screen pixel
| 12php
| y2w61 |
null | 1,030Color quantization
| 11kotlin
| ot48z |
def get_pixel_colour(i_x, i_y):
import win32gui
i_desktop_window_id = win32gui.GetDesktopWindow()
i_desktop_window_dc = win32gui.GetWindowDC(i_desktop_window_id)
long_colour = win32gui.GetPixel(i_desktop_window_dc, i_x, i_y)
i_colour = int(long_colour)
win32gui.ReleaseDC(i_desktop_window_id,i_desktop_window_dc)
return (i_colour & 0xff), ((i_colour >> 8) & 0xff), ((i_colour >> 16) & 0xff)
print (get_pixel_colour(0, 0)) | 1,027Color of a screen pixel
| 3python
| 1qcpc |
def settings
size(300, 300)
end
def setup
sketch_title 'Color Wheel'
background(0)
radius = width / 2.0
center = width / 2
grid(width, height) do |x, y|
rx = x - center
ry = y - center
sat = Math.hypot(rx, ry) / radius
if sat <= 1.0
hue = ((Math.atan2(ry, rx) / PI) + 1) / 2.0
color_mode(HSB)
col = color((hue * 255).to_i, (sat * 255).to_i, 255)
set(x, y, col)
end
end
end | 1,028Color wheel
| 14ruby
| 8fg01 |
null | 1,028Color wheel
| 15rust
| otr83 |
null | 1,024Comments
| 2perl
| ha9jl |
use strict ;
use GD ;
my $image = new GD::Image( 320 , 240 ) ;
my %colors = ( "white" => [ 255 , 255 , 255 ] , "red" => [255 , 0 , 0 ] ,
"green" => [ 0 , 255 , 0 ] , "blue" => [ 0 , 0 , 255 ] ,
"magenta" => [ 255 , 0 , 255 ] , "yellow" => [ 255 , 255 , 0 ] ,
"cyan" => [ 0 , 255 , 255 ] , "black" => [ 0 , 0 , 0 ] ) ;
my @paintcolors ;
foreach my $color ( keys %colors ) {
my $paintcolor = $image->colorAllocate( @{$colors{ $color }} ) ;
push @paintcolors, $paintcolor ;
}
my $startx = 0 ;
my $starty = 0 ;
my $run = 0 ;
my $barheight = 240 / 4 ;
my $colorindex = 0 ;
while ( $run < 4 ) {
my $barwidth = $run + 1 ;
while ( $startx + $barwidth < 320 ) {
$image->filledRectangle( $startx , $starty , $startx + $barwidth ,
$starty + $barheight - 1 , $paintcolors[ $colorindex % 8 ] ) ;
$startx += $barwidth ;
$colorindex++ ;
}
$starty += $barheight ;
$startx = 0 ;
$colorindex = 0 ;
$run++ ;
}
open ( DISPLAY , ">" , "pinstripes.png" ) || die ;
binmode DISPLAY ;
print DISPLAY $image->png ;
close DISPLAY ; | 1,029Colour pinstripe/Display
| 2perl
| tmkfg |
module Screen
IMPORT_COMMAND = '/usr/bin/import'
def self.pixel(x, y)
if m = `
m[1..3].map(&:to_i)
else
false
end
end
end | 1,027Color of a screen pixel
| 14ruby
| e02ax |
def getColorAt(x: Int, y: Int): Color = new Robot().getPixelColor(x, y) | 1,027Color of a screen pixel
| 16scala
| sn4qo |
typedef unsigned long marker;
marker one = 1;
void comb(int pool, int need, marker chosen, int at)
{
if (pool < need + at) return;
if (!need) {
for (at = 0; at < pool; at++)
if (chosen & (one << at)) printf(, at);
printf();
return;
}
comb(pool, need - 1, chosen | (one << at), at + 1);
comb(pool, need, chosen, at + 1);
}
int main()
{
comb(5, 3, 0, 0);
return 0;
} | 1,031Combinations
| 5c
| 9uam1 |
null | 1,024Comments
| 12php
| z9wt1 |
use strict;
use warnings;
use Imager;
my $img = Imager->new;
$img->read(file => 'frog.png');
my $img16 = $img->to_paletted({ max_colors => 16});
$img16->write(file => "frog-16.png") | 1,030Color quantization
| 2perl
| gki4e |
from PIL import Image
if __name__==:
im = Image.open()
im2 = im.quantize(16)
im2.show() | 1,030Color quantization
| 3python
| rbngq |
from turtle import *
colors = [, , , , , , , ]
screen = getscreen()
left_edge = -screen.window_width()
right_edge = screen.window_width()
quarter_height = screen.window_height()
half_height = quarter_height * 2
speed()
for quarter in range(4):
pensize(quarter+1)
colornum = 0
min_y = half_height - ((quarter + 1) * quarter_height)
max_y = half_height - ((quarter) * quarter_height)
for x in range(left_edge,right_edge,quarter+1):
penup()
pencolor(colors[colornum])
colornum = (colornum + 1)% len(colors)
setposition(x,min_y)
pendown()
setposition(x,max_y)
notused = input() | 1,029Colour pinstripe/Display
| 3python
| z9btt |
(defn combinations
"If m=1, generate a nested list of numbers [0,n)
If m>1, for each x in [0,n), and for each list in the recursion on [x+1,n), cons the two"
[m n]
(letfn [(comb-aux
[m start]
(if (= 1 m)
(for [x (range start n)]
(list x))
(for [x (range start n)
xs (comb-aux (dec m) (inc x))]
(cons x xs))))]
(comb-aux m 0)))
(defn print-combinations
[m n]
(doseq [line (combinations m n)]
(doseq [n line]
(printf "%s " n))
(printf "%n"))) | 1,031Combinations
| 6clojure
| u7svi |
import java.awt.Color._
import java.awt._
import javax.swing._
object ColourPinstripeDisplay extends App {
private def palette = Seq(black, red, green, blue, magenta, cyan, yellow, white)
SwingUtilities.invokeLater(() =>
new JFrame("Colour Pinstripe") {
class ColourPinstripe_Display extends JPanel {
override def paintComponent(g: Graphics): Unit = {
val bands = 4
super.paintComponent(g)
for (b <- 1 to bands) {
var colIndex = 0
for (x <- 0 until getWidth by b) {
g.setColor(ColourPinstripeDisplay.palette(colIndex % ColourPinstripeDisplay.palette.length))
g.fillRect(x, (b - 1) * (getHeight / bands), x + b, b * (getHeight / bands))
colIndex += 1
}
}
}
setPreferredSize(new Dimension(900, 600))
}
add(new ColourPinstripe_Display, BorderLayout.CENTER)
pack()
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
setLocationRelativeTo(null)
setVisible(true)
}
)
} | 1,029Colour pinstripe/Display
| 16scala
| c5x93 |
foo = 5 | 1,024Comments
| 3python
| kechf |
int main()
{
int colour=0,i,j,MAXROW,MAXCOL;
struct text_info tInfo;
gettextinfo(&tInfo);
MAXROW = tInfo.screenheight;
MAXCOL = tInfo.screenwidth;
textbackground(BLACK);
clrscr();
for(colour=0;colour<COLOURS;colour++)
{
getch();
gotoxy(1+colour*MAXCOL/COLOURS,1);
textbackground(colour);
for(j=0;j<MAXROW;j++){
for(i=0;i<MAXCOL/COLOURS;i++){
cprintf();
}
gotoxy(1+colour*MAXCOL/COLOURS,1+j);
}
}
getch();
textbackground(BLACK);
return 0;
} | 1,032Colour bars/Display
| 5c
| mvpys |
null | 1,024Comments
| 13r
| rb6gj |
x =
=begin hello
I a POD documentation comment like Perl
=end puts | 1,024Comments
| 14ruby
| px2bh |
package main
import "github.com/fogleman/gg"
var colors = [8]string{
"000000", | 1,032Colour bars/Display
| 0go
| as61f |
#!/usr/bin/env stack
import Graphics.Vty
colorBars :: Int -> [(Int, Attr)] -> Image
colorBars h bars = horizCat $ map colorBar bars
where colorBar (w, attr) = charFill attr ' ' w h
barWidths :: Int -> Int -> [Int]
barWidths nBars totalWidth = map barWidth [0..nBars-1]
where fracWidth = fromIntegral totalWidth / fromIntegral nBars
barWidth n =
let n' = fromIntegral n:: Double
in floor ((n' + 1) * fracWidth) - floor (n' * fracWidth)
barImage:: Int -> Int -> Image
barImage w h = colorBars h $ zip (barWidths nBars w) attrs
where attrs = map color2attr colors
nBars = length colors
colors = [black, brightRed, brightGreen, brightMagenta, brightCyan, brightYellow, brightWhite]
color2attr c = Attr Default Default (SetTo c)
main = do
cfg <- standardIOConfig
vty <- mkVty cfg
let output = outputIface vty
bounds <- displayBounds output
let showBars (w,h) = do
let img = barImage w h
pic = picForImage img
update vty pic
e <- nextEvent vty
case e of
EvResize w' h' -> showBars (w',h')
_ -> return ()
showBars bounds
shutdown vty | 1,032Colour bars/Display
| 8haskell
| z9jt0 |
null | 1,024Comments
| 15rust
| 1qvpu |
typedef int (*f_int)();
int _tmpl() {
volatile int x = TAG;
return x * x;
}
f_int dupf(int v)
{
size_t len = (void*)dupf - (void*)_tmpl;
f_int ret = mmap(NULL, len, PROT, FLAGS, 0, 0);
char *p;
if(ret == MAP_FAILED) {
perror();
exit(-1);
}
memcpy(ret, _tmpl, len);
for (p = (char*)ret; p < (char*)ret + len - sizeof(int); p++)
if (*(int *)p == TAG) *(int *)p = v;
return ret;
}
int main()
{
f_int funcs[10];
int i;
for (i = 0; i < 10; i++) funcs[i] = dupf(i);
for (i = 0; i < 9; i++)
printf(, i, funcs[i]());
return 0;
} | 1,033Closures/Value capture
| 5c
| 4hs5t |
null | 1,024Comments
| 16scala
| w84es |
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
public class ColorFrame extends JFrame {
public ColorFrame(int width, int height) {
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setSize(width, height);
this.setVisible(true);
}
@Override
public void paint(Graphics g) {
Color[] colors = { Color.black, Color.red, Color.green, Color.blue,
Color.pink, Color.CYAN, Color.yellow, Color.white };
for (int i = 0; i < colors.length; i++) {
g.setColor(colors[i]);
g.fillRect(this.getWidth() / colors.length * i, 0, this.getWidth()
/ colors.length, this.getHeight());
}
}
public static void main(String args[]) {
new ColorFrame(200, 200);
}
} | 1,032Colour bars/Display
| 9java
| otu8d |
import java.awt.Color
import java.awt.Graphics
import javax.swing.JFrame
class ColorFrame(width: Int, height: Int): JFrame() {
init {
defaultCloseOperation = EXIT_ON_CLOSE
setSize(width, height)
isVisible = true
}
override fun paint(g: Graphics) {
val colors = listOf(Color.black, Color.red, Color.green, Color.blue,
Color.pink, Color.cyan, Color.yellow, Color.white)
val size = colors.size
for (i in 0 until size) {
g.color = colors[i]
g.fillRect(width / size * i, 0, width / size, height)
}
}
}
fun main(args: Array<String>) {
ColorFrame(400, 400)
} | 1,032Colour bars/Display
| 11kotlin
| xo9ws |
bool is_prime(uint32_t n) {
if (n == 2)
return true;
if (n < 2 || n % 2 == 0)
return false;
for (uint32_t p = 3; p * p <= n; p += 2) {
if (n % p == 0)
return false;
}
return true;
}
uint32_t cycle(uint32_t n) {
uint32_t m = n, p = 1;
while (m >= 10) {
p *= 10;
m /= 10;
}
return m + 10 * (n % p);
}
bool is_circular_prime(uint32_t p) {
if (!is_prime(p))
return false;
uint32_t p2 = cycle(p);
while (p2 != p) {
if (p2 < p || !is_prime(p2))
return false;
p2 = cycle(p2);
}
return true;
}
void test_repunit(uint32_t digits) {
char* str = malloc(digits + 1);
if (str == 0) {
fprintf(stderr, );
exit(1);
}
memset(str, '1', digits);
str[digits] = 0;
mpz_t bignum;
mpz_init_set_str(bignum, str, 10);
free(str);
if (mpz_probab_prime_p(bignum, 10))
printf(, digits);
else
printf(, digits);
mpz_clear(bignum);
}
int main() {
uint32_t p = 2;
printf();
for (int count = 0; count < 19; ++p) {
if (is_circular_prime(p)) {
if (count > 0)
printf();
printf(, p);
++count;
}
}
printf();
printf();
uint32_t repunit = 1, digits = 1;
for (; repunit < p; ++digits)
repunit = 10 * repunit + 1;
mpz_t bignum;
mpz_init_set_ui(bignum, repunit);
for (int count = 0; count < 4; ) {
if (mpz_probab_prime_p(bignum, 15)) {
if (count > 0)
printf();
printf(, digits);
++count;
}
++digits;
mpz_mul_ui(bignum, bignum, 10);
mpz_add_ui(bignum, bignum, 1);
}
mpz_clear(bignum);
printf();
test_repunit(5003);
test_repunit(9887);
test_repunit(15073);
test_repunit(25031);
test_repunit(35317);
test_repunit(49081);
return 0;
} | 1,034Circular primes
| 5c
| 5jxuk |
(def funcs (map #(fn [] (* % %)) (range 11)))
(printf "%d\n%d\n" ((nth funcs 3)) ((nth funcs 4))) | 1,033Closures/Value capture
| 6clojure
| hanjr |
use strict ;
use GD ;
my %colors = ( white => [ 255 , 255 , 255 ] , red => [255 , 0 , 0 ] ,
green => [ 0 , 255 , 0 ] , blue => [ 0 , 0 , 255 ] ,
magenta => [ 255 , 0 , 255 ] , yellow => [ 255 , 255 , 0 ] ,
cyan => [ 0 , 255 , 255 ] , black => [ 0 , 0 , 0 ] ) ;
my $barwidth = 160 / 8 ;
my $image = new GD::Image( 160 , 100 ) ;
my $start = 0 ;
foreach my $rgb ( values %colors ) {
my $paintcolor = $image->colorAllocate( @$rgb ) ;
$image->filledRectangle( $start * $barwidth , 0 , $start * $barwidth +
$barwidth - 1 , 99 , $paintcolor ) ;
$start++ ;
}
open ( DISPLAY , ">" , "testprogram.png" ) || die ;
binmode DISPLAY ;
print DISPLAY $image->png ;
close DISPLAY ; | 1,032Colour bars/Display
| 2perl
| 2gwlf |
SELECT * FROM mytable -- Selects all columns and rows | 1,024Comments
| 19sql
| sn7qp |
<?php
$colors = array(array( 0, 0, 0),
array(255, 0, 0),
array( 0, 255, 0),
array( 0, 0, 255),
array(255, 0, 255),
array( 0, 255, 255),
array(255, 255, 0),
array(255, 255, 255));
define('BARWIDTH', 640 / count($colors));
define('HEIGHT', 480);
$image = imagecreate(BARWIDTH * count($colors), HEIGHT);
foreach ($colors as $position => $color) {
$color = imagecolorallocate($image, $color[0], $color[1], $color[2]);
imagefilledrectangle($image, $position * BARWIDTH, 0,
$position * BARWIDTH + BARWIDTH - 1,
HEIGHT - 1, $color);
}
header('Content-type:image/png');
imagepng($image);
imagedestroy($image); | 1,032Colour bars/Display
| 12php
| snlqs |
null | 1,024Comments
| 17swift
| bwlkd |
char canvas[GRID_SIZE][GRID_SIZE];
void initN() {
int i, j;
for (i = 0; i < GRID_SIZE; i++) {
for (j = 0; j < GRID_SIZE; j++) {
canvas[i][j] = ' ';
}
canvas[i][5] = 'x';
}
}
void horizontal(size_t c1, size_t c2, size_t r) {
size_t c;
for (c = c1; c <= c2; c++) {
canvas[r][c] = 'x';
}
}
void vertical(size_t r1, size_t r2, size_t c) {
size_t r;
for (r = r1; r <= r2; r++) {
canvas[r][c] = 'x';
}
}
void diagd(size_t c1, size_t c2, size_t r) {
size_t c;
for (c = c1; c <= c2; c++) {
canvas[r + c - c1][c] = 'x';
}
}
void diagu(size_t c1, size_t c2, size_t r) {
size_t c;
for (c = c1; c <= c2; c++) {
canvas[r - c + c1][c] = 'x';
}
}
void drawOnes(int v) {
switch (v) {
case 1:
horizontal(6, 10, 0);
break;
case 2:
horizontal(6, 10, 4);
break;
case 3:
diagd(6, 10, 0);
break;
case 4:
diagu(6, 10, 4);
break;
case 5:
drawOnes(1);
drawOnes(4);
break;
case 6:
vertical(0, 4, 10);
break;
case 7:
drawOnes(1);
drawOnes(6);
break;
case 8:
drawOnes(2);
drawOnes(6);
break;
case 9:
drawOnes(1);
drawOnes(8);
break;
default:
break;
}
}
void drawTens(int v) {
switch (v) {
case 1:
horizontal(0, 4, 0);
break;
case 2:
horizontal(0, 4, 4);
break;
case 3:
diagu(0, 4, 4);
break;
case 4:
diagd(0, 4, 0);
break;
case 5:
drawTens(1);
drawTens(4);
break;
case 6:
vertical(0, 4, 0);
break;
case 7:
drawTens(1);
drawTens(6);
break;
case 8:
drawTens(2);
drawTens(6);
break;
case 9:
drawTens(1);
drawTens(8);
break;
default:
break;
}
}
void drawHundreds(int hundreds) {
switch (hundreds) {
case 1:
horizontal(6, 10, 14);
break;
case 2:
horizontal(6, 10, 10);
break;
case 3:
diagu(6, 10, 14);
break;
case 4:
diagd(6, 10, 10);
break;
case 5:
drawHundreds(1);
drawHundreds(4);
break;
case 6:
vertical(10, 14, 10);
break;
case 7:
drawHundreds(1);
drawHundreds(6);
break;
case 8:
drawHundreds(2);
drawHundreds(6);
break;
case 9:
drawHundreds(1);
drawHundreds(8);
break;
default:
break;
}
}
void drawThousands(int thousands) {
switch (thousands) {
case 1:
horizontal(0, 4, 14);
break;
case 2:
horizontal(0, 4, 10);
break;
case 3:
diagd(0, 4, 10);
break;
case 4:
diagu(0, 4, 14);
break;
case 5:
drawThousands(1);
drawThousands(4);
break;
case 6:
vertical(10, 14, 0);
break;
case 7:
drawThousands(1);
drawThousands(6);
break;
case 8:
drawThousands(2);
drawThousands(6);
break;
case 9:
drawThousands(1);
drawThousands(8);
break;
default:
break;
}
}
void draw(int v) {
int thousands = v / 1000;
v %= 1000;
int hundreds = v / 100;
v %= 100;
int tens = v / 10;
int ones = v % 10;
if (thousands > 0) {
drawThousands(thousands);
}
if (hundreds > 0) {
drawHundreds(hundreds);
}
if (tens > 0) {
drawTens(tens);
}
if (ones > 0) {
drawOnes(ones);
}
}
void write(FILE *out) {
int i;
for (i = 0; i < GRID_SIZE; i++) {
fprintf(out, , GRID_SIZE, canvas[i]);
putc('\n', out);
}
}
void test(int n) {
printf(, n);
initN();
draw(n);
write(stdout);
printf();
}
int main() {
test(0);
test(1);
test(20);
test(300);
test(4000);
test(5555);
test(6789);
test(9999);
return 0;
} | 1,035Cistercian numerals
| 5c
| qiyxc |
from livewires import *
horiz=640; vert=480
begin_graphics(width=horiz,height=vert,title=,background=Colour.black)
NameColors=[,,,,,,,]
stepik=horiz/len(NameColors)
for index,each in enumerate(NameColors):
ExcStrng=+each+
exec ExcStrng
box(index*stepik,0,(index+1)*stepik,vert,filled=1)
while keys_pressed() != ['x']:
pass
end_graphics() | 1,032Colour bars/Display
| 3python
| vrx29 |
package main
import (
"fmt"
big "github.com/ncw/gmp"
"strings"
) | 1,034Circular primes
| 0go
| 8fl0g |
pal <- c("black", "red", "green", "blue", "magenta", "cyan", "yellow", "white")
par(mar = rep(0, 4))
image(matrix(1:8), col = pal, axes = FALSE) | 1,032Colour bars/Display
| 13r
| 9u1mg |
import Math.NumberTheory.Primes (Prime, unPrime, nextPrime)
import Math.NumberTheory.Primes.Testing (isPrime, millerRabinV)
import Text.Printf (printf)
rotated :: [Integer] -> [Integer]
rotated xs
| any (< head xs) xs = []
| otherwise = map asNum $ take (pred $ length xs) $ rotate xs
where
rotate [] = []
rotate (d:ds) = ds <> [d]: rotate (ds <> [d])
asNum :: [Integer] -> Integer
asNum [] = 0
asNum n@(d:ds)
| all (==1) n = read $ concatMap show n
| otherwise = (d * (10 ^ length ds)) + asNum ds
digits :: Integer -> [Integer]
digits 0 = []
digits n = digits d <> [r]
where (d, r) = n `quotRem` 10
isCircular :: Bool -> Integer -> Bool
isCircular repunit n
| repunit = millerRabinV 0 n
| n < 10 = True
| even n = False
| null rotations = False
| any (<n) rotations = False
| otherwise = all isPrime rotations
where
rotations = rotated $ digits n
repunits :: [Integer]
repunits = go 2
where go n = asNum (replicate n 1): go (succ n)
asRepunit :: Int -> Integer
asRepunit n = asNum $ replicate n 1
main :: IO ()
main = do
printf "The first 19 circular primes are:\n%s\n\n" $ circular primes
printf "The next 4 circular primes, in repunit format are:\n"
mapM_ (printf "R(%d) ") $ reps repunits
printf "\n\nThe following repunits are probably circular primes:\n"
mapM_ (uncurry (printf "R(%d):%s\n") . checkReps) [5003, 9887, 15073, 25031, 35317, 49081]
where
primes = map unPrime [nextPrime 1..]
circular = show . take 19 . filter (isCircular False)
reps = map (sum . digits). tail . take 5 . filter (isCircular True)
checkReps = (,) <$> id <*> show . isCircular True . asRepunit | 1,034Circular primes
| 8haskell
| l41ch |
class Segment
{
public Segment(PointF p1, PointF p2)
{
P1 = p1;
P2 = p2;
}
public readonly PointF P1;
public readonly PointF P2;
public float Length()
{
return (float)Math.Sqrt(LengthSquared());
}
public float LengthSquared()
{
return (P1.X - P2.X) * (P1.X - P2.X)
+ (P1.Y - P2.Y) * (P1.Y - P2.Y);
}
} | 1,036Closest-pair problem
| 5c
| 3cgza |
package main
import (
"fmt"
)
func main() {
comb(5, 3, func(c []int) {
fmt.Println(c)
})
}
func comb(n, m int, emit func([]int)) {
s := make([]int, m)
last := m - 1
var rc func(int, int)
rc = func(i, next int) {
for j := next; j < n; j++ {
s[i] = j
if i == last {
emit(s)
} else {
rc(i+1, j+1)
}
}
return
}
rc(0, 0)
} | 1,031Combinations
| 0go
| e0ma6 |
PALETTE = %w[
def settings
full_screen
end
def setup
PALETTE.each_with_index do |col, idx|
fill color(col)
rect(idx * width / 8, 0, width / 8, height)
end
end | 1,032Colour bars/Display
| 14ruby
| 5jsuj |
use pixels::{Pixels, SurfaceTexture}; | 1,032Colour bars/Display
| 15rust
| 4h05u |
package main
import "fmt"
func main() {
fs := make([]func() int, 10)
for i := range fs {
i := i
fs[i] = func() int {
return i * i
}
}
fmt.Println("func #0:", fs[0]())
fmt.Println("func #3:", fs[3]())
} | 1,033Closures/Value capture
| 0go
| otv8q |
import java.math.BigInteger;
import java.util.Arrays;
public class CircularPrimes {
public static void main(String[] args) {
System.out.println("First 19 circular primes:");
int p = 2;
for (int count = 0; count < 19; ++p) {
if (isCircularPrime(p)) {
if (count > 0)
System.out.print(", ");
System.out.print(p);
++count;
}
}
System.out.println();
System.out.println("Next 4 circular primes:");
int repunit = 1, digits = 1;
for (; repunit < p; ++digits)
repunit = 10 * repunit + 1;
BigInteger bignum = BigInteger.valueOf(repunit);
for (int count = 0; count < 4; ) {
if (bignum.isProbablePrime(15)) {
if (count > 0)
System.out.print(", ");
System.out.printf("R(%d)", digits);
++count;
}
++digits;
bignum = bignum.multiply(BigInteger.TEN);
bignum = bignum.add(BigInteger.ONE);
}
System.out.println();
testRepunit(5003);
testRepunit(9887);
testRepunit(15073);
testRepunit(25031);
}
private static boolean isPrime(int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
return false;
}
return true;
}
private static int cycle(int n) {
int m = n, p = 1;
while (m >= 10) {
p *= 10;
m /= 10;
}
return m + 10 * (n % p);
}
private static boolean isCircularPrime(int p) {
if (!isPrime(p))
return false;
int p2 = cycle(p);
while (p2 != p) {
if (p2 < p || !isPrime(p2))
return false;
p2 = cycle(p2);
}
return true;
}
private static void testRepunit(int digits) {
BigInteger repunit = repunit(digits);
if (repunit.isProbablePrime(15))
System.out.printf("R(%d) is probably prime.\n", digits);
else
System.out.printf("R(%d) is not prime.\n", digits);
}
private static BigInteger repunit(int digits) {
char[] ch = new char[digits];
Arrays.fill(ch, '1');
return new BigInteger(new String(ch));
}
} | 1,034Circular primes
| 9java
| 3c7zg |
def comb
comb = { m, list ->
def n = list.size()
m == 0 ?
[[]]:
(0..(n-m)).inject([]) { newlist, k ->
def sublist = (k+1 == n) ? []: list[(k+1)..<n]
newlist += comb(m-1, sublist).collect { [list[k]] + it }
}
} | 1,031Combinations
| 7groovy
| keth7 |
if ($expression) {
do_something;
} | 1,023Conditional structures
| 2perl
| rbygd |
import java.awt.Color
import scala.swing._
class ColorBars extends Component {
override def paintComponent(g:Graphics2D)={
val colors=List(Color.BLACK, Color.RED, Color.GREEN, Color.BLUE, Color.MAGENTA, Color.CYAN, Color.YELLOW, Color.WHITE)
val colCount=colors.size
val deltaX=size.width.toDouble/colCount
for(x <- 0 until colCount){
val startX=(deltaX*x).toInt
val endX=(deltaX*(x+1)).toInt
g.setColor(colors(x))
g.fillRect(startX, 0, endX-startX, size.height)
}
}
} | 1,032Colour bars/Display
| 16scala
| 7pir9 |
def closures = (0..9).collect{ i -> { -> i*i } } | 1,033Closures/Value capture
| 7groovy
| xomwl |
fs = map (\i _ -> i * i) [1 .. 10] | 1,033Closures/Value capture
| 8haskell
| 2gell |
int ar[10];
ar[0] = 1;
ar[1] = 2;
int* p;
for (p=ar;
p<(ar+cSize(ar));
p++) {
printf(,*p);
} | 1,037Collections
| 5c
| rbxg7 |
comb :: Int -> [a] -> [[a]]
comb 0 _ = [[]]
comb _ [] = []
comb m (x:xs) = map (x:) (comb (m-1) xs) ++ comb m xs | 1,031Combinations
| 8haskell
| 3ckzj |
typedef struct sMyClass
{
int variable;
} *MyClass;
MyClass MyClass_new()
{
MyClass pthis = malloc(sizeof *pthis);
pthis->variable = 0;
return pthis;
}
void MyClass_delete(MyClass* pthis)
{
if (pthis)
{
free(*pthis);
*pthis = NULL;
}
}
void MyClass_someMethod(MyClass pthis)
{
pthis->variable = 1;
}
MyClass obj = MyClass_new();
MyClass_someMethod(obj);
MyClass_delete(&obj); | 1,038Classes
| 5c
| 8fy04 |
package main
import "fmt"
var n = make([][]string, 15)
func initN() {
for i := 0; i < 15; i++ {
n[i] = make([]string, 11)
for j := 0; j < 11; j++ {
n[i][j] = " "
}
n[i][5] = "x"
}
}
func horiz(c1, c2, r int) {
for c := c1; c <= c2; c++ {
n[r][c] = "x"
}
}
func verti(r1, r2, c int) {
for r := r1; r <= r2; r++ {
n[r][c] = "x"
}
}
func diagd(c1, c2, r int) {
for c := c1; c <= c2; c++ {
n[r+c-c1][c] = "x"
}
}
func diagu(c1, c2, r int) {
for c := c1; c <= c2; c++ {
n[r-c+c1][c] = "x"
}
}
var draw map[int]func() | 1,035Cistercian numerals
| 0go
| 2g1l7 |
(defn distance [[x1 y1] [x2 y2]]
(let [dx (- x2 x1), dy (- y2 y1)]
(Math/sqrt (+ (* dx dx) (* dy dy)))))
(defn brute-force [points]
(let [n (count points)]
(when (< 1 n)
(apply min-key first
(for [i (range 0 (dec n)),:let [p1 (nth points i)],
j (range (inc i) n),:let [p2 (nth points j)]]
[(distance p1 p2) p1 p2])))))
(defn combine [yS [dmin pmin1 pmin2]]
(apply min-key first
(conj (for [[p1 p2] (partition 2 1 yS)
:let [[_ py1] p1 [_ py2] p2]
:while (< (- py1 py2) dmin)]
[(distance p1 p2) p1 p2])
[dmin pmin1 pmin2])))
(defn closest-pair
([points]
(closest-pair
(sort-by first points)
(sort-by second points)))
([xP yP]
(if (< (count xP) 4)
(brute-force xP)
(let [[xL xR] (partition-all (Math/ceil (/ (count xP) 2)) xP)
[xm _] (last xL)
{yL true yR false} (group-by (fn [[px _]] (<= px xm)) yP)
dL&pairL (closest-pair xL yL)
dR&pairR (closest-pair xR yR)
[dmin pmin1 pmin2] (min-key first dL&pairL dR&pairR)
{yS true} (group-by (fn [[px _]] (< (Math/abs (- xm px)) dmin)) yP)]
(combine yS [dmin pmin1 pmin2]))))) | 1,036Closest-pair problem
| 6clojure
| c5k9b |
import java.math.BigInteger
val SMALL_PRIMES = listOf(
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,
101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199,
211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293,
307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397,
401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499,
503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599,
601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691,
701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797,
809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887,
907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997
)
fun isPrime(n: BigInteger): Boolean {
if (n < 2.toBigInteger()) {
return false
}
for (sp in SMALL_PRIMES) {
val spb = sp.toBigInteger()
if (n == spb) {
return true
}
if (n % spb == BigInteger.ZERO) {
return false
}
if (n < spb * spb) { | 1,034Circular primes
| 11kotlin
| n3uij |
(defn zero [f] identity)
(defn succ [n] (fn [f] (fn [x] (f ((n f) x)))))
(defn add [n,m] (fn [f] (fn [x] ((m f)((n f) x)))))
(defn mult [n,m] (fn [f] (fn [x] ((m (n f)) x))))
(defn power [b,e] (e b))
(defn to-int [c] ((c inc) 0))
(defn from-int [n]
(letfn [(countdown [i] (if (zero? i) zero (succ (countdown (- i 1)))))]
(countdown n)))
(def three (succ (succ (succ zero))))
(def four (from-int 4))
(doseq [n [(add three four) (mult three four)
(power three four) (power four three)]]
(println (to-int n))) | 1,039Church numerals
| 6clojure
| n39ik |
import java.util.Arrays;
import java.util.List;
public class Cistercian {
private static final int SIZE = 15;
private final char[][] canvas = new char[SIZE][SIZE];
public Cistercian(int n) {
initN();
draw(n);
}
public void initN() {
for (var row : canvas) {
Arrays.fill(row, ' ');
row[5] = 'x';
}
}
private void horizontal(int c1, int c2, int r) {
for (int c = c1; c <= c2; c++) {
canvas[r][c] = 'x';
}
}
private void vertical(int r1, int r2, int c) {
for (int r = r1; r <= r2; r++) {
canvas[r][c] = 'x';
}
}
private void diagd(int c1, int c2, int r) {
for (int c = c1; c <= c2; c++) {
canvas[r + c - c1][c] = 'x';
}
}
private void diagu(int c1, int c2, int r) {
for (int c = c1; c <= c2; c++) {
canvas[r - c + c1][c] = 'x';
}
}
private void draw(int v) {
var thousands = v / 1000;
v %= 1000;
var hundreds = v / 100;
v %= 100;
var tens = v / 10;
var ones = v % 10;
drawPart(1000 * thousands);
drawPart(100 * hundreds);
drawPart(10 * tens);
drawPart(ones);
}
private void drawPart(int v) {
switch (v) {
case 1:
horizontal(6, 10, 0);
break;
case 2:
horizontal(6, 10, 4);
break;
case 3:
diagd(6, 10, 0);
break;
case 4:
diagu(6, 10, 4);
break;
case 5:
drawPart(1);
drawPart(4);
break;
case 6:
vertical(0, 4, 10);
break;
case 7:
drawPart(1);
drawPart(6);
break;
case 8:
drawPart(2);
drawPart(6);
break;
case 9:
drawPart(1);
drawPart(8);
break;
case 10:
horizontal(0, 4, 0);
break;
case 20:
horizontal(0, 4, 4);
break;
case 30:
diagu(0, 4, 4);
break;
case 40:
diagd(0, 4, 0);
break;
case 50:
drawPart(10);
drawPart(40);
break;
case 60:
vertical(0, 4, 0);
break;
case 70:
drawPart(10);
drawPart(60);
break;
case 80:
drawPart(20);
drawPart(60);
break;
case 90:
drawPart(10);
drawPart(80);
break;
case 100:
horizontal(6, 10, 14);
break;
case 200:
horizontal(6, 10, 10);
break;
case 300:
diagu(6, 10, 14);
break;
case 400:
diagd(6, 10, 10);
break;
case 500:
drawPart(100);
drawPart(400);
break;
case 600:
vertical(10, 14, 10);
break;
case 700:
drawPart(100);
drawPart(600);
break;
case 800:
drawPart(200);
drawPart(600);
break;
case 900:
drawPart(100);
drawPart(800);
break;
case 1000:
horizontal(0, 4, 14);
break;
case 2000:
horizontal(0, 4, 10);
break;
case 3000:
diagd(0, 4, 10);
break;
case 4000:
diagu(0, 4, 14);
break;
case 5000:
drawPart(1000);
drawPart(4000);
break;
case 6000:
vertical(10, 14, 0);
break;
case 7000:
drawPart(1000);
drawPart(6000);
break;
case 8000:
drawPart(2000);
drawPart(6000);
break;
case 9000:
drawPart(1000);
drawPart(8000);
break;
}
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
for (var row : canvas) {
builder.append(row);
builder.append('\n');
}
return builder.toString();
}
public static void main(String[] args) {
for (int number : List.of(0, 1, 20, 300, 4000, 5555, 6789, 9999)) {
System.out.printf("%d:\n", number);
var c = new Cistercian(number);
System.out.println(c);
}
}
} | 1,035Cistercian numerals
| 9java
| j187c |
null | 1,034Circular primes
| 1lua
| d65nq |
<?php
$foo = 3;
if ($foo == 2)
if ($foo == 3)
else
if ($foo != 0)
{
}
else
{
}
?> | 1,023Conditional structures
| 12php
| d6an8 |
null | 1,035Cistercian numerals
| 10javascript
| 1qfp7 |
import java.util.function.Supplier;
import java.util.ArrayList;
public class ValueCapture {
public static void main(String[] args) {
ArrayList<Supplier<Integer>> funcs = new ArrayList<>();
for (int i = 0; i < 10; i++) {
int j = i;
funcs.add(() -> j * j);
}
Supplier<Integer> foo = funcs.get(3);
System.out.println(foo.get()); | 1,033Closures/Value capture
| 9java
| 6lh3z |
{1 "a", "Q" 10}
(hash-map 1 "a" "Q" 10)
(let [my-map {1 "a"}]
(assoc my-map "Q" 10)) | 1,037Collections
| 6clojure
| bwokz |
(defprotocol Foo (getFoo [this]))
(defrecord Example1 [foo] Foo (getFoo [this] foo))
(-> (Example1. "Hi") .getFoo)
"Hi" | 1,038Classes
| 6clojure
| fy2dm |
import java.io.StringWriter
class Cistercian() {
constructor(number: Int) : this() {
draw(number)
}
private val size = 15
private var canvas = Array(size) { Array(size) { ' ' } }
init {
initN()
}
private fun initN() {
for (row in canvas) {
row.fill(' ')
row[5] = 'x'
}
}
private fun horizontal(c1: Int, c2: Int, r: Int) {
for (c in c1..c2) {
canvas[r][c] = 'x'
}
}
private fun vertical(r1: Int, r2: Int, c: Int) {
for (r in r1..r2) {
canvas[r][c] = 'x'
}
}
private fun diagd(c1: Int, c2: Int, r: Int) {
for (c in c1..c2) {
canvas[r + c - c1][c] = 'x'
}
}
private fun diagu(c1: Int, c2: Int, r: Int) {
for (c in c1..c2) {
canvas[r - c + c1][c] = 'x'
}
}
private fun drawPart(v: Int) {
when (v) {
1 -> {
horizontal(6, 10, 0)
}
2 -> {
horizontal(6, 10, 4)
}
3 -> {
diagd(6, 10, 0)
}
4 -> {
diagu(6, 10, 4)
}
5 -> {
drawPart(1)
drawPart(4)
}
6 -> {
vertical(0, 4, 10)
}
7 -> {
drawPart(1)
drawPart(6)
}
8 -> {
drawPart(2)
drawPart(6)
}
9 -> {
drawPart(1)
drawPart(8)
}
10 -> {
horizontal(0, 4, 0)
}
20 -> {
horizontal(0, 4, 4)
}
30 -> {
diagu(0, 4, 4)
}
40 -> {
diagd(0, 4, 0)
}
50 -> {
drawPart(10)
drawPart(40)
}
60 -> {
vertical(0, 4, 0)
}
70 -> {
drawPart(10)
drawPart(60)
}
80 -> {
drawPart(20)
drawPart(60)
}
90 -> {
drawPart(10)
drawPart(80)
}
100 -> {
horizontal(6, 10, 14)
}
200 -> {
horizontal(6, 10, 10)
}
300 -> {
diagu(6, 10, 14)
}
400 -> {
diagd(6, 10, 10)
}
500 -> {
drawPart(100)
drawPart(400)
}
600 -> {
vertical(10, 14, 10)
}
700 -> {
drawPart(100)
drawPart(600)
}
800 -> {
drawPart(200)
drawPart(600)
}
900 -> {
drawPart(100)
drawPart(800)
}
1000 -> {
horizontal(0, 4, 14)
}
2000 -> {
horizontal(0, 4, 10)
}
3000 -> {
diagd(0, 4, 10)
}
4000 -> {
diagu(0, 4, 14)
}
5000 -> {
drawPart(1000)
drawPart(4000)
}
6000 -> {
vertical(10, 14, 0)
}
7000 -> {
drawPart(1000)
drawPart(6000)
}
8000 -> {
drawPart(2000)
drawPart(6000)
}
9000 -> {
drawPart(1000)
drawPart(8000)
}
}
}
private fun draw(v: Int) {
var v2 = v
val thousands = v2 / 1000
v2 %= 1000
val hundreds = v2 / 100
v2 %= 100
val tens = v2 / 10
val ones = v % 10
if (thousands > 0) {
drawPart(1000 * thousands)
}
if (hundreds > 0) {
drawPart(100 * hundreds)
}
if (tens > 0) {
drawPart(10 * tens)
}
if (ones > 0) {
drawPart(ones)
}
}
override fun toString(): String {
val sw = StringWriter()
for (row in canvas) {
for (cell in row) {
sw.append(cell)
}
sw.appendLine()
}
return sw.toString()
}
}
fun main() {
for (number in arrayOf(0, 1, 20, 300, 4000, 5555, 6789, 9999)) {
println("$number:")
val c = Cistercian(number)
println(c)
}
} | 1,035Cistercian numerals
| 11kotlin
| 5jwua |
var funcs = [];
for (var i = 0; i < 10; i++) {
funcs.push( (function(i) {
return function() { return i * i; }
})(i) );
}
window.alert(funcs[3]()); | 1,033Closures/Value capture
| 10javascript
| l4acf |
import java.util.Collections;
import java.util.LinkedList;
public class Comb{
public static void main(String[] args){
System.out.println(comb(3,5));
}
public static String bitprint(int u){
String s= "";
for(int n= 0;u > 0;++n, u>>= 1)
if((u & 1) > 0) s+= n + " ";
return s;
}
public static int bitcount(int u){
int n;
for(n= 0;u > 0;++n, u&= (u - 1)); | 1,031Combinations
| 9java
| iz4os |
typedef unsigned long long int u64;
int primality_pretest(u64 k) {
if (!(k % 3) || !(k % 5) || !(k % 7) || !(k % 11) || !(k % 13) || !(k % 17) || !(k % 19) || !(k % 23)) return (k <= 23);
return TRUE;
}
int probprime(u64 k, mpz_t n) {
mpz_set_ui(n, k);
return mpz_probab_prime_p(n, 0);
}
int is_chernick(int n, u64 m, mpz_t z) {
u64 t = 9 * m;
if (primality_pretest(6 * m + 1) == FALSE) return FALSE;
if (primality_pretest(12 * m + 1) == FALSE) return FALSE;
for (int i = 1; i <= n - 2; i++) if (primality_pretest((t << i) + 1) == FALSE) return FALSE;
if (probprime(6 * m + 1, z) == FALSE) return FALSE;
if (probprime(12 * m + 1, z) == FALSE) return FALSE;
for (int i = 1; i <= n - 2; i++) if (probprime((t << i) + 1, z) == FALSE) return FALSE;
return TRUE;
}
int main(int argc, char const *argv[]) {
mpz_t z;
mpz_inits(z, NULL);
for (int n = 3; n <= 10; n ++) {
u64 multiplier = (n > 4) ? (1 << (n - 4)) : 1;
if (n > 5) multiplier *= 5;
for (u64 k = 1; ; k++) {
u64 m = k * multiplier;
if (is_chernick(n, m, z) == TRUE) {
printf(, n, m);
break;
}
}
}
return 0;
} | 1,040Chernick's Carmichael numbers
| 5c
| ot680 |
function initN()
local n = {}
for i=1,15 do
n[i] = {}
for j=1,11 do
n[i][j] = " "
end
n[i][6] = "x"
end
return n
end
function horiz(n, c1, c2, r)
for c=c1,c2 do
n[r+1][c+1] = "x"
end
end
function verti(n, r1, r2, c)
for r=r1,r2 do
n[r+1][c+1] = "x"
end
end
function diagd(n, c1, c2, r)
for c=c1,c2 do
n[r+c-c1+1][c+1] = "x"
end
end
function diagu(n, c1, c2, r)
for c=c1,c2 do
n[r-c+c1+1][c+1] = "x"
end
end
function initDraw()
local draw = {}
draw[1] = function(n) horiz(n, 6, 10, 0) end
draw[2] = function(n) horiz(n, 6, 10, 4) end
draw[3] = function(n) diagd(n, 6, 10, 0) end
draw[4] = function(n) diagu(n, 6, 10, 4) end
draw[5] = function(n) draw[1](n) draw[4](n) end
draw[6] = function(n) verti(n, 0, 4, 10) end
draw[7] = function(n) draw[1](n) draw[6](n) end
draw[8] = function(n) draw[2](n) draw[6](n) end
draw[9] = function(n) draw[1](n) draw[8](n) end
draw[10] = function(n) horiz(n, 0, 4, 0) end
draw[20] = function(n) horiz(n, 0, 4, 4) end
draw[30] = function(n) diagu(n, 0, 4, 4) end
draw[40] = function(n) diagd(n, 0, 4, 0) end
draw[50] = function(n) draw[10](n) draw[40](n) end
draw[60] = function(n) verti(n, 0, 4, 0) end
draw[70] = function(n) draw[10](n) draw[60](n) end
draw[80] = function(n) draw[20](n) draw[60](n) end
draw[90] = function(n) draw[10](n) draw[80](n) end
draw[100] = function(n) horiz(n, 6, 10, 14) end
draw[200] = function(n) horiz(n, 6, 10, 10) end
draw[300] = function(n) diagu(n, 6, 10, 14) end
draw[400] = function(n) diagd(n, 6, 10, 10) end
draw[500] = function(n) draw[100](n) draw[400](n) end
draw[600] = function(n) verti(n, 10, 14, 10) end
draw[700] = function(n) draw[100](n) draw[600](n) end
draw[800] = function(n) draw[200](n) draw[600](n) end
draw[900] = function(n) draw[100](n) draw[800](n) end
draw[1000] = function(n) horiz(n, 0, 4, 14) end
draw[2000] = function(n) horiz(n, 0, 4, 10) end
draw[3000] = function(n) diagd(n, 0, 4, 10) end
draw[4000] = function(n) diagu(n, 0, 4, 14) end
draw[5000] = function(n) draw[1000](n) draw[4000](n) end
draw[6000] = function(n) verti(n, 10, 14, 0) end
draw[7000] = function(n) draw[1000](n) draw[6000](n) end
draw[8000] = function(n) draw[2000](n) draw[6000](n) end
draw[9000] = function(n) draw[1000](n) draw[8000](n) end
return draw
end
function printNumeral(n)
for i,v in pairs(n) do
for j,w in pairs(v) do
io.write(w .. " ")
end
print()
end
print()
end
function main()
local draw = initDraw()
for i,number in pairs({0, 1, 20, 300, 4000, 5555, 6789, 9999}) do
local n = initN()
print(number..":")
local thousands = math.floor(number / 1000)
number = number % 1000
local hundreds = math.floor(number / 100)
number = number % 100
local tens = math.floor(number / 10)
local ones = number % 10
if thousands > 0 then
draw[thousands * 1000](n)
end
if hundreds > 0 then
draw[hundreds * 100](n)
end
if tens > 0 then
draw[tens * 10](n)
end
if ones > 0 then
draw[ones](n)
end
printNumeral(n)
end
end
main() | 1,035Cistercian numerals
| 1lua
| 4hx5c |
null | 1,033Closures/Value capture
| 11kotlin
| d64nz |
use strict;
use warnings;
use feature 'say';
use List::Util 'min';
use ntheory 'is_prime';
sub rotate { my($i,@a) = @_; join '', @a[$i .. @a-1, 0 .. $i-1] }
sub isCircular {
my ($n) = @_;
return 0 unless is_prime($n);
my @circular = split //, $n;
return 0 if min(@circular) < $circular[0];
for (1 .. scalar @circular) {
my $r = join '', rotate($_,@circular);
return 0 unless is_prime($r) and $r >= $n;
}
1
}
say "The first 19 circular primes are:";
for ( my $i = 1, my $count = 0; $count < 19; $i++ ) {
++$count and print "$i " if isCircular($i);
}
say "\n\nThe next 4 circular primes, in repunit format, are:";
for ( my $i = 7, my $count = 0; $count < 4; $i++ ) {
++$count and say "R($i)" if is_prime 1 x $i
}
say "\nRepunit testing:";
for (5003, 9887, 15073, 25031, 35317, 49081) {
say "R($_): Prime? " . (is_prime 1 x $_ ? 'True' : 'False');
} | 1,034Circular primes
| 2perl
| 7p8rh |
function bitprint(u) {
var s="";
for (var n=0; u; ++n, u>>=1)
if (u&1) s+=n+" ";
return s;
}
function bitcount(u) {
for (var n=0; u; ++n, u=u&(u-1));
return n;
}
function comb(c,n) {
var s=[];
for (var u=0; u<1<<n; u++)
if (bitcount(u)==c)
s.push(bitprint(u))
return s.sort();
}
comb(3,5) | 1,031Combinations
| 10javascript
| z9ht2 |
package main
import "fmt"
type any = interface{}
type fn func(any) any
type church func(fn) fn
func zero(f fn) fn {
return func(x any) any {
return x
}
}
func (c church) succ() church {
return func(f fn) fn {
return func(x any) any {
return f(c(f)(x))
}
}
}
func (c church) add(d church) church {
return func(f fn) fn {
return func(x any) any {
return c(f)(d(f)(x))
}
}
}
func (c church) mul(d church) church {
return func(f fn) fn {
return func(x any) any {
return c(d(f))(x)
}
}
}
func (c church) pow(d church) church {
di := d.toInt()
prod := c
for i := 1; i < di; i++ {
prod = prod.mul(c)
}
return prod
}
func (c church) toInt() int {
return c(incr)(0).(int)
}
func intToChurch(i int) church {
if i == 0 {
return zero
} else {
return intToChurch(i - 1).succ()
}
}
func incr(i any) any {
return i.(int) + 1
}
func main() {
z := church(zero)
three := z.succ().succ().succ()
four := three.succ()
fmt.Println("three ->", three.toInt())
fmt.Println("four ->", four.toInt())
fmt.Println("three + four ->", three.add(four).toInt())
fmt.Println("three * four ->", three.mul(four).toInt())
fmt.Println("three ^ four ->", three.pow(four).toInt())
fmt.Println("four ^ three ->", four.pow(three).toInt())
fmt.Println("5 -> five ->", intToChurch(5).toInt())
} | 1,039Church numerals
| 0go
| vrk2m |
unsigned chowla(const unsigned n) {
unsigned sum = 0;
for (unsigned i = 2, j; i * i <= n; i ++) if (n % i == 0) sum += i + (i == (j = n / i) ? 0 : j);
return sum;
}
int main(int argc, char const *argv[]) {
unsigned a;
for (unsigned n = 1; n < 38; n ++) printf(, n, chowla(n));
unsigned n, count = 0, power = 100;
for (n = 2; n < 10000001; n ++) {
if (chowla(n) == 0) count ++;
if (n % power == 0) printf(, count, power), power *= 10;
}
count = 0;
unsigned limit = 350000000;
unsigned k = 2, kk = 3, p;
for ( ; ; ) {
if ((p = k * kk) > limit) break;
if (chowla(p) == p - 1) {
printf(, p);
count ++;
}
k = kk + 1; kk += k;
}
printf(, count, limit);
return 0;
} | 1,041Chowla numbers
| 5c
| 1q0pj |
class ChurchNumerals {
static void main(args) {
def zero = { f -> { a -> a } }
def succ = { n -> { f -> { a -> f(n(f)(a)) } } }
def add = { n -> { k -> { n(succ)(k) } } }
def mult = { f -> { g -> { a -> f(g(a)) } } }
def pow = { f -> { g -> g(f) } }
def toChurchNum
toChurchNum = { n ->
n == 0 ? zero: succ(toChurchNum(n - 1))
}
def toInt = { n ->
n(x -> x + 1)(0)
}
def three = succ(succ(succ(zero)))
println toInt(three) | 1,039Church numerals
| 7groovy
| mvgy5 |
Subsets and Splits