code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
null | 606Magic squares of odd order
| 2perl
| drbnw |
package main
import (
"fmt"
"gonum.org/v1/gonum/mat"
)
func main() {
m := mat.NewDense(2, 3, []float64{
1, 2, 3,
4, 5, 6,
})
fmt.Println(mat.Formatted(m))
fmt.Println()
fmt.Println(mat.Formatted(m.T()))
} | 605Matrix transposition
| 0go
| ngbi1 |
package main
import (
"fmt"
"gonum.org/v1/gonum/mat"
)
func main() {
a := mat.NewDense(2, 4, []float64{
1, 2, 3, 4,
5, 6, 7, 8,
})
b := mat.NewDense(4, 3, []float64{
1, 2, 3,
4, 5, 6,
7, 8, 9,
10, 11, 12,
})
var m mat.Dense
m.Mul(a, b)
fmt.Println(mat.Formatted(&m))
} | 604Matrix multiplication
| 0go
| bzlkh |
import sys
sys.setrecursionlimit(1025)
def a(in_k, x1, x2, x3, x4, x5):
k = [in_k]
def b():
k[0] -= 1
return a(k[0], b, x1, x2, x3, x4)
return x4() + x5() if k[0] <= 0 else b()
x = lambda i: lambda: i
print(a(10, x(1), x(-1), x(-1), x(1), x(0))) | 599Man or boy test
| 3python
| usyvd |
def matrix = [ [ 1, 2, 3, 4 ],
[ 5, 6, 7, 8 ] ]
matrix.each { println it }
println()
def transpose = matrix.transpose()
transpose.each { println it } | 605Matrix transposition
| 7groovy
| s2rq1 |
>>> def maprange( a, b, s):
(a1, a2), (b1, b2) = a, b
return b1 + ((s - a1) * (b2 - b1) / (a2 - a1))
>>> for s in range(11):
print(% (s, maprange( (0, 10), (-1, 0), s)))
0 maps to -1
1 maps to -0.9
2 maps to -0.8
3 maps to -0.7
4 maps to -0.6
5 maps to -0.5
6 maps to -0.4
7 maps to -0.3
8 maps to -0.2
9 maps to -0.1
10 maps to 0 | 602Map range
| 3python
| jdc7p |
def assertConformable = { a, b ->
assert a instanceof List
assert b instanceof List
assert a.every { it instanceof List && it.size() == b.size() }
assert b.every { it instanceof List && it.size() == b[0].size() }
}
def matmulWOIL = { a, b ->
assertConformable(a, b)
def bt = b.transpose()
a.collect { ai ->
bt.collect { btj ->
[ai, btj].transpose().collect { it[0] * it[1] }.sum()
}
}
} | 604Matrix multiplication
| 7groovy
| ri6gh |
n <- function(x) function()x
A <- function(k, x1, x2, x3, x4, x5) {
B <- function() A(k <<- k-1, B, x1, x2, x3, x4)
if (k <= 0) x4() + x5() else B()
}
A(10, n(1), n(-1), n(-1), n(1), n(0)) | 599Man or boy test
| 13r
| cet95 |
*Main> transpose [[1,2],[3,4],[5,6]]
[[1,3,5],[2,4,6]] | 605Matrix transposition
| 8haskell
| usdv2 |
tRange <- function(aRange, bRange, s)
{
stopifnot(length(aRange) == 2, length(bRange) == 2,
is.numeric(aRange), is.numeric(bRange), is.numeric(s),
s >= aRange[1], s <= aRange[2])
bRange[1] + ((s - aRange[1]) * (bRange[2] - bRange[1])) / (aRange[2] - aRange[1])
}
data.frame(s = 0:10, t = sapply(0:10, tRange, aRange = c(0, 10), bRange = c(-1, 0))) | 602Map range
| 13r
| 4865y |
import Data.List
mmult :: Num a => [[a]] -> [[a]] -> [[a]]
mmult a b = [ [ sum $ zipWith (*) ar bc | bc <- (transpose b) ] | ar <- a ]
test = [[1, 2],
[3, 4]] `mmult` [[-3, -8, 3],
[-2, 1, 4]] | 604Matrix multiplication
| 8haskell
| dr1n4 |
use Digest::MD5 qw(md5_hex);
print md5_hex("The quick brown fox jumped over the lazy dog's back"), "\n"; | 590MD5
| 2perl
| gij4e |
>>> def magic(n):
for row in range(1, n + 1):
print(' '.join('%*i'% (len(str(n**2)), cell) for cell in
(n * ((row + col - 1 + n
((row + 2 * col - 2)% n) + 1
for col in range(1, n + 1))))
print('\nAll sum to magic number%i'% ((n * n + 1) * n
>>> for n in (5, 3, 7):
print('\nOrder%i\n======='% n)
magic(n)
Order 5
=======
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
All sum to magic number 65
Order 3
=======
8 1 6
3 5 7
4 9 2
All sum to magic number 15
Order 7
=======
30 39 48 1 10 19 28
38 47 7 9 18 27 29
46 6 8 17 26 35 37
5 14 16 25 34 36 45
13 15 24 33 42 44 4
21 23 32 41 43 3 12
22 31 40 49 2 11 20
All sum to magic number 175
>>> | 606Magic squares of odd order
| 3python
| f7pde |
def a(k, x1, x2, x3, x4, x5)
b = lambda { k -= 1; a(k, b, x1, x2, x3, x4) }
k <= 0? x4[] + x5[]: b[]
end
puts a(10, lambda {1}, lambda {-1}, lambda {-1}, lambda {1}, lambda {0}) | 599Man or boy test
| 14ruby
| 4895p |
> magic(5)
[,1] [,2] [,3] [,4] [,5]
[1,] 17 24 1 8 15
[2,] 23 5 7 14 16
[3,] 4 6 13 20 22
[4,] 10 12 19 21 3
[5,] 11 18 25 2 9 | 606Magic squares of odd order
| 13r
| o5j84 |
use std::cell::Cell;
trait Arg {
fn run(&self) -> i32;
}
impl Arg for i32 {
fn run(&self) -> i32 { *self }
}
struct B<'a> {
k: &'a Cell<i32>,
x1: &'a Arg,
x2: &'a Arg,
x3: &'a Arg,
x4: &'a Arg,
}
impl<'a> Arg for B<'a> {
fn run(&self) -> i32 {
self.k.set(self.k.get() - 1);
a(self.k.get(), self, self.x1, self.x2, self.x3, self.x4)
}
}
fn a(k: i32, x1: &Arg, x2: &Arg, x3: &Arg, x4: &Arg, x5: &Arg) -> i32 {
if k <= 0 {
x4.run() + x5.run()
} else {
B{
k: &Cell::new(k),
x1, x2, x3, x4
}.run()
}
}
pub fn main() {
println!("{}", a(10, &1, &-1, &-1, &1, &0));
} | 599Man or boy test
| 15rust
| goc4o |
def A(in_k: Int, x1: =>Int, x2: =>Int, x3: =>Int, x4: =>Int, x5: =>Int): Int = {
var k = in_k
def B: Int = {
k = k-1
A(k, B, x1, x2, x3, x4)
}
if (k<=0) x4+x5 else B
}
println(A(10, 1, -1, -1, 1, 0)) | 599Man or boy test
| 16scala
| jdv7i |
def map_range(a, b, s)
af, al, bf, bl = a.first, a.last, b.first, b.last
bf + (s - af)*(bl - bf).quo(al - af)
end
(0..10).each{|s| puts % [s, map_range(0..10, -1..0, s)]} | 602Map range
| 14ruby
| kt2hg |
$string = ;
echo md5( $string ); | 590MD5
| 12php
| nrtig |
from random import shuffle, randrange
def make_maze(w = 16, h = 8):
vis = [[0] * w + [1] for _ in range(h)] + [[1] * (w + 1)]
ver = [[] * w + ['|'] for _ in range(h)] + [[]]
hor = [[] * w + ['+'] for _ in range(h + 1)]
def walk(x, y):
vis[y][x] = 1
d = [(x - 1, y), (x, y + 1), (x + 1, y), (x, y - 1)]
shuffle(d)
for (xx, yy) in d:
if vis[yy][xx]: continue
if xx == x: hor[max(y, yy)][x] =
if yy == y: ver[y][max(x, xx)] =
walk(xx, yy)
walk(randrange(w), randrange(h))
s =
for (a, b) in zip(hor, ver):
s += ''.join(a + ['\n'] + b + ['\n'])
return s
if __name__ == '__main__':
print(make_maze()) | 597Maze generation
| 3python
| zhitt |
use std::ops::{Add, Sub, Mul, Div};
fn map_range<T: Copy>(from_range: (T, T), to_range: (T, T), s: T) -> T
where T: Add<T, Output=T> +
Sub<T, Output=T> +
Mul<T, Output=T> +
Div<T, Output=T>
{
to_range.0 + (s - from_range.0) * (to_range.1 - to_range.0) / (from_range.1 - from_range.0)
}
fn main() {
let input: Vec<f64> = vec![0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0];
let result = input.into_iter()
.map(|x| map_range((0.0, 10.0), (-1.0, 0.0), x))
.collect::<Vec<f64>>();
print!("{:?}", result);
} | 602Map range
| 15rust
| bzvkx |
def mapRange(a1:Double, a2:Double, b1:Double, b2:Double, x:Double):Double=b1+(x-a1)*(b2-b1)/(a2-a1)
for(i <- 0 to 10)
println("%2d in [0, 10] maps to%5.2f in [-1, 0]".format(i, mapRange(0,10, -1,0, i))) | 602Map range
| 16scala
| ay41n |
def odd_magic_square(n)
raise ArgumentError if n.even? || n <= 0
n.times.map{|i| n.times.map{|j| n*((i+j+1+n/2)%n) + ((i+2*j-5)%n) + 1} }
end
[3, 5, 9].each do |n|
puts
fmt = * n
odd_magic_square(n).each{|row| puts fmt % row}
end | 606Magic squares of odd order
| 14ruby
| zhatw |
import Foundation
func mapRanges(_ r1: ClosedRange<Double>, _ r2: ClosedRange<Double>, to: Double) -> Double {
let num = (to - r1.lowerBound) * (r2.upperBound - r2.lowerBound)
let denom = r1.upperBound - r1.lowerBound
return r2.lowerBound + num / denom
}
for i in 0...10 {
print(String(format: "%2d maps to%5.2f", i, mapRanges(0...10, -1...0, to: Double(i))))
} | 602Map range
| 17swift
| hflj0 |
fn main() {
let n = 9;
let mut square = vec![vec![0; n]; n];
for (i, row) in square.iter_mut().enumerate() {
for (j, e) in row.iter_mut().enumerate() {
*e = n * (((i + 1) + (j + 1) - 1 + (n >> 1))% n) + (((i + 1) + (2 * (j + 1)) - 2)% n) + 1;
print!("{:3} ", e);
}
println!("");
}
let sum = n * (((n * n) + 1) / 2);
println!("The sum of the square is {}.", sum);
} | 606Magic squares of odd order
| 15rust
| 3kez8 |
def magicSquare( n:Int ) : Option[Array[Array[Int]]] = {
require(n % 2 != 0, "n must be an odd number")
val a = Array.ofDim[Int](n,n) | 606Magic squares of odd order
| 16scala
| m1qyc |
public static double[][] mult(double a[][], double b[][]){ | 604Matrix multiplication
| 9java
| s27q0 |
func A(_ k: Int,
_ x1: @escaping () -> Int,
_ x2: @escaping () -> Int,
_ x3: @escaping () -> Int,
_ x4: @escaping () -> Int,
_ x5: @escaping () -> Int) -> Int {
var k1 = k
func B() -> Int {
k1 -= 1
return A(k1, B, x1, x2, x3, x4)
}
if k1 <= 0 {
return x4() + x5()
} else {
return B()
}
}
print(A(10, {1}, {-1}, {-1}, {1}, {0})) | 599Man or boy test
| 17swift
| 50mu8 |
null | 604Matrix multiplication
| 10javascript
| ngpiy |
import java.util.Arrays;
public class Transpose{
public static void main(String[] args){
double[][] m = {{1, 1, 1, 1},
{2, 4, 8, 16},
{3, 9, 27, 81},
{4, 16, 64, 256},
{5, 25, 125, 625}};
double[][] ans = new double[m[0].length][m.length];
for(int rows = 0; rows < m.length; rows++){
for(int cols = 0; cols < m[0].length; cols++){
ans[cols][rows] = m[rows][cols];
}
}
for(double[] i:ans){ | 605Matrix transposition
| 9java
| m1sym |
>>> import hashlib
>>>
>>> tests = (
(b, 'd41d8cd98f00b204e9800998ecf8427e'),
(b, '0cc175b9c0f1b6a831c399e269772661'),
(b, '900150983cd24fb0d6963f7d28e17f72'),
(b, 'f96b697d7cb7938d525a2f31aaf161d0'),
(b, 'c3fcd3d76192e4007dfb496cca67e13b'),
(b, 'd174ab98d277d9f5a5611c2c9f419d9f'),
(b, '57edf4a22be3c955ac49da2e2107b67a') )
>>> for text, golden in tests: assert hashlib.md5(text).hexdigest() == golden
>>> | 590MD5
| 3python
| rnhgq |
extension String: Error {}
struct Point: CustomStringConvertible {
var x: Int
var y: Int
init(_ _x: Int,
_ _y: Int) {
self.x = _x
self.y = _y
}
var description: String {
return "(\(x), \(y))\n"
}
}
extension Point: Equatable,Comparable {
static func == (lhs: Point, rhs: Point) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y
}
static func < (lhs: Point, rhs: Point) -> Bool {
return lhs.y!= rhs.y? lhs.y < rhs.y: lhs.x < rhs.x
}
}
class MagicSquare: CustomStringConvertible {
var grid:[Int:Point] = [:]
var number: Int = 1
init(base n:Int) {
grid = [:]
number = n
}
func createOdd() throws -> MagicSquare {
guard number < 1 || number% 2!= 0 else {
throw "Must be odd and >= 1, try again"
return self
}
var x = 0
var y = 0
let middle = Int(number/2)
x = middle
grid[1] = Point(x,y)
for i in 2 ... number*number {
let oldXY = Point(x,y)
x += 1
y -= 1
if x >= number {x -= number}
if y < 0 {y += number}
var tempCoord = Point(x,y)
if let _ = grid.firstIndex(where: { (k,v) -> Bool in
v == tempCoord
})
{
x = oldXY.x
y = oldXY.y + 1
if y >= number {y -= number}
tempCoord = Point(x,y)
}
grid[i] = tempCoord
}
print(self)
return self
}
fileprivate func gridToText(_ result: inout String) {
let sorted = sortedGrid()
let sc = sorted.count
var i = 0
for c in sorted {
result += " \(c.key)"
if c.key < 10 && sc > 10 { result += " "}
if c.key < 100 && sc > 100 { result += " "}
if c.key < 1000 && sc > 1000 { result += " "}
if i%number==(number-1) { result += "\n"}
i += 1
}
result += "\nThe magic number is \(number * (number * number + 1) / 2)"
result += "\nRows and Columns are "
result += checkRows() == checkColumns()? "Equal": " Not Equal!"
result += "\nRows and Columns and Diagonals are "
let allEqual = (checkDiagonals() == checkColumns() && checkDiagonals() == checkRows())
result += allEqual? "Equal": " Not Equal!"
result += "\n"
}
var description: String {
var result = "base \(number)\n"
gridToText(&result)
return result
}
}
extension MagicSquare {
private func sortedGrid()->[(key:Int,value:Point)] {
return grid.sorted(by: {$0.1 < $1.1})
}
private func checkRows() -> (Bool, Int?)
{
var result = Set<Int>()
var index = 0
var rowtotal = 0
for (cell, _) in sortedGrid()
{
rowtotal += cell
if index%number==(number-1)
{
result.insert(rowtotal)
rowtotal = 0
}
index += 1
}
return (result.count == 1, result.first?? nil)
}
private func checkColumns() -> (Bool, Int?)
{
var result = Set<Int>()
var sorted = sortedGrid()
for i in 0 ..< number {
var rowtotal = 0
for cell in stride(from: i, to: sorted.count, by: number) {
rowtotal += sorted[cell].key
}
result.insert(rowtotal)
}
return (result.count == 1, result.first)
}
private func checkDiagonals() -> (Bool, Int?)
{
var result = Set<Int>()
var sorted = sortedGrid()
var rowtotal = 0
for cell in stride(from: 0, to: sorted.count, by: number+1) {
rowtotal += sorted[cell].key
}
result.insert(rowtotal)
rowtotal = 0
for cell in stride(from: number-1, to: sorted.count-(number-1), by: number-1) {
rowtotal += sorted[cell].key
}
result.insert(rowtotal)
return (result.count == 1, result.first)
}
}
try MagicSquare(base: 3).createOdd()
try MagicSquare(base: 5).createOdd()
try MagicSquare(base: 7).createOdd() | 606Magic squares of odd order
| 17swift
| tj1fl |
function Matrix(ary) {
this.mtx = ary
this.height = ary.length;
this.width = ary[0].length;
}
Matrix.prototype.toString = function() {
var s = []
for (var i = 0; i < this.mtx.length; i++)
s.push( this.mtx[i].join(",") );
return s.join("\n");
} | 605Matrix transposition
| 10javascript
| vqn25 |
library(digest)
hexdigest <- digest("The quick brown fox jumped over the lazy dog's back",
algo="md5", serialize=FALSE) | 590MD5
| 13r
| u0gvx |
class Maze
DIRECTIONS = [ [1, 0], [-1, 0], [0, 1], [0, -1] ]
def initialize(width, height)
@width = width
@height = height
@start_x = rand(width)
@start_y = 0
@end_x = rand(width)
@end_y = height - 1
@vertical_walls = Array.new(width) { Array.new(height, true) }
@horizontal_walls = Array.new(width) { Array.new(height, true) }
@path = Array.new(width) { Array.new(height) }
@horizontal_walls[@end_x][@end_y] = false
generate
end
def print
puts @width.times.inject() {|str, x| str << (x == @start_x? : )}
@height.times do |y|
line = @width.times.inject() do |str, x|
str << (@path[x][y]? : ) << (@vertical_walls[x][y]? : )
end
puts line
puts @width.times.inject() {|str, x| str << (@horizontal_walls[x][y]? : )}
end
end
private
def reset_visiting_state
@visited = Array.new(@width) { Array.new(@height) }
end
def move_valid?(x, y)
(0...@width).cover?(x) && (0...@height).cover?(y) &&!@visited[x][y]
end
def generate
reset_visiting_state
generate_visit_cell(@start_x, @start_y)
end
def generate_visit_cell(x, y)
@visited[x][y] = true
coordinates = DIRECTIONS.shuffle.map { |dx, dy| [x + dx, y + dy] }
for new_x, new_y in coordinates
next unless move_valid?(new_x, new_y)
connect_cells(x, y, new_x, new_y)
generate_visit_cell(new_x, new_y)
end
end
def connect_cells(x1, y1, x2, y2)
if x1 == x2
@horizontal_walls[x1][ [y1, y2].min ] = false
else
@vertical_walls[ [x1, x2].min ][y1] = false
end
end
end
maze = Maze.new 20, 10
maze.print | 597Maze generation
| 14ruby
| 6bd3t |
use rand::{thread_rng, Rng, rngs::ThreadRng};
const WIDTH: usize = 16;
const HEIGHT: usize = 16;
#[derive(Clone, Copy)]
struct Cell {
col: usize,
row: usize,
}
impl Cell {
fn from(col: usize, row: usize) -> Cell {
Cell {col, row}
}
}
struct Maze {
cells: [[bool; HEIGHT]; WIDTH], | 597Maze generation
| 15rust
| ypf68 |
import scala.util.Random
object MazeTypes {
case class Direction(val dx: Int, val dy: Int)
case class Loc(val x: Int, val y: Int) {
def +(that: Direction): Loc = Loc(x + that.dx, y + that.dy)
}
case class Door(val from: Loc, to: Loc)
val North = Direction(0,-1)
val South = Direction(0,1)
val West = Direction(-1,0)
val East = Direction(1,0)
val directions = Set(North, South, West, East)
}
object MazeBuilder {
import MazeTypes._
def shuffle[T](set: Set[T]): List[T] = Random.shuffle(set.toList)
def buildImpl(current: Loc, grid: Grid): Grid = {
var newgrid = grid.markVisited(current)
val nbors = shuffle(grid.neighbors(current))
nbors.foreach { n =>
if (!newgrid.isVisited(n)) {
newgrid = buildImpl(n, newgrid.markVisited(current).addDoor(Door(current, n)))
}
}
newgrid
}
def build(width: Int, height: Int): Grid = {
val exit = Loc(width-1, height-1)
buildImpl(exit, new Grid(width, height, Set(), Set()))
}
}
class Grid(val width: Int, val height: Int, val doors: Set[Door], val visited: Set[Loc]) {
def addDoor(door: Door): Grid =
new Grid(width, height, doors + door, visited)
def markVisited(loc: Loc): Grid =
new Grid(width, height, doors, visited + loc)
def isVisited(loc: Loc): Boolean =
visited.contains(loc)
def neighbors(current: Loc): Set[Loc] =
directions.map(current + _).filter(inBounds(_)) -- visited
def printGrid(): List[String] = {
(0 to height).toList.flatMap(y => printRow(y))
}
private def inBounds(loc: Loc): Boolean =
loc.x >= 0 && loc.x < width && loc.y >= 0 && loc.y < height
private def printRow(y: Int): List[String] = {
val row = (0 until width).toList.map(x => printCell(Loc(x, y)))
val rightSide = if (y == height-1) " " else "|"
val newRow = row :+ List("+", rightSide)
List.transpose(newRow).map(_.mkString)
}
private val entrance = Loc(0,0)
private def printCell(loc: Loc): List[String] = {
if (loc.y == height)
List("+--")
else List(
if (openNorth(loc)) "+ " else "+--",
if (openWest(loc) || loc == entrance) " " else "| "
)
}
def openNorth(loc: Loc): Boolean = openInDirection(loc, North)
def openWest(loc: Loc): Boolean = openInDirection(loc, West)
private def openInDirection(loc: Loc, dir: Direction): Boolean =
doors.contains(Door(loc, loc + dir)) || doors.contains(Door(loc + dir, loc))
} | 597Maze generation
| 16scala
| ce393 |
package main
import "fmt"
import "math/cmplx"
func mandelbrot(a complex128) (z complex128) {
for i := 0; i < 50; i++ {
z = z*z + a
}
return
}
func main() {
for y := 1.0; y >= -1.0; y -= 0.05 {
for x := -2.0; x <= 0.5; x += 0.0315 {
if cmplx.Abs(mandelbrot(complex(x, y))) < 2 {
fmt.Print("*")
} else {
fmt.Print(" ")
}
}
fmt.Println("")
}
} | 607Mandelbrot set
| 0go
| vqo2m |
null | 604Matrix multiplication
| 11kotlin
| ayu13 |
import Foundation
extension Array {
mutating func shuffle() {
guard count > 1 else { return }
for i in 0..<self.count - 1 {
let j = Int(arc4random_uniform(UInt32(count - i))) + i
guard i!= j else { continue }
swap(&self[i], &self[j])
}
}
}
enum Direction:Int {
case north = 1
case south = 2
case east = 4
case west = 8
static var allDirections:[Direction] {
return [Direction.north, Direction.south, Direction.east, Direction.west]
}
var opposite:Direction {
switch self {
case .north:
return .south
case .south:
return .north
case .east:
return .west
case .west:
return .east
}
}
var diff:(Int, Int) {
switch self {
case .north:
return (0, -1)
case .south:
return (0, 1)
case .east:
return (1, 0)
case .west:
return (-1, 0)
}
}
var char:String {
switch self {
case .north:
return "N"
case .south:
return "S"
case .east:
return "E"
case .west:
return "W"
}
}
}
class MazeGenerator {
let x:Int
let y:Int
var maze:[[Int]]
init(_ x:Int, _ y:Int) {
self.x = x
self.y = y
let column = [Int](repeating: 0, count: y)
self.maze = [[Int]](repeating: column, count: x)
generateMaze(0, 0)
}
private func generateMaze(_ cx:Int, _ cy:Int) {
var directions = Direction.allDirections
directions.shuffle()
for direction in directions {
let (dx, dy) = direction.diff
let nx = cx + dx
let ny = cy + dy
if inBounds(nx, ny) && maze[nx][ny] == 0 {
maze[cx][cy] |= direction.rawValue
maze[nx][ny] |= direction.opposite.rawValue
generateMaze(nx, ny)
}
}
}
private func inBounds(_ testX:Int, _ testY:Int) -> Bool {
return inBounds(value:testX, upper:self.x) && inBounds(value:testY, upper:self.y)
}
private func inBounds(value:Int, upper:Int) -> Bool {
return (value >= 0) && (value < upper)
}
func display() {
let cellWidth = 3
for j in 0..<y { | 597Maze generation
| 17swift
| 3knz2 |
import Data.Bool
import Data.Complex (Complex((:+)), magnitude)
mandelbrot
:: RealFloat a
=> Complex a -> Complex a
mandelbrot a = iterate ((a +) . (^ 2)) 0 !! 50
main :: IO ()
main =
mapM_
putStrLn
[ [ bool ' ' '*' (2 > magnitude (mandelbrot (x:+ y)))
| x <- [-2,-1.9685 .. 0.5] ]
| y <- [1,0.95 .. -1] ] | 607Mandelbrot set
| 8haskell
| em2ai |
null | 605Matrix transposition
| 11kotlin
| tjaf0 |
require 'digest'
Digest::MD5.hexdigest() | 590MD5
| 14ruby
| jfb7x |
[dependencies]
rust-crypto = "0.2" | 590MD5
| 15rust
| htpj2 |
function Transpose( m )
local res = {}
for i = 1, #m[1] do
res[i] = {}
for j = 1, #m do
res[i][j] = m[j][i]
end
end
return res
end | 605Matrix transposition
| 1lua
| zhety |
function MatMul( m1, m2 )
if #m1[1] ~= #m2 then | 604Matrix multiplication
| 1lua
| em5ac |
object RosettaMD5 extends App {
def MD5(s: String): String = { | 590MD5
| 16scala
| p6ebj |
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
public class Mandelbrot extends JFrame {
private final int MAX_ITER = 570;
private final double ZOOM = 150;
private BufferedImage I;
private double zx, zy, cX, cY, tmp;
public Mandelbrot() {
super("Mandelbrot Set");
setBounds(100, 100, 800, 600);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
I = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
for (int y = 0; y < getHeight(); y++) {
for (int x = 0; x < getWidth(); x++) {
zx = zy = 0;
cX = (x - 400) / ZOOM;
cY = (y - 300) / ZOOM;
int iter = MAX_ITER;
while (zx * zx + zy * zy < 4 && iter > 0) {
tmp = zx * zx - zy * zy + cX;
zy = 2.0 * zx * zy + cY;
zx = tmp;
iter--;
}
I.setRGB(x, y, iter | (iter << 8));
}
}
}
@Override
public void paint(Graphics g) {
g.drawImage(I, 0, 0, this);
}
public static void main(String[] args) {
new Mandelbrot().setVisible(true);
}
} | 607Mandelbrot set
| 9java
| hf6jm |
function mandelIter(cx, cy, maxIter) {
var x = 0.0;
var y = 0.0;
var xx = 0;
var yy = 0;
var xy = 0;
var i = maxIter;
while (i-- && xx + yy <= 4) {
xy = x * y;
xx = x * x;
yy = y * y;
x = xx - yy + cx;
y = xy + xy + cy;
}
return maxIter - i;
}
function mandelbrot(canvas, xmin, xmax, ymin, ymax, iterations) {
var width = canvas.width;
var height = canvas.height;
var ctx = canvas.getContext('2d');
var img = ctx.getImageData(0, 0, width, height);
var pix = img.data;
for (var ix = 0; ix < width; ++ix) {
for (var iy = 0; iy < height; ++iy) {
var x = xmin + (xmax - xmin) * ix / (width - 1);
var y = ymin + (ymax - ymin) * iy / (height - 1);
var i = mandelIter(x, y, iterations);
var ppos = 4 * (width * iy + ix);
if (i > iterations) {
pix[ppos] = 0;
pix[ppos + 1] = 0;
pix[ppos + 2] = 0;
} else {
var c = 3 * Math.log(i) / Math.log(iterations - 1.0);
if (c < 1) {
pix[ppos] = 255 * c;
pix[ppos + 1] = 0;
pix[ppos + 2] = 0;
}
else if ( c < 2 ) {
pix[ppos] = 255;
pix[ppos + 1] = 255 * (c - 1);
pix[ppos + 2] = 0;
} else {
pix[ppos] = 255;
pix[ppos + 1] = 255;
pix[ppos + 2] = 255 * (c - 2);
}
}
pix[ppos + 3] = 255;
}
}
ctx.putImageData(img, 0, 0);
}
var canvas = document.createElement('canvas');
canvas.width = 900;
canvas.height = 600;
document.body.insertBefore(canvas, document.body.childNodes[0]);
mandelbrot(canvas, -2, 1, -1, 1, 1000); | 607Mandelbrot set
| 10javascript
| ayl10 |
SELECT MD5('The quick brown fox jumped over the lazy dog\'s back') | 590MD5
| 19sql
| e9qau |
null | 607Mandelbrot set
| 11kotlin
| 48d57 |
use Math::Matrix;
$m = Math::Matrix->new(
[1, 1, 1, 1],
[2, 4, 8, 16],
[3, 9, 27, 81],
[4, 16, 64, 256],
[5, 25, 125, 625],
);
$m->transpose->print; | 605Matrix transposition
| 2perl
| kt9hc |
function transpose($m) {
if (count($m) == 0)
return array();
else if (count($m) == 1)
return array_chunk($m[0], 1);
array_unshift($m, NULL);
return call_user_func_array('array_map', $m);
} | 605Matrix transposition
| 12php
| 3kwzq |
local maxIterations = 250
local minX, maxX, minY, maxY = -2.5, 2.5, -2.5, 2.5
local miX, mxX, miY, mxY
function remap( x, t1, t2, s1, s2 )
local f = ( x - t1 ) / ( t2 - t1 )
local g = f * ( s2 - s1 ) + s1
return g;
end
function drawMandelbrot()
local pts, a, as, za, b, bs, zb, cnt, clr = {}
for j = 0, hei - 1 do
for i = 0, wid - 1 do
a = remap( i, 0, wid, minX, maxX )
b = remap( j, 0, hei, minY, maxY )
cnt = 0; za = a; zb = b
while( cnt < maxIterations ) do
as = a * a - b * b; bs = 2 * a * b
a = za + as; b = zb + bs
if math.abs( a ) + math.abs( b ) > 16 then break end
cnt = cnt + 1
end
if cnt == maxIterations then clr = 0
else clr = remap( cnt, 0, maxIterations, 0, 255 )
end
pts[1] = { i, j, clr, clr, 0, 255 }
love.graphics.points( pts )
end
end
end
function startFractal()
love.graphics.setCanvas( canvas ); love.graphics.clear()
love.graphics.setColor( 255, 255, 255 )
drawMandelbrot(); love.graphics.setCanvas()
end
function love.load()
wid, hei = love.graphics.getWidth(), love.graphics.getHeight()
canvas = love.graphics.newCanvas( wid, hei )
startFractal()
end
function love.mousepressed( x, y, button, istouch )
if button == 1 then
startDrag = true; miX = x; miY = y
else
minX = -2.5; maxX = 2.5; minY = minX; maxY = maxX
startFractal()
startDrag = false
end
end
function love.mousereleased( x, y, button, istouch )
if startDrag then
local l
if x > miX then mxX = x
else l = x; mxX = miX; miX = l
end
if y > miY then mxY = y
else l = y; mxY = miY; miY = l
end
miX = remap( miX, 0, wid, minX, maxX )
mxX = remap( mxX, 0, wid, minX, maxX )
miY = remap( miY, 0, hei, minY, maxY )
mxY = remap( mxY, 0, hei, minY, maxY )
minX = miX; maxX = mxX; minY = miY; maxY = mxY
startFractal()
end
end
function love.draw()
love.graphics.draw( canvas )
end | 607Mandelbrot set
| 1lua
| gof4j |
sub mmult
{
our @a; local *a = shift;
our @b; local *b = shift;
my @p = [];
my $rows = @a;
my $cols = @{ $b[0] };
my $n = @b - 1;
for (my $r = 0 ; $r < $rows ; ++$r)
{
for (my $c = 0 ; $c < $cols ; ++$c)
{
$p[$r][$c] += $a[$r][$_] * $b[$_][$c]
foreach 0 .. $n;
}
}
return [@p];
}
sub display { join("\n" => map join(" " => map(sprintf("%4d", $_), @$_)), @{+shift})."\n" }
@a =
(
[1, 2],
[3, 4]
);
@b =
(
[-3, -8, 3],
[-2, 1, 4]
);
$c = mmult(\@a,\@b);
display($c) | 604Matrix multiplication
| 2perl
| 9a8mn |
a=((1, 1, 1, 1),
(2, 4, 8, 16),
(3, 9, 27, 81),
(4, 16, 64, 256))
b=(( 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.))
def MatrixMul( mtx_a, mtx_b):
tpos_b = zip( *mtx_b)
rtn = [[ sum( ea*eb for ea,eb in zip(a,b)) for b in tpos_b] for a in mtx_a]
return rtn
v = MatrixMul( a, b )
print 'v = ('
for r in v:
print '[',
for val in r:
print '%8.2f '%val,
print ']'
print ')'
u = MatrixMul(b,a)
print 'u = '
for r in u:
print '[',
for val in r:
print '%8.2f '%val,
print ']'
print ')' | 604Matrix multiplication
| 3python
| ceo9q |
m=((1, 1, 1, 1),
(2, 4, 8, 16),
(3, 9, 27, 81),
(4, 16, 64, 256),
(5, 25,125, 625))
print(zip(*m)) | 605Matrix transposition
| 3python
| bzckr |
a%*% b | 604Matrix multiplication
| 13r
| 6bq3e |
b <- 1:5
m <- matrix(c(b, b^2, b^3, b^4), 5, 4)
print(m)
tm <- t(m)
print(tm) | 605Matrix transposition
| 13r
| 7n6ry |
struct MemoryStruct {
char *memory;
size_t size;
};
static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp)
{
size_t realsize = size * nmemb;
struct MemoryStruct *mem = (struct MemoryStruct *)userp;
mem->memory = realloc(mem->memory, mem->size + realsize + 1);
memcpy(&(mem->memory[mem->size]), contents, realsize);
mem->size += realsize;
mem->memory[mem->size] = 0;
return realsize;
}
void checkResponse(char* str){
char ref[] = ;
int len = strlen(str),flag = 1,i;
if(len<16)
fputs(str,stdout);
else{
for(i=0;i<len && i<16;i++)
flag = flag && (ref[i]==str[i]);
flag==1?fputs(,stdout):fputs(str,stdout);
}
}
int main(int argC,char* argV[])
{
if(argC!=2)
printf(,argV[0]);
else{
CURL *curl;
int len = strlen(argV[1]);
char* str = (char*)malloc((FIXED_LENGTH + len)*sizeof(char));
struct MemoryStruct chunk;
CURLcode res;
chunk.memory = malloc(1);
chunk.size = 0;
if ((curl = curl_easy_init()) != NULL) {
sprintf(str,,argV[1]);
curl_easy_setopt(curl, CURLOPT_URL, str);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
free(str);
res = curl_easy_perform(curl);
if (res == CURLE_OK) {
checkResponse(chunk.memory);
return EXIT_SUCCESS;
}
curl_easy_cleanup(curl);
}
}
return EXIT_FAILURE;
} | 608MAC Vendor Lookup
| 5c
| o5r80 |
require 'matrix'
Matrix[[1, 2],
[3, 4]] * Matrix[[-3, -8, 3],
[-2, 1, 4]] | 604Matrix multiplication
| 14ruby
| 2xnlw |
m=[[1, 1, 1, 1],
[2, 4, 8, 16],
[3, 9, 27, 81],
[4, 16, 64, 256],
[5, 25,125, 625]]
puts m.transpose | 605Matrix transposition
| 14ruby
| 162pw |
struct Matrix {
dat: [[f32; 3]; 3]
}
impl Matrix {
pub fn mult_m(a: Matrix, b: Matrix) -> Matrix
{
let mut out = Matrix {
dat: [[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]
]
};
for i in 0..3{
for j in 0..3 {
for k in 0..3 {
out.dat[i][j] += a.dat[i][k] * b.dat[k][j];
}
}
}
out
}
pub fn print(self)
{
for i in 0..3 {
for j in 0..3 {
print!("{} ", self.dat[i][j]);
}
print!("\n");
}
}
}
fn main()
{
let a = Matrix {
dat: [[1., 2., 3.],
[4., 5., 6.],
[7., 8., 9.]
]
};
let b = Matrix {
dat: [[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]]
};
let c = Matrix::mult_m(a, b);
c.print();
} | 604Matrix multiplication
| 15rust
| vqd2t |
use Math::Complex;
sub mandelbrot {
my ($z, $c) = @_[0,0];
for (1 .. 20) {
$z = $z * $z + $c;
return $_ if abs $z > 2;
}
}
for (my $y = 1; $y >= -1; $y -= 0.05) {
for (my $x = -2; $x <= 0.5; $x += 0.0315)
{print mandelbrot($x + $y * i) ? ' ' : '
print "\n"
} | 607Mandelbrot set
| 2perl
| i4jo3 |
struct Matrix {
dat: [[i32; 3]; 3]
}
impl Matrix {
pub fn transpose_m(a: Matrix) -> Matrix
{
let mut out = Matrix {
dat: [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]
]
};
for i in 0..3{
for j in 0..3{
out.dat[i][j] = a.dat[j][i];
}
}
out
}
pub fn print(self)
{
for i in 0..3 {
for j in 0..3 {
print!("{} ", self.dat[i][j]);
}
print!("\n");
}
}
}
fn main()
{
let a = Matrix {
dat: [[1, 2, 3],
[4, 5, 6],
[7, 8, 9] ]
};
let c = Matrix::transpose_m(a);
c.print();
} | 605Matrix transposition
| 15rust
| ayv14 |
def mult[A](a: Array[Array[A]], b: Array[Array[A]])(implicit n: Numeric[A]) = {
import n._
for (row <- a)
yield for(col <- b.transpose)
yield row zip col map Function.tupled(_*_) reduceLeft (_+_)
} | 604Matrix multiplication
| 16scala
| 48z50 |
scala> Array.tabulate(4)(i => Array.tabulate(4)(j => i*4 + j))
res12: Array[Array[Int]] = Array(Array(0, 1, 2, 3), Array(4, 5, 6, 7), Array(8, 9, 10, 11), Array(12, 13, 14, 15))
scala> res12.transpose
res13: Array[Array[Int]] = Array(Array(0, 4, 8, 12), Array(1, 5, 9, 13), Array(2, 6, 10, 14), Array(3, 7, 11, 15))
scala> res12 map (_ map ("%2d" format _) mkString " ") mkString "\n"
res16: String =
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
scala> res13 map (_ map ("%2d" format _) mkString " ") mkString "\n"
res17: String =
0 4 8 12
1 5 9 13
2 6 10 14
3 7 11 15 | 605Matrix transposition
| 16scala
| xc4wg |
package main
import (
"net/http"
"fmt"
"io/ioutil"
)
func macLookUp(mac string) (res string){
resp, _ := http.Get("http: | 608MAC Vendor Lookup
| 0go
| 48n52 |
#!/usr/bin/env stack
import Control.Exception (try)
import Control.Monad (forM_)
import qualified Data.ByteString.Lazy.Char8 as L8 (ByteString, unpack)
import Network.HTTP.Client
(Manager, parseRequest, httpLbs, responseStatus, responseBody,
newManager, defaultManagerSettings, Response, HttpException)
import Network.HTTP.Types.Status (statusIsSuccessful, notFound404)
import System.Environment (getArgs)
import Text.Printf (printf)
fetchURL :: Manager
-> String
-> IO (Either HttpException (Response L8.ByteString))
fetchURL mgr url = try $ do
req <- parseRequest url
httpLbs req mgr
lookupMac :: Manager -> String -> IO String
lookupMac mgr mac = do
eth <- fetchURL mgr $ "http://api.macvendors.com/" ++ mac
return $ case eth of
Left _ -> "null"
Right resp -> let body = responseBody resp
status = responseStatus resp
in if | status == notFound404 -> "N/A"
| not (statusIsSuccessful status) -> "null"
| otherwise -> L8.unpack body
main :: IO ()
main = do
args <- getArgs
mgr <- newManager defaultManagerSettings
forM_ args $ \mac -> do
putStr $ printf "%-17s" mac ++ " = "
vendor <- lookupMac mgr mac
putStrLn vendor | 608MAC Vendor Lookup
| 8haskell
| qlux9 |
$min_x=-2;
$max_x=1;
$min_y=-1;
$max_y=1;
$dim_x=400;
$dim_y=300;
$im = @imagecreate($dim_x, $dim_y)
or die();
header();
$black_color = imagecolorallocate($im, 0, 0, 0);
$white_color = imagecolorallocate($im, 255, 255, 255);
for($y=0;$y<=$dim_y;$y++) {
for($x=0;$x<=$dim_x;$x++) {
$c1=$min_x+($max_x-$min_x)/$dim_x*$x;
$c2=$min_y+($max_y-$min_y)/$dim_y*$y;
$z1=0;
$z2=0;
for($i=0;$i<100;$i++) {
$new1=$z1*$z1-$z2*$z2+$c1;
$new2=2*$z1*$z2+$c2;
$z1=$new1;
$z2=$new2;
if($z1*$z1+$z2*$z2>=4) {
break;
}
}
if($i<100) {
imagesetpixel ($im, $x, $y, $white_color);
}
}
}
imagepng($im);
imagedestroy($im); | 607Mandelbrot set
| 12php
| ritge |
package com.jamesdonnell.MACVendor;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Lookup {
private static final String baseURL = "http: | 608MAC Vendor Lookup
| 9java
| p3mb3 |
var mac = "88:53:2E:67:07:BE";
function findmac(){
window.open("http: | 608MAC Vendor Lookup
| 10javascript
| xcvw9 |
null | 608MAC Vendor Lookup
| 11kotlin
| 7ntr4 |
int test (int a, int b)
{
char code[] = {0x8B, 0x44, 0x24, 0x4, 0x3, 0x44, 0x24, 0x8, 0xC3};
void *buf;
int c;
buf = mmap (0,sizeof(code),PROT_READ|PROT_WRITE|PROT_EXEC,
MAP_PRIVATE|MAP_ANON,-1,0);
memcpy (buf, code, sizeof(code));
c = ((int (*) (int, int))buf)(a, b);
munmap (buf, sizeof(code));
return c;
}
int main ()
{
printf(, test(7,12));
return 0;
} | 609Machine code
| 5c
| 16mpj |
null | 608MAC Vendor Lookup
| 1lua
| jdz71 |
@inlinable
public func matrixTranspose<T>(_ matrix: [[T]]) -> [[T]] {
guard!matrix.isEmpty else {
return []
}
var ret = Array(repeating: [T](), count: matrix[0].count)
for row in matrix {
for j in 0..<row.count {
ret[j].append(row[j])
}
}
return ret
}
@inlinable
public func printMatrix<T>(_ matrix: [[T]]) {
guard!matrix.isEmpty else {
print()
return
}
let rows = matrix.count
let cols = matrix[0].count
for i in 0..<rows {
for j in 0..<cols {
print(matrix[i][j], terminator: " ")
}
print()
}
}
let m1 = [
[1, 2, 3],
[4, 5, 6]
]
print("Input:")
printMatrix(m1)
let m2 = matrixTranspose(m1)
print("Output:")
printMatrix(m2) | 605Matrix transposition
| 17swift
| p3lbl |
use 5.018_002;
use warnings;
use LWP;
our $VERSION = 1.000_000;
my $ua = LWP::UserAgent->new;
my @macs = (
'FC-A1-3EFC:FB:FB:01:FA:21', '00,0d,4b',
'Rhubarb', '00-14-22-01-23-45',
'10:dd:b1', 'D4:F4:6F:C9:EF:8D',
'FC-A1-3E', '88:53:2E:67:07:BE',
'23:45:67', 'FC:FB:FB:01:FA:21',
'BC:5F:F4',
);
for my $mac (@macs) {
my $vendor = get_mac_vendor($mac);
if ($vendor) {
say "$mac = $vendor";
}
}
sub get_mac_vendor {
my $s = shift;
my $req = HTTP::Request->new( GET => "http://api.macvendors.com/$s" );
my $res = $ua->request($req);
if ( $res->is_error ) {
return;
}
if ( !$res->content
or $res->content eq 'Vendor not found' )
{
return 'N/A';
}
return $res->content;
} | 608MAC Vendor Lookup
| 2perl
| f7kd7 |
CREATE TABLE a (x INTEGER, y INTEGER, e REAL);
CREATE TABLE b (x INTEGER, y INTEGER, e REAL);
-- test data
-- A is a 2x2 matrix
INSERT INTO a VALUES(0,0,1); INSERT INTO a VALUES(1,0,2);
INSERT INTO a VALUES(0,1,3); INSERT INTO a VALUES(1,1,4);
-- B is a 2x3 matrix
INSERT INTO b VALUES(0,0,-3); INSERT INTO b VALUES(1,0,-8); INSERT INTO b VALUES(2,0,3);
INSERT INTO b VALUES(0,1,-2); INSERT INTO b VALUES(1,1, 1); INSERT INTO b VALUES(2,1,4);
-- C is 2x2 * 2x3 so will be a 2x3 matrix
SELECT rhs.x, lhs.y, (SELECT SUM(a.e*b.e) FROM a, b
WHERE a.y = lhs.y
AND b.x = rhs.x
AND a.x = b.y)
INTO TABLE c
FROM a AS lhs, b AS rhs
WHERE lhs.x = 0 AND rhs.y = 0; | 604Matrix multiplication
| 19sql
| 7nyrt |
import requests
for addr in ['88:53:2E:67:07:BE', 'FC:FB:FB:01:FA:21',
'D4:F4:6F:C9:EF:8D', '23:45:67']:
vendor = requests.get('http:
print(addr, vendor) | 608MAC Vendor Lookup
| 3python
| tjbfw |
package main
import "fmt"
import "C"
func main() {
code := []byte{
0x55, 0x48, 0x89, 0xe5, 0x89, 0x7d,
0xfc, 0x89, 0x75, 0xf8, 0x8b, 0x75,
0xfc, 0x03, 0x75, 0xf8, 0x89, 0x75,
0xf4, 0x8b, 0x45, 0xf4, 0x5d, 0xc3,
}
le := len(code)
buf := C.mmap(nil, C.size_t(le), C.PROT_READ|C.PROT_WRITE|C.PROT_EXEC,
C.MAP_PRIVATE|C.MAP_ANON, -1, 0)
codePtr := C.CBytes(code)
C.memcpy(buf, codePtr, C.size_t(le))
var a, b byte = 7, 12
fmt.Printf("%d +%d = ", a, b)
C.runMachineCode(buf, C.byte(a), C.byte(b))
C.munmap(buf, C.size_t(le))
C.free(codePtr)
} | 609Machine code
| 0go
| ypa64 |
try:
from functools import reduce
except:
pass
def mandelbrot(a):
return reduce(lambda z, _: z * z + a, range(50), 0)
def step(start, step, iterations):
return (start + (i * step) for i in range(iterations))
rows = (( if abs(mandelbrot(complex(x, y))) < 2 else
for x in step(-2.0, .0315, 80))
for y in step(1, -.05, 41))
print(.join(.join(row) for row in rows)) | 607Mandelbrot set
| 3python
| nghiz |
int main() {
char *question = NULL;
size_t len = 0;
ssize_t read;
const char* answers[20] = {
, , ,
, , ,
, , , ,
, ,
, ,
, ,
, , ,
};
srand(time(NULL));
printf();
while (1) {
printf();
read = getline(&question, &len, stdin);
if (read < 2) break;
printf(, answers[rand() % 20]);
}
if (question) free(question);
return 0;
} | 610Magic 8-ball
| 5c
| tjhf4 |
null | 609Machine code
| 11kotlin
| cex98 |
iterate.until.escape <- function(z, c, trans, cond, max=50, response=dwell) {
active <- seq_along(z)
dwell <- z
dwell[] <- 0
for (i in 1:max) {
z[active] <- trans(z[active], c[active]);
survived <- cond(z[active])
dwell[active[!survived]] <- i
active <- active[survived]
if (length(active) == 0) break
}
eval(substitute(response))
}
re = seq(-2, 1, len=500)
im = seq(-1.5, 1.5, len=500)
c <- outer(re, im, function(x,y) complex(real=x, imaginary=y))
x <- iterate.until.escape(array(0, dim(c)), c,
function(z,c)z^2+c, function(z)abs(z) <= 2,
max=100)
image(x) | 607Mandelbrot set
| 13r
| 0vgsg |
@inlinable
public func matrixMult<T: Numeric>(_ m1: [[T]], _ m2: [[T]]) -> [[T]] {
let n = m1[0].count
let m = m1.count
let p = m2[0].count
guard m!= 0 else {
return []
}
precondition(n == m2.count)
var ret = Array(repeating: Array(repeating: T.zero, count: p), count: m)
for i in 0..<m {
for j in 0..<p {
for k in 0..<n {
ret[i][j] += m1[i][k] * m2[k][j]
}
}
}
return ret
}
@inlinable
public func printMatrix<T>(_ matrix: [[T]]) {
guard!matrix.isEmpty else {
print()
return
}
let rows = matrix.count
let cols = matrix[0].count
for i in 0..<rows {
for j in 0..<cols {
print(matrix[i][j], terminator: " ")
}
print()
}
}
let m1 = [
[6.5, 2, 3],
[4.5, 1, 5]
]
let m2 = [
[10.0, 16, 23, 50],
[12, -8, 16, -4],
[70, 60, -1, -2]
]
let m3 = matrixMult(m1, m2)
printMatrix(m3) | 604Matrix multiplication
| 17swift
| lwic2 |
require 'net/http'
arr = ['88:53:2E:67:07:BE', 'FC:FB:FB:01:FA:21', 'D4:F4:6F:C9:EF:8D', '23:45:67']
arr.each do |addr|
vendor = Net::HTTP.get('api.macvendors.com', ) rescue nil
puts
end | 608MAC Vendor Lookup
| 14ruby
| 3k1z7 |
extern crate reqwest;
use std::{thread, time};
fn get_vendor(mac: &str) -> Option<String> {
let mut url = String::from("http: | 608MAC Vendor Lookup
| 15rust
| 6ba3l |
object LookUp extends App {
val macs = Seq("FC-A1-3E", "FC:FB:FB:01:FA:21", "88:53:2E:67:07:BE", "D4:F4:6F:C9:EF:8D")
def lookupVendor(mac: String) =
scala.io.Source.fromURL("""http: | 608MAC Vendor Lookup
| 16scala
| 9axm5 |
(def responses
["It is certain" "It is decidedly so" "Without a doubt"
"Yes, definitely" "You may rely on it" "As I see it, yes"
"Most likely" "Outlook good" "Signs point to yes" "Yes"
"Reply hazy, try again" "Ask again later"
"Better not tell you now" "Cannot predict now"
"Concentrate and ask again" "Don't bet on it"
"My reply is no" "My sources say no" "Outlook not so good"
"Very doubtful"])
(do
(println "Ask a question. ")
(read-line)
(println (rand-nth responses))) | 610Magic 8-ball
| 6clojure
| m1ayq |
require 'complex'
def mandelbrot(a)
Array.new(50).inject(0) { |z,c| z*z + a }
end
(1.0).step(-1,-0.05) do |y|
(-2.0).step(0.5,0.0315) do |x|
print mandelbrot(Complex(x,y)).abs < 2? '*': ' '
end
puts
end | 607Mandelbrot set
| 14ruby
| f7bdr |
import ctypes
import os
from ctypes import c_ubyte, c_int
code = bytes([0x8b, 0x44, 0x24, 0x04, 0x03, 0x44, 0x24, 0x08, 0xc3])
code_size = len(code)
if (os.name == 'posix'):
import mmap
executable_map = mmap.mmap(-1, code_size, mmap.MAP_PRIVATE | mmap.MAP_ANON, mmap.PROT_READ | mmap.PROT_WRITE | mmap.PROT_EXEC)
executable_map.write(code)
func_address = ctypes.addressof(c_ubyte.from_buffer(executable_map))
elif (os.name == 'nt'):
code_buffer = ctypes.create_string_buffer(code)
PAGE_EXECUTE_READWRITE = 0x40
MEM_COMMIT = 0x1000
executable_buffer_address = ctypes.windll.kernel32.VirtualAlloc(0, code_size, MEM_COMMIT, PAGE_EXECUTE_READWRITE)
if (executable_buffer_address == 0):
print('Warning: Failed to enable code execution, call will likely cause a protection fault.')
func_address = ctypes.addressof(code_buffer)
else:
ctypes.memmove(executable_buffer_address, code_buffer, code_size)
func_address = executable_buffer_address
else:
code_buffer = ctypes.create_string_buffer(code)
func_address = ctypes.addressof(code_buffer)
prototype = ctypes.CFUNCTYPE(c_int, c_ubyte, c_ubyte)
func = prototype(func_address)
res = func(7,12)
print(res) | 609Machine code
| 3python
| qlvxi |
extern crate image;
extern crate num_complex;
use std::fs::File;
use num_complex::Complex;
fn main() {
let max_iterations = 256u16;
let img_side = 800u32;
let cxmin = -2f32;
let cxmax = 1f32;
let cymin = -1.5f32;
let cymax = 1.5f32;
let scalex = (cxmax - cxmin) / img_side as f32;
let scaley = (cymax - cymin) / img_side as f32; | 607Mandelbrot set
| 15rust
| tjpfd |
extern crate libc;
#[cfg(all(
target_os = "linux",
any(target_pointer_width = "32", target_pointer_width = "64")
))]
fn main() {
use std::mem;
use std::ptr;
let page_size: usize = 4096;
let (bytes, size): (Vec<u8>, usize) = if cfg!(target_pointer_width = "32") {
(
vec![0x8b, 0x44, 0x24, 0x04, 0x03, 0x44, 0x24, 0x08, 0xc3],
9,
)
} else {
(vec![0x48, 0x89, 0xf8, 0x48, 0x01, 0xf0, 0xc3], 7)
};
let f: fn(u8, u8) -> u8 = unsafe {
let mut page: *mut libc::c_void = ptr::null_mut();
libc::posix_memalign(&mut page, page_size, size);
libc::mprotect(
page,
size,
libc::PROT_EXEC | libc::PROT_READ | libc::PROT_WRITE,
);
let contents: *mut u8 = page as *mut u8;
ptr::copy(bytes.as_ptr(), contents, 9);
mem::transmute(contents)
};
let return_value = f(7, 12);
println!("Returned value: {}", return_value);
assert_eq!(return_value, 19);
}
#[cfg(any(
not(target_os = "linux"),
not(any(target_pointer_width = "32", target_pointer_width = "64"))
))]
fn main() {
println!("Not supported on this platform.");
} | 609Machine code
| 15rust
| 8u407 |
import org.rosettacode.ArithmeticComplex._
import java.awt.Color
object Mandelbrot
{
def generate(width:Int =600, height:Int =400)={
val bm=new RgbBitmap(width, height)
val maxIter=1000
val xMin = -2.0
val xMax = 1.0
val yMin = -1.0
val yMax = 1.0
val cx=(xMax-xMin)/width
val cy=(yMax-yMin)/height
for(y <- 0 until bm.height; x <- 0 until bm.width){
val c=Complex(xMin+x*cx, yMin+y*cy)
val iter=itMandel(c, maxIter, 4)
bm.setPixel(x, y, getColor(iter, maxIter))
}
bm
}
def itMandel(c:Complex, imax:Int, bailout:Int):Int={
var z=Complex()
for(i <- 0 until imax){
z=z*z+c;
if(z.abs > bailout) return i
}
imax;
}
def getColor(iter:Int, max:Int):Color={
if (iter==max) return Color.BLACK
var c=3*math.log(iter)/math.log(max-1.0)
if(c<1) new Color((255*c).toInt, 0, 0)
else if(c<2) new Color(255, (255*(c-1)).toInt, 0)
else new Color(255, 255, (255*(c-2)).toInt)
}
} | 607Mandelbrot set
| 16scala
| 6be31 |
package main
import (
"bufio"
"bytes"
"fmt"
"log"
"math/rand"
"os"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
answers := [...]string{
"It is certain", "It is decidedly so", "Without a doubt",
"Yes, definitely", "You may rely on it", "As I see it, yes",
"Most likely", "Outlook good", "Signs point to yes", "Yes",
"Reply hazy, try again", "Ask again later",
"Better not tell you now", "Cannot predict now",
"Concentrate and ask again", "Don't bet on it",
"My reply is no", "My sources say no", "Outlook not so good",
"Very doubtful",
}
const prompt = "\n?: "
fmt.Print("Please enter your question or a blank line to quit.\n" + prompt)
sc := bufio.NewScanner(os.Stdin)
for sc.Scan() {
question := sc.Bytes()
question = bytes.TrimSpace(question)
if len(question) == 0 {
break
}
answer := answers[rand.Intn(len(answers))]
fmt.Printf("\n%s\n"+prompt, answer)
}
if err := sc.Err(); err != nil {
log.Fatal(err)
}
} | 610Magic 8-ball
| 0go
| hftjq |
!ExternalBytes class methods!
mapExecutableBytes:size
%{
# include <sys/mman.h>
void *mem;
OBJ retVal;
int nBytes = __intVal(size);
mem = mmap(nil, nBytes, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_PRIVATE|MAP_ANON, -1, 0);
if (mem!= MAP_FAILED) {
RETURN( __MKEXTERNALBYTES_N(mem, nBytes));
}
%}.
self primitiveFailed
!! | 609Machine code
| 16scala
| ng7ic |
import Foundation
typealias TwoIntsOneInt = @convention(c) (Int, Int) -> Int
let code = [
144, | 609Machine code
| 17swift
| s2uqt |
import System.Random (getStdRandom, randomR)
import Control.Monad (forever)
answers :: [String]
answers =
[ "It is certain"
, "It is decidedly so"
, "Without a doubt"
, "Yes, definitely"
, "You may rely on it"
, "As I see it, yes"
, "Most likely"
, "Outlook good"
, "Signs point to yes"
, "Yes"
, "Reply hazy, try again"
, "Ask again later"
, "Better not tell you now"
, "Cannot predict now"
, "Concentrate and ask again"
, "Don't bet on it"
, "My reply is no"
, "My sources say no"
, "Outlook not so good"
, "Very doubtful"]
main :: IO ()
main = do
putStrLn "Hello. The Magic 8 Ball knows all. Type your question."
forever $ do
getLine
n <- getStdRandom (randomR (0, pred $ length answers))
putStrLn $ answers !! n | 610Magic 8-ball
| 8haskell
| i4gor |
import java.util.Random;
import java.util.Scanner;
public class MagicEightBall {
public static void main(String[] args) {
new MagicEightBall().run();
}
private static String[] ANSWERS = new String[] {"It is certain.", "It is decidedly so.", "Without a doubt.", "Yes - definitely.",
"You may rely on it.", "As I see it, yes.", "Most likely.", "Outlook good.", "Yes.", "Signs point to yes.",
"Reply hazy, try again.", "Ask again later.", "Better not tell you now.", "Cannot predict now.", "Concentrate and ask again.",
"Don't count on it.", "My reply is no.", "My sources say no.", "Outlook not so good.", "Very doubtful. "};
public void run() {
Random random = new Random();
System.out.printf("Hello. The Magic 8 Ball knows all. Type your question.%n%n");
try ( Scanner in = new Scanner(System.in); ) {
System.out.printf("? ");
while ( (in.nextLine()).length() > 0 ) {
System.out.printf("8 Ball Response: %s%n", ANSWERS[random.nextInt(ANSWERS.length)]);
System.out.printf("? ");
}
}
System.out.printf("%n8 Ball Done. Bye.");
}
} | 610Magic 8-ball
| 9java
| xclwy |
null | 610Magic 8-ball
| 10javascript
| o5486 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.