code stringlengths 1 46.1k ⌀ | label class label 1.18k
classes | domain_label class label 21
classes | index stringlengths 4 5 |
|---|---|---|---|
public class Tree<T>{
private T value;
private Tree<T> left;
private Tree<T> right;
public void replaceAll(T value){
this.value = value;
if (left != null)
left.replaceAll(value);
if (right != null)
right.replaceAll(value);
}
} | 470Parametric polymorphism | 9java | nhrih |
def fs = { fn, values -> values.collect { fn(it) } }
def f1 = { v -> v * 2 }
def f2 = { v -> v ** 2 }
def fsf1 = fs.curry(f1)
def fsf2 = fs.curry(f2) | 468Partial function application | 7groovy | dkhn3 |
fs = map
f1 = (* 2)
f2 = (^ 2)
fsf1 = fs f1
fsf2 = fs f2
main :: IO ()
main = do
print $ fsf1 [0, 1, 2, 3]
print $ fsf2 [0, 1, 2, 3]
print $ fsf1 [2, 4, 6, 8]
print $ fsf2 [2, 4, 6, 8] | 468Partial function application | 8haskell | j3z7g |
function randPW (length)
local index, pw, rnd = 0, ""
local chars = {
"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"abcdefghijklmnopqrstuvwxyz",
"0123456789",
"!\"#$%&'()*+,-./:;<=>?@[]^_{|}~"
}
repeat
index = index + 1
rnd = math.random(chars[index]:len())
if ma... | 463Password generator | 1lua | gf64j |
void die(const char *msg)
{
fprintf(stderr, , msg);
abort();
}
double stack[MAX_D];
int depth;
void push(double v)
{
if (depth >= MAX_D) die();
stack[depth++] = v;
}
double pop()
{
if (!depth) die();
return stack[--depth];
}
double rpn(char *s)
{
double a, b;
int i;
char *e, *w = ;
for (s = strtok(s, w)... | 479Parsing/RPN calculator algorithm | 5c | e2nav |
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
public class DBDemo{
private String protocol; | 475Parameterized SQL statement | 9java | 9qkmu |
null | 469Parse an IP Address | 11kotlin | vo021 |
null | 470Parametric polymorphism | 11kotlin | s4vq7 |
from itertools import combinations as cmb
def isP(n):
if n == 2:
return True
if n% 2 == 0:
return False
return all(n% x > 0 for x in range(3, int(n ** 0.5) + 1, 2))
def genP(n):
p = [2]
p.extend([x for x in range(3, n + 1, 2) if isP(x)])
return p
data = [
(99809, 1), (1... | 467Partition an integer x into n primes | 3python | gff4h |
extension Numeric where Self: Strideable {
@inlinable
public func power(_ n: Self) -> Self {
return stride(from: 0, to: n, by: 1).lazy.map({_ in self }).reduce(1, *)
}
}
protocol PathologicalFloat: SignedNumeric, Strideable, ExpressibleByFloatLiteral {
static var e: Self { get }
static func /(_ lhs: Sel... | 461Pathological floating point problems | 17swift | p95bl |
package main
import "fmt"
func pancake(n int) int {
gap, sum, adj := 2, 2, -1
for sum < n {
adj++
gap = gap*2 - 1
sum += gap
}
return n + adj
}
func main() {
for i := 0; i < 4; i++ {
for j := 1; j < 6; j++ {
n := i*5 + j
fmt.Printf("p(%2d) =... | 477Pancake numbers | 0go | ui1vt |
public class Pancake {
private static int pancake(int n) {
int gap = 2;
int sum = 2;
int adj = -1;
while (sum < n) {
adj++;
gap = 2 * gap - 1;
sum += gap;
}
return n + adj;
}
public static void main(String[] args) {
... | 477Pancake numbers | 9java | ky8hm |
null | 475Parameterized SQL statement | 11kotlin | z1gts |
sub parse_v4 {
my ($ip, $port) = @_;
my @quad = split(/\./, $ip);
return unless @quad == 4;
for (@quad) { return if ($_ > 255) }
if (!length $port) { $port = -1 }
elsif ($port =~ /^(\d+)$/) { $port = $1 }
else { return }
my $h = join '' => map(sprintf("%02x", $_), @quad);
return $... | 469Parse an IP Address | 2perl | 0g5s4 |
package main
import (
"fmt"
"strings"
)
var tests = []string{
"3 4 2 * 1 5 - 2 3 ^ ^ / +",
"1 2 + 3 4 + ^ 5 6 + ^",
}
var opa = map[string]struct {
prec int
rAssoc bool
}{
"^": {4, true},
"*": {3, false},
"/": {3, false},
"+": {2, false},
"-": {2, false},
}
const nPrec ... | 472Parsing/RPN to infix conversion | 0go | kyfhz |
import java.util.Arrays;
public class PartialApplication {
interface IntegerFunction {
int call(int arg);
} | 468Partial function application | 9java | uiovv |
fun pancake(n: Int): Int {
var gap = 2
var sum = 2
var adj = -1
while (sum < n) {
adj++
gap = gap * 2 - 1
sum += gap
}
return n + adj
}
fun main() {
(1 .. 20).map {"p(%2d) =%2d".format(it, pancake(it))}
val lines = results.chunked(5).map { it.joinToString(" ") }... | 477Pancake numbers | 11kotlin | gfw4d |
use strict;
use warnings;
use feature 'say';
sub pancake {
my($n) = @_;
my ($gap, $sum, $adj) = (2, 2, -1);
while ($sum < $n) { $sum += $gap = $gap * 2 - 1 and $adj++ }
$n + $adj;
}
my $out;
$out .= sprintf "p(%2d) =%2d ", $_, pancake $_ for 1..20;
say $out =~ s/.{1,55}\K /\n/gr;
sub pancake2 {
... | 477Pancake numbers | 2perl | nhliw |
package main
import (
"fmt"
"math/big"
)
const branches = 4
const nMax = 500
var rooted, unrooted [nMax + 1]big.Int
var c [branches]big.Int
var tmp = new(big.Int)
var one = big.NewInt(1)
func tree(br, n, l, sum int, cnt *big.Int) {
for b := br + 1; b <= branches; b++ {
sum += n
if sum > ... | 478Paraffins | 0go | 7zxr2 |
class PostfixToInfix {
static class Expression {
final static String ops = "-+/*^"
String op, ex
int precedence = 3
Expression(String e) {
ex = e
}
Expression(String e1, String e2, String o) {
ex = String.format "%s%s%s", e1, o, e2
... | 472Parsing/RPN to infix conversion | 7groovy | gf846 |
var f1 = function (x) { return x * 2; },
f2 = function (x) { return x * x; },
fs = function (f, s) {
return function (s) {
return s.map(f);
}
},
fsf1 = fs(f1),
fsf2 = fs(f2); | 468Partial function application | 10javascript | 7ztrd |
def combine( snl, snr ):
cl = {}
if isinstance(snl, int):
cl['1'] = snl
elif isinstance(snl, string):
cl[snl] = 1
else:
cl.update( snl)
if isinstance(snr, int):
n = cl.get('1', 0)
cl['1'] = n + snr
elif isinstance(snr, string):
n = cl.get(snr, 0)
cl[snr] = n + 1
else:
for k,v in snr.items():
... | 466Pascal's triangle/Puzzle | 3python | mxqyh |
import time
from collections import deque
from operator import itemgetter
from typing import Tuple
Pancakes = Tuple[int, ...]
def flip(pancakes: Pancakes, position: int) -> Pancakes:
return tuple([*reversed(pancakes[:position]), *pancakes[position:]])
def pancake(n: int) -> Tuple[Pancakes, int]:
... | 477Pancake numbers | 3python | dk2n1 |
typedef uint64_t integer;
integer reverse(integer n) {
integer rev = 0;
while (n > 0) {
rev = rev * 10 + (n % 10);
n /= 10;
}
return rev;
}
typedef struct palgen_tag {
integer power;
integer next;
int digit;
bool even;
} palgen_t;
void init_palgen(palgen_t* palgen, int... | 480Palindromic gapful numbers | 5c | xudwu |
package main
import (
"fmt"
"strings"
)
var input = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"
var opa = map[string]struct {
prec int
rAssoc bool
}{
"^": {4, true},
"*": {3, false},
"/": {3, false},
"+": {2, false},
"-": {2, false},
}
func main() {
fmt.Println("infix: ", input)
f... | 471Parsing/Shunting-yard algorithm | 0go | xucwf |
a `nmul` n = map (*n) a
a `ndiv` n = map (`div` n) a
instance (Integral a) => Num [a] where
(+) = zipWith (+)
negate = map negate
a * b = foldr f undefined b where
f x z = (a `nmul` x) + (0: z)
abs _ = undefined
signum _ = undefined
fromInteger n = fromInteger n: repeat 0
repl a n = concatMap (: repl... | 478Paraffins | 8haskell | 8ry0z |
import Debug.Trace
data Expression = Const String | Exp Expression String Expression
infixFromRPN :: String -> Expression
infixFromRPN = head . foldl buildExp [] . words
buildExp :: [Expression] -> String -> [Expression]
buildExp stack x
| (not . isOp) x =
let v = Const x: stack
in trace (show v) v
| ... | 472Parsing/RPN to infix conversion | 8haskell | nh4ie |
require
def prime_partition(x, n)
Prime.each(x).to_a.combination(n).detect{|primes| primes.sum == x}
end
TESTCASES = [[99809, 1], [18, 2], [19, 3], [20, 4], [2017, 24],
[22699, 1], [22699, 2], [22699, 3], [22699, 4], [40355, 3]]
TESTCASES.each do |prime, num|
res = prime_partition(prime, num)
s... | 467Partition an integer x into n primes | 14ruby | 7zzri |
package main
import (
"fmt"
"math/big"
) | 473Parallel calculations | 0go | p9tbg |
(ns rosettacode.parsing-rpn-calculator-algorithm
(:require clojure.math.numeric-tower
clojure.string
clojure.pprint))
(def operators
"the only allowable operators for our calculator"
{"+" +
"-" -
"*" *
"/" /
"^" clojure.math.numeric-tower/expt})
(defn rpn
"takes a string an... | 479Parsing/RPN calculator algorithm | 6clojure | 0g3sj |
import Text.Printf
prec :: String -> Int
prec "^" = 4
prec "*" = 3
prec "/" = 3
prec "+" = 2
prec "-" = 2
leftAssoc :: String -> Bool
leftAssoc "^" = False
leftAssoc _ = True
isOp :: String -> Bool
isOp [t] = t `elem` "-+/*^"
isOp _ = False
simSYA :: [String] -> [([String], [String], String)]
simSYA xs = final <> [... | 471Parsing/Shunting-yard algorithm | 8haskell | ywp66 |
struct TreeNode<T> {
value: T,
left: Option<Box<TreeNode<T>>>,
right: Option<Box<TreeNode<T>>>,
}
impl <T> TreeNode<T> {
fn my_map<U,F>(&self, f: &F) -> TreeNode<U> where
F: Fn(&T) -> U {
TreeNode {
value: f(&self.value),
left: match self.left {
... | 470Parametric polymorphism | 15rust | rtng5 |
case class Tree[+A](value: A, left: Option[Tree[A]], right: Option[Tree[A]]) {
def map[B](f: A => B): Tree[B] =
Tree(f(value), left map (_.map(f)), right map (_.map(f)))
} | 470Parametric polymorphism | 16scala | h6tja |
null | 468Partial function application | 11kotlin | 9qxmh |
null | 467Partition an integer x into n primes | 15rust | j3372 |
object PartitionInteger {
def sieve(nums: LazyList[Int]): LazyList[Int] =
LazyList.cons(nums.head, sieve((nums.tail) filter (_ % nums.head != 0))) | 467Partition an integer x into n primes | 16scala | bmmk6 |
import Control.Parallel.Strategies (parMap, rdeepseq)
import Control.DeepSeq (NFData)
import Data.List (maximumBy)
import Data.Function (on)
nums :: [Integer]
nums =
[ 112272537195293
, 112582718962171
, 112272537095293
, 115280098190773
, 115797840077099
, 1099726829285419
]
lowestFactor
:: Integral ... | 473Parallel calculations | 8haskell | fbgd1 |
def pancake(n)
gap = 2
sum = 2
adj = -1
while sum < n
adj = adj + 1
gap = gap * 2 - 1
sum = sum + gap
end
return n + adj
end
for i in 0 .. 3
for j in 1 .. 5
n = i * 5 + j
print % [n, pancake(n)]
end
print
end | 477Pancake numbers | 14ruby | tpuf2 |
import java.math.BigInteger;
import java.util.Arrays;
class Test {
final static int nMax = 250;
final static int nBranches = 4;
static BigInteger[] rooted = new BigInteger[nMax + 1];
static BigInteger[] unrooted = new BigInteger[nMax + 1];
static BigInteger[] c = new BigInteger[nBranches];
st... | 478Paraffins | 9java | e2da5 |
use DBI;
my $db = DBI->connect('DBI:mysql:mydatabase:host','login','password');
$statment = $db->prepare("UPDATE players SET name =?, score =?, active =? WHERE jerseyNum =?");
$rows_affected = $statment->execute("Smith, Steve",42,'true',99); | 475Parameterized SQL statement | 2perl | bmnk4 |
void pascaltriangle(unsigned int n)
{
unsigned int c, i, j, k;
for(i=0; i < n; i++) {
c = 1;
for(j=1; j <= 2*(n-1-i); j++) printf();
for(k=0; k <= i; k++) {
printf(, c);
c = c * (i-k)/(k+1);
}
printf();
}
}
int main()
{
pascaltriangle(8);
return 0;
} | 481Pascal's triangle | 5c | ywu6f |
class Tree<T> {
var value: T?
var left: Tree<T>?
var right: Tree<T>?
func replaceAll(value: T?) {
self.value = value
left?.replaceAll(value)
right?.replaceAll(value)
}
} | 470Parametric polymorphism | 17swift | 4do5g |
require 'rref'
pyramid = [
[ 151],
[nil,nil],
[40,nil,nil],
[nil,nil,nil,nil],
[, 11,, 4,]
]
pyramid.each{|row| p row}
equations = [[1,-1,1,0]]
def parse_equation(str)
eqn = [0] * 4
lhs, rhs = str.split()
eqn[3] = rhs.to_i
for term in lhs.split()
case term
wh... | 466Pascal's triangle/Puzzle | 14ruby | cs09k |
package main
import (
"crypto/sha256"
"encoding/hex"
"log"
"sync"
)
var hh = []string{
"1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad",
"3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b",
"74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f",... | 476Parallel brute force | 0go | j307d |
$updatePlayers = .
;
$dbh = new PDO( , , );
$updateStatement = $dbh->prepare( $updatePlayers );
$updateStatement->bindValue( 1, , PDO::PARAM_STR );
$updateStatement->bindValue( 2, 42, PDO::PARAM_INT );
$updateStatement->bindValue( 3, 1, PDO::PARAM_INT );
$updateStatement->bindValue( 4, 99, PDO::PARAM_INT );
$upda... | 475Parameterized SQL statement | 12php | 6e73g |
from ipaddress import ip_address
from urllib.parse import urlparse
tests = [
,
,
,
,
,
,
]
def parse_ip_port(netloc):
try:
ip = ip_address(netloc)
port = None
except ValueError:
parsed = urlparse('
ip = ip_address(parsed.hostname)
port = par... | 469Parse an IP Address | 3python | 8r40o |
import java.util.Stack;
public class PostfixToInfix {
public static void main(String[] args) {
for (String e : new String[]{"3 4 2 * 1 5 - 2 3 ^ ^ / +",
"1 2 + 3 4 + ^ 5 6 + ^"}) {
System.out.printf("Postfix:%s%n", e);
System.out.printf("Infix:%s%n", postfixToInfix(e));... | 472Parsing/RPN to infix conversion | 9java | q5cxa |
import Foundation
class BitArray {
var array: [UInt32]
init(size: Int) {
array = Array(repeating: 0, count: (size + 31)/32)
}
func get(index: Int) -> Bool {
let bit = UInt32(1) << (index & 31)
return (array[index >> 5] & bit)!= 0
}
func set(index: Int, value: Bool) {
... | 467Partition an integer x into n primes | 17swift | rttgg |
object PascalTriangle extends App {
val (x, y, z) = pascal(11, 4, 40, 151)
def pascal(a: Int, b: Int, mid: Int, top: Int): (Int, Int, Int) = {
val y = (top - 4 * (a + b)) / 7
val x = mid - 2 * a - y
(x, y, y - x)
}
println(if (x != 0) s"Solution is: x = $x, y = $y, z = $z" else "There is no solut... | 466Pascal's triangle/Puzzle | 16scala | uinv8 |
use strict;
use warnings;
use feature 'say';
use English;
use Const::Fast;
use Getopt::Long;
use Math::Random;
const my @lcs => 'a' .. 'z';
const my @ucs => 'A' .. 'Z';
const my @digits => 0 .. 9;
const my $others => q{!"
my $pwd_length = 8;
my $num_pwds = 6;
my $seed_phrase = 'TOO MANY SECRETS';
my %opts... | 463Password generator | 2perl | ijpo3 |
import Control.Concurrent (setNumCapabilities)
import Crypto.Hash (hashWith, SHA256 (..), Digest)
import Control.Monad (replicateM, join, (>=>))
import Control.Monad.Par (runPar, get, spawnP)
import Data.ByteString (pack)
import Data.List.Split... | 476Parallel brute force | 8haskell | o7c8p |
import static java.lang.System.out;
import static java.util.Arrays.stream;
import static java.util.Comparator.comparing;
public interface ParallelCalculations {
public static final long[] NUMBERS = {
12757923,
12878611,
12878893,
12757923,
15808973,
15780709,
197622519
... | 473Parallel calculations | 9java | 0glse |
import java.util.Stack;
public class ShuntingYard {
public static void main(String[] args) {
String infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3";
System.out.printf("infix: %s%n", infix);
System.out.printf("postfix:%s%n", infixToPostfix(infix));
}
static String infixToPostfix(String in... | 471Parsing/Shunting-yard algorithm | 9java | dkrn9 |
null | 478Paraffins | 11kotlin | ky0h3 |
const Associativity = {
left: 0,
right: 1,
both: 2,
};
const operators = {
'+': { precedence: 2, associativity: Associativity.both },
'-': { precedence: 2, associativity: Associativity.left },
'*': { precedence: 3, associativity: Associativity.both },
'/': { precedence: 3, ass... | 472Parsing/RPN to infix conversion | 10javascript | ij5ol |
function map(f, ...)
local t = {}
for k, v in ipairs(...) do
t[#t+1] = f(v)
end
return t
end
function timestwo(n)
return n * 2
end
function squared(n)
return n ^ 2
end
function partial(f, arg)
return function(...)
return f(arg, ...)
end
end
timestwo_s = partial(map, t... | 468Partial function application | 1lua | csq92 |
import javax.xml.bind.DatatypeConverter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ParallelBruteForce {
public static void main(String[] args) throws ... | 476Parallel brute force | 9java | wvzej |
var onmessage = function(event) {
postMessage({"n" : event.data.n,
"factors" : factor(event.data.n),
"id" : event.data.id});
};
function factor(n) {
var factors = [];
for(p = 2; p <= n; p++) {
if((n % p) == 0) {
factors[factors.length] = p;
... | 473Parallel calculations | 10javascript | dk4nu |
function Stack() {
this.dataStore = [];
this.top = 0;
this.push = push;
this.pop = pop;
this.peek = peek;
this.length = length;
}
function push(element) {
this.dataStore[this.top++] = element;
}
function pop() {
return this.dataStore[--this.top];
}
function peek() {
return this.dataStore[this.top-1... | 471Parsing/Shunting-yard algorithm | 10javascript | 6eb38 |
import sqlite3
db = sqlite3.connect(':memory:')
db.execute('create temp table players (name, score, active, jerseyNum)')
db.execute('insert into players values (,0,,99)')
db.execute('insert into players values (,0,,100)')
db.execute('update players set name=?, score=?, active=? where jerseyNum=?', ('Smith, Steve... | 475Parameterized SQL statement | 3python | p9dbm |
(defn pascal [n]
(let [newrow (fn newrow [lst ret]
(if lst
(recur (rest lst)
(conj ret (+ (first lst) (or (second lst) 0))))
ret))
genrow (fn genrow [n lst]
(when (< 0 n)
(do ... | 481Pascal's triangle | 6clojure | 287l1 |
null | 472Parsing/RPN to infix conversion | 11kotlin | 1c3pd |
null | 476Parallel brute force | 11kotlin | bmikb |
null | 473Parallel calculations | 11kotlin | e26a4 |
package main
import (
"fmt"
"strings"
)
func binomial(n, k int) int {
if n < k {
return 0
}
if n == 0 || k == 0 {
return 1
}
num := 1
for i := k + 1; i <= n; i++ {
num *= i
}
den := 1
for i := 2; i <= n-k; i++ {
den *= i
}
return num ... | 474Pascal matrix generation | 0go | xuywf |
require 'sqlite3'
db = SQLite3::Database.new()
db.execute('create temp table players (name, score, active, jerseyNum)')
db.execute('insert into players values (,0,,99)')
db.execute('insert into players values (,0,,100)')
db.execute('insert into players values (,0,,101)')
db.execute('update players set name=?, sc... | 475Parameterized SQL statement | 14ruby | alt1s |
function tokenize(rpn)
local out = {}
local cnt = 0
for word in rpn:gmatch("%S+") do
table.insert(out, word)
cnt = cnt + 1
end
return {tokens = out, pos = 1, size = cnt}
end
function advance(lex)
if lex.pos <= lex.size then
lex.pos = lex.pos + 1
return true
e... | 472Parsing/RPN to infix conversion | 1lua | al61v |
package main
import "fmt"
func reverse(s uint64) uint64 {
e := uint64(0)
for s > 0 {
e = e*10 + (s % 10)
s /= 10
}
return e
}
func commatize(n uint) string {
s := fmt.Sprintf("%d", n)
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
... | 480Palindromic gapful numbers | 0go | l07cw |
null | 471Parsing/Shunting-yard algorithm | 11kotlin | 0gvsf |
import Data.List (transpose)
import System.Environment (getArgs)
import Text.Printf (printf)
pascal :: [[Int]]
pascal = iterate (\row -> 1: zipWith (+) row (tail row) ++ [1]) [1]
pascLow :: Int -> [[Int]]
pascLow n = zipWith (\row i -> row ++ replicate (n-i) 0) (take n pascal) [1..]
pascUp :: Int -> [[Int]]
pascU... | 474Pascal matrix generation | 8haskell | ywh66 |
import slick.jdbc.H2Profile.api._
import slick.sql.SqlProfile.ColumnOption.SqlType
import scala.concurrent.Await
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration.Duration
object PlayersApp extends App {
lazy val playerRecords = TableQuery[PlayerRecords]
val db = Database.... | 475Parameterized SQL statement | 16scala | q5yxw |
require 'ipaddr'
TESTCASES = [, ,
, ,
, ]
output = [%w(String Address Port Family Hex),
%w(------ ------- ---- ------ ---)]
def output_table(rows)
widths = []
rows.each {|row| row.each_with_index {|col, i| ... | 469Parse an IP Address | 14ruby | ijroh |
use Digest::SHA qw/sha256_hex/;
use threads;
use threads::shared;
my @results :shared;
print "$_: ",join(" ",search($_)), "\n" for (qw/
1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad
3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b
74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7... | 476Parallel brute force | 2perl | 6er36 |
import Control.Monad (guard)
palindromic :: Int -> Bool
palindromic n = d == reverse d
where
d = show n
gapful :: Int -> Bool
gapful n = n `rem` firstLastDigit == 0
where
firstLastDigit = read [head asDigits, last asDigits]
asDigits = show n
result :: Int -> [Int]
result d = do
x <- [(d+100),(d+110)..]
... | 480Palindromic gapful numbers | 8haskell | 1c8ps |
use Math::GMPz;
my $nmax = 250;
my $nbranches = 4;
my @rooted = map { Math::GMPz->new($_) } 1,1,(0) x $nmax;
my @unrooted = map { Math::GMPz->new($_) } 1,1,(0) x $nmax;
my @c = map { Math::GMPz->new(0) } 0 .. $nbranches-1;
sub tree {
my($br, $n, $l, $sum, $cnt) = @_;
for my $b ($br+1 .. $nbranches) {
... | 478Paraffins | 2perl | 3a5zs |
int is_pangram(const char *s)
{
const char *alpha =
;
char ch, wasused[26] = {0};
int total = 0;
while ((ch = *s++) != '\0') {
const char *p;
int idx;
if ((p = strchr(alpha, ch)) == NULL)
continue;
idx = (p - alpha) % 26;
total += !wasused[idx];
wasused[idx] = 1;
if (total == 26)
retu... | 482Pangram checker | 5c | vo72o |
-- This works in Oracle's SQL*Plus command line utility
VARIABLE P_NAME VARCHAR2(20);
VARIABLE P_SCORE NUMBER;
VARIABLE P_ACTIVE VARCHAR2(5);
VARIABLE P_JERSEYNUM NUMBER;
BEGIN
:P_NAME:= 'Smith, Steve';
:P_SCORE:= 42;
:P_ACTIVE:= 'TRUE';
:P_JERSEYNUM:= 99;
END;
/
DROP TABLE players;
CREATE TABLE players
(
NAME V... | 475Parameterized SQL statement | 19sql | 8rc02 |
use std::{
net::{IpAddr, SocketAddr},
str::FromStr,
};
#[derive(Clone, Debug)]
struct Addr {
addr: IpAddr,
port: Option<u16>,
}
impl std::fmt::Display for Addr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let ipv = if self.addr.is_ipv4() { "4" } else { "6" };
... | 469Parse an IP Address | 15rust | nh7i4 |
object IPparser extends App {
def myCases = Map(
"http:" -> IPInvalidAddressComponents(remark = "No match at all: 'http:'."),
"http: | 469Parse an IP Address | 16scala | tpkfb |
use strict;
use warnings;
use feature 'say';
my $number = '[+-/$]?(?:\.\d+|\d+(?:\.\d*)?)';
my $operator = '[-+*/^]';
my @tests = ('1 2 + 3 4 + ^ 5 6 + ^', '3 4 2 * 1 5 - 2 3 ^ ^ / +');
for (@tests) {
my(@elems,$n);
$n = -1;
while (
s/
\s* (?<left>$number)
\s+ (?<righ... | 472Parsing/RPN to infix conversion | 2perl | mxpyz |
null | 471Parsing/Shunting-yard algorithm | 1lua | 8ru0e |
import static java.lang.System.out;
import java.util.List;
import java.util.function.Function;
import java.util.stream.*;
import static java.util.stream.Collectors.toList;
import static java.util.stream.IntStream.range;
public class PascalMatrix {
static int binomialCoef(int n, int k) {
int result = 1;
... | 474Pascal matrix generation | 9java | dk5n9 |
sub fs(&) {
my $func = shift;
sub { map $func->($_), @_ }
}
sub double($) { shift() * 2 }
sub square($) { shift() ** 2 }
my $fs_double = fs(\&double);
my $fs_square = fs(\&square);
my @s = 0 .. 3;
print "fs_double(@s): @{[ $fs_double->(@s) ]}\n";
print "fs_square(@s): @{[ $fs_square->(@s) ]}\n";
@s... | 468Partial function application | 2perl | wv2e6 |
import random
lowercase = 'abcdefghijklmnopqrstuvwxyz'
uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
digits = '0123456789'
punctuation = '!password length={} is too short,minimum length=4")
return ''
choice = random.SystemRandom().choice
while True:
password_chars = [
... | 463Password generator | 3python | nh1iz |
use ntheory qw/factor vecmax/;
use threads;
use threads::shared;
my @results :shared;
my $tnum = 0;
$_->join() for
map { threads->create('tfactor', $tnum++, $_) }
(qw/576460752303423487 576460752303423487 576460752303423487 112272537195293
115284584522153 115280098190773 115797840077099 112582718962171 299866111... | 473Parallel calculations | 2perl | cs19a |
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PalindromicGapfulNumbers {
public static void main(String[] args) {
System.out.println("First 20 palindromic gapful numbers ending in:");
displayMap(getPalindromicGapfulEnding(20, 20));
... | 480Palindromic gapful numbers | 9java | 7zerj |
(defn pangram? [s]
(let [letters (into #{} "abcdefghijklmnopqrstuvwxyz")]
(= (->> s .toLowerCase (filter letters) (into #{})) letters))) | 482Pangram checker | 6clojure | rtpg2 |
(() => {
'use strict'; | 474Pascal matrix generation | 10javascript | 6ej38 |
passwords <- function(nl = 8, npw = 1, help = FALSE) {
if (help) return("gives npw passwords with nl characters each")
if (nl < 4) nl <- 4
spch <- c("!", "\"", "
for(i in 1:npw) {
pw <- c(sample(letters, 1), sample(LETTERS, 1), sample(0:9, 1), sample(spch, 1))
pw <- c(pw, sample(c(letters, LETTERS, 0:9,... | 463Password generator | 13r | 0ghsg |
import multiprocessing
from hashlib import sha256
h1 = bytes().fromhex()
h2 = bytes().fromhex()
h3 = bytes().fromhex()
def brute(firstletterascii: int):
global h1, h2, h3
letters = bytearray(5)
letters[0] = firstletterascii
for letters[1] in range(97, 97 + 26):
for letters[2] in range(97, 97 +... | 476Parallel brute force | 3python | yw76q |
package main
import (
"fmt"
"math"
"strconv"
"strings"
)
var input = "3 4 2 * 1 5 - 2 3 ^ ^ / +"
func main() {
fmt.Printf("For postfix%q\n", input)
fmt.Println("\nToken Action Stack")
var stack []float64
for _, tok := range strings.Fields(input) {
action ... | 479Parsing/RPN calculator algorithm | 0go | 9qrmt |
try:
import psyco
psyco.full()
except ImportError:
pass
MAX_N = 300
BRANCH = 4
ra = [0] * MAX_N
unrooted = [0] * MAX_N
def tree(br, n, l, sum = 1, cnt = 1):
global ra, unrooted, MAX_N, BRANCH
for b in xrange(br + 1, BRANCH + 1):
sum += n
if sum >= MAX_N:
return
... | 478Paraffins | 3python | 6e43w |
import 'dart:io';
pascal(n) {
if(n<=0) print("Not defined");
else if(n==1) print(1);
else {
List<List<int>> matrix = new List<List<int>>();
matrix.add(new List<int>());
matrix.add(new List<int>());
matrix[0].add(1);
matrix[1].add(1);
matrix[1].add(1);
for (var i = 2; i < n; i++) {
... | 481Pascal's triangle | 18dart | dkmnj |
prec_dict = {'^':4, '*':3, '/':3, '+':2, '-':2}
assoc_dict = {'^':1, '*':0, '/':0, '+':0, '-':0}
class Node:
def __init__(self,x,op,y=None):
self.precedence = prec_dict[op]
self.assocright = assoc_dict[op]
self.op = op
self.x,self.y = x,y
def __str__(self):
... | 472Parsing/RPN to infix conversion | 3python | 9q1mf |
def evaluateRPN(expression) {
def stack = [] as Stack
def binaryOp = { action -> return { action.call(stack.pop(), stack.pop()) } }
def actions = [
'+': binaryOp { a, b -> b + a },
'-': binaryOp { a, b -> b - a },
'*': binaryOp { a, b -> b * a },
'/': binaryOp { a, b -> b / a... | 479Parsing/RPN calculator algorithm | 7groovy | z1vt5 |
my %prec = (
'^' => 4,
'*' => 3,
'/' => 3,
'+' => 2,
'-' => 2,
'(' => 1
);
my %assoc = (
'^' => 'right',
'*' => 'left',
'/' => 'left',
'+' => 'left',
'-' => 'left'
);
sub shunting_yard {
my @inp = split ' ', $_[0];
my @ops;
my @res;
my $report = sub { print... | 471Parsing/Shunting-yard algorithm | 2perl | 5n0u2 |
from functools import partial
def fs(f, s): return [f(value) for value in s]
def f1(value): return value * 2
def f2(value): return value ** 2
fsf1 = partial(fs, f1)
fsf2 = partial(fs, f2)
s = [0, 1, 2, 3]
assert fs(f1, s) == fsf1(s)
assert fs(f2, s) == fsf2(s)
s = [2, 4, 6, 8]
assert fs(f1, s) == fsf1(s)
asser... | 468Partial function application | 3python | xuvwr |
null | 476Parallel brute force | 15rust | csk9z |
import java.security.MessageDigest
import scala.collection.parallel.immutable.ParVector
object EncryptionCracker {
def main(args: Array[String]): Unit = {
val hash1 = "1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad"
val hash2 = "3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4... | 476Parallel brute force | 16scala | vo12s |
from concurrent import futures
from math import floor, sqrt
NUMBERS = [
112272537195293,
112582718962171,
112272537095293,
115280098190773,
115797840077099,
1099726829285419]
def lowest_factor(n, _start=3):
if n% 2 == 0:
return 2
search_max = int(floor(sqrt(n))) + 1
for i ... | 473Parallel calculations | 3python | l0acv |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.