code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
def a(n):
n += 2
return n*(n**2 + 1)/2
def inv_a(x):
k = 0
while k*(k**2+1)/2+2 < x:
k+=1
return k
if __name__ == '__main__':
print();
for n in range(1, 20):
print(int(a(n)), end = );
print(,int(a(1000)));
for e in range(1, 20):
print(f'10^{e}: {inv_a(10**e)}'); | 601Magic constant
| 3python
| hf2jw |
use File::Path qw(make_path);
make_path('path/to/dir') | 595Make directory path
| 2perl
| p3hb0 |
use strict;
use warnings;
use ntheory 'fromdigits';
my @sbox = (
[4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3],
[14, 11, 4, 12, 6, 13, 15, 10, 2, 3, 8, 1, 0, 7, 5, 9],
[5, 8, 1, 13, 10, 3, 4, 2, 14, 15, 12, 7, 6, 0, 9, 11],
[7, 13, 10, 1, 0, 8, 9, 15, 14, 4, 6, 12, 11, 2, 5, 3],
[6, 12, 7, 1, 5, 15, 13, 8, 4, 10, 9, 14, 0, 3, 11, 2],
[4, 11, 10, 0, 7, 2, 1, 13, 3, 6, 8, 5, 9, 12, 15, 14],
[13, 11, 4, 1, 3, 15, 5, 9, 0, 10, 14, 7, 6, 8, 2, 12],
[1, 15, 13, 0, 5, 7, 10, 4, 9, 2, 3, 14, 6, 11, 8, 12]
);
sub rol32 {
my($y, $n) = @_;
($y << $n) % 2**32 | ($y >> (32 - $n))
}
sub GOST_round {
my($R, $K) = @_;
my $a = ($R + $K) % 2**32;
my $b = fromdigits([map { $sbox[$_][($a >> (4*$_))%16] } reverse 0..7],16);
rol32($b,11);
}
sub feistel_step {
my($F, $L, $R, $K) = @_;
$R, $L ^ &$F($R, $K)
}
my @input = (0x21, 0x04, 0x3B, 0x04, 0x30, 0x04, 0x32, 0x04);
my @key = (0xF9, 0x04, 0xC1, 0xE2);
my $R = fromdigits([reverse @input[0..3]], 256);
my $L = fromdigits([reverse @input[4..7]], 256);
my $K = fromdigits([reverse @key ], 256);
($L,$R) = feistel_step(\&GOST_round, $L, $R, $K);
printf '%02X ', (($L << 32) + $R >> (8*$_))%256 for 0..7;
print "\n"; | 596Main step of GOST 28147-89
| 2perl
| qlax6 |
import java.util.ArrayList;
import java.util.List;
public class MagnanimousNumbers {
public static void main(String[] args) {
runTask("Find and display the first 45 magnanimous numbers.", 1, 45);
runTask("241st through 250th magnanimous numbers.", 241, 250);
runTask("391st through 400th magnanimous numbers.", 391, 400);
}
private static void runTask(String message, int startN, int endN) {
int count = 0;
List<Integer> nums = new ArrayList<>();
for ( int n = 0 ; count < endN ; n++ ) {
if ( isMagnanimous(n) ) {
nums.add(n);
count++;
}
}
System.out.printf("%s%n", message);
System.out.printf("%s%n%n", nums.subList(startN-1, endN));
}
private static boolean isMagnanimous(long n) {
if ( n >= 0 && n <= 9 ) {
return true;
}
long q = 11;
for ( long div = 10 ; q >= 10 ; div *= 10 ) {
q = n / div;
long r = n % div;
if ( ! isPrime(q+r) ) {
return false;
}
}
return true;
}
private static final int MAX = 100_000;
private static final boolean[] primes = new boolean[MAX];
private static boolean SIEVE_COMPLETE = false;
private static final boolean isPrimeTrivial(long test) {
if ( ! SIEVE_COMPLETE ) {
sieve();
SIEVE_COMPLETE = true;
}
return primes[(int) test];
}
private static final void sieve() { | 598Magnanimous numbers
| 9java
| tj8f9 |
def Dijkstra(Graph, source):
'''
+ +---+---+
| 0 1 2 |
+---+ + +
| 3 4 | 5
+---+---+---+
>>> graph = (
... (0,1,0,0,0,0,),
... (1,0,1,0,1,0,),
... (0,1,0,0,0,1,),
... (0,0,0,0,1,0,),
... (0,1,0,1,0,0,),
... (0,0,1,0,0,0,),
... )
...
>>> Dijkstra(graph, 0)
([0, 1, 2, 3, 2, 3], [1e+140, 0, 1, 4, 1, 2])
>>> display_solution([1e+140, 0, 1, 4, 1, 2])
5<2<1<0
'''
infinity = float('infinity')
n = len(graph)
dist = [infinity]*n
previous = [infinity]*n
dist[source] = 0
Q = list(range(n))
while Q:
u = min(Q, key=lambda n:dist[n])
Q.remove(u)
if dist[u] == infinity:
break
for v in range(n):
if Graph[u][v] and (v in Q):
alt = dist[u] + Graph[u][v]
if alt < dist[v]:
dist[v] = alt
previous[v] = u
return dist,previous
def display_solution(predecessor):
cell = len(predecessor)-1
while cell:
print(cell,end='<')
cell = predecessor[cell]
print(0) | 587Maze solving
| 3python
| 0ufsq |
import java.security.MessageDigest
String.metaClass.md5Checksum = {
MessageDigest.getInstance('md5').digest(delegate.bytes).collect { String.format("%02x", it) }.join('')
} | 590MD5
| 7groovy
| amx1p |
package main
import (
"fmt"
"log"
)
func magicSquareOdd(n int) ([][]int, error) {
if n < 3 || n%2 == 0 {
return nil, fmt.Errorf("base must be odd and > 2")
}
value := 1
gridSize := n * n
c, r := n/2, 0
result := make([][]int, n)
for i := 0; i < n; i++ {
result[i] = make([]int, n)
}
for value <= gridSize {
result[r][c] = value
if r == 0 {
if c == n-1 {
r++
} else {
r = n - 1
c++
}
} else if c == n-1 {
r--
c = 0
} else if result[r-1][c+1] == 0 {
r--
c++
} else {
r++
}
value++
}
return result, nil
}
func magicSquareSinglyEven(n int) ([][]int, error) {
if n < 6 || (n-2)%4 != 0 {
return nil, fmt.Errorf("base must be a positive multiple of 4 plus 2")
}
size := n * n
halfN := n / 2
subSquareSize := size / 4
subSquare, err := magicSquareOdd(halfN)
if err != nil {
return nil, err
}
quadrantFactors := [4]int{0, 2, 3, 1}
result := make([][]int, n)
for i := 0; i < n; i++ {
result[i] = make([]int, n)
}
for r := 0; r < n; r++ {
for c := 0; c < n; c++ {
quadrant := r/halfN*2 + c/halfN
result[r][c] = subSquare[r%halfN][c%halfN]
result[r][c] += quadrantFactors[quadrant] * subSquareSize
}
}
nColsLeft := halfN / 2
nColsRight := nColsLeft - 1
for r := 0; r < halfN; r++ {
for c := 0; c < n; c++ {
if c < nColsLeft || c >= n-nColsRight ||
(c == nColsLeft && r == nColsLeft) {
if c == 0 && r == nColsLeft {
continue
}
tmp := result[r][c]
result[r][c] = result[r+halfN][c]
result[r+halfN][c] = tmp
}
}
}
return result, nil
}
func main() {
const n = 6
msse, err := magicSquareSinglyEven(n)
if err != nil {
log.Fatal(err)
}
for _, row := range msse {
for _, x := range row {
fmt.Printf("%2d ", x)
}
fmt.Println()
}
fmt.Printf("\nMagic constant:%d\n", (n*n+1)*n/2)
} | 600Magic squares of singly even order
| 0go
| ayr1f |
from errno import EEXIST
from os import mkdir, curdir
from os.path import split, exists
def mkdirp(path, mode=0777):
head, tail = split(path)
if not tail:
head, tail = split(head)
if head and tail and not exists(head):
try:
mkdirp(head, mode)
except OSError as e:
if e.errno != EEXIST:
raise
if tail == curdir:
return
try:
mkdir(path, mode)
except OSError as e:
if e.errno != EEXIST:
raise | 595Make directory path
| 3python
| 16kpc |
int** doublyEvenMagicSquare(int n) {
if (n < 4 || n % 4 != 0)
return NULL;
int bits = 38505;
int size = n * n;
int mult = n / 4,i,r,c,bitPos;
int** result = (int**)malloc(n*sizeof(int*));
for(i=0;i<n;i++)
result[i] = (int*)malloc(n*sizeof(int));
for (r = 0, i = 0; r < n; r++) {
for (c = 0; c < n; c++, i++) {
bitPos = c / mult + (r / mult) * 4;
result[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;
}
}
return result;
}
int numDigits(int n){
int count = 1;
while(n>=10){
n /= 10;
count++;
}
return count;
}
void printMagicSquare(int** square,int rows){
int i,j,baseWidth = numDigits(rows*rows) + 3;
printf(,rows,(rows * rows + 1) * rows / 2);
for(i=0;i<rows;i++){
for(j=0;j<rows;j++){
printf(,baseWidth - numDigits(square[i][j]),,square[i][j]);
}
printf();
}
}
int main(int argC,char* argV[])
{
int n;
if(argC!=2||isdigit(argV[1][0])==0)
printf(,argV[0]);
else{
n = atoi(argV[1]);
printMagicSquare(doublyEvenMagicSquare(n),n);
}
return 0;
} | 603Magic squares of doubly even order
| 5c
| ql7xc |
Matrix = {}
function Matrix.new( dim_y, dim_x )
assert( dim_y and dim_x )
local matrix = {}
local metatab = {}
setmetatable( matrix, metatab )
metatab.__add = Matrix.Add
metatab.__mul = Matrix.Mul
metatab.__pow = Matrix.Pow
matrix.dim_y = dim_y
matrix.dim_x = dim_x
matrix.data = {}
for i = 1, dim_y do
matrix.data[i] = {}
end
return matrix
end
function Matrix.Show( m )
for i = 1, m.dim_y do
for j = 1, m.dim_x do
io.write( tostring( m.data[i][j] ), " " )
end
io.write( "\n" )
end
end
function Matrix.Add( m, n )
assert( m.dim_x == n.dim_x and m.dim_y == n.dim_y )
local r = Matrix.new( m.dim_y, m.dim_x )
for i = 1, m.dim_y do
for j = 1, m.dim_x do
r.data[i][j] = m.data[i][j] + n.data[i][j]
end
end
return r
end
function Matrix.Mul( m, n )
assert( m.dim_x == n.dim_y )
local r = Matrix.new( m.dim_y, n.dim_x )
for i = 1, m.dim_y do
for j = 1, n.dim_x do
r.data[i][j] = 0
for k = 1, m.dim_x do
r.data[i][j] = r.data[i][j] + m.data[i][k] * n.data[k][j]
end
end
end
return r
end
function Matrix.Pow( m, p )
assert( m.dim_x == m.dim_y )
local r = Matrix.new( m.dim_y, m.dim_x )
if p == 0 then
for i = 1, m.dim_y do
for j = 1, m.dim_x do
if i == j then
r.data[i][j] = 1
else
r.data[i][j] = 0
end
end
end
elseif p == 1 then
for i = 1, m.dim_y do
for j = 1, m.dim_x do
r.data[i][j] = m.data[i][j]
end
end
else
r = m
for i = 2, p do
r = r * m
end
end
return r
end
m = Matrix.new( 2, 2 )
m.data = { { 1, 2 }, { 3, 4 } }
n = m^4;
Matrix.Show( n ) | 591Matrix-exponentiation operator
| 1lua
| nrfi8 |
extern crate rand;
use rand::prelude::*;
use std::io;
fn main() {
let mut input_line = String::new();
let colors_n;
let code_len;
let guesses_max;
let colors_dup;
loop {
println!("Please enter the number of colors to be used in the game (2 - 20): ");
input_line.clear();
io::stdin()
.read_line(&mut input_line)
.expect("The read line failed.");
match (input_line.trim()).parse::<i32>() {
Ok(n) => {
if n >= 2 && n <= 20 {
colors_n = n;
break;
} else {
println!("Outside of range (2 - 20).");
}
}
Err(_) => println!("Invalid input."),
}
}
let colors = &"ABCDEFGHIJKLMNOPQRST"[..colors_n as usize];
println!("Playing with colors {}.\n", colors);
loop {
println!("Are duplicated colors allowed in the code? (Y/N): ");
input_line.clear();
io::stdin()
.read_line(&mut input_line)
.expect("The read line failed.");
if ["Y", "N"].contains(&&input_line.trim().to_uppercase()[..]) {
colors_dup = input_line.trim().to_uppercase() == "Y";
break;
} else {
println!("Invalid input.");
}
}
println!(
"Duplicated colors {}allowed.\n",
if colors_dup { "" } else { "not " }
);
loop {
let min_len = if colors_dup { 4 } else { 4.min(colors_n) };
let max_len = if colors_dup { 10 } else { 10.min(colors_n) };
println!(
"Please enter the length of the code ({} - {}): ",
min_len, max_len
);
input_line.clear();
io::stdin()
.read_line(&mut input_line)
.expect("The read line failed.");
match (input_line.trim()).parse::<i32>() {
Ok(n) => {
if n >= min_len && n <= max_len {
code_len = n;
break;
} else {
println!("Outside of range ({} - {}).", min_len, max_len);
}
}
Err(_) => println!("Invalid input."),
}
}
println!("Code of length {}.\n", code_len);
loop {
println!("Please enter the number of guesses allowed (7 - 20): ");
input_line.clear();
io::stdin()
.read_line(&mut input_line)
.expect("The read line failed.");
match (input_line.trim()).parse::<i32>() {
Ok(n) => {
if n >= 7 && n <= 20 {
guesses_max = n;
break;
} else {
println!("Outside of range (7 - 20).");
}
}
Err(_) => println!("Invalid input."),
}
}
println!("{} guesses allowed.\n", guesses_max);
let mut rng = rand::thread_rng();
let mut code;
if colors_dup {
code = (0..code_len)
.map(|_| ((65 + rng.gen_range(0, colors_n) as u8) as char))
.collect::<Vec<_>>();
} else {
code = colors.chars().collect::<Vec<_>>();
code.shuffle(&mut rng);
code = code[..code_len as usize].to_vec();
} | 594Mastermind
| 15rust
| m16ya |
import Data.Digest.OpenSSL.MD5 (md5sum)
import Data.ByteString (pack)
import Data.Char (ord)
main = do
let message = "The quick brown fox jumped over the lazy dog's back"
digest = (md5sum . pack . map (fromIntegral . ord)) message
putStrLn digest | 590MD5
| 8haskell
| 9e2mo |
import qualified Data.Map.Strict as M
import Data.List (transpose, intercalate)
import Data.Maybe (fromJust, isJust)
import Control.Monad (forM_)
import Data.Monoid ((<>))
magic :: Int -> [[Int]]
magic n = mapAsTable ((4 * n) + 2) (hiResMap n)
hiResMap :: Int -> M.Map (Int, Int) Int
hiResMap n =
let mapLux = luxMap n
mapSiam = siamMap n
in M.fromList $
foldMap
(\(xy, n) ->
luxNums xy (fromJust (M.lookup xy mapLux)) ((4 * (n - 1)) + 1))
(M.toList mapSiam)
luxNums :: (Int, Int) -> Char -> Int -> [((Int, Int), Int)]
luxNums xy lux n =
zipWith (\x d -> (x, n + d)) (hiRes xy) $
case lux of
'L' -> [3, 0, 1, 2]
'U' -> [0, 3, 1, 2]
'X' -> [0, 3, 2, 1]
_ -> [0, 0, 0, 0]
mapAsTable :: Int -> M.Map (Int, Int) Int -> [[Int]]
mapAsTable nCols xyMap =
let axis = [0 .. nCols - 1]
in fmap (fromJust . flip M.lookup xyMap) <$>
(axis >>= \y -> [axis >>= \x -> [(x, y)]])
luxMap :: Int -> M.Map (Int, Int) Char
luxMap n =
(M.fromList . concat) $
zipWith
(\y xs -> (zipWith (\x c -> ((x, y), c)) [0 ..] xs))
[0 ..]
(luxPattern n)
luxPattern :: Int -> [String]
luxPattern n =
let d = (2 * n) + 1
[ls, us] = replicate n <$> "LU"
[lRow, xRow] = replicate d <$> "LX"
in replicate n lRow <> [ls <> ('U': ls)] <> [us <> ('L': us)] <>
replicate (n - 1) xRow
siamMap :: Int -> M.Map (Int, Int) Int
siamMap n =
let uBound = (2 * n)
sPath uBound sMap (x, y) n =
let newMap = M.insert (x, y) n sMap
in if y == uBound && x == quot uBound 2
then newMap
else sPath uBound newMap (nextSiam uBound sMap (x, y)) (n + 1)
in sPath uBound (M.fromList []) (n, 0) 1
nextSiam :: Int -> M.Map (Int, Int) Int -> (Int, Int) -> (Int, Int)
nextSiam uBound sMap (x, y) =
let alt (a, b)
| a > uBound && b < 0 = (uBound, 1)
| a > uBound = (0, b)
| b < 0 = (a, uBound)
| isJust (M.lookup (a, b) sMap) = (a - 1, b + 2)
| otherwise = (a, b)
in alt (x + 1, y - 1)
hiRes :: (Int, Int) -> [(Int, Int)]
hiRes (x, y) =
let [col, row] = (* 2) <$> [x, y]
[col1, row1] = succ <$> [col, row]
in [(col, row), (col1, row), (col, row1), (col1, row1)]
checked :: [[Int]] -> (Int, Bool)
checked square = (h, all (h ==) t)
where
diagonals = fmap (flip (zipWith (!!)) [0 ..]) . ((:) <*> (return . reverse))
h:t = sum <$> square <> transpose square <> diagonals square
table :: String -> [[String]] -> [String]
table delim rows =
let justifyRight c n s = drop (length s) (replicate n c <> s)
in intercalate delim <$>
transpose
((fmap =<< justifyRight ' ' . maximum . fmap length) <$> transpose rows)
main :: IO ()
main =
forM_ [1, 2, 3] $
\n -> do
let test = magic n
putStrLn $ unlines (table " " (fmap show <$> test))
print $ checked test
putStrLn "" | 600Magic squares of singly even order
| 8haskell
| zh0t0 |
require 'fileutils'
FileUtils.mkdir_p() | 595Make directory path
| 14ruby
| empax |
k8 = [ 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7 ]
k7 = [ 15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10 ]
k6 = [ 10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8 ]
k5 = [ 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15 ]
k4 = [ 2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9 ]
k3 = [ 12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11 ]
k2 = [ 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1 ]
k1 = [ 13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7 ]
k87 = [0] * 256
k65 = [0] * 256
k43 = [0] * 256
k21 = [0] * 256
def kboxinit():
for i in range(256):
k87[i] = k8[i >> 4] << 4 | k7[i & 15]
k65[i] = k6[i >> 4] << 4 | k5[i & 15]
k43[i] = k4[i >> 4] << 4 | k3[i & 15]
k21[i] = k2[i >> 4] << 4 | k1[i & 15]
def f(x):
x = ( k87[x>>24 & 255] << 24 | k65[x>>16 & 255] << 16 |
k43[x>> 8 & 255] << 8 | k21[x & 255] )
return x<<11 | x>>(32-11) | 596Main step of GOST 28147-89
| 3python
| s2eq9 |
-- Create Table
-- Distinct combination
--- R:Red, B:Blue, G: Green, V: Violet, O: Orange, Y: Yellow
DROP TYPE IF EXISTS color cascade;CREATE TYPE color AS ENUM ('R', 'B', 'G', 'V', 'O', 'Y');
DROP TABLE IF EXISTS guesses cascade; CREATE TABLE guesses (
FIRST color,
SECOND color,
third color ,
fourth color
);
CREATE TABLE mastermind () inherits (guesses);
INSERT INTO mastermind VALUES ('G', 'B', 'R', 'V');
INSERT INTO guesses VALUES ('Y', 'Y', 'B', 'B');
INSERT INTO guesses VALUES ('V', 'R', 'R', 'Y');
INSERT INTO guesses VALUES ('G', 'V', 'G', 'Y');
INSERT INTO guesses VALUES ('R', 'R', 'V', 'Y');
INSERT INTO guesses VALUES ('B', 'R', 'G', 'V');
INSERT INTO guesses VALUES ('G', 'B', 'R', 'V');
--- Matches Black
CREATE OR REPLACE FUNCTION check_black(guesses, mastermind) RETURNS INTEGER AS $$
SELECT (
($1.FIRST = $2.FIRST)::INT +
($1.SECOND = $2.SECOND)::INT +
($1.third = $2.third)::INT +
($1.fourth = $2.fourth)::INT
);
$$ LANGUAGE SQL;
--- Matches White
CREATE OR REPLACE FUNCTION check_white(guesses, mastermind) RETURNS INTEGER AS $$
SELECT (
CASE WHEN ($1.FIRST = $2.FIRST) THEN 0 ELSE 0 END +
CASE WHEN ($1.SECOND = $2.SECOND) THEN 0 ELSE 0 END +
CASE WHEN ($1.third = $2.third) THEN 0 ELSE 0 END +
CASE WHEN ($1.fourth = $2.fourth) THEN 0 ELSE 0 END +
CASE WHEN ($1.FIRST!= $2.FIRST) THEN (
$1.FIRST = $2.SECOND OR
$1.FIRST = $2.third OR
$1.FIRST = $2.fourth
)::INT ELSE 0 END +
CASE WHEN ($1.SECOND!= $2.SECOND) THEN (
$1.SECOND = $2.FIRST OR
$1.SECOND = $2.third OR
$1.SECOND = $2.fourth
)::INT ELSE 0 END +
CASE WHEN ($1.third!= $2.third) THEN (
$1.third = $2.FIRST OR
$1.third = $2.SECOND OR
$1.third = $2.fourth
)::INT ELSE 0 END +
CASE WHEN ($1.fourth!= $2.fourth) THEN (
$1.fourth = $2.FIRST OR
$1.fourth = $2.SECOND OR
$1.fourth = $2.third
)::INT ELSE 0 END
) FROM guesses
$$ LANGUAGE SQL;
SELECT guesses,
check_black(guesses.*, mastermind.*),
check_white(guesses.*, mastermind.*)
FROM guesses, mastermind | 594Mastermind
| 19sql
| us2vq |
public class MagicSquareSinglyEven {
public static void main(String[] args) {
int n = 6;
for (int[] row : magicSquareSinglyEven(n)) {
for (int x : row)
System.out.printf("%2s ", x);
System.out.println();
}
System.out.printf("\nMagic constant:%d ", (n * n + 1) * n / 2);
}
public static int[][] magicSquareOdd(final int n) {
if (n < 3 || n % 2 == 0)
throw new IllegalArgumentException("base must be odd and > 2");
int value = 0;
int gridSize = n * n;
int c = n / 2, r = 0;
int[][] result = new int[n][n];
while (++value <= gridSize) {
result[r][c] = value;
if (r == 0) {
if (c == n - 1) {
r++;
} else {
r = n - 1;
c++;
}
} else if (c == n - 1) {
r--;
c = 0;
} else if (result[r - 1][c + 1] == 0) {
r--;
c++;
} else {
r++;
}
}
return result;
}
static int[][] magicSquareSinglyEven(final int n) {
if (n < 6 || (n - 2) % 4 != 0)
throw new IllegalArgumentException("base must be a positive "
+ "multiple of 4 plus 2");
int size = n * n;
int halfN = n / 2;
int subSquareSize = size / 4;
int[][] subSquare = magicSquareOdd(halfN);
int[] quadrantFactors = {0, 2, 3, 1};
int[][] result = new int[n][n];
for (int r = 0; r < n; r++) {
for (int c = 0; c < n; c++) {
int quadrant = (r / halfN) * 2 + (c / halfN);
result[r][c] = subSquare[r % halfN][c % halfN];
result[r][c] += quadrantFactors[quadrant] * subSquareSize;
}
}
int nColsLeft = halfN / 2;
int nColsRight = nColsLeft - 1;
for (int r = 0; r < halfN; r++)
for (int c = 0; c < n; c++) {
if (c < nColsLeft || c >= n - nColsRight
|| (c == nColsLeft && r == nColsLeft)) {
if (c == 0 && r == nColsLeft)
continue;
int tmp = result[r][c];
result[r][c] = result[r + halfN][c];
result[r + halfN][c] = tmp;
}
}
return result;
}
} | 600Magic squares of singly even order
| 9java
| o5a8d |
use std::fs;
fn main() {
fs::create_dir_all("./path/to/dir").expect("An Error Occured!")
} | 595Make directory path
| 15rust
| w91e4 |
new java.io.File("/path/to/dir").mkdirs | 595Make directory path
| 16scala
| s2wqo |
use strict;
use warnings;
use feature 'say';
use ntheory 'is_prime';
sub magnanimous {
my($n) = @_;
my $last;
for my $c (1 .. length($n) - 1) {
++$last and last unless is_prime substr($n,0,$c) + substr($n,$c)
}
not $last;
}
my @M;
for ( my $i = 0, my $count = 0; $count < 400; $i++ ) {
++$count and push @M, $i if magnanimous($i);
}
say "First 45 magnanimous numbers\n".
(sprintf "@{['%4d' x 45]}", @M[0..45-1]) =~ s/(.{60})/$1\n/gr;
say "241st through 250th magnanimous numbers\n" .
join ' ', @M[240..249];
say "\n391st through 400th magnanimous numbers\n".
join ' ', @M[390..399]; | 598Magnanimous numbers
| 2perl
| gol4e |
use 5.10.0;
use List::Util 'max';
my @sum;
while (<>) {
my @x = split;
@sum = ($x[0] + $sum[0],
map($x[$_] + max(@sum[$_-1, $_]), 1 .. @x-2),
$x[-1] + $sum[-1]);
}
say max(@sum); | 588Maximum triangle path sum
| 2perl
| 85f0w |
null | 600Magic squares of singly even order
| 11kotlin
| xchws |
typedef double * const __restrict MAT_OUT_t;
typedef double * const restrict MAT_OUT_t;
typedef const double * const MAT_IN_t;
static inline void mat_mult(
const int m,
const int n,
const int p,
MAT_IN_t a,
MAT_IN_t b,
MAT_OUT_t c)
{
for (int row=0; row<m; row++) {
for (int col=0; col<p; col++) {
c[MAT_ELEM(m,p,row,col)] = 0;
for (int i=0; i<n; i++) {
c[MAT_ELEM(m,p,row,col)] += a[MAT_ELEM(m,n,row,i)]*b[MAT_ELEM(n,p,i,col)];
}
}
}
}
static inline void mat_show(
const int m,
const int p,
MAT_IN_t a)
{
for (int row=0; row<m;row++) {
for (int col=0; col<p;col++) {
printf(, a[MAT_ELEM(m,p,row,col)]);
}
putchar('\n');
}
}
int main(void)
{
double a[4*4] = {1, 1, 1, 1,
2, 4, 8, 16,
3, 9, 27, 81,
4, 16, 64, 256};
double b[4*3] = { 4.0, -3.0, 4.0/3,
-13.0/3, 19.0/4, -7.0/3,
3.0/2, -2.0, 7.0/6,
-1.0/6, 1.0/4, -1.0/6};
double c[4*3] = {0};
mat_mult(4,4,3,a,b,c);
mat_show(4,3,c);
return 0;
} | 604Matrix multiplication
| 5c
| 3kxza |
class Maze
def solve
reset_visiting_state
@queue = []
enqueue_cell([], @start_x, @start_y)
path = nil
until path || @queue.empty?
path = solve_visit_cell
end
if path
for x, y in path
@path[x][y] = true
end
else
puts
end
end
private
def solve_visit_cell
path = @queue.shift
x, y = path.last
return path if x == @end_x && y == @end_y
@visited[x][y] = true
for dx, dy in DIRECTIONS
if dx.nonzero?
new_x = x + dx
if move_valid?(new_x, y) &&!@vertical_walls[ [x, new_x].min ][y]
enqueue_cell(path, new_x, y)
end
else
new_y = y + dy
if move_valid?(x, new_y) &&!@horizontal_walls[x][ [y, new_y].min ]
enqueue_cell(path, x, new_y)
end
end
end
nil
end
def enqueue_cell(path, x, y)
@queue << path + [[x, y]]
end
end
maze = Maze.new 20, 10
maze.solve
maze.print | 587Maze solving
| 14ruby
| o4z8v |
import sequtils, strutils
type Square = seq[seq[int]]
func magicSquareOdd(n: Positive): Square =
## Build a magic square of odd order.
assert n >= 3 and (n and 1)!= 0, "base must be odd and greater than 2."
result = newSeqWith(n, newSeq[int](n))
var
r = 0
c = n div 2
value = 0
while value < n * n:
inc value
result[r][c] = value
if r == 0:
if c == n - 1:
inc r
else:
r = n - 1
inc c
elif c == n - 1:
dec r
c = 0
elif result[r - 1][c + 1] == 0:
dec r
inc c
else:
inc r
func magicSquareSinglyEven(n: int): Square =
## Build a magic square of singly even order.
assert n >= 6 and ((n - 2) and 3) == 0, "base must be a positive multiple of 4 plus 2."
result = newSeqWith(n, newSeq[int](n))
let
halfN = n div 2
subSquareSize = n * n div 4
subSquare = magicSquareOdd(halfN)
const QuadrantFactors = [0, 2, 3, 1]
for r in 0..<n:
for c in 0..<n:
let quadrant = r div halfN * 2 + c div halfN
result[r][c] = subSquare[r mod halfN][c mod halfN] + QuadrantFactors[quadrant] * subSquareSize
let
nColsLeft = halfN div 2
nColsRight = nColsLeft - 1
for r in 0..<halfN:
for c in 0..<n:
if c < nColsLeft or c >= n - nColsRight or (c == nColsLeft and r == nColsLeft):
if c!= 0 or r!= nColsLeft:
swap result[r][c], result[r + halfN][c]
func `$`(square: Square): string =
## Return the string representation of a magic square.
let length = len($(square.len * square.len))
for row in square:
result.add row.mapIt(($it).align(length)).join(" ") & '\n'
when isMainModule:
let n = 6
echo magicSquareSinglyEven(n)
echo "Magic constant = ", n * (n * n + 1) div 2 | 600Magic squares of singly even order
| 1lua
| qlkx0 |
null | 600Magic squares of singly even order
| 2perl
| 2xzlf |
use std::convert::TryInto;
use std::env;
use std::num::Wrapping;
const REPLACEMENT_TABLE: [[u8; 16]; 8] = [
[4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3],
[14, 11, 4, 12, 6, 13, 15, 10, 2, 3, 8, 1, 0, 7, 5, 9],
[5, 8, 1, 13, 10, 3, 4, 2, 14, 15, 12, 7, 6, 0, 9, 11],
[7, 13, 10, 1, 0, 8, 9, 15, 14, 4, 6, 12, 11, 2, 5, 3],
[6, 12, 7, 1, 5, 15, 13, 8, 4, 10, 9, 14, 0, 3, 11, 2],
[4, 11, 10, 0, 7, 2, 1, 13, 3, 6, 8, 5, 9, 12, 15, 14],
[13, 11, 4, 1, 3, 15, 5, 9, 0, 10, 14, 7, 6, 8, 2, 12],
[1, 15, 13, 0, 5, 7, 10, 4, 9, 2, 3, 14, 6, 11, 8, 12],
];
const KEYS: [u32; 8] = [
0xE2C1_04F9,
0xE41D_7CDE,
0x7FE5_E857,
0x0602_65B4,
0x281C_CC85,
0x2E2C_929A,
0x4746_4503,
0xE00_CE510,
];
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
let plain_text: Vec<u8> = vec![0x04, 0x3B, 0x04, 0x21, 0x04, 0x32, 0x04, 0x30];
println!(
"Before one step: {}\n",
plain_text
.iter()
.cloned()
.fold("".to_string(), |b, y| b + &format!("{:02X} ", y))
);
let encoded_text = main_step(plain_text, KEYS[0]);
println!(
"After one step: {}\n",
encoded_text
.iter()
.cloned()
.fold("".to_string(), |b, y| b + &format!("{:02X} ", y))
);
} else {
let mut t = args[1].clone(); | 596Main step of GOST 28147-89
| 15rust
| o5q83 |
use rand::{thread_rng, Rng, rngs::ThreadRng};
const WIDTH: usize = 16;
const HEIGHT: usize = 16;
#[derive(Clone, Copy, PartialEq)]
struct Cell {
col: usize,
row: usize,
}
impl Cell {
fn from(col: usize, row: usize) -> Cell {
Cell {col, row}
}
}
struct Maze {
cells: [[bool; HEIGHT]; WIDTH], | 587Maze solving
| 15rust
| ig3od |
void transpose(void *dest, void *src, int src_h, int src_w)
{
int i, j;
double (*d)[src_h] = dest, (*s)[src_w] = src;
for (i = 0; i < src_h; i++)
for (j = 0; j < src_w; j++)
d[j][i] = s[i][j];
}
int main()
{
int i, j;
double a[3][5] = {{ 0, 1, 2, 3, 4 },
{ 5, 6, 7, 8, 9 },
{ 1, 0, 0, 0, 42}};
double b[5][3];
transpose(b, a, 3, 5);
for (i = 0; i < 5; i++)
for (j = 0; j < 3; j++)
printf(, b[i][j], j == 2 ? '\n' : ' ');
return 0;
} | 605Matrix transposition
| 5c
| ri3g7 |
enum errors: Error { | 587Maze solving
| 17swift
| 85t0v |
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Digester {
public static void main(String[] args) {
System.out.println(hexDigest("Rosetta code", "MD5"));
}
static String hexDigest(String str, String digestName) {
try {
MessageDigest md = MessageDigest.getInstance(digestName);
byte[] digest = md.digest(str.getBytes(StandardCharsets.UTF_8));
char[] hex = new char[digest.length * 2];
for (int i = 0; i < digest.length; i++) {
hex[2 * i] = "0123456789abcdef".charAt((digest[i] & 0xf0) >> 4);
hex[2 * i + 1] = "0123456789abcdef".charAt(digest[i] & 0x0f);
}
return new String(hex);
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
}
}
} | 590MD5
| 9java
| th6f9 |
import math
from sys import stdout
LOG_10 = 2.302585092994
def build_oms(s):
if s% 2 == 0:
s += 1
q = [[0 for j in range(s)] for i in range(s)]
p = 1
i = s
j = 0
while p <= (s * s):
q[i][j] = p
ti = i + 1
if ti >= s: ti = 0
tj = j - 1
if tj < 0: tj = s - 1
if q[ti][tj] != 0:
ti = i
tj = j + 1
i = ti
j = tj
p = p + 1
return q, s
def build_sems(s):
if s% 2 == 1:
s += 1
while s% 4 == 0:
s += 2
q = [[0 for j in range(s)] for i in range(s)]
z = s
b = z * z
c = 2 * b
d = 3 * b
o = build_oms(z)
for j in range(0, z):
for i in range(0, z):
a = o[0][i][j]
q[i][j] = a
q[i + z][j + z] = a + b
q[i + z][j] = a + c
q[i][j + z] = a + d
lc = z
rc = lc
for j in range(0, z):
for i in range(0, s):
if i < lc or i > s - rc or (i == lc and j == lc):
if not (i == 0 and j == lc):
t = q[i][j]
q[i][j] = q[i][j + z]
q[i][j + z] = t
return q, s
def format_sqr(s, l):
for i in range(0, l - len(s)):
s = + s
return s +
def display(q):
s = q[1]
print(.format(s, s))
k = 1 + math.floor(math.log(s * s) / LOG_10)
for j in range(0, s):
for i in range(0, s):
stdout.write(format_sqr(.format(q[0][i][j]), k))
print()
print(.format(s * ((s * s) + 1)
stdout.write()
display(build_sems(6)) | 600Magic squares of singly even order
| 3python
| vq329 |
package main
import (
"fmt"
"log"
"strings"
)
const dimensions int = 8
func setupMagicSquareData(d int) ([][]int, error) {
var output [][]int
if d < 4 || d%4 != 0 {
return [][]int{}, fmt.Errorf("Square dimension must be a positive number which is divisible by 4")
}
var bits uint = 0x9669 | 603Magic squares of doubly even order
| 0go
| 2xdl7 |
require
magnanimouses = Enumerator.new do |y|
(0..).each {|n| y << n if (1..n.digits.size-1).all? {|k| n.divmod(10**k).sum.prime?} }
end
puts
puts magnanimouses.first(45).join(' ')
puts
puts magnanimouses.first(250).last(10).join(' ')
puts
puts magnanimouses.first(400).last(10).join(' ') | 598Magnanimous numbers
| 14ruby
| jdu7x |
use strict;
package SquareMatrix;
use Carp;
use overload (
'""' => \&_string,
'*' => \&_mult,
'*=' => \&_mult,
'**' => \&_expo,
'=' => \&_copy,
);
sub make {
my $cls = shift;
my $n = @_;
for (@_) {
confess "Bad data @$_: matrix must be square "
if @$_ != $n;
}
bless [ map [@$_], @_ ]
}
sub identity {
my $self = shift;
my $n = @$self - 1;
my @rows = map [ (0) x $_, 1, (0) x ($n - $_) ], 0 .. $n;
bless \@rows
}
sub zero {
my $self = shift;
my $n = @$self;
bless [ map [ (0) x $n ], 1 .. $n ]
}
sub _string {
"[ ".join("\n " =>
map join(" " => map(sprintf("%12.6g", $_), @$_)), @{+shift}
)." ]\n";
}
sub _mult {
my ($a, $b) = @_;
my $x = $a->zero;
my @idx = (0 .. $
for my $j (@idx) {
my @col = map($a->[$_][$j], @idx);
for my $i (@idx) {
my $row = $b->[$i];
$x->[$i][$j] += $row->[$_] * $col[$_] for @idx;
}
}
$x
}
sub _expo {
my ($self, $n) = @_;
confess "matrix **: must be non-negative integer power"
unless $n >= 0 && $n == int($n);
my ($tmp, $out) = ($self, $self->identity);
do {
$out *= $tmp if $n & 1;
$tmp *= $tmp;
} while $n >>= 1;
$out
}
sub _copy { bless [ map [ @$_ ], @{+shift} ] }
package main;
my $m = SquareMatrix->make(
[1, 2, 0],
[0, 3, 1],
[1, 0, 0] );
print "
$m = SquareMatrix->make(
[ 1.0001, 0, 0, 1 ],
[ 0, 1.001, 0, 0 ],
[ 0, 0, 1, 0.99998 ],
[ 1e-8, 0, 0, 1.0002 ]);
print "\n
print "\n
print "\n
print "\n
print "\n
$m->identity ** 1_000_000_000_000; | 591Matrix-exponentiation operator
| 2perl
| rnjgd |
> magic(6)
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 35 1 6 26 19 24
[2,] 3 32 7 21 23 25
[3,] 31 9 2 22 27 20
[4,] 8 28 33 17 10 15
[5,] 30 5 34 12 14 16
[6,] 4 36 29 13 18 11 | 600Magic squares of singly even order
| 13r
| 9admg |
def odd_magic_square(n)
n.times.map{|i| n.times.map{|j| n*((i+j+1+n/2)%n) + ((i+2*j-5)%n) + 1} }
end
def single_even_magic_square(n)
raise ArgumentError, unless (n-2) % 4 == 0
raise ArgumentError, if n == 2
order = (n-2)/4
odd_square = odd_magic_square(n/2)
to_add = (0..3).map{|f| f*n*n/4}
quarts = to_add.map{|f| odd_square.dup.map{|row|row.map{|el| el+f}} }
sq = []
quarts[0].zip(quarts[2]){|d1,d2| sq << [d1,d2].flatten}
quarts[3].zip(quarts[1]){|d1,d2| sq << [d1,d2].flatten}
sq = sq.transpose
order.times{|i| sq[i].rotate!(n/2)}
swap(sq[0][order], sq[0][-order-1])
swap(sq[order][order], sq[order][-order-1])
(order-1).times{|i| sq[-(i+1)].rotate!(n/2)}
randomize(sq)
end
def swap(a,b)
a,b = b,a
end
def randomize(square)
square.shuffle.transpose.shuffle
end
def to_string(square)
n = square.size
fmt = * n
square.inject(){|str,row| str << fmt % row << }
end
puts to_string(single_even_magic_square(6)) | 600Magic squares of singly even order
| 14ruby
| 50yuj |
import Data.List (transpose, unfoldr, intercalate)
import Data.List.Split (chunksOf)
import Data.Bool (bool)
import Control.Monad (forM_)
magicSquare :: Int -> [[Int]]
magicSquare n
| rem n 4 > 0 = []
| otherwise =
chunksOf n $ zipWith (flip (bool =<< (-) limit)) series [1 .. sqr]
where
sqr = n * n
limit = sqr + 1
series
| isPowerOf 2 n = magicSeries $ floor (logBase 2 (fromIntegral sqr))
| otherwise =
concat . concat . concat . scale $ scale <$> chunksOf 4 (magicSeries 4)
where
scale = replicate $ quot n 4
magicSeries :: Int -> [Bool]
magicSeries = (iterate ((++) <*> fmap not) [True] !!)
isPowerOf :: Int -> Int -> Bool
isPowerOf k n = until ((0 /=) . flip rem k) (`quot` k) n == 1
checked :: [[Int]] -> (Int, Bool)
checked square =
let diagonals =
fmap (flip (zipWith (!!)) [0 ..]) . ((:) <*> (return . reverse))
h:t =
sum <$>
square ++
transpose square ++
diagonals square
in (h, all (h ==) t)
table :: String -> [[String]] -> [String]
table delim rows =
let justifyRight c n s = drop (length s) (replicate n c ++ s)
in intercalate delim <$>
transpose
((fmap =<< justifyRight ' ' . maximum . fmap length) <$> transpose rows)
main :: IO ()
main =
forM_ [4, 8, 16] $
\n -> do
let test = magicSquare n
putStrLn $ unlines (table " " (fmap show <$> test))
print $ checked test
putStrLn [] | 603Magic squares of doubly even order
| 8haskell
| ay51g |
fn is_prime(n: u32) -> bool {
if n < 2 {
return false;
}
if n% 2 == 0 {
return n == 2;
}
if n% 3 == 0 {
return n == 3;
}
let mut p = 5;
while p * p <= n {
if n% p == 0 {
return false;
}
p += 2;
if n% p == 0 {
return false;
}
p += 4;
}
true
}
fn is_magnanimous(n: u32) -> bool {
let mut p: u32 = 10;
while n >= p {
if!is_prime(n% p + n / p) {
return false;
}
p *= 10;
}
true
}
fn main() {
let mut m = (0..).filter(|x| is_magnanimous(*x)).take(400);
println!("First 45 magnanimous numbers:");
for (i, n) in m.by_ref().take(45).enumerate() {
if i > 0 && i% 15 == 0 {
println!();
}
print!("{:3} ", n);
}
println!("\n\n241st through 250th magnanimous numbers:");
for n in m.by_ref().skip(195).take(10) {
print!("{} ", n);
}
println!("\n\n391st through 400th magnanimous numbers:");
for n in m.by_ref().skip(140) {
print!("{} ", n);
}
println!();
} | 598Magnanimous numbers
| 15rust
| hf5j2 |
import Foundation
func isPrime(_ n: Int) -> Bool {
if n < 2 {
return false
}
if n% 2 == 0 {
return n == 2
}
if n% 3 == 0 {
return n == 3
}
var p = 5
while p * p <= n {
if n% p == 0 {
return false
}
p += 2
if n% p == 0 {
return false
}
p += 4
}
return true
}
func isMagnanimous(_ n: Int) -> Bool {
var p = 10;
while n >= p {
if!isPrime(n% p + n / p) {
return false
}
p *= 10
}
return true
}
let m = (0...).lazy.filter{isMagnanimous($0)}.prefix(400);
print("First 45 magnanimous numbers:");
for (i, n) in m.prefix(45).enumerated() {
if i > 0 && i% 15 == 0 {
print()
}
print(String(format: "%3d", n), terminator: " ")
}
print("\n\n241st through 250th magnanimous numbers:");
for n in m.dropFirst(240).prefix(10) {
print(n, terminator: " ")
}
print("\n\n391st through 400th magnanimous numbers:");
for n in m.dropFirst(390) {
print(n, terminator: " ")
}
print() | 598Magnanimous numbers
| 17swift
| 7nvrq |
use std::env;
fn main() {
let n: usize =
match env::args().nth(1).and_then(|arg| arg.parse().ok()).ok_or(
"Please specify the size of the magic square, as a positive multiple of 4 plus 2.",
) {
Ok(arg) if arg% 2 == 1 || arg >= 6 && (arg - 2)% 4 == 0 => arg,
Err(e) => panic!(e),
_ => panic!("Argument must be a positive multiple of 4 plus 2."),
};
let (ms, mc) = magic_square_singly_even(n);
println!("n: {}", n);
println!("Magic constant: {}\n", mc);
let width = (n * n).to_string().len() + 1;
for row in ms {
for elem in row {
print!("{e:>w$}", e = elem, w = width);
}
println!();
}
}
fn magic_square_singly_even(n: usize) -> (Vec<Vec<usize>>, usize) {
let size = n * n;
let half = n / 2;
let sub_square_size = size / 4;
let sub_square = magic_square_odd(half);
let quadrant_factors = [0, 2, 3, 1];
let cols_left = half / 2;
let cols_right = cols_left - 1;
let ms = (0..n)
.map(|r| {
(0..n)
.map(|c| {
let localr = if (c < cols_left
|| c >= n - cols_right
|| c == cols_left && r% half == cols_left)
&&!(c == 0 && r% half == cols_left)
{
if r >= half {
r - half
} else {
r + half
}
} else {
r
};
let quadrant = localr / half * 2 + c / half;
let v = sub_square[localr% half][c% half];
v + quadrant_factors[quadrant] * sub_square_size
})
.collect()
})
.collect::<Vec<Vec<_>>>();
(ms, (n * n + 1) * n / 2)
}
fn magic_square_odd(n: usize) -> Vec<Vec<usize>> {
(0..n)
.map(|r| {
(0..n)
.map(|c| {
n * (((c + 1) + (r + 1) - 1 + (n >> 1))% n)
+ (((c + 1) + (2 * (r + 1)) - 2)% n)
+ 1
})
.collect::<Vec<_>>()
})
.collect::<Vec<Vec<_>>>()
} | 600Magic squares of singly even order
| 15rust
| 48m5u |
int f(int n, int x, int y)
{
return (x + y*2 + 1)%n;
}
int main(int argc, char **argv)
{
int i, j, n;
if(argc!=2) return 1;
n = atoi(argv[1]);
if (n < 3 || (n%2) == 0) return 2;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++)
printf(, f(n, n - j - 1, i)*n + f(n, j, i) + 1);
putchar('\n');
}
printf(, (n*n+1)/2*n);
return 0;
} | 606Magic squares of odd order
| 5c
| 8u704 |
(defn transpose
[s]
(apply map vector s))
(defn nested-for
[f x y]
(map (fn [a]
(map (fn [b]
(f a b)) y))
x))
(defn matrix-mult
[a b]
(nested-for (fn [x y] (reduce + (map * x y))) a (transpose b)))
(def ma [[1 1 1 1] [2 4 8 16] [3 9 27 81] [4 16 64 256]])
(def mb [[4 -3 4/3 -1/4] [-13/3 19/4 -7/3 11/24] [3/2 -2 7/6 -1/4] [-1/6 1/4 -1/6 1/24]]) | 604Matrix multiplication
| 6clojure
| ceo9b |
public class MagicSquareDoublyEven {
public static void main(String[] args) {
int n = 8;
for (int[] row : magicSquareDoublyEven(n)) {
for (int x : row)
System.out.printf("%2s ", x);
System.out.println();
}
System.out.printf("\nMagic constant:%d ", (n * n + 1) * n / 2);
}
static int[][] magicSquareDoublyEven(final int n) {
if (n < 4 || n % 4 != 0)
throw new IllegalArgumentException("base must be a positive "
+ "multiple of 4"); | 603Magic squares of doubly even order
| 9java
| jd97c |
(defmulti matrix-transpose
"Switch rows with columns."
class)
(defmethod matrix-transpose clojure.lang.PersistentList
[mtx]
(apply map list mtx))
(defmethod matrix-transpose clojure.lang.PersistentVector
[mtx]
(apply mapv vector mtx)) | 605Matrix transposition
| 6clojure
| bzckz |
>>> from operator import mul
>>> def matrixMul(m1, m2):
return map(
lambda row:
map(
lambda *column:
sum(map(mul, row, column)),
*m2),
m1)
>>> def identity(size):
size = range(size)
return [[(i==j)*1 for i in size] for j in size]
>>> def matrixExp(m, pow):
assert pow>=0 and int(pow)==pow,
accumulator = identity(len(m))
for i in range(pow):
accumulator = matrixMul(accumulator, m)
return accumulator
>>> def printtable(data):
for row in data:
print ' '.join('%-5s'% ('%s'% cell) for cell in row)
>>> m = [[3,2], [2,1]]
>>> for i in range(5):
print '\n%i:'% i
printtable( matrixExp(m, i) )
0:
1 0
0 1
1:
3 2
2 1
2:
13 8
8 5
3:
55 34
34 21
4:
233 144
144 89
>>> printtable( matrixExp(m, 10) )
1346269 832040
832040 514229
>>> | 591Matrix-exponentiation operator
| 3python
| 7dhrm |
def solve(tri):
while len(tri) > 1:
t0 = tri.pop()
t1 = tri.pop()
tri.append([max(t0[i], t0[i+1]) + t for i,t in enumerate(t1)])
return tri[0][0]
data =
print solve([map(int, row.split()) for row in data.splitlines()]) | 588Maximum triangle path sum
| 3python
| o4t81 |
null | 590MD5
| 11kotlin
| o4d8z |
(() => {
'use strict'; | 603Magic squares of doubly even order
| 10javascript
| 16up7 |
library(Biodem)
m <- matrix(c(3,2,2,1), nrow=2)
mtx.exp(m, 0)
mtx.exp(m, 1)
mtx.exp(m, 2)
mtx.exp(m, 3)
mtx.exp(m, 10) | 591Matrix-exponentiation operator
| 13r
| 58guy |
package main
import (
"bytes"
"fmt"
"math/rand"
"time"
)
type maze struct {
c []byte | 597Maze generation
| 0go
| go24n |
int main()
{
int iX,iY;
const int iXmax = 800;
const int iYmax = 800;
double Cx,Cy;
const double CxMin=-2.5;
const double CxMax=1.5;
const double CyMin=-2.0;
const double CyMax=2.0;
double PixelWidth=(CxMax-CxMin)/iXmax;
double PixelHeight=(CyMax-CyMin)/iYmax;
const int MaxColorComponentValue=255;
FILE * fp;
char *filename=;
char *comment=;
static unsigned char color[3];
double Zx, Zy;
double Zx2, Zy2;
int Iteration;
const int IterationMax=200;
const double EscapeRadius=2;
double ER2=EscapeRadius*EscapeRadius;
fp= fopen(filename,);
fprintf(fp,,comment,iXmax,iYmax,MaxColorComponentValue);
for(iY=0;iY<iYmax;iY++)
{
Cy=CyMin + iY*PixelHeight;
if (fabs(Cy)< PixelHeight/2) Cy=0.0;
for(iX=0;iX<iXmax;iX++)
{
Cx=CxMin + iX*PixelWidth;
Zx=0.0;
Zy=0.0;
Zx2=Zx*Zx;
Zy2=Zy*Zy;
for (Iteration=0;Iteration<IterationMax && ((Zx2+Zy2)<ER2);Iteration++)
{
Zy=2*Zx*Zy + Cy;
Zx=Zx2-Zy2 +Cx;
Zx2=Zx*Zx;
Zy2=Zy*Zy;
};
if (Iteration==IterationMax)
{
color[0]=0;
color[1]=0;
color[2]=0;
}
else
{
color[0]=255;
color[1]=255;
color[2]=255;
};
fwrite(color,1,3,fp);
}
}
fclose(fp);
return 0;
} | 607Mandelbrot set
| 5c
| s24q5 |
null | 603Magic squares of doubly even order
| 11kotlin
| 50zua |
package main
import "fmt"
func a(k int, x1, x2, x3, x4, x5 func() int) int {
var b func() int
b = func() int {
k--
return a(k, b, x1, x2, x3, x4)
}
if k <= 0 {
return x4() + x5()
}
return b()
}
func main() {
x := func(i int) func() int { return func() int { return i } }
fmt.Println(a(10, x(1), x(-1), x(-1), x(1), x(0)))
} | 599Man or boy test
| 0go
| emja6 |
import Data.Array.ST
(STArray, freeze, newArray, readArray, writeArray)
import Data.STRef (STRef, newSTRef, readSTRef, writeSTRef)
import System.Random (Random(..), getStdGen, StdGen)
import Control.Monad (forM_, unless)
import Control.Monad.ST (ST, stToIO)
import Data.Array (Array, (!), bounds)
import Data.Bool (bool)
rand
:: Random a
=> (a, a) -> STRef s StdGen -> ST s a
rand range gen = do
(a, g) <- randomR range <$> readSTRef gen
gen `writeSTRef` g
return a
data Maze = Maze
{ rightWalls, belowWalls :: Array (Int, Int) Bool
}
maze :: Int -> Int -> StdGen -> ST s Maze
maze width height gen = do
visited <- mazeArray False
rWalls <- mazeArray True
bWalls <- mazeArray True
gen <- newSTRef gen
(,) <$> rand (0, maxX) gen <*> rand (0, maxY) gen >>=
visit gen visited rWalls bWalls
Maze <$> freeze rWalls <*> freeze bWalls
where
visit gen visited rWalls bWalls here = do
writeArray visited here True
let ns = neighbors here
i <- rand (0, length ns - 1) gen
forM_ (ns !! i: take i ns ++ drop (i + 1) ns) $
\there -> do
seen <- readArray visited there
unless seen $
do removeWall here there
visit gen visited rWalls bWalls there
where
removeWall (x1, y1) (x2, y2) =
writeArray (bool rWalls bWalls (x1 == x2)) (min x1 x2, min y1 y2) False
neighbors (x, y) =
bool [(x - 1, y)] [] (0 == x) ++
bool [(x + 1, y)] [] (maxX == x) ++
bool [(x, y - 1)] [] (0 == y) ++ bool [(x, y + 1)] [] (maxY == y)
maxX = width - 1
maxY = height - 1
mazeArray =
newArray ((0, 0), (maxX, maxY)) :: Bool -> ST s (STArray s (Int, Int) Bool)
printMaze :: Maze -> IO ()
printMaze (Maze rWalls bWalls) = do
putStrLn $ '+': concat (replicate (maxX + 1) "
forM_ [0 .. maxY] $
\y -> do
putStr "|"
forM_ [0 .. maxX] $
\x -> do
putStr " "
putStr $ bool " " "|" (rWalls ! (x, y))
putStrLn ""
forM_ [0 .. maxX] $
\x -> do
putStr "+"
putStr $ bool " " "
putStrLn "+"
where
maxX = fst (snd $ bounds rWalls)
maxY = snd (snd $ bounds rWalls)
main :: IO ()
main = getStdGen >>= stToIO . maze 11 8 >>= printMaze | 597Maze generation
| 8haskell
| s2aqk |
$ irb
irb(main):001:0> require 'matrix'
=> true
irb(main):002:0> m=Matrix[[3,2],[2,1]]
=> Matrix[[3, 2], [2, 1]]
irb(main):003:0> m**0
=> Matrix[[1, 0], [0, 1]]
irb(main):004:0> m ** 1
=> Matrix[[3, 2], [2, 1]]
irb(main):005:0> m ** 2
=> Matrix[[13, 8], [8, 5]]
irb(main):006:0> m ** 5
=> Matrix[[987, 610], [610, 377]]
irb(main):007:0> m ** 10
=> Matrix[[1346269, 832040], [832040, 514229]] | 591Matrix-exponentiation operator
| 14ruby
| htbjx |
use std::fmt;
use std::ops;
const WIDTH: usize = 6;
#[derive(Clone)]
struct SqMat {
data: Vec<Vec<i64>>,
}
impl fmt::Debug for SqMat {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut row = "".to_string();
for i in &self.data {
for j in i {
row += &format!("{:>w$} ", j, w = WIDTH);
}
row += &"\n";
}
write!(f, "{}", row)
}
}
impl ops::BitXor<u32> for SqMat {
type Output = Self;
fn bitxor(self, n: u32) -> Self::Output {
let mut aux = self.data.clone();
let mut ans: SqMat = SqMat {
data: vec![vec![0; aux.len()]; aux.len()],
};
for i in 0..aux.len() {
ans.data[i][i] = 1;
}
let mut b = n;
while b > 0 {
if b & 1 > 0 { | 591Matrix-exponentiation operator
| 15rust
| kzph5 |
include "NSLog.incl"
local fn MapRange( s as double, a1 as double, a2 as double, b1 as double, b2 as double ) as double
end fn = b1+(s-a1)*(b2-b1)/(a2-a1)
NSInteger i
for i = 0 to 10
NSLog( @"%2d maps to%5.1f", i, fn MapRange( i, 0, 10, -1, 0 ) )
next
HandleEvents | 602Map range
| 0go
| 8ub0g |
package main
import "fmt"
type rangeBounds struct {
b1, b2 float64
}
func mapRange(x, y rangeBounds, n float64) float64 {
return y.b1 + (n - x.b1) * (y.b2 - y.b1) / (x.b2 - x.b1)
}
func main() {
r1 := rangeBounds{0, 10}
r2 := rangeBounds{-1, 0}
for n := float64(0); n <= 10; n += 2 {
fmt.Println(n, "maps to", mapRange(r1, r2, n))
}
} | 602Map range
| 0go
| 8ub0g |
import bitops, sequtils, strutils
type Square = seq[seq[int]]
func magicSquareDoublyEven(n: int): Square =
## Build a magic square of doubly even order.
assert n >= 4 and (n and 3) == 0, "base must be a positive multiple of 4."
result = newSeqWith(n, newSeq[int](n))
const bits = 0b1001_0110_0110_1001 # Pattern of count-up vs count-down zones.
let size = n * n
let mult = n div 4 # How many multiples of 4.
var i = 0
for r in 0..<n:
for c in 0..<n:
let bitPos = c div mult + r div mult * 4
result[r][c] = if bits.testBit(bitPos): i + 1 else: size - i
inc i
func `$`(square: Square): string =
## Return the string representation of a magic square.
let length = len($(square.len * square.len))
for row in square:
result.add row.mapIt(($it).align(length)).join(" ") & '\n'
when isMainModule:
let n = 8
echo magicSquareDoublyEven(n)
echo "Magic constant = ", n * (n * n + 1) div 2 | 603Magic squares of doubly even order
| 1lua
| 4835c |
def a; a = { k, x1, x2, x3, x4, x5 ->
def b; b = {
a (--k, b, x1, x2, x3, x4)
}
k <= 0 ? x4() + x5(): b()
}
def x = { n -> { it -> n } } | 599Man or boy test
| 7groovy
| kt5h7 |
class Matrix[T](matrix:Array[Array[T]])(implicit n: Numeric[T], m: ClassManifest[T])
{
import n._
val rows=matrix.size
val cols=matrix(0).size
def row(i:Int)=matrix(i)
def col(i:Int)=matrix map (_(i))
def *(other: Matrix[T]):Matrix[T] = new Matrix(
Array.tabulate(rows, other.cols)((row, col) =>
(this.row(row), other.col(col)).zipped.map(_*_) reduceLeft (_+_)
))
def **(x: Int)=x match {
case 0 => createIdentityMatrix
case 1 => this
case 2 => this * this
case _ => List.fill(x)(this) reduceLeft (_*_)
}
def createIdentityMatrix=new Matrix(Array.tabulate(rows, cols)((row,col) =>
if (row == col) one else zero)
)
override def toString = matrix map (_.mkString("[", ", ", "]")) mkString "\n"
}
object MatrixTest {
def main(args:Array[String])={
val m=new Matrix[BigInt](Array(Array(3,2), Array(2,1)))
println("-- m --\n"+m)
Seq(0,1,2,3,4,10,20,50) foreach {x =>
println("-- m**"+x+" --")
println(m**x)
}
}
} | 591Matrix-exponentiation operator
| 16scala
| 1yepf |
def mapRange(a1, a2, b1, b2, s) {
b1 + ((s - a1) * (b2 - b1)) / (a2 - a1)
}
(0..10).each { s ->
println(s + " in [0, 10] maps to " + mapRange(0, 10, -1, 0, s) + " in [-1, 0].")
} | 602Map range
| 7groovy
| w9rel |
import Data.Ratio
import Text.Printf (PrintfType, printf)
mapRange
:: Fractional a
=> (a, a) -> (a, a) -> a -> a
mapRange (a1, a2) (b1, b2) s = b1 + (s - a1) * (b2 - b1) / (a2 - a1)
main :: IO ()
main
= do
putStrLn "
mapM_ (\n -> prtD n . mapRange (0, 10) (-1, 0) $ fromIntegral n) [0 .. 10]
putStrLn "
mapM_ (\n -> prtR n . mapRange (0, 10) (-1, 0) $ n % 1) [0 .. 10]
where
prtD
:: PrintfType r
=> Integer -> Double -> r
prtD = printf "%2d ->%6.3f\n"
prtR
:: PrintfType r
=> Integer -> Rational -> r
prtR n x = printf "%2d ->%s\n" n (show x) | 602Map range
| 8haskell
| lwdch |
null | 603Magic squares of doubly even order
| 2perl
| o5b8x |
import Data.IORef (modifyIORef, newIORef, readIORef)
a
:: (Enum a, Num b, Num a, Ord a)
=> a -> IO b -> IO b -> IO b -> IO b -> IO b -> IO b
a k x1 x2 x3 x4 x5 = do
r <- newIORef k
let b = do
k <- pred ! r
a k b x1 x2 x3 x4
if k <= 0
then (+) <$> x4 <*> x5
else b
where
f !r = modifyIORef r f >> readIORef r
main :: IO ()
main = a 10 # 1 # (-1) # (-1) # 1 # 0 >>= print
where
( # ) f = f . return | 599Man or boy test
| 8haskell
| 3kozj |
triangle =
ar = triangle.each_line.map{|line| line.split.map(&:to_i)}
puts ar.inject([]){|res,x|
maxes = [0, *res, 0].each_cons(2).map(&:max)
x.zip(maxes).map{|a,b| a+b}
}.max | 588Maximum triangle path sum
| 14ruby
| nr3it |
require "md5" | 590MD5
| 1lua
| igfot |
public class Range {
public static void main(String[] args){
for(float s = 0;s <= 10; s++){
System.out.println(s + " in [0, 10] maps to "+
mapRange(0, 10, -1, 0, s)+" in [-1, 0].");
}
}
public static double mapRange(double a1, double a2, double b1, double b2, double s){
return b1 + ((s - a1)*(b2 - b1))/(a2 - a1);
}
} | 602Map range
| 9java
| 3kszg |
use std::cmp::max;
fn max_path(vector: &mut Vec<Vec<u32>>) -> u32 {
while vector.len() > 1 {
let last = vector.pop().unwrap();
let ante = vector.pop().unwrap();
let mut new: Vec<u32> = Vec::new();
for (i, value) in ante.iter().enumerate() {
new.push(max(last[i], last[i+1]) + value);
};
vector.push(new);
};
vector[0][0]
}
fn main() {
let mut data = "55
94 48
95 30 96
77 71 26 67
97 13 76 38 45
07 36 79 16 37 68
48 07 09 18 70 26 06
18 72 79 46 59 79 29 90
20 76 87 11 32 07 07 49 18
27 83 58 35 71 11 25 57 29 85
14 64 36 96 27 11 58 56 92 18 55
02 90 03 60 48 49 41 46 33 36 47 23
92 50 48 02 36 59 42 79 72 20 82 77 42
56 78 38 80 39 75 02 71 66 66 01 03 55 72
44 25 67 84 71 67 11 61 40 57 58 89 40 56 36
85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52
06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15
27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93";
let mut vector = data.split("\n").map(|x| x.split(" ").map(|s: &str| s.parse::<u32>().unwrap())
.collect::<Vec<u32>>()).collect::<Vec<Vec<u32>>>();
let max_value = max_path(&mut vector);
println!("{}", max_value); | 588Maximum triangle path sum
| 15rust
| d76ny |
package org.rosettacode;
import java.util.Collections;
import java.util.Arrays;
public class MazeGenerator {
private final int x;
private final int y;
private final int[][] maze;
public MazeGenerator(int x, int y) {
this.x = x;
this.y = y;
maze = new int[this.x][this.y];
generateMaze(0, 0);
}
public void display() {
for (int i = 0; i < y; i++) { | 597Maze generation
| 9java
| 16jp2 |
null | 602Map range
| 10javascript
| cen9j |
object MaximumTrianglePathSum extends App { | 588Maximum triangle path sum
| 16scala
| zk9tr |
(ns mandelbrot
(:refer-clojure :exclude [+ * <])
(:use (clojure.contrib complex-numbers)
(clojure.contrib.generic [arithmetic :only [+ *]]
[comparison :only [<]]
[math-functions :only [abs]])))
(defn mandelbrot? [z]
(loop [c 1
m (iterate #(+ z (* % %)) 0)]
(if (and (> 20 c)
(< (abs (first m)) 2) )
(recur (inc c)
(rest m))
(if (= 20 c) true false))))
(defn mandelbrot []
(for [y (range 1 -1 -0.05)
x (range -2 0.5 0.0315)]
(if (mandelbrot? (complex x y)) "#" " ")))
(println (interpose \newline (map #(apply str %) (partition 80 (mandelbrot))))) | 607Mandelbrot set
| 6clojure
| nghik |
def MagicSquareDoublyEven(order):
sq = [range(1+n*order,order + (n*order)+1) for n in range(order) ]
n1 = order/4
for r in range(n1):
r1 = sq[r][n1:-n1]
r2 = sq[order -r - 1][n1:-n1]
r1.reverse()
r2.reverse()
sq[r][n1:-n1] = r2
sq[order -r - 1][n1:-n1] = r1
for r in range(n1, order-n1):
r1 = sq[r][:n1]
r2 = sq[order -r - 1][order-n1:]
r1.reverse()
r2.reverse()
sq[r][:n1] = r2
sq[order -r - 1][order-n1:] = r1
return sq
def printsq(s):
n = len(s)
bl = len(str(n**2))+1
for i in range(n):
print ''.join( [ (+str(bl)+)%(str(x)) for x in s[i]] )
print %sum(s[0])
printsq(MagicSquareDoublyEven(8)) | 603Magic squares of doubly even order
| 3python
| i4pof |
import java.util.function.DoubleSupplier;
public class ManOrBoy {
static double A(int k, DoubleSupplier x1, DoubleSupplier x2,
DoubleSupplier x3, DoubleSupplier x4, DoubleSupplier x5) {
DoubleSupplier B = new DoubleSupplier() {
int m = k;
public double getAsDouble() {
return A(--m, this, x1, x2, x3, x4);
}
};
return k <= 0 ? x4.getAsDouble() + x5.getAsDouble() : B.getAsDouble();
}
public static void main(String[] args) {
System.out.println(A(10, () -> 1.0, () -> -1.0, () -> -1.0, () -> 1.0, () -> 0.0));
}
} | 599Man or boy test
| 9java
| i4wos |
function maze(x,y) {
var n=x*y-1;
if (n<0) {alert("illegal maze dimensions");return;}
var horiz =[]; for (var j= 0; j<x+1; j++) horiz[j]= [],
verti =[]; for (var j= 0; j<x+1; j++) verti[j]= [],
here = [Math.floor(Math.random()*x), Math.floor(Math.random()*y)],
path = [here],
unvisited = [];
for (var j = 0; j<x+2; j++) {
unvisited[j] = [];
for (var k= 0; k<y+1; k++)
unvisited[j].push(j>0 && j<x+1 && k>0 && (j != here[0]+1 || k != here[1]+1));
}
while (0<n) {
var potential = [[here[0]+1, here[1]], [here[0],here[1]+1],
[here[0]-1, here[1]], [here[0],here[1]-1]];
var neighbors = [];
for (var j = 0; j < 4; j++)
if (unvisited[potential[j][0]+1][potential[j][1]+1])
neighbors.push(potential[j]);
if (neighbors.length) {
n = n-1;
next= neighbors[Math.floor(Math.random()*neighbors.length)];
unvisited[next[0]+1][next[1]+1]= false;
if (next[0] == here[0])
horiz[next[0]][(next[1]+here[1]-1)/2]= true;
else
verti[(next[0]+here[0]-1)/2][next[1]]= true;
path.push(here = next);
} else
here = path.pop();
}
return {x: x, y: y, horiz: horiz, verti: verti};
}
function display(m) {
var text= [];
for (var j= 0; j<m.x*2+1; j++) {
var line= [];
if (0 == j%2)
for (var k=0; k<m.y*4+1; k++)
if (0 == k%4)
line[k]= '+';
else
if (j>0 && m.verti[j/2-1][Math.floor(k/4)])
line[k]= ' ';
else
line[k]= '-';
else
for (var k=0; k<m.y*4+1; k++)
if (0 == k%4)
if (k>0 && m.horiz[(j-1)/2][k/4-1])
line[k]= ' ';
else
line[k]= '|';
else
line[k]= ' ';
if (0 == j) line[1]= line[2]= line[3]= ' ';
if (m.x*2-1 == j) line[4*m.y]= ' ';
text.push(line.join('')+'\r\n');
}
return text.join('');
} | 597Maze generation
| 10javascript
| ql1x8 |
magic <- function(n) {
if (n%% 2 == 1) {
p <- (n + 1)%/% 2 - 2
ii <- seq(n)
outer(ii, ii, function(i, j) n * ((i + j + p)%% n) + (i + 2 * (j - 1))%% n + 1)
} else if (n%% 4 == 0) {
p <- n * (n + 1) + 1
ii <- seq(n)
outer(ii, ii, function(i, j) ifelse((i%/% 2 - j%/% 2)%% 2 == 0, p - n * i - j, n * (i - 1) + j))
} else {
p <- n%/% 2
q <- p * p
k <- (n - 2)%/% 4 + 1
a <- Recall(p)
a <- rbind(cbind(a, a + 2 * q), cbind(a + 3 * q, a + q))
ii <- seq(p)
jj <- c(seq(k - 1), seq(length.out=k - 2, to=n))
m <- a[ii, jj]; a[ii, jj] <- a[ii + p, jj]; a[ii + p, jj] <- m
jj <- c(1, k)
m <- a[k, jj]; a[k, jj] <- a[k + p, jj]; a[k + p, jj] <- m
a
}
} | 603Magic squares of doubly even order
| 13r
| s2jqy |
function a(k, x1, x2, x3, x4, x5) {
function b() {
k -= 1;
return a(k, b, x1, x2, x3, x4);
}
return (k > 0) ? b() : x4() + x5();
} | 599Man or boy test
| 10javascript
| zh8t2 |
null | 602Map range
| 11kotlin
| ngaij |
package main
import (
"fmt"
"log"
)
func ms(n int) (int, []int) {
M := func(x int) int { return (x + n - 1) % n }
if n <= 0 || n&1 == 0 {
n = 5
log.Println("forcing size", n)
}
m := make([]int, n*n)
i, j := 0, n/2
for k := 1; k <= n*n; k++ {
m[i*n+j] = k
if m[M(i)*n+M(j)] != 0 {
i = (i + 1) % n
} else {
i, j = M(i), M(j)
}
}
return n, m
}
func main() {
n, m := ms(5)
i := 2
for j := 1; j <= n*n; j *= 10 {
i++
}
f := fmt.Sprintf("%%%dd", i)
for i := 0; i < n; i++ {
for j := 0; j < n; j++ {
fmt.Printf(f, m[i*n+j])
}
fmt.Println()
}
} | 606Magic squares of odd order
| 0go
| 50dul |
import java.util.*
class MazeGenerator(val x: Int, val y: Int) {
private val maze = Array(x) { IntArray(y) }
fun generate(cx: Int, cy: Int) {
Direction.values().shuffle().forEach {
val nx = cx + it.dx
val ny = cy + it.dy
if (between(nx, x) && between(ny, y) && maze[nx][ny] == 0) {
maze[cx][cy] = maze[cx][cy] or it.bit
maze[nx][ny] = maze[nx][ny] or it.opposite!!.bit
generate(nx, ny)
}
}
}
fun display() {
for (i in 0..y - 1) { | 597Maze generation
| 11kotlin
| jd57r |
import Data.List
type Var = (Int, Int, Int, Int)
magicSum :: Int -> Int
magicSum x = ((x * x + 1) `div` 2) * x
wrapInc :: Int -> Int -> Int
wrapInc max x
| x + 1 == max = 0
| otherwise = x + 1
wrapDec :: Int -> Int -> Int
wrapDec max x
| x == 0 = max - 1
| otherwise = x - 1
isZero :: [[Int]] -> Int -> Int -> Bool
isZero m x y = m !! x !! y == 0
setAt :: (Int,Int) -> Int -> [[Int]] -> [[Int]]
setAt (x, y) val table
| (upper, current: lower) <- splitAt x table,
(left, this: right) <- splitAt y current
= upper ++ (left ++ val: right): lower
| otherwise = error "Outside"
create :: Int -> [[Int]]
create x = replicate x $ replicate x 0
cells :: [[Int]] -> Int
cells m = x*x where x = length m
fill :: Var -> [[Int]] -> [[Int]]
fill (sx, sy, sz, c) m
| c < cells m =
if isZero m sx sy
then fill ((wrapInc sz sx), (wrapDec sz sy), sz, c + 1) (setAt (sx, sy) (c + 1) m)
else fill ((wrapDec sz sx), (wrapInc sz(wrapInc sz sy)), sz, c) m
| otherwise = m
magicNumber :: Int -> [[Int]]
magicNumber d = transpose $ fill (d `div` 2, 0, d, 0) (create d)
display :: [[Int]] -> String
display (x:xs)
| null xs = vdisplay x
| otherwise = vdisplay x ++ ('\n': display xs)
vdisplay :: [Int] -> String
vdisplay (x:xs)
| null xs = show x
| otherwise = show x ++ " " ++ vdisplay xs
magicSquare x = do
putStr "Magic Square of "
putStr $ show x
putStr " = "
putStrLn $ show $ magicSum x
putStrLn $ display $ magicNumber x | 606Magic squares of odd order
| 8haskell
| xc5w4 |
def double_even_magic_square(n)
raise ArgumentError, if n%4 > 0
block_size, max = n/4, n*n
pre_pat = [true, false, false, true,
false, true, true, false]
pre_pat += pre_pat.reverse
pattern = pre_pat.flat_map{|b| [b] * block_size} * block_size
flat_ar = pattern.each_with_index.map{|yes, num| yes? num+1: max-num}
flat_ar.each_slice(n).to_a
end
def to_string(square)
n = square.size
fmt = * n
square.inject(){|str,row| str << fmt % row << }
end
puts to_string(double_even_magic_square(8)) | 603Magic squares of doubly even order
| 14ruby
| drans |
use std::env;
fn main() {
let n: usize = match env::args()
.nth(1)
.and_then(|arg| arg.parse().ok())
.ok_or("Please specify the size of the magic square, as a positive multiple of 4.")
{
Ok(arg) if arg >= 4 && arg% 4 == 0 => arg,
Err(e) => panic!(e),
_ => panic!("Argument must be a positive multiple of 4."),
};
let mc = (n * n + 1) * n / 2;
println!("Magic constant: {}\n", mc);
let bits = 0b1001_0110_0110_1001u32;
let size = n * n;
let width = size.to_string().len() + 1;
let mult = n / 4;
let mut i = 0;
for r in 0..n {
for c in 0..n {
let bit_pos = c / mult + (r / mult) * 4;
print!(
"{e:>w$}",
e = if bits & (1 << bit_pos)!= 0 {
i + 1
} else {
size - i
},
w = width
);
i += 1;
}
println!();
}
} | 603Magic squares of doubly even order
| 15rust
| f7ed6 |
null | 599Man or boy test
| 11kotlin
| qlbx1 |
math.randomseed( os.time() ) | 597Maze generation
| 1lua
| hf4j8 |
object MagicSquareDoublyEven extends App {
private val n = 8
private def magicSquareDoublyEven(n: Int): Array[Array[Int]] = {
require(n >= 4 || n % 4 == 0, "Base must be a positive multiple of 4.") | 603Magic squares of doubly even order
| 16scala
| 3kqzy |
function a(k,x1,x2,x3,x4,x5)
local function b()
k = k - 1
return a(k,b,x1,x2,x3,x4)
end
if k <= 0 then return x4() + x5() else return b() end
end
function K(n)
return function()
return n
end
end
print(a(10, K(1), K(-1), K(-1), K(1), K(0))) | 599Man or boy test
| 1lua
| s2pq8 |
function map_range( a1, a2, b1, b2, s )
return b1 + (s-a1)*(b2-b1)/(a2-a1)
end
for i = 0, 10 do
print( string.format( "f(%d) =%f", i, map_range( 0, 10, -1, 0, i ) ) )
end | 602Map range
| 1lua
| drenq |
class Complex {
double _r,_i;
Complex(this._r,this._i);
double get r => _r;
double get i => _i;
String toString() => "($r,$i)";
Complex operator +(Complex other) => new Complex(r+other.r,i+other.i);
Complex operator *(Complex other) =>
new Complex(r*other.r-i*other.i,r*other.i+other.r*i);
double abs() => r*r+i*i;
}
void main() {
double start_x=-1.5;
double start_y=-1.0;
double step_x=0.03;
double step_y=0.1;
for(int y=0;y<20;y++) {
String line="";
for(int x=0;x<70;x++) {
Complex c=new Complex(start_x+step_x*x,start_y+step_y*y);
Complex z=new Complex(0.0, 0.0);
for(int i=0;i<100;i++) {
z=z*(z)+c;
if(z.abs()>2) {
break;
}
}
line+=z.abs()>2? " ": "*";
}
print(line);
}
} | 607Mandelbrot set
| 18dart
| 16cp0 |
public class MagicSquare {
public static void main(String[] args) {
int n = 5;
for (int[] row : magicSquareOdd(n)) {
for (int x : row)
System.out.format("%2s ", x);
System.out.println();
}
System.out.printf("\nMagic constant:%d ", (n * n + 1) * n / 2);
}
public static int[][] magicSquareOdd(final int base) {
if (base % 2 == 0 || base < 3)
throw new IllegalArgumentException("base must be odd and > 2");
int[][] grid = new int[base][base];
int r = 0, number = 0;
int size = base * base;
int c = base / 2;
while (number++ < size) {
grid[r][c] = number;
if (r == 0) {
if (c == base - 1) {
r++;
} else {
r = base - 1;
c++;
}
} else {
if (c == base - 1) {
r--;
c = 0;
} else {
if (grid[r - 1][c + 1] == 0) {
r--;
c++;
} else {
r++;
}
}
}
}
return grid;
}
} | 606Magic squares of odd order
| 9java
| bz9k3 |
(function () { | 606Magic squares of odd order
| 10javascript
| w9ue2 |
null | 606Magic squares of odd order
| 11kotlin
| rizgo |
rp[v_, pos_]:= RotateRight[v, (Length[v] + 1)/2 - pos];
rho[m_]:= MapIndexed[rp, m];
magic[n_]:=
rho[Transpose[rho[Table[i*n + j, {i, 0, n - 1}, {j, 1, n}]]]];
square = magic[11] // Grid
Print["Magic number is ", Total[square[[1, 1]]]] | 606Magic squares of odd order
| 1lua
| 7n3ru |
sub A {
my ($k, $x1, $x2, $x3, $x4, $x5) = @_;
my($B);
$B = sub { A(--$k, $B, $x1, $x2, $x3, $x4) };
$k <= 0 ? &$x4 + &$x5 : &$B;
}
print A(10, sub{1}, sub {-1}, sub{-1}, sub{1}, sub{0} ), "\n"; | 599Man or boy test
| 2perl
| vq620 |
use List::Util 'max';
my ($w, $h) = @ARGV;
$w ||= 26;
$h ||= 127;
my $avail = $w * $h;
my @cell = (map([(('1') x $w), 0], 1 .. $h), [('') x ($w + 1)]);
my @ver = map([("| ") x $w], 1 .. $h);
my @hor = map([("+--") x $w], 0 .. $h);
sub walk {
my ($x, $y) = @_;
$cell[$y][$x] = '';
$avail-- or return;
my @d = ([-1, 0], [0, 1], [1, 0], [0, -1]);
while (@d) {
my $i = splice @d, int(rand @d), 1;
my ($x1, $y1) = ($x + $i->[0], $y + $i->[1]);
$cell[$y1][$x1] or next;
if ($x == $x1) { $hor[ max($y1, $y) ][$x] = '+ ' }
if ($y == $y1) { $ver[$y][ max($x1, $x) ] = ' ' }
walk($x1, $y1);
}
}
walk(int rand $w, int rand $h);
for (0 .. $h) {
print @{$hor[$_]}, "+\n";
print @{$ver[$_]}, "|\n" if $_ < $h;
} | 597Maze generation
| 2perl
| tjofg |
use strict ;
sub mapValue {
my ( $range1 , $range2 , $number ) = @_ ;
return ( $range2->[ 0 ] +
(( $number - $range1->[ 0 ] ) * ( $range2->[ 1 ] - $range2->[ 0 ] ) ) / ( $range1->[ -1 ]
- $range1->[ 0 ] ) ) ;
}
my @numbers = 0..10 ;
my @interval = ( -1 , 0 ) ;
print "The mapped value for $_ is " . mapValue( \@numbers , \@interval , $_ ) . "!\n" foreach @numbers ; | 602Map range
| 2perl
| 7n9rh |
<?php
function A($k,$x1,$x2,$x3,$x4,$x5) {
$b = function () use (&$b,&$k,$x1,$x2,$x3,$x4) {
return A(--$k,$b,$x1,$x2,$x3,$x4);
};
return $k <= 0? $x4() + $x5() : $b();
}
echo A(10, function () { return 1; },
function () { return -1; },
function () { return -1; },
function () { return 1; },
function () { return 0; }) . ;
?> | 599Man or boy test
| 12php
| 0v1sp |
<?php
class Maze
{
protected $width;
protected $height;
protected $grid;
protected $path;
protected $horWalls;
protected $vertWalls;
protected $dirs;
protected $isDebug;
public function __construct($x, $y, $debug = false)
{
$this->width = $x;
$this->height = $y;
$this->path = [];
$this->dirs = [ [0, -1], [0, 1], [-1, 0], [1, 0]];
$this->horWalls = [];
$this->vertWalls = [];
$this->isDebug = $debug;
$this->generate();
}
protected function generate()
{
$this->initMaze();
$this->walk(mt_rand(0, $this->width-1), mt_rand(0, $this->height-1));
}
public function printOut()
{
$this->log(, json_encode($this->horWalls));
$this->log(, json_encode($this->vertWalls));
$northDoor = mt_rand(0,$this->width-1);
$eastDoor = mt_rand(0, $this->height-1);
$str = '+';
for ($i=0;$i<$this->width;$i++) {
$str .= ($northDoor == $i)? ' +' : '---+';
}
$str .= PHP_EOL;
for ($i=0; $i<$this->height; $i++) {
for ($j=0; $j<$this->width; $j++) {
$str .= (!empty($this->vertWalls[$j][$i])? $this->vertWalls[$j][$i] : '| ');
}
$str .= ($i == $eastDoor? ' ' : '|').PHP_EOL.'+';
for ($j=0; $j<$this->width; $j++) {
$str .= (!empty($this->horWalls[$j][$i])? $this->horWalls[$j][$i] : '---+');
}
$str .= PHP_EOL;
}
echo $str;
}
protected function log(...$params)
{
if ($this->isDebug) {
echo vsprintf(array_shift($params), $params).PHP_EOL;
}
}
private function walk($x, $y)
{
$this->log('Entering cell%d,%d', $x, $y);
$this->grid[$x][$y] = true;
$this->path[] = [$x, $y];
$neighbors = $this->getNeighbors($x, $y);
$this->log(, json_encode($neighbors));
if(empty($neighbors)) {
$this->log(, json_encode($this->path));
array_pop($this->path);
if (!empty($this->path)) {
$next = array_pop($this->path);
return $this->walk($next[0], $next[1]);
}
} else {
shuffle($neighbors);
foreach ($neighbors as $n) {
$nextX = $n[0];
$nextY = $n[1];
if ($nextX == $x) {
$wallY = max($nextY, $y);
$this->log(, $nextX, $nextY, $x, $wallY);
$this->horWalls[$x][min($nextY, $y)] = ;
}
if ($nextY == $y) {
$wallX = max($nextX, $x);
$this->log(, $nextX, $nextY, $wallX, $y);
$this->vertWalls[$wallX][$y] = ;
}
return $this->walk($nextX, $nextY);
}
}
}
private function initMaze()
{
for ($i=0;$i<$this->width;$i++) {
for ($j = 0;$j<$this->height;$j++) {
$this->grid[$i][$j] = false;
}
}
}
private function getNeighbors($x, $y)
{
$neighbors = [];
foreach ($this->dirs as $dir) {
$nextX = $dir[0] + $x;
$nextY = $dir[1] + $y;
if (($nextX >= 0 && $nextX < $this->width && $nextY >= 0 && $nextY < $this->height) && !$this->grid[$nextX][$nextY]) {
$neighbors[] = [$nextX, $nextY];
}
}
return $neighbors;
}
}
$maze = new Maze(10,10);
$maze->printOut(); | 597Maze generation
| 12php
| ktghv |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.