code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
(ns penney.core
(:gen-class))
(def heads \H)
(def tails \T)
(defn flip-coin []
(let [flip (rand-int 2)]
(if (= flip 0) heads tails)))
(defn turn [coin]
(if (= coin heads) tails heads))
(defn first-index [combo coll]
(some #(if (= (second %) combo) (first %)) coll))
(defn find-winner [h c]
(if (< h c)
(do (println "YOU WIN!\n"):human)
(do (println "COMPUTER WINS!\n"):computer)))
(defn flip-off [human comp]
(let [flips (repeatedly flip-coin)
idx-flips (map-indexed vector (partition 3 1 flips))
h (first-index (seq human) idx-flips)
c (first-index (seq comp) idx-flips)]
(println (format "Tosses:%s" (apply str (take (+ 3 (min h c)) flips))))
(find-winner h c)))
(defn valid? [combo]
(if (empty? combo) true (and (= 3 (count combo)) (every? #(or (= heads %) (= tails %)) combo))))
(defn ask-move []
(println "What sequence of 3 Heads/Tails do you choose?")
(let [input (clojure.string/upper-case (read-line))]
(if-not (valid? input) (recur) input)))
(defn optimize-against [combo]
(let [mid (nth combo 1)
comp (str (turn mid) (first combo) mid)]
(println (format "Computer chooses%s: " comp)) comp))
(defn initial-move [game]
(let [combo (apply str (repeatedly 3 flip-coin))]
(println "--------------")
(println (format "Current score | CPU:%s, You:%s" (:computer game) (:human game)))
(if (= (:first-player game) tails)
(do
(println "Computer goes first and chooses: " combo)
combo)
(println "YOU get to go first."))))
(defn play-game [game]
(let [c-move (initial-move game)
h-move (ask-move)]
(if-not (empty? h-move)
(let [winner (flip-off h-move (if (nil? c-move) (optimize-against h-move) c-move))]
(recur (assoc game winner (inc (winner game)):first-player (flip-coin))))
(println "Thanks for playing!"))))
(defn -main [& args]
(println "Penney's Game.")
(play-game {:first-player (flip-coin)
:human 0,:computer 0})) | 460Penney's game
| 6clojure
| csf9b |
package main
import "github.com/fogleman/gg"
var points []gg.Point
const width = 81
func peano(x, y, lg, i1, i2 int) {
if lg == 1 {
px := float64(width-x) * 10
py := float64(width-y) * 10
points = append(points, gg.Point{px, py})
return
}
lg /= 3
peano(x+2*i1*lg, y+2*i1*lg, lg, i1, i2)
peano(x+(i1-i2+1)*lg, y+(i1+i2)*lg, lg, i1, 1-i2)
peano(x+lg, y+lg, lg, i1, 1-i2)
peano(x+(i1+i2)*lg, y+(i1-i2+1)*lg, lg, 1-i1, 1-i2)
peano(x+2*i2*lg, y+2*(1-i2)*lg, lg, i1, i2)
peano(x+(1+i2-i1)*lg, y+(2-i1-i2)*lg, lg, i1, i2)
peano(x+2*(1-i1)*lg, y+2*(1-i1)*lg, lg, i1, i2)
peano(x+(2-i1-i2)*lg, y+(1+i2-i1)*lg, lg, 1-i1, i2)
peano(x+2*(1-i2)*lg, y+2*i2*lg, lg, 1-i1, i2)
}
func main() {
peano(0, 0, width, 0, 0)
dc := gg.NewContext(820, 820)
dc.SetRGB(1, 1, 1) | 459Peano curve
| 0go
| 283l7 |
import java.io.*;
public class PeanoCurve {
public static void main(final String[] args) {
try (Writer writer = new BufferedWriter(new FileWriter("peano_curve.svg"))) {
PeanoCurve s = new PeanoCurve(writer);
final int length = 8;
s.currentAngle = 90;
s.currentX = length;
s.currentY = length;
s.lineLength = length;
s.begin(656);
s.execute(rewrite(4));
s.end();
} catch (final Exception ex) {
ex.printStackTrace();
}
}
private PeanoCurve(final Writer writer) {
this.writer = writer;
}
private void begin(final int size) throws IOException {
write("<svg xmlns='http: | 459Peano curve
| 9java
| j3v7c |
sub solve_pell {
my ($n) = @_;
use bigint try => 'GMP';
my $x = int(sqrt($n));
my $y = $x;
my $z = 1;
my $r = 2 * $x;
my ($e1, $e2) = (1, 0);
my ($f1, $f2) = (0, 1);
for (; ;) {
$y = $r * $z - $y;
$z = int(($n - $y * $y) / $z);
$r = int(($x + $y) / $z);
($e1, $e2) = ($e2, $r * $e2 + $e1);
($f1, $f2) = ($f2, $r * $f2 + $f1);
my $A = $e2 + $x * $f2;
my $B = $f2;
if ($A**2 - $n * $B**2 == 1) {
return ($A, $B);
}
}
}
foreach my $n (61, 109, 181, 277) {
my ($x, $y) = solve_pell($n);
printf("x^2 -%3d*y^2 = 1 for x =%-21s and y =%s\n", $n, $x, $y);
} | 458Pell's equation
| 2perl
| 7zvrh |
enum Piece {
Empty,
Black,
White,
};
typedef struct Position_t {
int x, y;
} Position;
struct Node_t {
Position pos;
struct Node_t *next;
};
void releaseNode(struct Node_t *head) {
if (head == NULL) return;
releaseNode(head->next);
head->next = NULL;
free(head);
}
typedef struct List_t {
struct Node_t *head;
struct Node_t *tail;
size_t length;
} List;
List makeList() {
return (List) { NULL, NULL, 0 };
}
void releaseList(List *lst) {
if (lst == NULL) return;
releaseNode(lst->head);
lst->head = NULL;
lst->tail = NULL;
}
void addNode(List *lst, Position pos) {
struct Node_t *newNode;
if (lst == NULL) {
exit(EXIT_FAILURE);
}
newNode = malloc(sizeof(struct Node_t));
if (newNode == NULL) {
exit(EXIT_FAILURE);
}
newNode->next = NULL;
newNode->pos = pos;
if (lst->head == NULL) {
lst->head = lst->tail = newNode;
} else {
lst->tail->next = newNode;
lst->tail = newNode;
}
lst->length++;
}
void removeAt(List *lst, size_t pos) {
if (lst == NULL) return;
if (pos == 0) {
struct Node_t *temp = lst->head;
if (lst->tail == lst->head) {
lst->tail = NULL;
}
lst->head = lst->head->next;
temp->next = NULL;
free(temp);
lst->length--;
} else {
struct Node_t *temp = lst->head;
struct Node_t *rem;
size_t i = pos;
while (i-- > 1) {
temp = temp->next;
}
rem = temp->next;
if (rem == lst->tail) {
lst->tail = temp;
}
temp->next = rem->next;
rem->next = NULL;
free(rem);
lst->length--;
}
}
bool isAttacking(Position queen, Position pos) {
return queen.x == pos.x
|| queen.y == pos.y
|| abs(queen.x - pos.x) == abs(queen.y - pos.y);
}
bool place(int m, int n, List *pBlackQueens, List *pWhiteQueens) {
struct Node_t *queenNode;
bool placingBlack = true;
int i, j;
if (pBlackQueens == NULL || pWhiteQueens == NULL) {
exit(EXIT_FAILURE);
}
if (m == 0) return true;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
Position pos = { i, j };
queenNode = pBlackQueens->head;
while (queenNode != NULL) {
if ((queenNode->pos.x == pos.x && queenNode->pos.y == pos.y) || !placingBlack && isAttacking(queenNode->pos, pos)) {
goto inner;
}
queenNode = queenNode->next;
}
queenNode = pWhiteQueens->head;
while (queenNode != NULL) {
if ((queenNode->pos.x == pos.x && queenNode->pos.y == pos.y) || placingBlack && isAttacking(queenNode->pos, pos)) {
goto inner;
}
queenNode = queenNode->next;
}
if (placingBlack) {
addNode(pBlackQueens, pos);
placingBlack = false;
} else {
addNode(pWhiteQueens, pos);
if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {
return true;
}
removeAt(pBlackQueens, pBlackQueens->length - 1);
removeAt(pWhiteQueens, pWhiteQueens->length - 1);
placingBlack = true;
}
inner: {}
}
}
if (!placingBlack) {
removeAt(pBlackQueens, pBlackQueens->length - 1);
}
return false;
}
void printBoard(int n, List *pBlackQueens, List *pWhiteQueens) {
size_t length = n * n;
struct Node_t *queenNode;
char *board;
size_t i, j, k;
if (pBlackQueens == NULL || pWhiteQueens == NULL) {
exit(EXIT_FAILURE);
}
board = calloc(length, sizeof(char));
if (board == NULL) {
exit(EXIT_FAILURE);
}
queenNode = pBlackQueens->head;
while (queenNode != NULL) {
board[queenNode->pos.x * n + queenNode->pos.y] = Black;
queenNode = queenNode->next;
}
queenNode = pWhiteQueens->head;
while (queenNode != NULL) {
board[queenNode->pos.x * n + queenNode->pos.y] = White;
queenNode = queenNode->next;
}
for (i = 0; i < length; i++) {
if (i != 0 && i % n == 0) {
printf();
}
switch (board[i]) {
case Black:
printf();
break;
case White:
printf();
break;
default:
j = i / n;
k = i - j * n;
if (j % 2 == k % 2) {
printf();
} else {
printf();
}
break;
}
}
printf();
}
void test(int n, int q) {
List blackQueens = makeList();
List whiteQueens = makeList();
printf(, q, q, n, n);
if (place(q, n, &blackQueens, &whiteQueens)) {
printBoard(n, &blackQueens, &whiteQueens);
} else {
printf();
}
releaseList(&blackQueens);
releaseList(&whiteQueens);
}
int main() {
test(2, 1);
test(3, 1);
test(3, 2);
test(4, 1);
test(4, 2);
test(4, 3);
test(5, 1);
test(5, 2);
test(5, 3);
test(5, 4);
test(5, 5);
test(6, 1);
test(6, 2);
test(6, 3);
test(6, 4);
test(6, 5);
test(6, 6);
test(7, 1);
test(7, 2);
test(7, 3);
test(7, 4);
test(7, 5);
test(7, 6);
test(7, 7);
return EXIT_SUCCESS;
} | 462Peaceful chess queen armies
| 5c
| 8rb04 |
next.perm <- function(a) {
n <- length(a)
i <- n
while (i > 1 && a[i - 1] >= a[i]) i <- i - 1
if (i == 1) {
NULL
} else {
j <- i
k <- n
while (j < k) {
s <- a[j]
a[j] <- a[k]
a[k] <- s
j <- j + 1
k <- k - 1
}
s <- a[i - 1]
j <- i
while (a[j] <= s) j <- j + 1
a[i - 1] <- a[j]
a[j] <- s
a
}
}
perm <- function(n) {
e <- NULL
a <- 1:n
repeat {
e <- cbind(e, a)
a <- next.perm(a)
if (is.null(a)) break
}
unname(e)
} | 456Permutations
| 13r
| 9q3mg |
local PeanoLSystem = {
axiom = "L",
rules = {
L = "LFRFL-F-RFLFR+F+LFRFL",
R = "RFLFR+F+LFRFL-F-RFLFR"
},
eval = function(self, n)
local source, result = self.axiom
for i = 1, n do
result = ""
for j = 1, #source do
local ch = source:sub(j,j)
result = result .. (self.rules[ch] and self.rules[ch] or ch)
end
source = result
end
return result
end
}
function Bitmap:drawPath(path, x, y, dx, dy)
self:set(x, y, "@")
for i = 1, #path do
local ch = path:sub(i,i)
if (ch == "F") then
local reps = dx==0 and 1 or 3 | 459Peano curve
| 1lua
| 4d95c |
char* symbols[] = {, , ,
int length = DEFAULT_LENGTH;
int count = DEFAULT_COUNT;
unsigned seed;
char exSymbols = 0;
void GetPassword () {
int lengths[4] = {1, 1, 1, 1};
int count = 4;
while (count < length) {
lengths[rand()%4]++;
count++;
}
char password[length + 1];
for (int i = 0; i < length; ) {
int str = rand()%4;
if (!lengths[str])continue;
char c;
switch (str) {
case 2:
c = symbols[str][rand()%10];
while (exSymbols && (c == 'I' || c == 'l' || c == '1' || c == 'O' || c == '0' || c == '5' || c == 'S' || c == '2' || c == 'Z'))
c = symbols[str][rand()%10];
password[i] = c;
break;
case 3:
c = symbols[str][rand()%30];
while (exSymbols && (c == 'I' || c == 'l' || c == '1' || c == 'O' || c == '0' || c == '5' || c == 'S' || c == '2' || c == 'Z'))
c = symbols[str][rand()%30];
password[i] = c;
break;
default:
c = symbols[str][rand()%26];
while (exSymbols && (c == 'I' || c == 'l' || c == '1' || c == 'O' || c == '0' || c == '5' || c == 'S' || c == '2' || c == 'Z'))
c = symbols[str][rand()%26];
password[i] = c;
break;
}
i++;
lengths[str]--;
}
password [length] = '\0';
printf (, password);
}
int main (int argc, char* argv[]) {
seed = (unsigned)time(NULL);
for (int i = 1; i < argc; i++) {
switch (argv[i][1]) {
case 'l':
if (sscanf (argv[i+1], , &length) != 1) {
puts ();
return -1;
}
if (length < 4) {
puts ();
return -1;
}
i++;
break;
case 'c':
if (sscanf (argv[i+1], , &count) != 1) {
puts ();
return -1;
}
if (count <= 0) {
puts ();
return -1;
}
i++;
break;
case 's':
if (sscanf (argv[i+1], , &seed) != 1) {
puts ();
return -1;
}
i++;
break;
case 'e':
exSymbols = 1;
break;
default:
help:
printf (
);
return 0;
break;
}
}
srand (seed);
for (int i = 0; i < count; i++)
GetPassword();
return 0;
} | 463Password generator
| 5c
| s4jq5 |
import math
def solvePell(n):
x = int(math.sqrt(n))
y, z, r = x, 1, x << 1
e1, e2 = 1, 0
f1, f2 = 0, 1
while True:
y = r * z - y
z = (n - y * y)
r = (x + y)
e1, e2 = e2, e1 + e2 * r
f1, f2 = f2, f1 + f2 * r
a, b = f2 * x + e2, f2
if a * a - n * b * b == 1:
return a, b
for n in [61, 109, 181, 277]:
x, y = solvePell(n)
print(% (n, x, y)) | 458Pell's equation
| 3python
| j3u7p |
use strict;
use warnings;
use Tk;
my $size = 900;
my @particles;
my $maxparticles = 500;
my @colors = qw( red green blue yellow cyan magenta orange white );
my $mw = MainWindow->new;
my $c = $mw->Canvas( -width => $size, -height => $size, -bg => 'black',
)->pack;
$mw->Button(-text => 'Exit', -command => sub {$mw->destroy},
)->pack(-fill => 'x');
step();
MainLoop;
-M $0 < 0 and exec $0;
sub step
{
$c->delete('all');
$c->createLine($size / 2 - 10, $size, $size / 2, $size - 10,
$size / 2 + 10, $size, -fill => 'white' );
for ( @particles )
{
my ($ox, $oy, $vx, $vy, $color) = @$_;
my $x = $ox + $vx;
my $y = $oy + $vy;
$c->createRectangle($ox, $oy, $x, $y, -fill => $color, -outline => $color);
if( $y < $size )
{
$_->[0] = $x;
$_->[1] = $y;
$_->[3] += 0.006;
}
else { $_ = undef }
}
@particles = grep defined, @particles;
if( @particles < $maxparticles and --$| )
{
push @particles, [ $size >> 1, $size - 10,
(1 - rand 2) / 2.5 , -3 - rand 0.05, $colors[rand @colors] ];
}
$mw->after(1 => \&step);
} | 464Particle fountain
| 2perl
| fbad7 |
use SVG;
use List::Util qw(max min);
use constant pi => 2 * atan2(1, 0);
my %rules = (
L => 'LFRFL-F-RFLFR+F+LFRFL',
R => 'RFLFR+F+LFRFL-F-RFLFR'
);
my $peano = 'L';
$peano =~ s/([LR])/$rules{$1}/eg for 1..4;
($x, $y) = (0, 0);
$theta = pi/2;
$r = 4;
for (split //, $peano) {
if (/F/) {
push @X, sprintf "%.0f", $x;
push @Y, sprintf "%.0f", $y;
$x += $r * cos($theta);
$y += $r * sin($theta);
}
elsif (/\+/) { $theta += pi/2; }
elsif (/\-/) { $theta -= pi/2; }
}
$max = max(@X,@Y);
$xt = -min(@X)+10;
$yt = -min(@Y)+10;
$svg = SVG->new(width=>$max+20, height=>$max+20);
$points = $svg->get_path(x=>\@X, y=>\@Y, -type=>'polyline');
$svg->rect(width=>"100%", height=>"100%", style=>{'fill'=>'black'});
$svg->polyline(%$points, style=>{'stroke'=>'orange', 'stroke-width'=>1}, transform=>"translate($xt,$yt)");
open $fh, '>', 'peano_curve.svg';
print $fh $svg->xmlify(-namespace=>'svg');
close $fh; | 459Peano curve
| 2perl
| o7e8x |
package main
import "fmt"
import "math/rand"
func main(){
var a1,a2,a3,y,match,j,k int
var inp string
y=1
for y==1{
fmt.Println("Enter your sequence:")
fmt.Scanln(&inp)
var Ai [3] int
var user [3] int
for j=0;j<3;j++{
if(inp[j]==104){
user[j]=1
}else{
user[j]=0
}
}
for k=0;k<3;k++{
Ai[k]=rand.Intn(2)
}
for user[0]==Ai[0]&&user[1]==Ai[1]&&user[2]==Ai[2]{
for k=0;k<3;k++{
Ai[k]=rand.Intn(2)
}
}
fmt.Println("You gave the sequence:")
printht(user)
fmt.Println()
fmt.Println("The computer generated sequence is:")
printht(Ai)
fmt.Println()
a1=rand.Intn(2)
a2=rand.Intn(2)
a3=rand.Intn(2)
fmt.Print("The generated sequence is:")
printh(a1)
printh(a2)
printh(a3)
match=0
for match==0{
if(matches(user,a1,a2,a3)==1){
fmt.Println()
fmt.Println("You have won!!!")
match=1
}else if(matches(Ai,a1,a2,a3)==1){
fmt.Println()
fmt.Println("You lost!! Computer wins")
match=1
}else{
a1=a2
a2=a3
a3=rand.Intn(2)
printh(a3)
}
}
fmt.Println("Do you want to continue(0/1):")
fmt.Scanln(&y)
}
}
func printht(a [3] int) int{
var i int
for i=0;i<3;i++{
if(a[i]==1){
fmt.Print("h")
}else{
fmt.Print("t")
}
}
return 1
}
func printh(a int) int{
if(a==1){
fmt.Print("h")
}else{
fmt.Print("t")
}
return 1
}
func matches(a [3] int,p int,q int,r int) int{
if(a[0]==p&&a[1]==q&&a[2]==r){
return 1
}else{
return 0
}
} | 460Penney's game
| 0go
| bm5kh |
mpz_t* partition(uint64_t n) {
mpz_t *pn = (mpz_t *)malloc((n + 2) * sizeof(mpz_t));
mpz_init_set_ui(pn[0], 1);
mpz_init_set_ui(pn[1], 1);
for (uint64_t i = 2; i < n + 2; i ++) {
mpz_init(pn[i]);
for (uint64_t k = 1, penta; ; k++) {
penta = k * (3 * k - 1) >> 1;
if (penta >= i) break;
if (k & 1) mpz_add(pn[i], pn[i], pn[i - penta]);
else mpz_sub(pn[i], pn[i], pn[i - penta]);
penta += k;
if (penta >= i) break;
if (k & 1) mpz_add(pn[i], pn[i], pn[i - penta]);
else mpz_sub(pn[i], pn[i], pn[i - penta]);
}
}
mpz_t *tmp = &pn[n + 1];
for (uint64_t i = 0; i < n + 1; i ++) mpz_clear(pn[i]);
free(pn);
return tmp;
}
int main(int argc, char const *argv[]) {
clock_t start = clock();
mpz_t *p = partition(6666);
gmp_printf(, p);
printf(,
(double)(clock() - start) / (double)CLOCKS_PER_SEC);
return 0;
} | 465Partition function P
| 5c
| 1c2pj |
import qualified Data.List as L
import System.IO
import System.Random
data CoinToss = H | T deriving (Read, Show, Eq)
parseToss :: String -> [CoinToss]
parseToss [] = []
parseToss (s:sx)
| s == 'h' || s == 'H' = H: parseToss sx
| s == 't' || s == 'T' = T: parseToss sx
| otherwise = parseToss sx
notToss :: CoinToss -> CoinToss
notToss H = T
notToss T = H
instance Random CoinToss where
random g = let (b, gb) = random g in (if b then H else T, gb)
randomR = undefined
prompt :: (Read a) => String -> String -> (String -> Maybe a) -> IO a
prompt msg err parse = do
putStrLn msg
line <- getLine
let ans = parse line
case ans of
Nothing -> do
putStrLn err
prompt msg err parse
Just ansB -> return ansB
showCat :: (Show a) => [a] -> String
showCat = concatMap show
data Winner = Player | CPU
runToss :: (RandomGen g) => [CoinToss] -> [CoinToss] -> g -> ([CoinToss], Winner)
runToss player cpu gen =
let stream = randoms gen
run ss@(s:sx)
| L.isPrefixOf player ss = player
| L.isPrefixOf cpu ss = cpu
| otherwise = s: run sx
winner = run stream
in if L.isSuffixOf player winner
then (winner, Player)
else (winner, CPU)
game :: (RandomGen g, Num a, Show a) => Bool -> a -> a -> g -> IO ()
game cpuTurn playerScore cpuScore gen = do
putStrLn $ "\nThe current score is CPU: " ++ show cpuScore
++ ", You: " ++ show playerScore
let (genA, genB) = split gen
promptPlayer check =
prompt "Pick 3 coin sides: " "Invalid input." $ \s ->
let tosses = parseToss s in
if check tosses then Just tosses else Nothing
promptCpu x = putStrLn $ "I have chosen: " ++ showCat x
(tosses, winner) <-
if cpuTurn
then do
let cpuChoice = take 3 $ randoms gen
promptCpu cpuChoice
playerChoice <- promptPlayer $ \n -> n /= cpuChoice && 3 == length n
return $ runToss playerChoice cpuChoice genA
else do
playerChoice <- promptPlayer $ \n -> 3 == length n
let cpuChoice = case playerChoice of [a,b,_] -> [notToss b, a, b]
promptCpu cpuChoice
return $ runToss playerChoice cpuChoice genA
putStrLn $ "The sequence tossed was: " ++ showCat tosses
case winner of
Player -> do
putStrLn "You win!"
game (not cpuTurn) (playerScore + 1) cpuScore genB
CPU -> do
putStrLn "I win!"
game (not cpuTurn) playerScore (cpuScore + 1) genB
main :: IO ()
main = do
hSetBuffering stdin LineBuffering
stdgen <- getStdGen
let (cpuFirst, genA) = random stdgen
game cpuFirst 0 0 genA | 460Penney's game
| 8haskell
| dkxn4 |
package main
import (
"fmt"
"math/big"
)
func main() {
sequence()
bank()
rump()
}
func sequence() { | 461Pathological floating point problems
| 0go
| nhei1 |
void pascal(int a, int b, int mid, int top, int* x, int* y, int* z)
{
double ytemp = (top - 4 * (a + b)) / 7.;
if(fmod(ytemp, 1.) >= 0.0001)
{
x = 0;
return;
}
*y = ytemp;
*x = mid - 2 * a - *y;
*z = *y - *x;
}
int main()
{
int a = 11, b = 4, mid = 40, top = 151;
int x, y, z;
pascal(a, b, mid, top, &x, &y, &z);
if(x != 0)
printf(, x, y, z);
else printf();
return 0;
} | 466Pascal's triangle/Puzzle
| 5c
| tp1f4 |
def solve_pell(n)
x = Integer.sqrt(n)
y = x
z = 1
r = 2*x
e1, e2 = 1, 0
f1, f2 = 0, 1
loop do
y = r*z - y
z = (n - y*y) / z
r = (x + y) / z
e1, e2 = e2, r*e2 + e1
f1, f2 = f2, r*f2 + f1
a, b = e2 + x*f2, f2
break a, b if a*a - n*b*b == 1
end
end
[61, 109, 181, 277].each {|n| puts % [n, *solve_pell(n)]} | 458Pell's equation
| 14ruby
| ky4hg |
typedef struct bit_array_tag {
uint32_t size;
uint32_t* array;
} bit_array;
bool bit_array_create(bit_array* b, uint32_t size) {
uint32_t* array = calloc((size + 31)/32, sizeof(uint32_t));
if (array == NULL)
return false;
b->size = size;
b->array = array;
return true;
}
void bit_array_destroy(bit_array* b) {
free(b->array);
b->array = NULL;
}
void bit_array_set(bit_array* b, uint32_t index, bool value) {
assert(index < b->size);
uint32_t* p = &b->array[index >> 5];
uint32_t bit = 1 << (index & 31);
if (value)
*p |= bit;
else
*p &= ~bit;
}
bool bit_array_get(const bit_array* b, uint32_t index) {
assert(index < b->size);
uint32_t bit = 1 << (index & 31);
return (b->array[index >> 5] & bit) != 0;
}
typedef struct sieve_tag {
uint32_t limit;
bit_array not_prime;
} sieve;
bool sieve_create(sieve* s, uint32_t limit) {
if (!bit_array_create(&s->not_prime, limit + 1))
return false;
bit_array_set(&s->not_prime, 0, true);
bit_array_set(&s->not_prime, 1, true);
for (uint32_t p = 2; p * p <= limit; ++p) {
if (bit_array_get(&s->not_prime, p) == false) {
for (uint32_t q = p * p; q <= limit; q += p)
bit_array_set(&s->not_prime, q, true);
}
}
s->limit = limit;
return true;
}
void sieve_destroy(sieve* s) {
bit_array_destroy(&s->not_prime);
}
bool is_prime(const sieve* s, uint32_t n) {
assert(n <= s->limit);
return bit_array_get(&s->not_prime, n) == false;
}
bool find_prime_partition(const sieve* s, uint32_t number, uint32_t count,
uint32_t min_prime, uint32_t* p) {
if (count == 1) {
if (number >= min_prime && is_prime(s, number)) {
*p = number;
return true;
}
return false;
}
for (uint32_t prime = min_prime; prime < number; ++prime) {
if (!is_prime(s, prime))
continue;
if (find_prime_partition(s, number - prime, count - 1,
prime + 1, p + 1)) {
*p = prime;
return true;
}
}
return false;
}
void print_prime_partition(const sieve* s, uint32_t number, uint32_t count) {
assert(count > 0);
uint32_t* primes = malloc(count * sizeof(uint32_t));
if (primes == NULL) {
fprintf(stderr, );
return;
}
if (!find_prime_partition(s, number, count, 2, primes)) {
printf(, number, count);
} else {
printf(, number, primes[0]);
for (uint32_t i = 1; i < count; ++i)
printf(, primes[i]);
printf();
}
free(primes);
}
int main() {
const uint32_t limit = 100000;
sieve s = { 0 };
if (!sieve_create(&s, limit)) {
fprintf(stderr, );
return 1;
}
print_prime_partition(&s, 99809, 1);
print_prime_partition(&s, 18, 2);
print_prime_partition(&s, 19, 3);
print_prime_partition(&s, 20, 4);
print_prime_partition(&s, 2017, 24);
print_prime_partition(&s, 22699, 1);
print_prime_partition(&s, 22699, 2);
print_prime_partition(&s, 22699, 3);
print_prime_partition(&s, 22699, 4);
print_prime_partition(&s, 40355, 3);
sieve_destroy(&s);
return 0;
} | 467Partition an integer x into n primes
| 5c
| 288lo |
package main
import "fmt"
const (
empty = iota
black
white
)
const (
bqueen = 'B'
wqueen = 'W'
bbullet = ''
wbullet = ''
)
type position struct{ i, j int }
func iabs(i int) int {
if i < 0 {
return -i
}
return i
}
func place(m, n int, pBlackQueens, pWhiteQueens *[]position) bool {
if m == 0 {
return true
}
placingBlack := true
for i := 0; i < n; i++ {
inner:
for j := 0; j < n; j++ {
pos := position{i, j}
for _, queen := range *pBlackQueens {
if queen == pos || !placingBlack && isAttacking(queen, pos) {
continue inner
}
}
for _, queen := range *pWhiteQueens {
if queen == pos || placingBlack && isAttacking(queen, pos) {
continue inner
}
}
if placingBlack {
*pBlackQueens = append(*pBlackQueens, pos)
placingBlack = false
} else {
*pWhiteQueens = append(*pWhiteQueens, pos)
if place(m-1, n, pBlackQueens, pWhiteQueens) {
return true
}
*pBlackQueens = (*pBlackQueens)[0 : len(*pBlackQueens)-1]
*pWhiteQueens = (*pWhiteQueens)[0 : len(*pWhiteQueens)-1]
placingBlack = true
}
}
}
if !placingBlack {
*pBlackQueens = (*pBlackQueens)[0 : len(*pBlackQueens)-1]
}
return false
}
func isAttacking(queen, pos position) bool {
if queen.i == pos.i {
return true
}
if queen.j == pos.j {
return true
}
if iabs(queen.i-pos.i) == iabs(queen.j-pos.j) {
return true
}
return false
}
func printBoard(n int, blackQueens, whiteQueens []position) {
board := make([]int, n*n)
for _, queen := range blackQueens {
board[queen.i*n+queen.j] = black
}
for _, queen := range whiteQueens {
board[queen.i*n+queen.j] = white
}
for i, b := range board {
if i != 0 && i%n == 0 {
fmt.Println()
}
switch b {
case black:
fmt.Printf("%c ", bqueen)
case white:
fmt.Printf("%c ", wqueen)
case empty:
if i%2 == 0 {
fmt.Printf("%c ", bbullet)
} else {
fmt.Printf("%c ", wbullet)
}
}
}
fmt.Println("\n")
}
func main() {
nms := [][2]int{
{2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3},
{5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5},
{6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6},
{7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7},
}
for _, nm := range nms {
n, m := nm[0], nm[1]
fmt.Printf("%d black and%d white queens on a%d x%d board:\n", m, m, n, n)
var blackQueens, whiteQueens []position
if place(m, n, &blackQueens, &whiteQueens) {
printBoard(n, blackQueens, whiteQueens)
} else {
fmt.Println("No solution exists.\n")
}
}
} | 462Peaceful chess queen armies
| 0go
| 5n3ul |
(ns pwdgen.core
(:require [clojure.set:refer [difference]]
[clojure.tools.cli:refer [parse-opts]])
(:gen-class))
(def minimum-length 4)
(def cli-options
[["-c" "--count NUMBER" "Number of passwords to generate"
:default 1
:parse-fn #(Integer/parseInt %)]
["-l" "--length NUMBER" "Length of the generated passwords"
:default 8
:parse-fn #(Integer/parseInt %)
:validate [#(<= minimum-length %) (str "Must be greater than or equal to " minimum-length)]]
["-x", "--exclude-similar" "Exclude similar characters"]
["-h" "--help"]])
(def lowercase (map char (range (int \a) (inc (int \z)))))
(def uppercase (map char (range (int \A) (inc (int \Z)))))
(def numbers (map char (range (int \0) (inc (int \9)))))
(def specials (remove (set (concat lowercase uppercase numbers [\` \\])) (map char (range (int \!) (inc (int \~))))))
(def similar #{\I \l \1 \| \O \0 \5 \S \2 \Z})
(defn sanitize [coll options]
(if (:exclude-similar options) (into '() (difference (set coll) similar)) coll))
(defn generate-password [options]
(let [upper (rand-nth (sanitize uppercase options))
lower (rand-nth (sanitize lowercase options))
number (rand-nth (sanitize numbers options))
special (rand-nth (sanitize specials options))
combined (shuffle (sanitize (concat lowercase uppercase numbers specials) options))]
(shuffle (into (list upper lower number special) (take (- (:length options) minimum-length) combined)))))
(defn -main [& args]
(let [{:keys [options summary]} (parse-opts args cli-options)]
(if (:help options) (println summary)
(dotimes [n (:count options)]
(println (apply str (generate-password options))))))) | 463Password generator
| 6clojure
| nh1ik |
import java.util.*;
public class PenneysGame {
public static void main(String[] args) {
Random rand = new Random();
String compChoice = "", playerChoice;
if (rand.nextBoolean()) {
for (int i = 0; i < 3; i++)
compChoice += "HT".charAt(rand.nextInt(2));
System.out.printf("Computer chooses%s%n", compChoice);
playerChoice = prompt(compChoice);
} else {
playerChoice = prompt(compChoice);
compChoice = "T";
if (playerChoice.charAt(1) == 'T')
compChoice = "H";
compChoice += playerChoice.substring(0, 2);
System.out.printf("Computer chooses%s%n", compChoice);
}
String tossed = "";
while (true) {
tossed += "HT".charAt(rand.nextInt(2));
System.out.printf("Tossed%s%n" , tossed);
if (tossed.endsWith(playerChoice)) {
System.out.println("You win!");
break;
}
if (tossed.endsWith(compChoice)) {
System.out.println("Computer wins!");
break;
}
}
}
private static String prompt(String otherChoice) {
Scanner sc = new Scanner(System.in);
String s;
do {
System.out.print("Choose a sequence: ");
s = sc.nextLine().trim().toUpperCase();
} while (!s.matches("[HT]{3}") || s.equals(otherChoice));
return s;
}
} | 460Penney's game
| 9java
| s4bq0 |
use num_bigint::{ToBigInt, BigInt};
use num_traits::{Zero, One}; | 458Pell's equation
| 15rust
| bmgkx |
def pellFermat(n: Int): (BigInt,BigInt) = {
import scala.math.{sqrt, floor}
val x = BigInt(floor(sqrt(n)).toInt)
var i = 0 | 458Pell's equation
| 16scala
| alj1n |
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Peaceful {
enum Piece {
Empty,
Black,
White,
}
public static class Position {
public int x, y;
public Position(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Position) {
Position pos = (Position) obj;
return pos.x == x && pos.y == y;
}
return false;
}
}
private static boolean place(int m, int n, List<Position> pBlackQueens, List<Position> pWhiteQueens) {
if (m == 0) {
return true;
}
boolean placingBlack = true;
for (int i = 0; i < n; ++i) {
inner:
for (int j = 0; j < n; ++j) {
Position pos = new Position(i, j);
for (Position queen : pBlackQueens) {
if (pos.equals(queen) || !placingBlack && isAttacking(queen, pos)) {
continue inner;
}
}
for (Position queen : pWhiteQueens) {
if (pos.equals(queen) || placingBlack && isAttacking(queen, pos)) {
continue inner;
}
}
if (placingBlack) {
pBlackQueens.add(pos);
placingBlack = false;
} else {
pWhiteQueens.add(pos);
if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {
return true;
}
pBlackQueens.remove(pBlackQueens.size() - 1);
pWhiteQueens.remove(pWhiteQueens.size() - 1);
placingBlack = true;
}
}
}
if (!placingBlack) {
pBlackQueens.remove(pBlackQueens.size() - 1);
}
return false;
}
private static boolean isAttacking(Position queen, Position pos) {
return queen.x == pos.x
|| queen.y == pos.y
|| Math.abs(queen.x - pos.x) == Math.abs(queen.y - pos.y);
}
private static void printBoard(int n, List<Position> blackQueens, List<Position> whiteQueens) {
Piece[] board = new Piece[n * n];
Arrays.fill(board, Piece.Empty);
for (Position queen : blackQueens) {
board[queen.x + n * queen.y] = Piece.Black;
}
for (Position queen : whiteQueens) {
board[queen.x + n * queen.y] = Piece.White;
}
for (int i = 0; i < board.length; ++i) {
if ((i != 0) && i % n == 0) {
System.out.println();
}
Piece b = board[i];
if (b == Piece.Black) {
System.out.print("B ");
} else if (b == Piece.White) {
System.out.print("W ");
} else {
int j = i / n;
int k = i - j * n;
if (j % 2 == k % 2) {
System.out.print(" ");
} else {
System.out.print(" ");
}
}
}
System.out.println('\n');
}
public static void main(String[] args) {
List<Position> nms = List.of(
new Position(2, 1),
new Position(3, 1),
new Position(3, 2),
new Position(4, 1),
new Position(4, 2),
new Position(4, 3),
new Position(5, 1),
new Position(5, 2),
new Position(5, 3),
new Position(5, 4),
new Position(5, 5),
new Position(6, 1),
new Position(6, 2),
new Position(6, 3),
new Position(6, 4),
new Position(6, 5),
new Position(6, 6),
new Position(7, 1),
new Position(7, 2),
new Position(7, 3),
new Position(7, 4),
new Position(7, 5),
new Position(7, 6),
new Position(7, 7)
);
for (Position nm : nms) {
int m = nm.y;
int n = nm.x;
System.out.printf("%d black and%d white queens on a%d x%d board:\n", m, m, n, n);
List<Position> blackQueens = new ArrayList<>();
List<Position> whiteQueens = new ArrayList<>();
if (place(m, n, blackQueens, whiteQueens)) {
printBoard(n, blackQueens, whiteQueens);
} else {
System.out.println("No solution exists.\n");
}
}
}
} | 462Peaceful chess queen armies
| 9java
| bmvk3 |
import turtle as tt
import inspect
stack = []
def peano(iterations=1):
global stack
ivan = tt.Turtle(shape = , visible = True)
screen = tt.Screen()
screen.title()
screen.bgcolor()
screen.delay(0)
screen.setup(width=0.95, height=0.9)
walk = 1
def screenlength(k):
if k != 0:
length = screenlength(k-1)
return 2*length + 1
else: return 0
kkkj = screenlength(iterations)
screen.setworldcoordinates(-1, -1, kkkj + 1, kkkj + 1)
ivan.color(, )
def step1(k):
global stack
stack.append(len(inspect.stack()))
if k != 0:
ivan.left(90)
step2(k - 1)
ivan.forward(walk)
ivan.right(90)
step1(k - 1)
ivan.forward(walk)
step1(k - 1)
ivan.right(90)
ivan.forward(walk)
step2(k - 1)
ivan.left(90)
def step2(k):
global stack
stack.append(len(inspect.stack()))
if k != 0:
ivan.right(90)
step1(k - 1)
ivan.forward(walk)
ivan.left(90)
step2(k - 1)
ivan.forward(walk)
step2(k - 1)
ivan.left(90)
ivan.forward(walk)
step1(k - 1)
ivan.right(90)
ivan.left(90)
step2(iterations)
tt.done()
if __name__ == :
peano(4)
import pylab as P
P.plot(stack)
P.show() | 459Peano curve
| 3python
| ijwof |
null | 460Penney's game
| 11kotlin
| alr13 |
import java.math.BigDecimal;
import java.math.RoundingMode;
public class FPProblems {
public static void wrongConvergence() {
int[] INDEXES = new int[] { 3, 4, 5, 6, 7, 8, 20, 30, 50, 100 }; | 461Pathological floating point problems
| 9java
| mxiym |
(def bottom [ [0 1 0], [11 0 0], [0 1 1], [4 0 0], [0 0 1] ])
(defn plus [v1 v2] (vec (map + v1 v2)))
(defn minus [v1 v2] (vec (map - v1 v2)))
(defn scale [n v] (vec (map #(* n %) v )))
(defn above [row] (map #(apply plus %) (partition 2 1 row)))
(def rows (reverse (take 5 (iterate above bottom)))) | 466Pascal's triangle/Puzzle
| 6clojure
| mxqyq |
p [1,2,3].permutation.to_a | 456Permutations
| 14ruby
| 5nluj |
install.packages("BiocManager")
BiocManager::install("HilbertCurve")
library(HilbertCurve)
library(circlize)
set.seed(123)
for(i in 1:512) {
peano = HilbertCurve(1, 512, level = 4, reference = TRUE, arrow = FALSE)
hc_points(peano, x1 = i, np = NULL, pch = 16, size = unit(3, "mm"))
} | 459Peano curve
| 13r
| s4pqy |
function penny_game()
local player, computer = "", ""
function player_choose()
io.write( "Enter your sequence of three H and/or T: " )
local t = io.read():upper()
if #t > 3 then t = t:sub( 1, 3 )
elseif #t < 3 then return ""
end
for i = 1, 3 do
c = t:sub( i, i )
if c ~= "T" and c ~= "H" then
print( "Just H's and T's!" )
return ""
end
end
return t
end
function computer_choose()
local t = ""
if #player > 0 then
if player:sub( 2, 2 ) == "T" then
t = "H"
else
t = "T";
end
t = t .. player:sub( 1, 2 )
else
for i = 1, 3 do
if math.random( 2 ) == 1 then
t = t .. "H"
else
t = t .. "T"
end
end
end
return t
end
if math.random( 2 ) == 1 then
computer = computer_choose()
io.write( "My sequence is: " .. computer .. "\n" )
while( true ) do
player = player_choose()
if player:len() == 3 then break end
end
else
while( true ) do
player = player_choose()
if player:len() == 3 then break end
end
computer = computer_choose()
io.write( "My sequence is: " .. computer .. "\n" )
end
local coin, i = "", 1
while( true ) do
if math.random( 2 ) == 1 then
coin = coin .. "T"
io.write( "T" )
else
coin = coin .. "H"
io.write( "H" )
end
if #coin > 2 then
local seq = coin:sub( i, i + 2 )
i = i + 1
if seq == player then
print( "\nPlayer WINS!!!" )
return 1
elseif seq == computer then
print( "\nComputer WINS!!!" )
return -1
end
end
end
end
math.randomseed( os.time() )
local cpu, user = 0, 0
repeat
r = penny_game()
if r > 0 then
user = user + 1
else
cpu = cpu + 1
end
print( "Player: " .. user .. " CPU: " .. cpu )
io.write( "Play again (Y/N)? " )
r = io.read()
until( r == "N" or r == "n" ) | 460Penney's game
| 1lua
| e27ac |
func solvePell<T: BinaryInteger>(n: T, _ a: inout T, _ b: inout T) {
func swap(_ a: inout T, _ b: inout T, mul by: T) {
(a, b) = (b, b * by + a)
}
let x = T(Double(n).squareRoot())
var y = x
var z = T(1)
var r = x << 1
var e1 = T(1)
var e2 = T(0)
var f1 = T(0)
var f2 = T(1)
while true {
y = r * z - y
z = (n - y * y) / z
r = (x + y) / z
swap(&e1, &e2, mul: r)
swap(&f1, &f2, mul: r)
(a, b) = (f2, e2)
swap(&b, &a, mul: x)
if a * a - n * b * b == 1 {
return
}
}
}
var x = BigInt(0)
var y = BigInt(0)
for n in [61, 109, 181, 277] {
solvePell(n: BigInt(n), &x, &y)
print("x\u{00b2} - \(n)y\u{00b2} = 1 for x = \(x) and y = \(y)")
} | 458Pell's equation
| 17swift
| h65j0 |
import kotlin.math.abs
enum class Piece {
Empty,
Black,
White,
}
typealias Position = Pair<Int, Int>
fun place(m: Int, n: Int, pBlackQueens: MutableList<Position>, pWhiteQueens: MutableList<Position>): Boolean {
if (m == 0) {
return true
}
var placingBlack = true
for (i in 0 until n) {
inner@
for (j in 0 until n) {
val pos = Position(i, j)
for (queen in pBlackQueens) {
if (queen == pos || !placingBlack && isAttacking(queen, pos)) {
continue@inner
}
}
for (queen in pWhiteQueens) {
if (queen == pos || placingBlack && isAttacking(queen, pos)) {
continue@inner
}
}
placingBlack = if (placingBlack) {
pBlackQueens.add(pos)
false
} else {
pWhiteQueens.add(pos)
if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {
return true
}
pBlackQueens.removeAt(pBlackQueens.lastIndex)
pWhiteQueens.removeAt(pWhiteQueens.lastIndex)
true
}
}
}
if (!placingBlack) {
pBlackQueens.removeAt(pBlackQueens.lastIndex)
}
return false
}
fun isAttacking(queen: Position, pos: Position): Boolean {
return queen.first == pos.first
|| queen.second == pos.second
|| abs(queen.first - pos.first) == abs(queen.second - pos.second)
}
fun printBoard(n: Int, blackQueens: List<Position>, whiteQueens: List<Position>) {
val board = MutableList(n * n) { Piece.Empty }
for (queen in blackQueens) {
board[queen.first * n + queen.second] = Piece.Black
}
for (queen in whiteQueens) {
board[queen.first * n + queen.second] = Piece.White
}
for ((i, b) in board.withIndex()) {
if (i != 0 && i % n == 0) {
println()
}
if (b == Piece.Black) {
print("B ")
} else if (b == Piece.White) {
print("W ")
} else {
val j = i / n
val k = i - j * n
if (j % 2 == k % 2) {
print(" ")
} else {
print(" ")
}
}
}
println('\n')
}
fun main() {
val nms = listOf(
Pair(2, 1), Pair(3, 1), Pair(3, 2), Pair(4, 1), Pair(4, 2), Pair(4, 3),
Pair(5, 1), Pair(5, 2), Pair(5, 3), Pair(5, 4), Pair(5, 5),
Pair(6, 1), Pair(6, 2), Pair(6, 3), Pair(6, 4), Pair(6, 5), Pair(6, 6),
Pair(7, 1), Pair(7, 2), Pair(7, 3), Pair(7, 4), Pair(7, 5), Pair(7, 6), Pair(7, 7)
)
for ((n, m) in nms) {
println("$m black and $m white queens on a $n x $n board:")
val blackQueens = mutableListOf<Position>()
val whiteQueens = mutableListOf<Position>()
if (place(m, n, blackQueens, whiteQueens)) {
printBoard(n, blackQueens, whiteQueens)
} else {
println("No solution exists.\n")
}
}
} | 462Peaceful chess queen armies
| 11kotlin
| rtmgo |
package main
import (
"fmt"
"math/big"
"time"
)
var p []*big.Int
var pd []int
func partDiffDiff(n int) int {
if n&1 == 1 {
return (n + 1) / 2
}
return n + 1
}
func partDiff(n int) int {
if n < 2 {
return 1
}
pd[n] = pd[n-1] + partDiffDiff(n-1)
return pd[n]
}
func partitionsP(n int) {
if n < 2 {
return
}
psum := new(big.Int)
for i := 1; i <= n; i++ {
pdi := partDiff(i)
if pdi > n {
break
}
sign := int64(-1)
if (i-1)%4 < 2 {
sign = 1
}
t := new(big.Int).Mul(p[n-pdi], big.NewInt(sign))
psum.Add(psum, t)
}
p[n] = psum
}
func main() {
start := time.Now()
const N = 6666
p = make([]*big.Int, N+1)
pd = make([]int, N+1)
p[0], pd[0] = big.NewInt(1), 1
p[1], pd[1] = big.NewInt(1), 1
for n := 2; n <= N; n++ {
partitionsP(n)
}
fmt.Printf("p[%d)] =%d\n", N, p[N])
fmt.Printf("Took%s\n", time.Since(start))
} | 465Partition function P
| 0go
| ywq64 |
pub fn permutations(size: usize) -> Permutations {
Permutations { idxs: (0..size).collect(), swaps: vec![0; size], i: 0 }
}
pub struct Permutations {
idxs: Vec<usize>,
swaps: Vec<usize>,
i: usize,
}
impl Iterator for Permutations {
type Item = Vec<usize>;
fn next(&mut self) -> Option<Self::Item> {
if self.i > 0 {
loop {
if self.i >= self.swaps.len() { return None; }
if self.swaps[self.i] < self.i { break; }
self.swaps[self.i] = 0;
self.i += 1;
}
self.idxs.swap(self.i, (self.i & 1) * self.swaps[self.i]);
self.swaps[self.i] += 1;
}
self.i = 1;
Some(self.idxs.clone())
}
}
fn main() {
let perms = permutations(3).collect::<Vec<_>>();
assert_eq!(perms, vec![
vec![0, 1, 2],
vec![1, 0, 2],
vec![2, 0, 1],
vec![0, 2, 1],
vec![1, 2, 0],
vec![2, 1, 0],
]);
} | 456Permutations
| 15rust
| 4d25u |
load_library :grammar
class Peano
include Processing::Proxy
attr_reader :draw_length, :vec, :theta, :axiom, :grammar
DELTA = 60
def initialize(vec)
@axiom = 'XF'
rules = {
'X' => 'X+YF++YF-FX--FXFX-YF+',
'Y' => '-FX+YFYF++YF+FX--FX-Y'
}
@grammar = Grammar.new(axiom, rules)
@theta = 0
@draw_length = 100
@vec = vec
end
def generate(gen)
@draw_length = draw_length * 0.6**gen
grammar.generate gen
end
def translate_rules(prod)
coss = ->(orig, alpha, len) { orig + len * DegLut.cos(alpha) }
sinn = ->(orig, alpha, len) { orig - len * DegLut.sin(alpha) }
[].tap do |pts|
prod.scan(/./) do |ch|
case ch
when 'F'
pts << vec.copy
@vec = Vec2D.new(
coss.call(vec.x, theta, draw_length),
sinn.call(vec.y, theta, draw_length)
)
pts << vec
when '+'
@theta += DELTA
when '-'
@theta -= DELTA
when 'X', 'Y'
else
puts()
end
end
end
end
end
attr_reader :points
def setup
sketch_title 'Peano'
peano = Peano.new(Vec2D.new(width * 0.65, height * 0.9))
production = peano.generate 4
@points = peano.translate_rules(production)
no_loop
end
def draw
background(0)
render points
end
def render(points)
no_fill
stroke 200.0
stroke_weight 3
begin_shape
points.each_slice(2) do |v0, v1|
v0.to_vertex(renderer)
v1.to_vertex(renderer)
end
end_shape
end
def renderer
@renderer ||= GfxRender.new(g)
end
def settings
size(800, 800)
end | 459Peano curve
| 14ruby
| dkqns |
null | 461Pathological floating point problems
| 11kotlin
| tpqf0 |
import java.math.BigInteger;
public class PartitionFunction {
public static void main(String[] args) {
long start = System.currentTimeMillis();
BigInteger result = partitions(6666);
long end = System.currentTimeMillis();
System.out.println("P(6666) = " + result);
System.out.printf("elapsed time:%d milliseconds\n", end - start);
}
private static BigInteger partitions(int n) {
BigInteger[] p = new BigInteger[n + 1];
p[0] = BigInteger.ONE;
for (int i = 1; i <= n; ++i) {
p[i] = BigInteger.ZERO;
for (int k = 1; ; ++k) {
int j = (k * (3 * k - 1))/2;
if (j > i)
break;
if ((k & 1) != 0)
p[i] = p[i].add(p[i - j]);
else
p[i] = p[i].subtract(p[i - j]);
j += k;
if (j > i)
break;
if ((k & 1) != 0)
p[i] = p[i].add(p[i - j]);
else
p[i] = p[i].subtract(p[i - j]);
}
}
return p[n];
}
} | 465Partition function P
| 9java
| 5nfuf |
null | 459Peano curve
| 15rust
| fbsd6 |
use 5.020;
use strict;
use warnings;
binaryRand() == 0 ? flipCoin(userFirst()) : flipCoin(compFirst());
sub binaryRand
{
return int(rand(2));
}
sub convert
{
my $randNum = binaryRand();
if($randNum == 0)
{
return "T"
}
else
{
return "H";
}
}
sub uSeq
{
print("Please enter a sequence of 3 of \"H\" and \"T\". EG: HHT\n>");
my $uString = <STDIN>;
while(1)
{
chomp($uString);
$uString = uc $uString;
if(length $uString == 3 && (substr($uString, 0, 1) =~ /[HT]/ &&
substr($uString, 1, 1) =~ /[HT]/ &&
substr($uString, 2, 1) =~ /[HT]/))
{
last;
}
else
{
print("Error, try again. \n");
print("Please enter a sequence of 3 of \"H\" and \"T\". EG: HHT\n");
$uString = <STDIN>;
}
}
return $uString;
}
sub compFirst
{
my $cSeq;
for(my $i = 0; $i < 3; $i++)
{
$cSeq = $cSeq . convert();
}
print("The computer guesses first:\ncomp- $cSeq\n");
my $uSeq = uSeq();
print("user- $uSeq\n");
my @seqArr = ($uSeq, $cSeq);
return @seqArr;
}
sub userFirst
{
print("The user quesses first:\n");
my $uSeq = uSeq();
my $cSeq;
my $middle = substr($uSeq, 1, 1);
$middle eq "H" ? $cSeq = "T" : $cSeq = "H";
$cSeq = $cSeq . substr($uSeq, 0, 2);
print("user- $uSeq\ncomp- $cSeq\n");
my @seqArr = ($uSeq, $cSeq);
return @seqArr;
}
sub flipCoin
{
my ($uSeq, $cSeq) = @_;
my $coin;
while(1)
{
$coin = $coin . convert();
if($coin =~ m/$uSeq/)
{
print("The sequence of tosses was: $coin\n");
say("The player wins! ");
last;
}
elsif($coin =~ m/$cSeq/)
{
print("The sequence of tosses was: $coin\n");
say("The computer wins! ");
last;
}
}
} | 460Penney's game
| 2perl
| 9qdmn |
package main
import (
"fmt"
"log"
)
var (
primes = sieve(100000)
foundCombo = false
)
func sieve(limit uint) []uint {
primes := []uint{2}
c := make([]bool, limit+1) | 467Partition an integer x into n primes
| 0go
| q55xz |
function p(n){
var a = new Array(n+1)
a[0] = 1n
for (let i = 1; i <= n; i++){
a[i] = 0n
for (let k = 1, s = 1; s <= i;){
a[i] += (k & 1 ? a[i-s]:-a[i-s])
k > 0 ? (s += k, k = -k):(k = -k+1, s = k*(3*k-1)/2)
}
}
return a[n]
}
var t = Date.now()
console.log("p(6666) = " + p(6666))
console.log("Computation time in ms: ", Date.now() - t) | 465Partition function P
| 10javascript
| j3y7n |
package main
import "fmt" | 466Pascal's triangle/Puzzle
| 0go
| h6yjq |
use strict;
use warnings;
my $m = shift // 4;
my $n = shift // 5;
my %seen;
my $gaps = join '|', qr/-*/, map qr/.{$_}(?:-.{$_})*/s, $n-1, $n, $n+1;
my $attack = qr/(\w)(?:$gaps)(?!\1)\w/;
place( scalar ('-' x $n . "\n") x $n );
print "No solution to $m $n\n";
sub place
{
local $_ = shift;
$seen{$_}++ || /$attack/ and return;
(my $have = tr/WB//) < $m * 2 or exit !print "Solution to $m $n\n\n$_";
place( s/-\G/ qw(W B)[$have % 2] /er ) while /-/g;
} | 462Peaceful chess queen armies
| 2perl
| dkenw |
List(1, 2, 3).permutations.foreach(println) | 456Permutations
| 16scala
| 7z5r9 |
typedef int (*intfunc)(int);
typedef void (*pfunc)(int*, int);
pfunc partial(intfunc fin)
{
pfunc f;
static int idx = 0;
char cc[256], lib[256];
FILE *fp;
sprintf(lib, , ++idx);
sprintf(cc, , lib);
fp = popen(cc, );
fprintf(fp,
, fin);
fclose(fp);
*(void **)(&f) = dlsym(dlopen(lib, RTLD_LAZY), );
unlink(lib);
return f;
}
int square(int a)
{
return a * a;
}
int dbl(int a)
{
return a + a;
}
int main()
{
int x[] = { 1, 2, 3, 4 };
int y[] = { 1, 2, 3, 4 };
int i;
pfunc f = partial(square);
pfunc g = partial(dbl);
printf();
f(x, 4);
for (i = 0; i < 4; i++) printf(, x[i]);
printf();
g(y, 4);
for (i = 0; i < 4; i++) printf(, y[i]);
return 0;
} | 468Partial function application
| 5c
| p9mby |
import Data.List (delete, intercalate)
import Data.Numbers.Primes (primes)
import Data.Bool (bool)
partitions :: Int -> Int -> [Int]
partitions x n
| n <= 1 =
[ x
| x == last ps ]
| otherwise = go ps x n
where
ps = takeWhile (<= x) primes
go ps_ x 1 =
[ x
| x `elem` ps_ ]
go ps_ x n = ((flip bool [] . head) <*> null) (ps_ >>= found)
where
found p =
((flip bool [] . return . (p:)) <*> null)
((go =<< delete p . flip takeWhile ps_ . (>=)) (x - p) (pred n))
main :: IO ()
main =
mapM_ putStrLn $
(\(x, n) ->
intercalate
" -> "
[ justifyLeft 9 ' ' (show (x, n))
, let xs = partitions x n
in bool
(tail $ concatMap (('+':) . show) xs)
"(no solution)"
(null xs)
]) <$>
concat
[ [(99809, 1), (18, 2), (19, 3), (20, 4), (2017, 24)]
, (,) 22699 <$> [1 .. 4]
, [(40355, 3)]
]
justifyLeft :: Int -> Char -> String -> String
justifyLeft n c s = take n (s ++ replicate n c) | 467Partition an integer x into n primes
| 8haskell
| mxxyf |
data Memo a = Node a (Memo a) (Memo a)
deriving Functor
memo :: Integral a => Memo p -> a -> p
memo (Node a l r) n
| n == 0 = a
| odd n = memo l (n `div` 2)
| otherwise = memo r (n `div` 2 - 1)
nats :: Memo Int
nats = Node 0 ((+1).(*2) <$> nats) ((*2).(+1) <$> nats)
partitions :: Memo Integer
partitions = partitionP <$> nats
partitionP :: Int -> Integer
partitionP n
| n < 2 = 1
| otherwise = sum $ zipWith (*) signs terms
where
terms = [ memo partitions (n - i)
| i <- takeWhile (<= n) ofsets ]
signs = cycle [1,1,-1,-1]
ofsets = scanl1 (+) $ mix [1,3..] [1,2..]
where
mix a b = concat $ zipWith (\x y -> [x,y]) a b
main = print $ partitionP 6666 | 465Partition function P
| 8haskell
| h6mju |
puzzle = [["151"],["",""],["40","",""],["","","",""],["X","11","Y","4","Z"]] | 466Pascal's triangle/Puzzle
| 8haskell
| ijhor |
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class PascalsTrianglePuzzle {
public static void main(String[] args) {
Matrix mat = new Matrix(Arrays.asList(1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d, 0d),
Arrays.asList(0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),
Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 1d, -1d),
Arrays.asList(0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),
Arrays.asList(0d, 0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d),
Arrays.asList(1d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d),
Arrays.asList(0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d, 0d),
Arrays.asList(0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d),
Arrays.asList(0d, 0d, 0d, 0d, -1d, 0d, 1d, 0d, 0d, 0d, 0d),
Arrays.asList(0d, 0d, 0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d),
Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 1d, 1d, 0d, 0d, 0d));
List<Double> b = Arrays.asList(11d, 11d, 0d, 4d, 4d, 40d, 0d, 0d, 40d, 0d, 151d);
List<Double> solution = cramersRule(mat, b);
System.out.println("Solution = " + cramersRule(mat, b));
System.out.printf("X =%.2f%n", solution.get(8));
System.out.printf("Y =%.2f%n", solution.get(9));
System.out.printf("Z =%.2f%n", solution.get(10));
}
private static List<Double> cramersRule(Matrix matrix, List<Double> b) {
double denominator = matrix.determinant();
List<Double> result = new ArrayList<>();
for ( int i = 0 ; i < b.size() ; i++ ) {
result.add(matrix.replaceColumn(b, i).determinant() / denominator);
}
return result;
}
private static class Matrix {
private List<List<Double>> matrix;
@Override
public String toString() {
return matrix.toString();
}
@SafeVarargs
public Matrix(List<Double> ... lists) {
matrix = new ArrayList<>();
for ( List<Double> list : lists) {
matrix.add(list);
}
}
public Matrix(List<List<Double>> mat) {
matrix = mat;
}
public double determinant() {
if ( matrix.size() == 1 ) {
return get(0, 0);
}
if ( matrix.size() == 2 ) {
return get(0, 0) * get(1, 1) - get(0, 1) * get(1, 0);
}
double sum = 0;
double sign = 1;
for ( int i = 0 ; i < matrix.size() ; i++ ) {
sum += sign * get(0, i) * coFactor(0, i).determinant();
sign *= -1;
}
return sum;
}
private Matrix coFactor(int row, int col) {
List<List<Double>> mat = new ArrayList<>();
for ( int i = 0 ; i < matrix.size() ; i++ ) {
if ( i == row ) {
continue;
}
List<Double> list = new ArrayList<>();
for ( int j = 0 ; j < matrix.size() ; j++ ) {
if ( j == col ) {
continue;
}
list.add(get(i, j));
}
mat.add(list);
}
return new Matrix(mat);
}
private Matrix replaceColumn(List<Double> b, int column) {
List<List<Double>> mat = new ArrayList<>();
for ( int row = 0 ; row < matrix.size() ; row++ ) {
List<Double> list = new ArrayList<>();
for ( int col = 0 ; col < matrix.size() ; col++ ) {
double value = get(row, col);
if ( col == column ) {
value = b.get(row);
}
list.add(value);
}
mat.add(list);
}
return new Matrix(mat);
}
private double get(int row, int col) {
return matrix.get(row).get(col);
}
}
} | 466Pascal's triangle/Puzzle
| 9java
| xu5wy |
from itertools import combinations, product, count
from functools import lru_cache, reduce
_bbullet, _wbullet = '\u2022\u25E6'
_or = set.__or__
def place(m, n):
board = set(product(range(n), repeat=2))
placements = {frozenset(c) for c in combinations(board, m)}
for blacks in placements:
black_attacks = reduce(_or,
(queen_attacks_from(pos, n) for pos in blacks),
set())
for whites in {frozenset(c)
for c in combinations(board - black_attacks, m)}:
if not black_attacks & whites:
return blacks, whites
return set(), set()
@lru_cache(maxsize=None)
def queen_attacks_from(pos, n):
x0, y0 = pos
a = set([pos])
a.update((x, y0) for x in range(n))
a.update((x0, y) for y in range(n))
for x1 in range(n):
y1 = y0 -x0 +x1
if 0 <= y1 < n:
a.add((x1, y1))
y1 = y0 +x0 -x1
if 0 <= y1 < n:
a.add((x1, y1))
return a
def pboard(black_white, n):
if black_white is None:
blk, wht = set(), set()
else:
blk, wht = black_white
print(f
f, end='')
for x, y in product(range(n), repeat=2):
if y == 0:
print()
xy = (x, y)
ch = ('?' if xy in blk and xy in wht
else 'B' if xy in blk
else 'W' if xy in wht
else _bbullet if (x + y)%2 else _wbullet)
print('%s'% ch, end='')
print()
if __name__ == '__main__':
n=2
for n in range(2, 7):
print()
for m in count(1):
ans = place(m, n)
if ans[0]:
pboard(ans, n)
else:
print (f)
break
print('\n')
m, n = 5, 7
ans = place(m, n)
pboard(ans, n) | 462Peaceful chess queen armies
| 3python
| fbwde |
from __future__ import print_function
import random
from time import sleep
first = random.choice([True, False])
you = ''
if first:
me = ''.join(random.sample('HT'*3, 3))
print('I choose first and will win on first seeing {} in the list of tosses'.format(me))
while len(you) != 3 or any(ch not in 'HT' for ch in you) or you == me:
you = input('What sequence of three Heads/Tails will you win with: ')
else:
while len(you) != 3 or any(ch not in 'HT' for ch in you):
you = input('After you: What sequence of three Heads/Tails will you win with: ')
me = ('H' if you[1] == 'T' else 'T') + you[:2]
print('I win on first seeing {} in the list of tosses'.format(me))
print('Rolling:\n ', end='')
rolled = ''
while True:
rolled += random.choice('HT')
print(rolled[-1], end='')
if rolled.endswith(you):
print('\n You win!')
break
if rolled.endswith(me):
print('\n I win!')
break
sleep(1) | 460Penney's game
| 3python
| csf9q |
use bigrat;
@s = qw(2, -4);
for my $n (2..99) {
$s[$n]= 111.0 - 1130.0/$s[-1] + 3000.0/($s[-1]*$s[-2]);
}
for $n (3..8, 20, 30, 35, 50, 100) {
($nu,$de) = $s[$n-1] =~ m
printf "n =%3d%18.15f\n", $n, $nu/$de;
} | 461Pathological floating point problems
| 2perl
| kyvhc |
static unsigned int _parseDecimal ( const char** pchCursor )
{
unsigned int nVal = 0;
char chNow;
while ( chNow = **pchCursor, chNow >= '0' && chNow <= '9' )
{
nVal *= 10;
nVal += chNow - '0';
++*pchCursor;
}
return nVal;
}
static unsigned int _parseHex ( const char** pchCursor )
{
unsigned int nVal = 0;
char chNow;
while ( chNow = **pchCursor & 0x5f,
(chNow >= ('0'&0x5f) && chNow <= ('9'&0x5f)) ||
(chNow >= 'A' && chNow <= 'F')
)
{
unsigned char nybbleValue;
chNow -= 0x10;
nybbleValue = ( chNow > 9 ? chNow - (0x31-0x0a) : chNow );
nVal <<= 4;
nVal += nybbleValue;
++*pchCursor;
}
return nVal;
}
int ParseIPv4OrIPv6 ( const char** ppszText,
unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 )
{
unsigned char* abyAddrLocal;
unsigned char abyDummyAddr[16];
const char* pchColon = strchr ( *ppszText, ':' );
const char* pchDot = strchr ( *ppszText, '.' );
const char* pchOpenBracket = strchr ( *ppszText, '[' );
const char* pchCloseBracket = NULL;
int bIsIPv6local = NULL != pchOpenBracket || NULL == pchDot ||
( NULL != pchColon && ( NULL == pchDot || pchColon < pchDot ) );
if ( bIsIPv6local )
{
pchCloseBracket = strchr ( *ppszText, ']' );
if ( NULL != pchOpenBracket && ( NULL == pchCloseBracket ||
pchCloseBracket < pchOpenBracket ) )
return 0;
}
else
{
if ( NULL == pchDot || ( NULL != pchColon && pchColon < pchDot ) )
return 0;
}
if ( NULL != pbIsIPv6 )
*pbIsIPv6 = bIsIPv6local;
abyAddrLocal = abyAddr;
if ( NULL == abyAddrLocal )
abyAddrLocal = abyDummyAddr;
if ( ! bIsIPv6local )
{
unsigned char* pbyAddrCursor = abyAddrLocal;
unsigned int nVal;
const char* pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText );
if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )
return 0;
*(pbyAddrCursor++) = (unsigned char) nVal;
++(*ppszText);
pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText );
if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )
return 0;
*(pbyAddrCursor++) = (unsigned char) nVal;
++(*ppszText);
pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText );
if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )
return 0;
*(pbyAddrCursor++) = (unsigned char) nVal;
++(*ppszText);
pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText );
if ( nVal > 255 || pszTextBefore == *ppszText )
return 0;
*(pbyAddrCursor++) = (unsigned char) nVal;
if ( ':' == **ppszText && NULL != pnPort )
{
unsigned short usPortNetwork;
++(*ppszText);
pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText );
if ( nVal > 65535 || pszTextBefore == *ppszText )
return 0;
((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8;
((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff );
*pnPort = usPortNetwork;
return 1;
}
else
{
if ( NULL != pnPort )
*pnPort = 0;
return 1;
}
}
else
{
unsigned char* pbyAddrCursor;
unsigned char* pbyZerosLoc;
int bIPv4Detected;
int nIdx;
if ( NULL != pchOpenBracket )
*ppszText = pchOpenBracket + 1;
pbyAddrCursor = abyAddrLocal;
pbyZerosLoc = NULL;
bIPv4Detected = 0;
for ( nIdx = 0; nIdx < 8; ++nIdx )
{
const char* pszTextBefore = *ppszText;
unsigned nVal =_parseHex ( ppszText );
if ( pszTextBefore == *ppszText )
{
if ( NULL != pbyZerosLoc )
{
if ( pbyZerosLoc == pbyAddrCursor )
{
--nIdx;
break;
}
return 0;
}
if ( ':' != **ppszText )
return 0;
if ( 0 == nIdx )
{
++(*ppszText);
if ( ':' != **ppszText )
return 0;
}
pbyZerosLoc = pbyAddrCursor;
++(*ppszText);
}
else
{
if ( '.' == **ppszText )
{
const char* pszTextlocal = pszTextBefore;
unsigned char abyAddrlocal[16];
int bIsIPv6local;
int bParseResultlocal = ParseIPv4OrIPv6 ( &pszTextlocal, abyAddrlocal, NULL, &bIsIPv6local );
*ppszText = pszTextlocal;
if ( ! bParseResultlocal || bIsIPv6local )
return 0;
*(pbyAddrCursor++) = abyAddrlocal[0];
*(pbyAddrCursor++) = abyAddrlocal[1];
*(pbyAddrCursor++) = abyAddrlocal[2];
*(pbyAddrCursor++) = abyAddrlocal[3];
++nIdx;
bIPv4Detected = 1;
break;
}
if ( nVal > 65535 )
return 0;
*(pbyAddrCursor++) = nVal >> 8;
*(pbyAddrCursor++) = nVal & 0xff;
if ( ':' == **ppszText )
{
++(*ppszText);
}
else
{
break;
}
}
}
if ( NULL != pbyZerosLoc )
{
int nHead = (int)( pbyZerosLoc - abyAddrLocal );
int nTail = nIdx * 2 - (int)( pbyZerosLoc - abyAddrLocal );
int nZeros = 16 - nTail - nHead;
memmove ( &abyAddrLocal[16-nTail], pbyZerosLoc, nTail );
memset ( pbyZerosLoc, 0, nZeros );
}
if ( bIPv4Detected )
{
static const unsigned char abyPfx[] = { 0,0, 0,0, 0,0, 0,0, 0,0, 0xff,0xff };
if ( 0 != memcmp ( abyAddrLocal, abyPfx, sizeof(abyPfx) ) )
return 0;
}
if ( NULL != pchOpenBracket )
{
if ( ']' != **ppszText )
return 0;
++(*ppszText);
}
if ( ':' == **ppszText && NULL != pnPort )
{
const char* pszTextBefore;
unsigned int nVal;
unsigned short usPortNetwork;
++(*ppszText);
pszTextBefore = *ppszText;
pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText );
if ( nVal > 65535 || pszTextBefore == *ppszText )
return 0;
((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8;
((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff );
*pnPort = usPortNetwork;
return 1;
}
else
{
if ( NULL != pnPort )
*pnPort = 0;
return 1;
}
}
}
int ParseIPv4OrIPv6_2 ( const char* pszText,
unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 )
{
const char* pszTextLocal = pszText;
return ParseIPv4OrIPv6 ( &pszTextLocal, abyAddr, pnPort, pbIsIPv6);
} | 469Parse an IP Address
| 5c
| wvlec |
typedef struct node_
struct node_
\
node_
node_
node->value = v; \
node->left = node->right = 0; \
return node; \
} \
node_
node_
while (root) { \
if (root->value < n->value) \
if (!root->left) return root->left = n; \
else root = root->left; \
else \
if (!root->right) return root->right = n; \
else root = root->right; \
} \
return 0; \
}
decl_tree_type(double);
decl_tree_type(int);
int main()
{
int i;
tree_node(double) root_d = node_new(double, (double)rand() / RAND_MAX);
for (i = 0; i < 10000; i++)
node_insert(double, root_d, (double)rand() / RAND_MAX);
tree_node(int) root_i = node_new(int, rand());
for (i = 0; i < 10000; i++)
node_insert(int, root_i, rand());
return 0;
} | 470Parametric polymorphism
| 5c
| csw9c |
import java.util.Arrays;
import java.util.stream.IntStream;
public class PartitionInteger {
private static final int[] primes = IntStream.concat(IntStream.of(2), IntStream.iterate(3, n -> n + 2))
.filter(PartitionInteger::isPrime)
.limit(50_000)
.toArray();
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;
int d = 5;
while (d * d <= n) {
if (n % d == 0) return false;
d += 2;
if (n % d == 0) return false;
d += 4;
}
return true;
}
private static boolean findCombo(int k, int x, int m, int n, int[] combo) {
boolean foundCombo = false;
if (k >= m) {
if (Arrays.stream(combo).map(i -> primes[i]).sum() == x) {
String s = m > 1 ? "s" : "";
System.out.printf("Partitioned%5d with%2d prime%s: ", x, m, s);
for (int i = 0; i < m; ++i) {
System.out.print(primes[combo[i]]);
if (i < m - 1) System.out.print('+');
else System.out.println();
}
foundCombo = true;
}
} else {
for (int j = 0; j < n; ++j) {
if (k == 0 || j > combo[k - 1]) {
combo[k] = j;
if (!foundCombo) {
foundCombo = findCombo(k + 1, x, m, n, combo);
}
}
}
}
return foundCombo;
}
private static void partition(int x, int m) {
if (x < 2 || m < 1 || m >= x) {
throw new IllegalArgumentException();
}
int[] filteredPrimes = Arrays.stream(primes).filter(it -> it <= x).toArray();
int n = filteredPrimes.length;
if (n < m) throw new IllegalArgumentException("Not enough primes");
int[] combo = new int[m];
boolean foundCombo = findCombo(0, x, m, n, combo);
if (!foundCombo) {
String s = m > 1 ? "s" : " ";
System.out.printf("Partitioned%5d with%2d prime%s: (not possible)\n", x, m, s);
}
}
public static void main(String[] args) {
partition(99809, 1);
partition(18, 2);
partition(19, 3);
partition(20, 4);
partition(2017, 24);
partition(22699, 1);
partition(22699, 2);
partition(22699, 3);
partition(22699, 4);
partition(40355, 3);
}
} | 467Partition an integer x into n primes
| 9java
| fbbdv |
null | 466Pascal's triangle/Puzzle
| 11kotlin
| p9cb6 |
package main
import (
"crypto/rand"
"math/big"
"strings"
"flag"
"math"
"fmt"
)
var lowercase = "abcdefghijklmnopqrstuvwxyz"
var uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var numbers = "0123456789"
var signs = "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~"
var similar = "Il1O05S2Z"
func check(e error){
if e != nil {
panic(e)
}
}
func randstr(length int, alphastr string) string{
alphabet := []byte(alphastr)
pass := make([]byte,length)
for i := 0; i < length; i++ {
bign, err := rand.Int(rand.Reader, big.NewInt(int64(len(alphabet))))
check(err)
n := bign.Int64()
pass[i] = alphabet[n]
}
return string(pass)
}
func verify(pass string,checkUpper bool,checkLower bool, checkNumber bool, checkSign bool) bool{
isValid := true
if(checkUpper){
isValid = isValid && strings.ContainsAny(pass,uppercase)
}
if(checkLower){
isValid = isValid && strings.ContainsAny(pass,lowercase)
}
if(checkNumber){
isValid = isValid && strings.ContainsAny(pass,numbers)
}
if(checkSign){
isValid = isValid && strings.ContainsAny(pass,signs)
}
return isValid
}
func main() {
passCount := flag.Int("pc", 6, "Number of passwords")
passLength := flag.Int("pl", 10, "Passwordlength")
useUpper := flag.Bool("upper", true, "Enables or disables uppercase letters")
useLower := flag.Bool("lower", true, "Enables or disables lowercase letters")
useSign := flag.Bool("sign", true, "Enables or disables signs")
useNumbers := flag.Bool("number", true, "Enables or disables numbers")
useSimilar := flag.Bool("similar", true,"Enables or disables visually similar characters")
flag.Parse()
passAlphabet := ""
if *useUpper {
passAlphabet += uppercase
}
if *useLower {
passAlphabet += lowercase
}
if *useSign {
passAlphabet += signs
}
if *useNumbers {
passAlphabet += numbers
}
if !*useSimilar {
for _, r := range similar{
passAlphabet = strings.Replace(passAlphabet,string(r),"", 1)
}
}
fmt.Printf("Generating passwords with an average entropy of%.1f bits \n", math.Log2(float64(len(passAlphabet))) * float64(*passLength))
for i := 0; i < *passCount;i++{
passFound := false
pass := ""
for(!passFound){
pass = randstr(*passLength,passAlphabet)
passFound = verify(pass,*useUpper,*useLower,*useNumbers,*useSign)
}
fmt.Println(pass)
}
} | 463Password generator
| 0go
| vof2m |
penneysgame <- function() {
first <- sample(c("PC", "Human"), 1)
if (first == "PC") {
pc.seq <- sample(c("H", "T"), 3, replace = TRUE)
cat(paste("\nI choose first and will win on first seeing", paste(pc.seq, collapse = ""), "in the list of tosses.\n\n"))
human.seq <- readline("What sequence of three Heads/Tails will you win with: ")
human.seq <- unlist(strsplit(human.seq, ""))
} else if (first == "Human") {
cat(paste("\nYou can choose your winning sequence first.\n\n"))
human.seq <- readline("What sequence of three Heads/Tails will you win with: ")
human.seq <- unlist(strsplit(human.seq, ""))
pc.seq <- c(human.seq[2], human.seq[1:2])
pc.seq[1] <- ifelse(pc.seq[1] == "H", "T", "H")
cat(paste("\nI win on first seeing", paste(pc.seq, collapse = ""), "in the list of tosses.\n"))
}
cat("\nThrowing:\n")
ran.seq <- NULL
while(TRUE) {
ran.seq <- c(ran.seq, sample(c("H", "T"), 1))
cat("\n", paste(ran.seq, sep = "", collapse = ""))
if (length(ran.seq) >= 3 && all(tail(ran.seq, 3) == pc.seq)) {
cat("\n\nI win!\n")
break
}
if (length(ran.seq) >= 3 && all(tail(ran.seq, 3) == human.seq)) {
cat("\n\nYou win!\n")
break
}
Sys.sleep(0.5)
}
} | 460Penney's game
| 13r
| 6eo3e |
(defn fs [f s] (map f s))
(defn f1 [x] (* 2 x))
(defn f2 [x] (* x x))
(def fsf1 (partial fs f1))
(def fsf2 (partial fs f2))
(doseq [s [(range 4) (range 2 9 2)]]
(println "seq: " s)
(println " fsf1: " (fsf1 s))
(println " fsf2: " (fsf2 s))) | 468Partial function application
| 6clojure
| xuvwk |
use strict;
use warnings;
no warnings qw(recursion);
use Math::AnyNum qw(:overload);
use Memoize;
memoize('partitionsP');
memoize('partDiff');
sub partDiffDiff { my($n) = @_; $n%2 != 0 ? ($n+1)/2 : $n+1 }
sub partDiff { my($n) = @_; $n<2 ? 1 : partDiff($n-1) + partDiffDiff($n-1) }
sub partitionsP {
my($n) = @_;
return 1 if $n < 2;
my $psum = 0;
for my $i (1..$n) {
my $pd = partDiff($i);
last if $pd > $n;
if ( (($i-1)%4) < 2 ) { $psum += partitionsP($n-$pd) }
else { $psum -= partitionsP($n-$pd) }
}
return $psum
}
print partitionsP($_) . ' ' for 0..25; print "\n";
print partitionsP(6666) . "\n"; | 465Partition function P
| 2perl
| xu4w8 |
class Position
attr_reader :x, :y
def initialize(x, y)
@x = x
@y = y
end
def ==(other)
self.x == other.x &&
self.y == other.y
end
def to_s
'(%d,%d)' % [@x, @y]
end
def to_str
to_s
end
end
def isAttacking(queen, pos)
return queen.x == pos.x ||
queen.y == pos.y ||
(queen.x - pos.x).abs() == (queen.y - pos.y).abs()
end
def place(m, n, blackQueens, whiteQueens)
if m == 0 then
return true
end
placingBlack = true
for i in 0 .. n-1
for j in 0 .. n-1
catch :inner do
pos = Position.new(i, j)
for queen in blackQueens
if pos == queen ||!placingBlack && isAttacking(queen, pos) then
throw :inner
end
end
for queen in whiteQueens
if pos == queen || placingBlack && isAttacking(queen, pos) then
throw :inner
end
end
if placingBlack then
blackQueens << pos
placingBlack = false
else
whiteQueens << pos
if place(m - 1, n, blackQueens, whiteQueens) then
return true
end
blackQueens.pop
whiteQueens.pop
placingBlack = true
end
end
end
end
if!placingBlack then
blackQueens.pop
end
return false
end
def printBoard(n, blackQueens, whiteQueens)
board = Array.new(n) { Array.new(n) { ' ' } }
for i in 0 .. n-1
for j in 0 .. n-1
if i % 2 == j % 2 then
board[i][j] = ''
else
board[i][j] = ''
end
end
end
for queen in blackQueens
board[queen.y][queen.x] = 'B'
end
for queen in whiteQueens
board[queen.y][queen.x] = 'W'
end
for row in board
for cell in row
print cell, ' '
end
print
end
print
end
nms = [
[2, 1],
[3, 1], [3, 2],
[4, 1], [4, 2], [4, 3],
[5, 1], [5, 2], [5, 3], [5, 4], [5, 5],
[6, 1], [6, 2], [6, 3], [6, 4], [6, 5], [6, 6],
[7, 1], [7, 2], [7, 3], [7, 4], [7, 5], [7, 6], [7, 7]
]
for nm in nms
m = nm[1]
n = nm[0]
print % [m, m, n, n]
blackQueens = []
whiteQueens = []
if place(m, n, blackQueens, whiteQueens) then
printBoard(n, blackQueens, whiteQueens)
else
print
end
end | 462Peaceful chess queen armies
| 14ruby
| z1qtw |
import Control.Monad
import Control.Monad.Random
import Data.List
password :: MonadRandom m => [String] -> Int -> m String
password charSets n = do
parts <- getPartition n
chars <- zipWithM replicateM parts (uniform <$> charSets)
shuffle (concat chars)
where
getPartition n = adjust <$> replicateM (k-1) (getRandomR (1, n `div` k))
k = length charSets
adjust p = (n - sum p): p
shuffle :: (Eq a, MonadRandom m) => [a] -> m [a]
shuffle [] = pure []
shuffle lst = do
x <- uniform lst
xs <- shuffle (delete x lst)
return (x: xs) | 463Password generator
| 8haskell
| e24ai |
typedef struct {
const char *s;
int len, prec, assoc;
} str_tok_t;
typedef struct {
const char * str;
int assoc, prec;
regex_t re;
} pat_t;
enum assoc { A_NONE, A_L, A_R };
pat_t pat_eos = {, A_NONE, 0};
pat_t pat_ops[] = {
{, A_NONE, -1},
{, A_R, 3},
{, A_R, 3},
{, A_L, 2},
{, A_L, 2},
{, A_L, 1},
{, A_L, 1},
{0}
};
pat_t pat_arg[] = {
{},
{},
{, A_L, -1},
{0}
};
str_tok_t stack[256];
str_tok_t queue[256];
int l_queue, l_stack;
void display(const char *s)
{
int i;
printf(, s);
printf();
for (i = 0; i < l_stack; i++)
printf(, stack[i].len, stack[i].s);
printf();
for (i = 0; i < l_queue; i++)
printf(, queue[i].len, queue[i].s);
puts();
getchar();
}
int prec_booster;
int init(void)
{
int i;
pat_t *p;
for (i = 0, p = pat_ops; p[i].str; i++)
if (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))
fail(, p[i].str);
for (i = 0, p = pat_arg; p[i].str; i++)
if (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))
fail(, p[i].str);
return 1;
}
pat_t* match(const char *s, pat_t *p, str_tok_t * t, const char **e)
{
int i;
regmatch_t m;
while (*s == ' ') s++;
*e = s;
if (!*s) return &pat_eos;
for (i = 0; p[i].str; i++) {
if (regexec(&(p[i].re), s, 1, &m, REG_NOTEOL))
continue;
t->s = s;
*e = s + (t->len = m.rm_eo - m.rm_so);
return p + i;
}
return 0;
}
int parse(const char *s) {
pat_t *p;
str_tok_t *t, tok;
prec_booster = l_queue = l_stack = 0;
display(s);
while (*s) {
p = match(s, pat_arg, &tok, &s);
if (!p || p == &pat_eos) fail(, s);
if (p->prec == -1) {
prec_booster += 100;
continue;
}
qpush(tok);
display(s);
re_op: p = match(s, pat_ops, &tok, &s);
if (!p) fail(, s);
tok.assoc = p->assoc;
tok.prec = p->prec;
if (p->prec > 0)
tok.prec = p->prec + prec_booster;
else if (p->prec == -1) {
if (prec_booster < 100)
fail(, s);
tok.prec = prec_booster;
}
while (l_stack) {
t = stack + l_stack - 1;
if (!(t->prec == tok.prec && t->assoc == A_L)
&& t->prec <= tok.prec)
break;
qpush(spop());
display(s);
}
if (p->prec == -1) {
prec_booster -= 100;
goto re_op;
}
if (!p->prec) {
display(s);
if (prec_booster)
fail(, s);
return 1;
}
spush(tok);
display(s);
}
if (p->prec > 0)
fail(, s);
return 1;
}
int main()
{
int i;
const char *tests[] = {
,
,
,
,
,
,
,
0
};
if (!init()) return 1;
for (i = 0; tests[i]; i++) {
printf(, tests[i]);
getchar();
printf(, tests[i],
parse(tests[i]) ? : );
}
return 0;
} | 471Parsing/Shunting-yard algorithm
| 5c
| l0wcy |
char** components;
int counter = 0;
typedef struct elem{
char data[10];
struct elem* left;
struct elem* right;
}node;
typedef node* tree;
int precedenceCheck(char oper1,char oper2){
return (oper1==oper2)? 0:(oper1=='^')? 1:(oper2=='^')? 2:(oper1=='/')? 1:(oper2=='/')? 2:(oper1=='*')? 1:(oper2=='*')? 2:(oper1=='+')? 1:(oper2=='+')? 2:(oper1=='-')? 1:2;
}
int isOperator(char c){
return (c=='+'||c=='-'||c=='*'||c=='/'||c=='^');
}
void inorder(tree t){
if(t!=NULL){
if(t->left!=NULL && isOperator(t->left->data[0])==1 && (precedenceCheck(t->data[0],t->left->data[0])==1 || (precedenceCheck(t->data[0],t->left->data[0])==0 && t->data[0]=='^'))){
printf();
inorder(t->left);
printf();
}
else
inorder(t->left);
printf(,t->data);
if(t->right!=NULL && isOperator(t->right->data[0])==1 && (precedenceCheck(t->data[0],t->right->data[0])==1 || (precedenceCheck(t->data[0],t->right->data[0])==0 && t->data[0]!='^'))){
printf();
inorder(t->right);
printf();
}
else
inorder(t->right);
}
}
char* getNextString(){
if(counter<0){
printf();
exit(0);
}
return components[counter--];
}
tree buildTree(char* obj,char* trace){
tree t = (tree)malloc(sizeof(node));
strcpy(t->data,obj);
t->right = (isOperator(obj[0])==1)?buildTree(getNextString(),trace):NULL;
t->left = (isOperator(obj[0])==1)?buildTree(getNextString(),trace):NULL;
if(trace!=NULL){
printf();
inorder(t);
}
return t;
}
int checkRPN(){
int i, operSum = 0, numberSum = 0;
if(isOperator(components[counter][0])==0)
return 0;
for(i=0;i<=counter;i++)
(isOperator(components[i][0])==1)?operSum++:numberSum++;
return (numberSum - operSum == 1);
}
void buildStack(char* str){
int i;
char* token;
for(i=0;str[i]!=00;i++)
if(str[i]==' ')
counter++;
components = (char**)malloc((counter + 1)*sizeof(char*));
token = strtok(str,);
i = 0;
while(token!=NULL){
components[i] = (char*)malloc(strlen(token)*sizeof(char));
strcpy(components[i],token);
token = strtok(NULL,);
i++;
}
}
int main(int argC,char* argV[]){
int i;
tree t;
if(argC==1)
printf(,argV[0]);
else{
buildStack(argV[1]);
if(checkRPN()==0){
printf();
return 0;
}
t = buildTree(getNextString(),argV[2]);
printf();
inorder(t);
}
return 0;
} | 472Parsing/RPN to infix conversion
| 5c
| z1jtx |
null | 467Partition an integer x into n primes
| 11kotlin
| 8rr0q |
from fractions import Fraction
def muller_seq(n:int) -> float:
seq = [Fraction(0), Fraction(2), Fraction(-4)]
for i in range(3, n+1):
next_value = (111 - 1130/seq[i-1]
+ 3000/(seq[i-1]*seq[i-2]))
seq.append(next_value)
return float(seq[n])
for n in [3, 4, 5, 6, 7, 8, 20, 30, 50, 100]:
print(.format(n, muller_seq(n))) | 461Pathological floating point problems
| 3python
| bmukr |
int main()
{
int data[] = {12757923, 12878611, 12878893, 12757923, 15808973, 15780709, 197622519};
int largest, largest_factor = 0;
omp_set_num_threads(4);
for (int i = 0; i < 7; i++) {
int p, n = data[i];
for (p = 3; p * p <= n && n % p; p += 2);
if (p * p > n) p = n;
if (p > largest_factor) {
largest_factor = p;
largest = n;
printf(,
omp_get_thread_num(), p, n);
} else {
printf(,
omp_get_thread_num(), p, n);
}
}
printf(, largest_factor, largest);
return 0;
} | 473Parallel calculations
| 5c
| 6eh32 |
void pascal_low(int **mat, int n) {
int i, j;
for (i = 0; i < n; ++i)
for (j = 0; j < n; ++j)
if (i < j)
mat[i][j] = 0;
else if (i == j || j == 0)
mat[i][j] = 1;
else
mat[i][j] = mat[i - 1][j - 1] + mat[i - 1][j];
}
void pascal_upp(int **mat, int n) {
int i, j;
for (i = 0; i < n; ++i)
for (j = 0; j < n; ++j)
if (i > j)
mat[i][j] = 0;
else if (i == j || i == 0)
mat[i][j] = 1;
else
mat[i][j] = mat[i - 1][j - 1] + mat[i][j - 1];
}
void pascal_sym(int **mat, int n) {
int i, j;
for (i = 0; i < n; ++i)
for (j = 0; j < n; ++j)
if (i == 0 || j == 0)
mat[i][j] = 1;
else
mat[i][j] = mat[i - 1][j] + mat[i][j - 1];
}
int main(int argc, char * argv[]) {
int **mat;
int i, j, n;
n = 5;
mat = calloc(n, sizeof(int *));
for (i = 0; i < n; ++i)
mat[i] = calloc(n, sizeof(int));
printf();
pascal_upp(mat, n);
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
printf(, mat[i][j], j < n - 1 ? ' ' : '\n');
printf();
pascal_low(mat, n);
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
printf(, mat[i][j], j < n - 1 ? ' ' : '\n');
printf();
pascal_sym(mat, n);
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
printf(, mat[i][j], j < n - 1 ? ' ' : '\n');
return 0;
} | 474Pascal matrix generation
| 5c
| l01cy |
gcc example.c -lsqlite3 | 475Parameterized SQL statement
| 5c
| 7z0rg |
package main
import (
"encoding/hex"
"fmt"
"io"
"net"
"os"
"strconv"
"strings"
"text/tabwriter"
) | 469Parse an IP Address
| 0go
| csx9g |
class TreeNode<T> {
T value;
TreeNode<T> left;
TreeNode<T> right;
TreeNode(this.value);
TreeNode map(T f(T t)) {
var node = new TreeNode(f(value));
if(left!= null) {
node.left = left.map(f);
}
if(right!= null) {
node.right = right.map(f);
}
return node;
}
void forEach(void f(T t)) {
f(value);
if(left!= null) {
left.forEach(f);
}
if(right!= null) {
right.forEach(f);
}
}
}
void main() {
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.right = new TreeNode(4);
print('first tree');
root.forEach(print);
var newRoot = root.map((t) => t * 222);
print('second tree');
newRoot.forEach(print);
} | 470Parametric polymorphism
| 18dart
| z1kte |
enum Piece {
case empty, black, white
}
typealias Position = (Int, Int)
func place(_ m: Int, _ n: Int, pBlackQueens: inout [Position], pWhiteQueens: inout [Position]) -> Bool {
guard m!= 0 else {
return true
}
var placingBlack = true
for i in 0..<n {
inner: for j in 0..<n {
let pos = (i, j)
for queen in pBlackQueens where queen == pos ||!placingBlack && isAttacking(queen, pos) {
continue inner
}
for queen in pWhiteQueens where queen == pos || placingBlack && isAttacking(queen, pos) {
continue inner
}
if placingBlack {
pBlackQueens.append(pos)
placingBlack = false
} else {
placingBlack = true
pWhiteQueens.append(pos)
if place(m - 1, n, pBlackQueens: &pBlackQueens, pWhiteQueens: &pWhiteQueens) {
return true
} else {
pBlackQueens.removeLast()
pWhiteQueens.removeLast()
}
}
}
}
if!placingBlack {
pBlackQueens.removeLast()
}
return false
}
func isAttacking(_ queen: Position, _ pos: Position) -> Bool {
queen.0 == pos.0 || queen.1 == pos.1 || abs(queen.0 - pos.0) == abs(queen.1 - pos.1)
}
func printBoard(n: Int, pBlackQueens: [Position], pWhiteQueens: [Position]) {
var board = Array(repeating: Piece.empty, count: n * n)
for queen in pBlackQueens {
board[queen.0 * n + queen.1] = .black
}
for queen in pWhiteQueens {
board[queen.0 * n + queen.1] = .white
}
for (i, p) in board.enumerated() {
if i!= 0 && i% n == 0 {
print()
}
switch p {
case .black:
print("B ", terminator: "")
case .white:
print("W ", terminator: "")
case .empty:
let j = i / n
let k = i - j * n
if j% 2 == k% 2 {
print(" ", terminator: "")
} else {
print(" ", terminator: "")
}
}
}
print("\n")
}
let nms = [
(2, 1), (3, 1), (3, 2), (4, 1), (4, 2), (4, 3),
(5, 1), (5, 2), (5, 3), (5, 4), (5, 5),
(6, 1), (6, 2), (6, 3), (6, 4), (6, 5), (6, 6),
(7, 1), (7, 2), (7, 3), (7, 4), (7, 5), (7, 6), (7, 7)
]
for (n, m) in nms {
print("\(m) black and white queens on \(n) x \(n) board")
var blackQueens = [Position]()
var whiteQueens = [Position]()
if place(m, n, pBlackQueens: &blackQueens, pWhiteQueens: &whiteQueens) {
printBoard(n: n, pBlackQueens: blackQueens, pWhiteQueens: whiteQueens)
} else {
print("No solution")
}
} | 462Peaceful chess queen armies
| 17swift
| tpxfl |
import java.util.*;
public class PasswordGenerator {
final static Random rand = new Random();
public static void main(String[] args) {
int num, len;
try {
if (args.length != 2)
throw new IllegalArgumentException();
len = Integer.parseInt(args[0]);
if (len < 4 || len > 16)
throw new IllegalArgumentException();
num = Integer.parseInt(args[1]);
if (num < 1 || num > 10)
throw new IllegalArgumentException();
for (String pw : generatePasswords(num, len))
System.out.println(pw);
} catch (IllegalArgumentException e) {
String s = "Provide the length of the passwords (min 4, max 16) you "
+ "want to generate,\nand how many (min 1, max 10)";
System.out.println(s);
}
}
private static List<String> generatePasswords(int num, int len) {
final String s = "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~";
List<String> result = new ArrayList<>();
for (int i = 0; i < num; i++) {
StringBuilder sb = new StringBuilder();
sb.append(s.charAt(rand.nextInt(s.length())));
sb.append((char) (rand.nextInt(10) + '0'));
sb.append((char) (rand.nextInt(26) + 'a'));
sb.append((char) (rand.nextInt(26) + 'A'));
for (int j = 4; j < len; j++) {
int r = rand.nextInt(93) + '!';
if (r == 92 || r == 96) {
j--;
} else {
sb.append((char) r);
}
}
result.add(shuffle(sb));
}
return result;
}
public static String shuffle(StringBuilder sb) {
int len = sb.length();
for (int i = len - 1; i > 0; i--) {
int r = rand.nextInt(i);
char tmp = sb.charAt(i);
sb.setCharAt(i, sb.charAt(r));
sb.setCharAt(r, tmp);
}
return sb.toString();
}
} | 463Password generator
| 9java
| h6cjm |
Toss = [:Heads, :Tails]
def yourChoice
puts
choice = []
3.times do
until (c = $stdin.getc.upcase) == or c ==
end
choice << (c==? Toss[0]: Toss[1])
end
puts
choice
end
loop do
puts % [*Toss, coin = Toss.sample]
if coin == Toss[0]
myC = Toss.shuffle << Toss.sample
puts
yC = yourChoice
else
yC = yourChoice
myC = Toss - [yC[1]] + yC.first(2)
puts
end
seq = Array.new(3){Toss.sample}
print seq.join(' ')
loop do
puts or break if seq == myC
puts or break if seq == yC
seq.push(Toss.sample).shift
print
end
end | 460Penney's game
| 14ruby
| 28zlw |
typedef unsigned char byte;
int matches(byte *a, byte* b) {
for (int i = 0; i < 32; i++)
if (a[i] != b[i])
return 0;
return 1;
}
byte* StringHashToByteArray(const char* s) {
byte* hash = (byte*) malloc(32);
char two[3];
two[2] = 0;
for (int i = 0; i < 32; i++) {
two[0] = s[i * 2];
two[1] = s[i * 2 + 1];
hash[i] = (byte)strtol(two, 0, 16);
}
return hash;
}
void printResult(byte* password, byte* hash) {
char sPass[6];
memcpy(sPass, password, 5);
sPass[5] = 0;
printf(, sPass);
for (int i = 0; i < SHA256_DIGEST_LENGTH; i++)
printf(, hash[i]);
printf();
}
int main(int argc, char **argv)
{
{
for (int a = 0; a < 26; a++)
{
byte password[5] = { 97 + a };
byte* one = StringHashToByteArray();
byte* two = StringHashToByteArray();
byte* three = StringHashToByteArray();
for (password[1] = 97; password[1] < 123; password[1]++)
for (password[2] = 97; password[2] < 123; password[2]++)
for (password[3] = 97; password[3] < 123; password[3]++)
for (password[4] = 97; password[4] < 123; password[4]++) {
byte *hash = SHA256(password, 5, 0);
if (matches(one, hash) || matches(two, hash) || matches(three, hash))
printResult(password, hash);
}
free(one);
free(two);
free(three);
}
}
return 0;
} | 476Parallel brute force
| 5c
| fbud3 |
import Data.List (isInfixOf)
import Numeric (showHex)
import Data.Char (isDigit)
data IPChunk = IPv6Chunk String | IPv4Chunk (String, String) |
IPv6WithPort [IPChunk] String | IPv6NoPort [IPChunk] |
IPv4WithPort IPChunk String | IPv4NoPort IPChunk |
IPInvalid | IPZeroSection | IPUndefinedWithPort String |
IPUndefinedNoPort
instance Show IPChunk where
show (IPv6Chunk a) = a
show (IPv4Chunk (a,b)) = a ++ b
show (IPv6WithPort a p) = "IPv6 " ++ concatMap show a ++ " port " ++ p
show (IPv6NoPort a) = "IPv6 " ++ concatMap show a ++ " no port"
show (IPv4WithPort a p) = "IPv4 " ++ show a ++ " port " ++ p
show (IPv4NoPort a) = "IPv4 " ++ show a
show IPInvalid = "Invalid IP address"
isIPInvalid IPInvalid = True
isIPInvalid _ = False
isIPZeroSection IPZeroSection = True
isIPZeroSection _ = False
splitOn _ [] = []
splitOn x xs = let (a, b) = break (== x) xs in a: splitOn x (drop 1 b)
count x = length . filter (== x)
between a b x = x >= a && x <= b
none f = all (not . f)
parse1 [] = IPInvalid
parse1 "::" = IPUndefinedNoPort
parse1 ('[':':':':':']':':':ps) = if portIsValid ps then IPUndefinedWithPort ps else IPInvalid
parse1 ('[':xs) = if "]:" `isInfixOf` xs
then let (a, b) = break (== ']') xs in
if tail b == ":" then IPInvalid else IPv6WithPort (map chunk (splitOn ':' a)) (drop 2 b)
else IPInvalid
parse1 xs
| count ':' xs <= 1 && count '.' xs == 3 =
let (a, b) = break (== ':') xs in case b of
"" -> IPv4NoPort (chunk a)
(':':ps) -> IPv4WithPort (chunk a) ps
_ -> IPInvalid
| count ':' xs > 1 && count '.' xs <= 3 =
IPv6NoPort (map chunk (splitOn ':' xs))
chunk [] = IPZeroSection
chunk xs
| '.' `elem` xs = case splitOn '.' xs of
[a,b,c,d] -> let [e,f,g,h] = map read [a,b,c,d]
in if all (between 0 255) [e,f,g,h]
then let [i,j,k,l] = map (\n -> fill 2 $ showHex n "") [e,f,g,h]
in IPv4Chunk (i ++ j, k ++ l)
else IPInvalid
| ':' `notElem` xs && between 1 4 (length xs) && all (`elem` "0123456789abcdef") xs = IPv6Chunk (fill 4 xs)
| otherwise = IPInvalid
fill n xs = replicate (n - length xs) '0' ++ xs
parse2 IPInvalid = IPInvalid
parse2 (IPUndefinedWithPort p) = IPv6WithPort (replicate 8 zeroChunk) p
parse2 IPUndefinedNoPort = IPv6NoPort (replicate 8 zeroChunk)
parse2 a = case a of
IPv6WithPort xs p -> if none isIPInvalid xs && portIsValid p
then let ys = complete xs
in if countChunks ys == 8
then IPv6WithPort ys p
else IPInvalid
else IPInvalid
IPv6NoPort xs -> if none isIPInvalid xs
then let ys = complete xs
in if countChunks ys == 8
then IPv6NoPort ys
else IPInvalid
else IPInvalid
IPv4WithPort (IPv4Chunk a) p -> if portIsValid p
then IPv4WithPort (IPv4Chunk a) p
else IPInvalid
IPv4NoPort (IPv4Chunk a) -> IPv4NoPort (IPv4Chunk a)
_ -> IPInvalid
zeroChunk = IPv6Chunk "0000"
portIsValid a = all isDigit a && between 0 65535 (read a)
complete xs = case break isIPZeroSection xs of
(_, [IPZeroSection]) -> []
(ys, []) -> ys
([], (IPZeroSection:IPZeroSection:ys)) -> if any isIPZeroSection ys || countChunks ys > 7
then []
else replicate (8 - countChunks ys) zeroChunk ++ ys
(ys, (IPZeroSection:zs)) -> if any isIPZeroSection zs || countChunks ys + countChunks zs > 7
then []
else ys ++ replicate (8 - countChunks ys - countChunks zs) zeroChunk ++ zs
_ -> []
countChunks xs = foldl f 0 xs
where f n (IPv4Chunk _) = n + 2
f n (IPv6Chunk _) = n + 1
ip = parse2 . parse1
main = mapM_ (putStrLn . show . ip)
["127.0.0.1",
"127.0.0.1:80",
"::1",
"[::1]:80",
"2605:2700:0:3::4713:93e3",
"[2605:2700:0:3::4713:93e3]:80"] | 469Parse an IP Address
| 8haskell
| p9ybt |
from itertools import islice
def posd():
count, odd = 1, 3
while True:
yield count
yield odd
count, odd = count + 1, odd + 2
def pos_gen():
val = 1
diff = posd()
while True:
yield val
val += next(diff)
def plus_minus():
n, sign = 0, [1, 1]
p_gen = pos_gen()
out_on = next(p_gen)
while True:
n += 1
if n == out_on:
next_sign = sign.pop(0)
if not sign:
sign = [-next_sign] * 2
yield -n, next_sign
out_on = next(p_gen)
else:
yield 0
def part(n):
p = [1]
p_m = plus_minus()
mods = []
for _ in range(n):
next_plus_minus = next(p_m)
if next_plus_minus:
mods.append(next_plus_minus)
p.append(sum(p[offset] * sign for offset, sign in mods))
return p[-1]
print()
print(, list(islice(posd(), 10)))
print(, list(islice(pos_gen(), 10)))
print(, list(islice(plus_minus(), 15)))
print(, [part(x) for x in range(15)]) | 465Partition function P
| 3python
| q5gxi |
String.prototype.shuffle = function() {
return this.split('').sort(() => Math.random() - .5).join('');
}
function createPwd(opts = {}) {
let len = opts.len || 5, | 463Password generator
| 10javascript
| al510 |
func perms<T>(var ar: [T]) -> [[T]] {
return heaps(&ar, ar.count)
}
func heaps<T>(inout ar: [T], n: Int) -> [[T]] {
return n == 1? [ar]:
Swift.reduce(0..<n, [[T]]()) {
(var shuffles, i) in
shuffles.extend(heaps(&ar, n - 1))
swap(&ar[n% 2 == 0? i: 0], &ar[n - 1])
return shuffles
}
}
perms([1, 2, 3]) | 456Permutations
| 17swift
| uicvg |
extern crate rand;
use std::io::{stdin, stdout, Write};
use std::thread;
use std::time::Duration;
use rand::Rng;
fn toss_coin<R: Rng>(rng: &mut R, print: bool) -> char {
let c = if rng.gen() { 'H' } else { 'T' };
if print {
print!("{}", c);
stdout().flush().expect("Could not flush stdout");
}
c
}
fn gen_sequence<R: Rng>(rng: &mut R, seed: Option<&str>) -> String {
let mut seq = String::new();
match seed {
Some(s) => {
let mut iter = s.chars();
let c0 = iter.next().unwrap();
let next = if c0 == 'H' { 'T' } else { 'H' };
seq.push(next);
seq.push(c0);
seq.push(iter.next().unwrap());
}
None => {
for _ in 0..3 {
seq.push(toss_coin(rng, false))
}
}
}
seq
}
fn read_sequence(used_seq: Option<&str>) -> String {
let mut seq = String::new();
loop {
seq.clear();
println!("Please, enter sequence of 3 coins: H (heads) or T (tails): ");
stdin().read_line(&mut seq).expect("failed to read line");
seq = seq.trim().to_uppercase(); | 460Penney's game
| 15rust
| vo32t |
package main
import "fmt"
func average(c intCollection) float64 {
var sum, count int
c.mapElements(func(n int) {
sum += n
count++
})
return float64(sum) / float64(count)
}
func main() {
t1 := new(binaryTree)
t2 := new(bTree)
a1 := average(t1)
a2 := average(t2)
fmt.Println("binary tree average:", a1)
fmt.Println("b-tree average:", a2)
}
type intCollection interface {
mapElements(func(int))
}
type binaryTree struct { | 470Parametric polymorphism
| 0go
| wvceg |
class Tree<T> {
T value
Tree<T> left
Tree<T> right
Tree(T value = null, Tree<T> left = null, Tree<T> right = null) {
this.value = value
this.left = left
this.right = right
}
void replaceAll(T value) {
this.value = value
left?.replaceAll(value)
right?.replaceAll(value)
}
} | 470Parametric polymorphism
| 7groovy
| bm3ky |
use ntheory ":all";
sub prime_partition {
my($num, $parts) = @_;
return is_prime($num) ? [$num] : undef if $parts == 1;
my @p = @{primes($num)};
my $r;
forcomb { lastfor, $r = [@p[@_]] if vecsum(@p[@_]) == $num; } @p, $parts;
$r;
}
foreach my $test ([18,2], [19,3], [20,4], [99807,1], [99809,1], [2017,24], [22699,1], [22699,2], [22699,3], [22699,4], [40355,3]) {
my $partar = prime_partition(@$test);
printf "Partition%5d into%2d prime piece%s%s\n", $test->[0], $test->[1], ($test->[1] == 1) ? ": " : "s:", defined($partar) ? join("+",@$partar) : "not possible";
} | 467Partition an integer x into n primes
| 2perl
| 4dd5d |
my $rows = 5;
my @tri = map { [ map { {x=>0,z=>0,v=>0,rhs=>undef} } 1..$_ ] } 1..$rows;
$tri[0][0]{rhs} = 151;
$tri[2][0]{rhs} = 40;
$tri[4][0]{x} = 1;
$tri[4][1]{v} = 11;
$tri[4][2]{x} = 1;
$tri[4][2]{z} = 1;
$tri[4][3]{v} = 4;
$tri[4][4]{z} = 1;
for my $row ( reverse 0..@tri-2 ) {
for my $col ( 0..@{$tri[$row]}-1 ){
$tri[$row][$col]{$_} = $tri[$row+1][$col]{$_}+$tri[$row+1][$col+1]{$_} for 'x','z','v';
}
}
my @eqn;
for my $row ( @tri ) {
for my $col ( @$row ){
push @eqn, [ $$col{x}, $$col{z}, $$col{rhs}-$$col{v} ] if defined $$col{rhs};
}
}
print "Equations:\n";
print " x + z = y\n";
printf "%d x +%d z =%d\n", @$_ for @eqn;
my $f = $eqn[0][1] / $eqn[1][1];
$eqn[0][$_] -= $f * $eqn[1][$_] for 0..2;
$f = $eqn[1][0] / $eqn[0][0];
$eqn[1][$_] -= $f * $eqn[0][$_] for 0..2;
print "Solution:\n";
my $x = $eqn[0][2]/$eqn[0][0];
my $z = $eqn[1][2]/$eqn[1][1];
my $y = $x+$z;
printf "x=%d, y=%d, z=%d\n", $x, $y, $z; | 466Pascal's triangle/Puzzle
| 2perl
| ywx6u |
(use '[clojure.contrib.lazy-seqs:only [primes]])
(defn lpf [n]
[n (or (last
(for [p (take-while #(<= (* % %) n) primes)
:when (zero? (rem n p))]
p))
1)])
(->> (range 2 100000)
(pmap lpf)
(apply max-key second)
println
time) | 473Parallel calculations
| 6clojure
| l0acb |
int pancake(int n) {
int gap = 2, sum = 2, adj = -1;
while (sum < n) {
adj++;
gap = gap * 2 - 1;
sum += gap;
}
return n + adj;
}
int main() {
int i, j;
for (i = 0; i < 4; i++) {
for (j = 1; j < 6; j++) {
int n = i * 5 + j;
printf(, n, pancake(n));
}
printf();
}
return 0;
} | 477Pancake numbers
| 5c
| 0gyst |
(defn binomial-coeff [n k]
(reduce #(quot (* %1 (inc (- n %2))) %2)
1
(range 1 (inc k))))
(defn pascal-upper [n]
(map
(fn [i]
(map (fn [j]
(binomial-coeff j i))
(range n)))
(range n)))
(defn pascal-lower [n]
(map
(fn [i]
(map (fn [j]
(binomial-coeff i j))
(range n)))
(range n)))
(defn pascal-symmetric [n]
(map
(fn [i]
(map (fn [j]
(binomial-coeff (+ i j) i))
(range n)))
(range n)))
(defn pascal-matrix [n]
(println "Upper:")
(run! println (pascal-upper n))
(println)
(println "Lower:")
(run! println (pascal-lower n))
(println)
(println "Symmetric:")
(run! println (pascal-symmetric n))) | 474Pascal matrix generation
| 6clojure
| 4dq5o |
(require '[clojure.java.jdbc:as sql])
(def db {:classname "org.h2.Driver"
:subprotocol "h2:file"
:subname "db/my-dbname"})
(sql/update! db:players {:name "Smith, Steve":score 42:active true} ["jerseyNum =?" 99])
(sql/execute! db ["UPDATE players SET name =?, score =?, active =? WHERE jerseyNum =?" "Smith, Steve" 42 true 99]) | 475Parameterized SQL statement
| 6clojure
| p9dbd |
data Tree a = Empty | Node a (Tree a) (Tree a)
mapTree :: (a -> b) -> Tree a -> Tree b
mapTree f Empty = Empty
mapTree f (Node x l r) = Node (f x) (mapTree f l) (mapTree f r) | 470Parametric polymorphism
| 8haskell
| 6ep3k |
package main
import "fmt" | 468Partial function application
| 0go
| 6ea3p |
null | 465Partition function P
| 15rust
| 8rj07 |
import BigInt
func partitions(n: Int) -> BigInt {
var p = [BigInt(1)]
for i in 1...n {
var num = BigInt(0)
var k = 1
while true {
var j = (k * (3 * k - 1)) / 2
if j > i {
break
}
if k & 1 == 1 {
num += p[i - j]
} else {
num -= p[i - j]
}
j += k
if j > i {
break
}
if k & 1 == 1 {
num += p[i - j]
} else {
num -= p[i - j]
}
k += 1
}
p.append(num)
}
return p[n]
}
print("partitions(6666) = \(partitions(n: 6666))") | 465Partition function P
| 17swift
| s4rqt |
null | 463Password generator
| 11kotlin
| 4d357 |
ar = [0, 2, -4]
100.times{ar << (111 - 1130.quo(ar[-1])+ 3000.quo(ar[-1]*ar[-2])) }
[3, 4, 5, 6, 7, 8, 20, 30, 50, 100].each do |n|
puts % [n, ar[n]]
end | 461Pathological floating point problems
| 14ruby
| 1c4pw |
(ns rosetta.brute-force
(:require [clojure.math.combinatorics:refer [selections]])
(:import [java.util Arrays]
[java.security MessageDigest]))
(def targets
["1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad"
"3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b"
"74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f"])
(defn digest
"Given a byte-array <bs> returns its hash (also a byte-array)."
^bytes [^MessageDigest md ^bytes bs]
(.digest md bs))
(defn char-range
"Helper fn for easily producing character ranges."
[start end]
(map char (range (int start)
(inc (int end)))))
(def low-case-eng-bytes
"Our search-space (all lower case english characters converted to bytes)."
(map byte (char-range \a \z)))
(defn hex->bytes
"Converts a hex string to a byte-array."
^bytes [^String hex]
(let [len (.length hex)
ret (byte-array (/ len 2))]
(run! (fn [i]
(aset ret
(/ i 2)
^byte (unchecked-add-int
(bit-shift-left
(Character/digit (.charAt hex i) 16)
4)
(Character/digit (.charAt hex (inc i)) 16))))
(range 0 len 2))
ret))
(defn bytes->hex
"Converts a byte-array to a hex string."
[^bytes bs]
(.toString
^StringBuilder
(areduce bs idx ret (StringBuilder.)
(doto ret (.append (format "%02x" (aget bs idx)))))))
(defn check-candidate
"Checks whether the SHA256 hash of <candidate> (a list of 5 bytes),
matches <target>. If it does, returns that hash as a hex-encoded String.
Otherwise returns nil."
[^bytes target sha256 candidate]
(let [candidate-bytes (byte-array candidate)
^bytes candidate-hash (sha256 candidate-bytes)]
(when (Arrays/equals target candidate-hash)
(let [answer (String. candidate-bytes)]
(println "Answer found for:" (bytes->hex candidate-hash) "=>" answer)
answer))))
(defn sha256-brute-force
"Top level function. Returns a list with the 3 answers."
[space hex-hashes]
(->> hex-hashes
(map hex->bytes)
(pmap
(fn [target-bytes]
(let [message-digest (MessageDigest/getInstance "SHA-256")
sha256 (partial digest message-digest)]
(some (partial check-candidate target-bytes sha256)
(selections space 5))))))) | 476Parallel brute force
| 6clojure
| yw76b |
typedef unsigned long long xint;
xint rooted[MAX_N] = {1, 1, 0};
xint unrooted[MAX_N] = {1, 1, 0};
xint choose(xint m, xint k)
{
xint i, r;
if (k == 1) return m;
for (r = m, i = 1; i < k; i++)
r = r * (m + i) / (i + 1);
return r;
}
void tree(xint br, xint n, xint cnt, xint sum, xint l)
{
xint b, c, m, s;
for (b = br + 1; b <= BRANCH; b++) {
s = sum + (b - br) * n;
if (s >= MAX_N) return;
c = choose(rooted[n], b - br) * cnt;
if (l * 2 < s) unrooted[s] += c;
if (b == BRANCH) return;
rooted[s] += c;
for (m = n; --m; ) tree(b, m, c, s, l);
}
}
void bicenter(int s)
{
if (s & 1) return;
unrooted[s] += rooted[s/2] * (rooted[s/2] + 1) / 2;
}
int main()
{
xint n;
for (n = 1; n < MAX_N; n++) {
tree(0, n, 1, 1, n);
bicenter(n);
printf(FMTFMT, n, unrooted[n]);
}
return 0;
} | 478Paraffins
| 5c
| dklnv |
package main
import (
"database/sql"
"fmt"
_ "github.com/mattn/go-sqlite3"
)
func main() {
db, _ := sql.Open("sqlite3", "rc.db")
defer db.Close()
db.Exec(`create table players (name, score, active, jerseyNum)`)
db.Exec(`insert into players values ("",0,0,"99")`)
db.Exec(`insert into players values ("",0,0,"100")`) | 475Parameterized SQL statement
| 0go
| dkune |
module Main (main) where
import Database.HDBC (IConnection, commit, run, toSql)
updatePlayers :: IConnection a => a -> String -> Int -> Bool -> Int -> IO Bool
updatePlayers conn name score active jerseyNum = do
rowCount <- run conn
"UPDATE players\
\ SET name =?, score =?, active =?\
\ WHERE jerseyNum =?"
[ toSql name
, toSql score
, toSql active
, toSql jerseyNum
]
commit conn
return $ rowCount == 1
main :: IO ()
main = undefined | 475Parameterized SQL statement
| 8haskell
| 5nwug |
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ParseIPAddress {
public static void main(String[] args) {
String [] tests = new String[] {"192.168.0.1", "127.0.0.1", "256.0.0.1", "127.0.0.1:80", "::1", "[::1]:80", "[32e::12f]:80", "2605:2700:0:3::4713:93e3", "[2605:2700:0:3::4713:93e3]:80", "2001:db8:85a3:0:0:8a2e:370:7334"};
System.out.printf("%-40s%-32s %s%n", "Test Case", "Hex Address", "Port");
for ( String ip : tests ) {
try {
String [] parsed = parseIP(ip);
System.out.printf("%-40s%-32s %s%n", ip, parsed[0], parsed[1]);
}
catch (IllegalArgumentException e) {
System.out.printf("%-40s Invalid address: %s%n", ip, e.getMessage());
}
}
}
private static final Pattern IPV4_PAT = Pattern.compile("^(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)(?::(\\d+)){0,1}$");
private static final Pattern IPV6_DOUBL_COL_PAT = Pattern.compile("^\\[{0,1}([0-9a-f:]*)::([0-9a-f:]*)(?:\\]:(\\d+)){0,1}$");
private static String ipv6Pattern;
static {
ipv6Pattern = "^\\[{0,1}";
for ( int i = 1 ; i <= 7 ; i ++ ) {
ipv6Pattern += "([0-9a-f]+):";
}
ipv6Pattern += "([0-9a-f]+)(?:\\]:(\\d+)){0,1}$";
}
private static final Pattern IPV6_PAT = Pattern.compile(ipv6Pattern);
private static String[] parseIP(String ip) {
String hex = "";
String port = ""; | 469Parse an IP Address
| 9java
| rtdg0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.