code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
use List::Util qw(sum min);
$source = <<'END';
............................................................
..
..
..
..
....
....
....
....
....
....
....
....
..
..
..
..
............................................................
END
for $line (split "\n", $source) {
push @lines, [map { 1 & ord $_ } split '', $line]
}
$v = @lines;
$h = @{$lines[0]};
push @black, @$_ for @lines;
@p8 = ((-$h-1), (-$h+0), (-$h+1),
0-1, 0+1,
$h-1, $h+0, $h+1)[1,2,4,7,6,5,3,0];
@cand = grep { $black[$_] } map { my $x = $_; map $_*$h + $x, 1..$v-2 } 1..$h-2;
do {
sub seewhite {
my($w1,$w2) = @_;
my(@results);
sub cycles { my(@neighbors)=@_; my $c; $c += $neighbors[$_] < $neighbors[($_+1)%8] for 0..$
sub blacks { my(@neighbors)=@_; sum @neighbors }
@prior = @cand; @cand = ();
for $p (@prior) {
@n = @black[map { $_+$p } @p8];
if (cycles(@n) == 1 and 2 <= sum(blacks(@n)) and sum(blacks(@n)) <= 6 and min(@n[@$w1]) == 0 and min(@n[@$w2]) == 0) {
push @results, $p;
} else {
push @cand, $p
}
}
return @results;
}
@goners1 = seewhite [0,2,4], [2,4,6]; @black[@goners1] = 0 x @goners1;
@goners2 = seewhite [0,2,6], [0,4,6]; @black[@goners2] = 0 x @goners2;
} until @goners1 == 0 and @goners2 == 0;
while (@black) { push @thinned, join '', qw<.
print join "\n", @thinned; | 15Zhang-Suen thinning algorithm
| 2perl
| rngd |
use std::cmp::Ordering;
use std::ops::{Add, AddAssign, Sub, SubAssign, Mul, MulAssign, Div, DivAssign, Neg};
fn gcd(a: i64, b: i64) -> i64 {
match b {
0 => a,
_ => gcd(b, a% b),
}
}
fn lcm(a: i64, b: i64) -> i64 {
a / gcd(a, b) * b
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord)]
pub struct Rational {
numerator: i64,
denominator: i64,
}
impl Rational {
fn new(numerator: i64, denominator: i64) -> Self {
let divisor = gcd(numerator, denominator);
Rational {
numerator: numerator / divisor,
denominator: denominator / divisor,
}
}
}
impl Add for Rational {
type Output = Self;
fn add(self, other: Self) -> Self {
let multiplier = lcm(self.denominator, other.denominator);
Rational::new(self.numerator * multiplier / self.denominator +
other.numerator * multiplier / other.denominator,
multiplier)
}
}
impl AddAssign for Rational {
fn add_assign(&mut self, other: Self) {
*self = *self + other;
}
}
impl Sub for Rational {
type Output = Self;
fn sub(self, other: Self) -> Self {
self + -other
}
}
impl SubAssign for Rational {
fn sub_assign(&mut self, other: Self) {
*self = *self - other;
}
}
impl Mul for Rational {
type Output = Self;
fn mul(self, other: Self) -> Self {
Rational::new(self.numerator * other.numerator,
self.denominator * other.denominator)
}
}
impl MulAssign for Rational {
fn mul_assign(&mut self, other: Self) {
*self = *self * other;
}
}
impl Div for Rational {
type Output = Self;
fn div(self, other: Self) -> Self {
self *
Rational {
numerator: other.denominator,
denominator: other.numerator,
}
}
}
impl DivAssign for Rational {
fn div_assign(&mut self, other: Self) {
*self = *self / other;
}
}
impl Neg for Rational {
type Output = Self;
fn neg(self) -> Self {
Rational {
numerator: -self.numerator,
denominator: self.denominator,
}
}
}
impl PartialOrd for Rational {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
(self.numerator * other.denominator).partial_cmp(&(self.denominator * other.numerator))
}
}
impl<T: Into<i64>> From<T> for Rational {
fn from(value: T) -> Self {
Rational::new(value.into(), 1)
}
}
fn main() {
let max = 1 << 19;
for candidate in 2..max {
let mut sum = Rational::new(1, candidate);
for factor in 2..(candidate as f64).sqrt().ceil() as i64 {
if candidate% factor == 0 {
sum += Rational::new(1, factor);
sum += Rational::new(1, candidate / factor);
}
}
if sum == 1.into() {
println!("{} is perfect", candidate);
}
}
} | 8Arithmetic/Rational
| 15rust
| ci9z |
> Math.pow(0, 0);
1 | 14Zero to the zero power
| 10javascript
| meyv |
class Rational(n: Long, d:Long) extends Ordered[Rational]
{
require(d!=0)
private val g:Long = gcd(n, d)
val numerator:Long = n/g
val denominator:Long = d/g
def this(n:Long)=this(n,1)
def +(that:Rational):Rational=new Rational(
numerator*that.denominator + that.numerator*denominator,
denominator*that.denominator)
def -(that:Rational):Rational=new Rational(
numerator*that.denominator - that.numerator*denominator,
denominator*that.denominator)
def *(that:Rational):Rational=
new Rational(numerator*that.numerator, denominator*that.denominator)
def /(that:Rational):Rational=
new Rational(numerator*that.denominator, that.numerator*denominator)
def unary_~ :Rational=new Rational(denominator, numerator)
def unary_- :Rational=new Rational(-numerator, denominator)
def abs :Rational=new Rational(Math.abs(numerator), Math.abs(denominator))
override def compare(that:Rational):Int=
(this.numerator*that.denominator-that.numerator*this.denominator).toInt
override def toString()=numerator+"/"+denominator
private def gcd(x:Long, y:Long):Long=
if(y==0) x else gcd(y, x%y)
}
object Rational
{
def apply(n: Long, d:Long)=new Rational(n,d)
def apply(n:Long)=new Rational(n)
implicit def longToRational(i:Long)=new Rational(i)
} | 8Arithmetic/Rational
| 16scala
| vf2s |
package main
import (
"fmt"
"log"
"os/exec"
)
func gcd(x, y int) int {
for y != 0 {
x, y = y, x%y
}
return x
}
func yellowstone(n int) []int {
m := make(map[int]bool)
a := make([]int, n+1)
for i := 1; i < 4; i++ {
a[i] = i
m[i] = true
}
min := 4
for c := 4; c <= n; c++ {
for i := min; ; i++ {
if !m[i] && gcd(a[c-1], i) == 1 && gcd(a[c-2], i) > 1 {
a[c] = i
m[i] = true
if i == min {
min++
}
break
}
}
}
return a[1:]
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
x := make([]int, 100)
for i := 0; i < 100; i++ {
x[i] = i + 1
}
y := yellowstone(100)
fmt.Println("The first 30 Yellowstone numbers are:")
fmt.Println(y[:30])
g := exec.Command("gnuplot", "-persist")
w, err := g.StdinPipe()
check(err)
check(g.Start())
fmt.Fprintln(w, "unset key; plot '-'")
for i, xi := range x {
fmt.Fprintf(w, "%d%d\n", xi, y[i])
}
fmt.Fprintln(w, "e")
w.Close()
g.Wait()
} | 20Yellowstone sequence
| 0go
| mhyi |
import scala.collection.mutable.ListBuffer
object ZeckendorfArithmetic extends App {
val elapsed: (=> Unit) => Long = f => {
val s = System.currentTimeMillis
f
(System.currentTimeMillis - s) / 1000
}
val add: (Z, Z) => Z = (z1, z2) => z1 + z2
val subtract: (Z, Z) => Z = (z1, z2) => z1 - z2
val multiply: (Z, Z) => Z = (z1, z2) => z1 * z2
val divide: (Z, Z) => Option[Z] = (z1, z2) => z1 / z2
val modulo: (Z, Z) => Option[Z] = (z1, z2) => z1 % z2
val ops = Map(("+", add), ("-", subtract), ("*", multiply), ("/", divide), ("%", modulo))
val calcs = List(
(Z("101"), "+", Z("10100"))
, (Z("101"), "-", Z("10100"))
, (Z("101"), "*", Z("10100"))
, (Z("101"), "/", Z("10100"))
, (Z("-1010101"), "+", Z("10100"))
, (Z("-1010101"), "-", Z("10100"))
, (Z("-1010101"), "*", Z("10100"))
, (Z("-1010101"), "/", Z("10100"))
, (Z("1000101010"), "+", Z("10101010"))
, (Z("1000101010"), "-", Z("10101010"))
, (Z("1000101010"), "*", Z("10101010"))
, (Z("1000101010"), "/", Z("10101010"))
, (Z("10100"), "+", Z("1010"))
, (Z("100101"), "-", Z("100"))
, (Z("1010101010101010101"), "+", Z("-1010101010101"))
, (Z("1010101010101010101"), "-", Z("-1010101010101"))
, (Z("1010101010101010101"), "*", Z("-1010101010101"))
, (Z("1010101010101010101"), "/", Z("-1010101010101"))
, (Z("1010101010101010101"), "%", Z("-1010101010101"))
, (Z("1010101010101010101"), "+", Z("101010101010101"))
, (Z("1010101010101010101"), "-", Z("101010101010101"))
, (Z("1010101010101010101"), "*", Z("101010101010101"))
, (Z("1010101010101010101"), "/", Z("101010101010101"))
, (Z("1010101010101010101"), "%", Z("101010101010101"))
, (Z("10101010101010101010"), "+", Z("1010101010101010"))
, (Z("10101010101010101010"), "-", Z("1010101010101010"))
, (Z("10101010101010101010"), "*", Z("1010101010101010"))
, (Z("10101010101010101010"), "/", Z("1010101010101010"))
, (Z("10101010101010101010"), "%", Z("1010101010101010"))
, (Z("1010"), "%", Z("10"))
, (Z("1010"), "%", Z("-10"))
, (Z("-1010"), "%", Z("10"))
, (Z("-1010"), "%", Z("-10"))
, (Z("100"), "/", Z("0"))
, (Z("100"), "%", Z("0"))
)
val iadd: (BigInt, BigInt) => BigInt = (a, b) => a + b
val isub: (BigInt, BigInt) => BigInt = (a, b) => a - b | 17Zeckendorf arithmetic
| 16scala
| btk6 |
from sympy import divisors
from sympy.combinatorics.subsets import Subset
def isZumkeller(n):
d = divisors(n)
s = sum(d)
if not s% 2 and max(d) <= s/2:
for x in range(1, 2**len(d)):
if sum(Subset.unrank_binary(x, d).subset) == s/2:
return True
return False
def printZumkellers(N, oddonly=False):
nprinted = 0
for n in range(1, 10**5):
if (oddonly == False or n% 2) and isZumkeller(n):
print(f'{n:>8}', end='')
nprinted += 1
if nprinted% 10 == 0:
print()
if nprinted >= N:
return
print()
printZumkellers(220)
print()
printZumkellers(40, True) | 19Zumkeller numbers
| 3python
| 1tpc |
beforeTxt = '''\
1100111
1100111
1100111
1100111
1100110
1100110
1100110
1100110
1100110
1100110
1100110
1100110
1111110
0000000\
'''
smallrc01 = '''\
00000000000000000000000000000000
01111111110000000111111110000000
01110001111000001111001111000000
01110000111000001110000111000000
01110001111000001110000000000000
01111111110000001110000000000000
01110111100000001110000111000000
01110011110011101111001111011100
01110001111011100111111110011100
00000000000000000000000000000000\
'''
rc01 = '''\
00000000000000000000000000000000000000000000000000000000000
01111111111111111100000000000000000001111111111111000000000
01111111111111111110000000000000001111111111111111000000000
01111111111111111111000000000000111111111111111111000000000
01111111100000111111100000000001111111111111111111000000000
00011111100000111111100000000011111110000000111111000000000
00011111100000111111100000000111111100000000000000000000000
00011111111111111111000000000111111100000000000000000000000
00011111111111111110000000000111111100000000000000000000000
00011111111111111111000000000111111100000000000000000000000
00011111100000111111100000000111111100000000000000000000000
00011111100000111111100000000111111100000000000000000000000
00011111100000111111100000000011111110000000111111000000000
01111111100000111111100000000001111111111111111111000000000
01111111100000111111101111110000111111111111111111011111100
01111111100000111111101111110000001111111111111111011111100
01111111100000111111101111110000000001111111111111011111100
00000000000000000000000000000000000000000000000000000000000\
'''
def intarray(binstring):
'''Change a 2D matrix of 01 chars into a list of lists of ints'''
return [[1 if ch == '1' else 0 for ch in line]
for line in binstring.strip().split()]
def chararray(intmatrix):
'''Change a 2d list of lists of 1/0 ints into lines of 1/0 chars'''
return '\n'.join(''.join(str(p) for p in row) for row in intmatrix)
def toTxt(intmatrix):
'''Change a 2d list of lists of 1/0 ints into lines of '
return '\n'.join(''.join(('
def neighbours(x, y, image):
'''Return 8-neighbours of point p1 of picture, in order'''
i = image
x1, y1, x_1, y_1 = x+1, y-1, x-1, y+1
return [i[y1][x], i[y1][x1], i[y][x1], i[y_1][x1],
i[y_1][x], i[y_1][x_1], i[y][x_1], i[y1][x_1]]
def transitions(neighbours):
n = neighbours + neighbours[0:1]
return sum((n1, n2) == (0, 1) for n1, n2 in zip(n, n[1:]))
def zhangSuen(image):
changing1 = changing2 = [(-1, -1)]
while changing1 or changing2:
changing1 = []
for y in range(1, len(image) - 1):
for x in range(1, len(image[0]) - 1):
P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image)
if (image[y][x] == 1 and
P4 * P6 * P8 == 0 and
P2 * P4 * P6 == 0 and
transitions(n) == 1 and
2 <= sum(n) <= 6):
changing1.append((x,y))
for x, y in changing1: image[y][x] = 0
changing2 = []
for y in range(1, len(image) - 1):
for x in range(1, len(image[0]) - 1):
P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image)
if (image[y][x] == 1 and
P2 * P6 * P8 == 0 and
P2 * P4 * P8 == 0 and
transitions(n) == 1 and
2 <= sum(n) <= 6):
changing2.append((x,y))
for x, y in changing2: image[y][x] = 0
return image
if __name__ == '__main__':
for picture in (beforeTxt, smallrc01, rc01):
image = intarray(picture)
print('\nFrom:\n%s'% toTxt(image))
after = zhangSuen(image)
print('\nTo thinned:\n%s'% toTxt(after)) | 15Zhang-Suen thinning algorithm
| 3python
| 7drm |
package main
import "fmt"
func main() {
for i := 0; i <= 20; i++ {
fmt.Printf("%2d%7b\n", i, zeckendorf(i))
}
}
func zeckendorf(n int) int { | 16Zeckendorf number representation
| 0go
| i4og |
>>> z1 = 1.5 + 3j
>>> z2 = 1.5 + 1.5j
>>> z1 + z2
(3+4.5j)
>>> z1 - z2
1.5j
>>> z1 * z2
(-2.25+6.75j)
>>> z1 / z2
(1.5+0.5j)
>>> - z1
(-1.5-3j)
>>> z1.conjugate()
(1.5-3j)
>>> abs(z1)
3.3541019662496847
>>> z1 ** z2
(-1.1024829553277784-0.38306415117199333j)
>>> z1.real
1.5
>>> z1.imag
3.0
>>> | 9Arithmetic/Complex
| 3python
| d1n1 |
null | 14Zero to the zero power
| 11kotlin
| og8z |
import Data.List (unfoldr)
yellowstone :: [Integer]
yellowstone = 1: 2: 3: unfoldr (Just . f) (2, 3, [4 ..])
where
f ::
(Integer, Integer, [Integer]) ->
(Integer, (Integer, Integer, [Integer]))
f (p2, p1, rest) = (next, (p1, next, rest_))
where
(next, rest_) = select rest
select :: [Integer] -> (Integer, [Integer])
select (x: xs)
| gcd x p1 == 1 && gcd x p2 /= 1 = (x, xs)
| otherwise = (y, x: ys)
where
(y, ys) = select xs
main :: IO ()
main = print $ take 30 yellowstone | 20Yellowstone sequence
| 8haskell
| kih0 |
package main
import (
"fmt"
"golang.org/x/net/html"
"io/ioutil"
"net/http"
"regexp"
"strings"
)
var (
expr = `<h3 class="title"><a class=.*?href="(.*?)".*?>(.*?)</a></h3>` +
`.*?<div class="compText aAbs" ><p class=.*?>(.*?)</p></div>`
rx = regexp.MustCompile(expr)
)
type YahooResult struct {
title, url, content string
}
func (yr YahooResult) String() string {
return fmt.Sprintf("Title :%s\nUrl :%s\nContent:%s\n", yr.title, yr.url, yr.content)
}
type YahooSearch struct {
query string
page int
}
func (ys YahooSearch) results() []YahooResult {
search := fmt.Sprintf("http: | 22Yahoo! search interface
| 0go
| s6qa |
import Data.Bits
import Numeric
zeckendorf = map b $ filter ones [0..] where
ones :: Int -> Bool
ones x = 0 == x .&. (x `shiftR` 1)
b x = showIntAtBase 2 ("01"!!) x ""
main = mapM_ putStrLn $ take 21 zeckendorf | 16Zeckendorf number representation
| 8haskell
| vq2k |
z1 <- 1.5 + 3i
z2 <- 1.5 + 1.5i
print(z1 + z2)
print(z1 - z2)
print(z1 * z2)
print(z1 / z2)
print(-z1)
print(Conj(z1))
print(abs(z1))
print(z1^z2)
print(exp(z1))
print(Re(z1))
print(Im(z1)) | 9Arithmetic/Complex
| 13r
| 8h0x |
import java.util.ArrayList;
import java.util.List;
public class YellowstoneSequence {
public static void main(String[] args) {
System.out.printf("First 30 values in the yellowstone sequence:%n%s%n", yellowstoneSequence(30));
}
private static List<Integer> yellowstoneSequence(int sequenceCount) {
List<Integer> yellowstoneList = new ArrayList<Integer>();
yellowstoneList.add(1);
yellowstoneList.add(2);
yellowstoneList.add(3);
int num = 4;
List<Integer> notYellowstoneList = new ArrayList<Integer>();
int yellowSize = 3;
while ( yellowSize < sequenceCount ) {
int found = -1;
for ( int index = 0 ; index < notYellowstoneList.size() ; index++ ) {
int test = notYellowstoneList.get(index);
if ( gcd(yellowstoneList.get(yellowSize-2), test) > 1 && gcd(yellowstoneList.get(yellowSize-1), test) == 1 ) {
found = index;
break;
}
}
if ( found >= 0 ) {
yellowstoneList.add(notYellowstoneList.remove(found));
yellowSize++;
}
else {
while ( true ) {
if ( gcd(yellowstoneList.get(yellowSize-2), num) > 1 && gcd(yellowstoneList.get(yellowSize-1), num) == 1 ) {
yellowstoneList.add(num);
yellowSize++;
num++;
break;
}
notYellowstoneList.add(num);
num++;
}
}
}
return yellowstoneList;
}
private static final int gcd(int a, int b) {
if ( b == 0 ) {
return a;
}
return gcd(b, a%b);
}
} | 20Yellowstone sequence
| 9java
| 4x58 |
import Network.HTTP
import Text.Parsec
data YahooSearchItem = YahooSearchItem {
itemUrl, itemTitle, itemContent :: String }
data YahooSearch = YahooSearch {
searchQuery :: String,
searchPage :: Int,
searchItems :: [YahooSearchItem] }
yahooUrl = "http://search.yahoo.com/search?p="
yahoo :: String -> IO YahooSearch
yahoo q = simpleHTTP (getRequest $ yahooUrl ++ q) >>=
getResponseBody >>= return . YahooSearch q 1 . items
next :: YahooSearch -> IO YahooSearch
next (YahooSearch q p _) =
simpleHTTP (getRequest $
yahooUrl ++ q ++ "&b=" ++ show (p + 1)) >>=
getResponseBody >>= return . YahooSearch q (p + 1) . items
printResults :: YahooSearch -> IO ()
printResults (YahooSearch q p items) = do
putStrLn $ "Showing Yahoo! search results for query: " ++ q
putStrLn $ "Page: " ++ show p
putChar '\n'
mapM_ printOne items
where
printOne (YahooSearchItem itemUrl itemTitle itemContent) = do
putStrLn $ "URL : " ++ itemUrl
putStrLn $ "Title: " ++ itemTitle
putStrLn $ "Abstr: " ++ itemContent
putChar '\n'
urlTag, titleTag, contentTag1, contentTag2, ignoreTag,
ignoreText :: Parsec String () String
urlTag = do { string "<a id=\"link-";
many digit; string "\" class=\"yschttl spt\" href=\"";
url <- manyTill anyChar (char '"'); manyTill anyChar (char '>');
return url }
titleTag = do { urlTag; manyTill anyChar (try (string "</a>")) }
contentTag1 = do { string "<div class=\"sm-abs\">";
manyTill anyChar (try (string "</div>")) }
contentTag2 = do { string "<div class=\"abstr\">";
manyTill anyChar (try (string "</div>")) }
ignoreTag = do { char ('<'); manyTill anyChar (char '>');
return "" }
ignoreText = do { many1 (noneOf "<"); return "" }
nonempty :: [String] -> Parsec String () [String]
nonempty xs = return [ x | x <- xs, not (null x) ]
parseCategory x = do
res <- many x
eof
nonempty res
urls, titles, contents :: Parsec String () [String]
urls = parseCategory url where
url = (try urlTag) <|> ignoreTag <|> ignoreText
titles = parseCategory title where
title = (try titleTag) <|> ignoreTag <|> ignoreText
contents = parseCategory content where
content = (try contentTag1) <|> (try contentTag2) <|>
ignoreTag <|> ignoreText
items :: String -> [YahooSearchItem]
items q =
let ignoreOrKeep = either (const []) id
us = ignoreOrKeep $ parse urls "" q
ts = ignoreOrKeep $ parse titles "" q
cs = ignoreOrKeep $ parse contents "" q
in [ YahooSearchItem { itemUrl = u, itemTitle = t, itemContent = c } |
(u, t, c) <- zip3 us ts cs ] | 22Yahoo! search interface
| 8haskell
| 9jmo |
print(0^0) | 14Zero to the zero power
| 1lua
| irot |
(() => {
'use strict'; | 20Yellowstone sequence
| 10javascript
| hojh |
class Integer
def divisors
res = [1, self]
(2..Integer.sqrt(self)).each do |n|
div, mod = divmod(n)
res << n << div if mod.zero?
end
res.uniq.sort
end
def zumkeller?
divs = divisors
sum = divs.sum
return false unless sum.even? && sum >= self*2
half = sum / 2
max_combi_size = divs.size / 2
1.upto(max_combi_size).any? do |combi_size|
divs.combination(combi_size).any?{|combi| combi.sum == half}
end
end
end
def p_enum(enum, cols = 10, col_width = 8)
enum.each_slice(cols) {|slice| puts *slice.size % slice}
end
puts
p_enum 1.step.lazy.select(&:zumkeller?).take(n), 14, 6
puts
p_enum 1.step(by: 2).lazy.select(&:zumkeller?).take(n)
puts
p_enum 1.step(by: 2).lazy.select{|x| x % 5 > 0 && x.zumkeller?}.take(n) | 19Zumkeller numbers
| 14ruby
| e3ax |
class ZhangSuen
NEIGHBOUR8 = [[-1,0],[-1,1],[0,1],[1,1],[1,0],[1,-1],[0,-1],[-1,-1]]
CIRCULARS = NEIGHBOUR8 + [NEIGHBOUR8.first]
def initialize(str, black=)
s1 = str.each_line.map{|line| line.chomp.each_char.map{|c| c==black? 1: 0}}
s2 = s1.map{|line| line.map{0}}
xrange = 1 ... s1.size-1
yrange = 1 ... s1[0].size-1
printout(s1)
begin
@r = 0
xrange.each{|x| yrange.each{|y| s2[x][y] = s1[x][y] - zs(s1,x,y,1)}}
xrange.each{|x| yrange.each{|y| s1[x][y] = s2[x][y] - zs(s2,x,y,0)}}
end until @r == 0
printout(s1)
end
def zs(ng,x,y,g)
return 0 if ng[x][y] == 0 or
(ng[x-1][y] + ng[x][y+1] + ng[x+g][y-1+g]) == 3 or
(ng[x-1+g][y+g] + ng[x+1][y] + ng[x][y-1]) == 3
bp1 = NEIGHBOUR8.inject(0){|res,(i,j)| res += ng[x+i][y+j]}
return 0 if bp1 < 2 or 6 < bp1
ap1 = CIRCULARS.map{|i,j| ng[x+i][y+j]}.each_cons(2).count{|a,b| a<b}
return 0 if ap1!= 1
@r = 1
end
def printout(image)
puts image.map{|row| row.map{|col| [col]}.join}
end
end
str = <<EOS
...........................................................
.
.
.
.
...
...
...
...
...
...
...
...
.
.
.
.
...........................................................
EOS
ZhangSuen.new(str)
task_example = <<EOS
00000000000000000000000000000000
01111111110000000111111110000000
01110001111000001111001111000000
01110000111000001110000111000000
01110001111000001110000000000000
01111111110000001110000000000000
01110111100000001110000111000000
01110011110011101111001111011100
01110001111011100111111110011100
00000000000000000000000000000000
EOS
ZhangSuen.new(task_example, ) | 15Zhang-Suen thinning algorithm
| 14ruby
| htjx |
import java.util.*;
class Zeckendorf
{
public static String getZeckendorf(int n)
{
if (n == 0)
return "0";
List<Integer> fibNumbers = new ArrayList<Integer>();
fibNumbers.add(1);
int nextFib = 2;
while (nextFib <= n)
{
fibNumbers.add(nextFib);
nextFib += fibNumbers.get(fibNumbers.size() - 2);
}
StringBuilder sb = new StringBuilder();
for (int i = fibNumbers.size() - 1; i >= 0; i--)
{
int fibNumber = fibNumbers.get(i);
sb.append((fibNumber <= n) ? "1" : "0");
if (fibNumber <= n)
n -= fibNumber;
}
return sb.toString();
}
public static void main(String[] args)
{
for (int i = 0; i <= 20; i++)
System.out.println("Z(" + i + ")=" + getZeckendorf(i));
}
} | 16Zeckendorf number representation
| 9java
| yp6g |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class YahooSearch {
private String query; | 22Yahoo! search interface
| 9java
| tuf9 |
use std::convert::TryInto; | 19Zumkeller numbers
| 15rust
| w6e4 |
package main
import (
"fmt"
"math/big"
)
func main() {
x := big.NewInt(2)
x = x.Exp(big.NewInt(3), x, nil)
x = x.Exp(big.NewInt(4), x, nil)
x = x.Exp(big.NewInt(5), x, nil)
str := x.String()
fmt.Printf("5^(4^(3^2)) has%d digits:%s ...%s\n",
len(str),
str[:20],
str[len(str)-20:],
)
} | 18Arbitrary-precision integers (included)
| 0go
| r8gm |
(() => {
'use strict';
const main = () =>
unlines(
map(n => concat(zeckendorf(n)),
enumFromTo(0, 20)
)
); | 16Zeckendorf number representation
| 10javascript
| 2xlr |
(defn doors []
(let [doors (into-array (repeat 100 false))]
(doseq [pass (range 1 101)
i (range (dec pass) 100 pass) ]
(aset doors i (not (aget doors i))))
doors))
(defn open-doors [] (for [[d n] (map vector (doors) (iterate inc 1)):when d] n))
(defn print-open-doors []
(println
"Open doors after 100 passes:"
(apply str (interpose ", " (open-doors))))) | 21100 doors
| 6clojure
| z4tj |
xmlDocPtr getdoc (char *docname) {
xmlDocPtr doc;
doc = xmlParseFile(docname);
return doc;
}
xmlXPathObjectPtr getnodeset (xmlDocPtr doc, xmlChar *xpath){
xmlXPathContextPtr context;
xmlXPathObjectPtr result;
context = xmlXPathNewContext(doc);
result = xmlXPathEvalExpression(xpath, context);
xmlXPathFreeContext(context);
return result;
}
int main(int argc, char **argv) {
if (argc <= 2) {
printf(, argv[0]);
return 0;
}
char *docname;
xmlDocPtr doc;
xmlChar *xpath = (xmlChar*) argv[2];
xmlNodeSetPtr nodeset;
xmlXPathObjectPtr result;
int i;
xmlChar *keyword;
docname = argv[1];
doc = getdoc(docname);
result = getnodeset (doc, xpath);
if (result) {
nodeset = result->nodesetval;
for (i=0; i < nodeset->nodeNr; i++) {
xmlNodePtr titleNode = nodeset->nodeTab[i];
keyword = xmlNodeListGetString(doc, titleNode->xmlChildrenNode, 1);
printf(,i+1, keyword);
xmlFree(keyword);
}
xmlXPathFreeObject (result);
}
xmlFreeDoc(doc);
xmlCleanupParser();
return 0;
} | 23XML/XPath
| 5c
| 97m1 |
fun main() {
println("First 30 values in the yellowstone sequence:")
println(yellowstoneSequence(30))
}
private fun yellowstoneSequence(sequenceCount: Int): List<Int> {
val yellowstoneList = mutableListOf(1, 2, 3)
var num = 4
val notYellowstoneList = mutableListOf<Int>()
var yellowSize = 3
while (yellowSize < sequenceCount) {
var found = -1
for (index in notYellowstoneList.indices) {
val test = notYellowstoneList[index]
if (gcd(yellowstoneList[yellowSize - 2], test) > 1 && gcd(
yellowstoneList[yellowSize - 1], test
) == 1
) {
found = index
break
}
}
if (found >= 0) {
yellowstoneList.add(notYellowstoneList.removeAt(found))
yellowSize++
} else {
while (true) {
if (gcd(yellowstoneList[yellowSize - 2], num) > 1 && gcd(
yellowstoneList[yellowSize - 1], num
) == 1
) {
yellowstoneList.add(num)
yellowSize++
num++
break
}
notYellowstoneList.add(num)
num++
}
}
}
return yellowstoneList
}
private fun gcd(a: Int, b: Int): Int {
return if (b == 0) {
a
} else gcd(b, a % b)
} | 20Yellowstone sequence
| 11kotlin
| lpcp |
null | 22Yahoo! search interface
| 11kotlin
| o98z |
import Foundation
extension BinaryInteger {
@inlinable
public var isZumkeller: Bool {
let divs = factors(sorted: false)
let sum = divs.reduce(0, +)
guard sum & 1!= 1 else {
return false
}
guard self & 1!= 1 else {
let abundance = sum - 2*self
return abundance > 0 && abundance & 1 == 0
}
return isPartSum(divs: divs[...], sum: sum / 2)
}
@inlinable
public func factors(sorted: Bool = true) -> [Self] {
let maxN = Self(Double(self).squareRoot())
var res = Set<Self>()
for factor in stride(from: 1, through: maxN, by: 1) where self% factor == 0 {
res.insert(factor)
res.insert(self / factor)
}
return sorted? res.sorted(): Array(res)
}
}
@usableFromInline
func isPartSum<T: BinaryInteger>(divs: ArraySlice<T>, sum: T) -> Bool {
guard sum!= 0 else {
return true
}
guard!divs.isEmpty else {
return false
}
let last = divs.last!
if last > sum {
return isPartSum(divs: divs.dropLast(), sum: sum)
}
return isPartSum(divs: divs.dropLast(), sum: sum) || isPartSum(divs: divs.dropLast(), sum: sum - last)
}
let zums = (2...).lazy.filter({ $0.isZumkeller })
let oddZums = zums.filter({ $0 & 1 == 1 })
let oddZumsWithout5 = oddZums.filter({ String($0).last!!= "5" })
print("First 220 zumkeller numbers are \(Array(zums.prefix(220)))")
print("First 40 odd zumkeller numbers are \(Array(oddZums.prefix(40)))")
print("First 40 odd zumkeller numbers that don't end in a 5 are: \(Array(oddZumsWithout5.prefix(40)))") | 19Zumkeller numbers
| 17swift
| az1i |
def bigNumber = 5G ** (4 ** (3 ** 2)) | 18Arbitrary-precision integers (included)
| 7groovy
| vw28 |
main :: IO ()
main = do
let y = show (5 ^ 4 ^ 3 ^ 2)
let l = length y
putStrLn
("5**4**3**2 = " ++
take 20 y ++ "..." ++ drop (l - 20) y ++ " and has " ++ show l ++ " digits") | 18Arbitrary-precision integers (included)
| 8haskell
| 0ls7 |
import UIKit | 15Zhang-Suen thinning algorithm
| 17swift
| jf74 |
a = Complex(1, 1)
i = Complex::I
b = 3.14159 + 1.25 * i
c = '1/2+3/4i'.to_c
c = 1.0/2+3/4i
puts a + b
puts a * b
puts -a
puts 1.quo a
puts a.conjugate
puts a.conj | 9Arithmetic/Complex
| 14ruby
| tef2 |
import Foundation
extension BinaryInteger {
@inlinable
public func gcd(with other: Self) -> Self {
var gcd = self
var b = other
while b!= 0 {
(gcd, b) = (b, gcd% b)
}
return gcd
}
@inlinable
public func lcm(with other: Self) -> Self {
let g = gcd(with: other)
return self / g * other
}
}
public struct Frac<NumType: BinaryInteger & SignedNumeric>: Equatable {
@usableFromInline
var _num: NumType
@usableFromInline
var _dom: NumType
@usableFromInline
init(_num: NumType, _dom: NumType) {
self._num = _num
self._dom = _dom
}
@inlinable
public init(numerator: NumType, denominator: NumType) {
let divisor = numerator.gcd(with: denominator)
self._num = numerator / divisor
self._dom = denominator / divisor
}
@inlinable
public static func + (lhs: Frac, rhs: Frac) -> Frac {
let multiplier = lhs._dom.lcm(with: rhs.denominator)
return Frac(
numerator: lhs._num * multiplier / lhs._dom + rhs._num * multiplier / rhs._dom,
denominator: multiplier
)
}
@inlinable
public static func += (lhs: inout Frac, rhs: Frac) {
lhs = lhs + rhs
}
@inlinable
public static func - (lhs: Frac, rhs: Frac) -> Frac {
return lhs + -rhs
}
@inlinable
public static func -= (lhs: inout Frac, rhs: Frac) {
lhs = lhs + -rhs
}
@inlinable
public static func * (lhs: Frac, rhs: Frac) -> Frac {
return Frac(numerator: lhs._num * rhs._num, denominator: lhs._dom * rhs._dom)
}
@inlinable
public static func *= (lhs: inout Frac, rhs: Frac) {
lhs = lhs * rhs
}
@inlinable
public static func / (lhs: Frac, rhs: Frac) -> Frac {
return lhs * Frac(_num: rhs._dom, _dom: rhs._num)
}
@inlinable
public static func /= (lhs: inout Frac, rhs: Frac) {
lhs = lhs / rhs
}
@inlinable
prefix static func - (rhs: Frac) -> Frac {
return Frac(_num: -rhs._num, _dom: rhs._dom)
}
}
extension Frac {
@inlinable
public var numerator: NumType {
get { _num }
set {
let divisor = newValue.gcd(with: denominator)
_num = newValue / divisor
_dom = denominator / divisor
}
}
@inlinable
public var denominator: NumType {
get { _dom }
set {
let divisor = newValue.gcd(with: numerator)
_num = numerator / divisor
_dom = newValue / divisor
}
}
}
extension Frac: CustomStringConvertible {
public var description: String {
let neg = numerator < 0 || denominator < 0
return "Frac(\(neg? "-": "")\(abs(numerator)) / \(abs(denominator)))"
}
}
extension Frac: Comparable {
@inlinable
public static func <(lhs: Frac, rhs: Frac) -> Bool {
return lhs._num * rhs._dom < lhs._dom * rhs._num
}
}
extension Frac: ExpressibleByIntegerLiteral {
public init(integerLiteral value: Int) {
self._num = NumType(value)
self._dom = 1
}
}
for candidate in 2..<1<<19 {
var sum = Frac(numerator: 1, denominator: candidate)
let m = Int(ceil(Double(candidate).squareRoot()))
for factor in 2..<m where candidate% factor == 0 {
sum += Frac(numerator: 1, denominator: factor)
sum += Frac(numerator: 1, denominator: candidate / factor)
}
if sum == 1 {
print("\(candidate) is perfect")
}
} | 8Arithmetic/Rational
| 17swift
| m8yk |
enum HouseStatus { Invalid, Underfull, Valid };
enum Attrib { C, M, D, A, S };
enum Colors { Red, Green, White, Yellow, Blue };
enum Mans { English, Swede, Dane, German, Norwegian };
enum Drinks { Tea, Coffee, Milk, Beer, Water };
enum Animals { Dog, Birds, Cats, Horse, Zebra };
enum Smokes { PallMall, Dunhill, Blend, BlueMaster, Prince };
void printHouses(int ha[5][5]) {
const char *color[] = { , , , , };
const char *man[] = { , , , , };
const char *drink[] = { , , , , };
const char *animal[] = { , , , , };
const char *smoke[] = { , , , , };
printf(,
, , , , , );
for (int i = 0; i < 5; i++) {
printf(, i);
if (ha[i][C] >= 0)
printf(, color[ha[i][C]]);
else
printf(, );
if (ha[i][M] >= 0)
printf(, man[ha[i][M]]);
else
printf(, );
if (ha[i][D] >= 0)
printf(, drink[ha[i][D]]);
else
printf(, );
if (ha[i][A] >= 0)
printf(, animal[ha[i][A]]);
else
printf(, );
if (ha[i][S] >= 0)
printf(, smoke[ha[i][S]]);
else
printf();
}
}
int checkHouses(int ha[5][5]) {
int c_add = 0, c_or = 0;
int m_add = 0, m_or = 0;
int d_add = 0, d_or = 0;
int a_add = 0, a_or = 0;
int s_add = 0, s_or = 0;
if (ha[2][D] >= 0 && ha[2][D] != Milk)
return Invalid;
if (ha[0][M] >= 0 && ha[0][M] != Norwegian)
return Invalid;
for (int i = 0; i < 5; i++) {
if (ha[i][C] >= 0) {
c_add += (1 << ha[i][C]);
c_or |= (1 << ha[i][C]);
}
if (ha[i][M] >= 0) {
m_add += (1 << ha[i][M]);
m_or |= (1 << ha[i][M]);
}
if (ha[i][D] >= 0) {
d_add += (1 << ha[i][D]);
d_or |= (1 << ha[i][D]);
}
if (ha[i][A] >= 0) {
a_add += (1 << ha[i][A]);
a_or |= (1 << ha[i][A]);
}
if (ha[i][S] >= 0) {
s_add += (1 << ha[i][S]);
s_or |= (1 << ha[i][S]);
}
if ((ha[i][M] >= 0 && ha[i][C] >= 0) &&
((ha[i][M] == English && ha[i][C] != Red) ||
(ha[i][M] != English && ha[i][C] == Red)))
return Invalid;
if ((ha[i][M] >= 0 && ha[i][A] >= 0) &&
((ha[i][M] == Swede && ha[i][A] != Dog) ||
(ha[i][M] != Swede && ha[i][A] == Dog)))
return Invalid;
if ((ha[i][M] >= 0 && ha[i][D] >= 0) &&
((ha[i][M] == Dane && ha[i][D] != Tea) ||
(ha[i][M] != Dane && ha[i][D] == Tea)))
return Invalid;
if ((i > 0 && ha[i][C] >= 0 ) &&
((ha[i - 1][C] == Green && ha[i][C] != White) ||
(ha[i - 1][C] != Green && ha[i][C] == White)))
return Invalid;
if ((ha[i][C] >= 0 && ha[i][D] >= 0) &&
((ha[i][C] == Green && ha[i][D] != Coffee) ||
(ha[i][C] != Green && ha[i][D] == Coffee)))
return Invalid;
if ((ha[i][S] >= 0 && ha[i][A] >= 0) &&
((ha[i][S] == PallMall && ha[i][A] != Birds) ||
(ha[i][S] != PallMall && ha[i][A] == Birds)))
return Invalid;
if ((ha[i][S] >= 0 && ha[i][C] >= 0) &&
((ha[i][S] == Dunhill && ha[i][C] != Yellow) ||
(ha[i][S] != Dunhill && ha[i][C] == Yellow)))
return Invalid;
if (ha[i][S] == Blend) {
if (i == 0 && ha[i + 1][A] >= 0 && ha[i + 1][A] != Cats)
return Invalid;
else if (i == 4 && ha[i - 1][A] != Cats)
return Invalid;
else if (ha[i + 1][A] >= 0 && ha[i + 1][A] != Cats && ha[i - 1][A] != Cats)
return Invalid;
}
if (ha[i][S] == Dunhill) {
if (i == 0 && ha[i + 1][A] >= 0 && ha[i + 1][A] != Horse)
return Invalid;
else if (i == 4 && ha[i - 1][A] != Horse)
return Invalid;
else if (ha[i + 1][A] >= 0 && ha[i + 1][A] != Horse && ha[i - 1][A] != Horse)
return Invalid;
}
if ((ha[i][S] >= 0 && ha[i][D] >= 0) &&
((ha[i][S] == BlueMaster && ha[i][D] != Beer) ||
(ha[i][S] != BlueMaster && ha[i][D] == Beer)))
return Invalid;
if ((ha[i][M] >= 0 && ha[i][S] >= 0) &&
((ha[i][M] == German && ha[i][S] != Prince) ||
(ha[i][M] != German && ha[i][S] == Prince)))
return Invalid;
if (ha[i][M] == Norwegian &&
((i < 4 && ha[i + 1][C] >= 0 && ha[i + 1][C] != Blue) ||
(i > 0 && ha[i - 1][C] != Blue)))
return Invalid;
if (ha[i][S] == Blend) {
if (i == 0 && ha[i + 1][D] >= 0 && ha[i + 1][D] != Water)
return Invalid;
else if (i == 4 && ha[i - 1][D] != Water)
return Invalid;
else if (ha[i + 1][D] >= 0 && ha[i + 1][D] != Water && ha[i - 1][D] != Water)
return Invalid;
}
}
if ((c_add != c_or) || (m_add != m_or) || (d_add != d_or)
|| (a_add != a_or) || (s_add != s_or)) {
return Invalid;
}
if ((c_add != 0b11111) || (m_add != 0b11111) || (d_add != 0b11111)
|| (a_add != 0b11111) || (s_add != 0b11111)) {
return Underfull;
}
return Valid;
}
int bruteFill(int ha[5][5], int hno, int attr) {
int stat = checkHouses(ha);
if ((stat == Valid) || (stat == Invalid))
return stat;
int hb[5][5];
memcpy(hb, ha, sizeof(int) * 5 * 5);
for (int i = 0; i < 5; i++) {
hb[hno][attr] = i;
stat = checkHouses(hb);
if (stat != Invalid) {
int nexthno, nextattr;
if (attr < 4) {
nextattr = attr + 1;
nexthno = hno;
} else {
nextattr = 0;
nexthno = hno + 1;
}
stat = bruteFill(hb, nexthno, nextattr);
if (stat != Invalid) {
memcpy(ha, hb, sizeof(int) * 5 * 5);
return stat;
}
}
}
return Invalid;
}
int main() {
int ha[5][5] = {{-1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1}};
bruteFill(ha, 0, 0);
printHouses(ha);
return 0;
} | 24Zebra puzzle
| 5c
| mgys |
typedef struct func_t *func;
typedef struct func_t {
func (*fn) (func, func);
func _;
int num;
} func_t;
func new(func(*f)(func, func), func _) {
func x = malloc(sizeof(func_t));
x->fn = f;
x->_ = _;
x->num = 0;
return x;
}
func call(func f, func n) {
return f->fn(f, n);
}
func Y(func(*f)(func, func)) {
func g = new(f, 0);
g->_ = g;
return g;
}
func num(int n) {
func x = new(0, 0);
x->num = n;
return x;
}
func fac(func self, func n) {
int nn = n->num;
return nn > 1 ? num(nn * call(self->_, num(nn - 1))->num)
: num(1);
}
func fib(func self, func n) {
int nn = n->num;
return nn > 1
? num( call(self->_, num(nn - 1))->num +
call(self->_, num(nn - 2))->num )
: num(1);
}
void show(func n) { printf(, n->num); }
int main() {
int i;
func f = Y(fac);
printf();
for (i = 1; i < 10; i++)
show( call(f, num(i)) );
printf();
f = Y(fib);
printf();
for (i = 1; i < 10; i++)
show( call(f, num(i)) );
printf();
return 0;
} | 25Y combinator
| 5c
| 4p5t |
function gcd(a, b)
if b == 0 then
return a
end
return gcd(b, a % b)
end
function printArray(a)
io.write('[')
for i,v in pairs(a) do
if i > 1 then
io.write(', ')
end
io.write(v)
end
io.write(']')
return nil
end
function removeAt(a, i)
local na = {}
for j,v in pairs(a) do
if j ~= i then
table.insert(na, v)
end
end
return na
end
function yellowstone(sequenceCount)
local yellow = {1, 2, 3}
local num = 4
local notYellow = {}
local yellowSize = 3
while yellowSize < sequenceCount do
local found = -1
for i,test in pairs(notYellow) do
if gcd(yellow[yellowSize - 1], test) > 1 and gcd(yellow[yellowSize - 0], test) == 1 then
found = i
break
end
end
if found >= 0 then
table.insert(yellow, notYellow[found])
notYellow = removeAt(notYellow, found)
yellowSize = yellowSize + 1
else
while true do
if gcd(yellow[yellowSize - 1], num) > 1 and gcd(yellow[yellowSize - 0], num) == 1 then
table.insert(yellow, num)
yellowSize = yellowSize + 1
num = num + 1
break
end
table.insert(notYellow, num)
num = num + 1
end
end
end
return yellow
end
function main()
print("First 30 values in the yellowstone sequence:")
printArray(yellowstone(30))
print()
end
main() | 20Yellowstone sequence
| 1lua
| 21l3 |
null | 16Zeckendorf number representation
| 11kotlin
| f7do |
extern crate num;
use num::complex::Complex;
fn main() { | 9Arithmetic/Complex
| 15rust
| zwto |
package org.rosettacode
package object ArithmeticComplex {
val i = Complex(0, 1)
implicit def fromDouble(d: Double) = Complex(d)
implicit def fromInt(i: Int) = Complex(i.toDouble)
}
package ArithmeticComplex {
case class Complex(real: Double = 0.0, imag: Double = 0.0) {
def this(s: String) =
this("[\\d.]+(?!i)".r findFirstIn s getOrElse "0" toDouble,
"[\\d.]+(?=i)".r findFirstIn s getOrElse "0" toDouble)
def +(b: Complex) = Complex(real + b.real, imag + b.imag)
def -(b: Complex) = Complex(real - b.real, imag - b.imag)
def *(b: Complex) = Complex(real * b.real - imag * b.imag, real * b.imag + imag * b.real)
def inverse = {
val denom = real * real + imag * imag
Complex(real / denom, -imag / denom)
}
def /(b: Complex) = this * b.inverse
def unary_- = Complex(-real, -imag)
lazy val abs = math.hypot(real, imag)
override def toString = real + " + " + imag + "i"
def i = { require(imag == 0.0); Complex(imag = real) }
}
object Complex {
def apply(s: String) = new Complex(s)
def fromPolar(rho:Double, theta:Double) = Complex(rho*math.cos(theta), rho*math.sin(theta))
}
} | 9Arithmetic/Complex
| 16scala
| ys63 |
use strict;
use warnings;
use feature 'say';
use List::Util qw(first);
use GD::Graph::bars;
use constant Inf => 1e5;
sub gcd {
my ($u, $v) = @_;
while ($v) {
($u, $v) = ($v, $u % $v);
}
return abs($u);
}
sub yellowstone {
my($terms) = @_;
my @s = (1, 2, 3);
my @used = (1) x 4;
my $min = 3;
while (1) {
my $index = first { not defined $used[$_] and gcd($_,$s[-2]) != 1 and gcd($_,$s[-1]) == 1 } $min .. Inf;
$used[$index] = 1;
$min = (first { not defined $used[$_] } 0..@used-1) || @used-1;
push @s, $index;
last if @s == $terms;
}
@s;
}
say "The first 30 terms in the Yellowstone sequence:\n" . join ' ', yellowstone(30);
my @data = ( [1..500], [yellowstone(500)]);
my $graph = GD::Graph::bars->new(800, 600);
$graph->set(
title => 'Yellowstone sequence',
y_max_value => 1400,
x_tick_number => 5,
r_margin => 10,
dclrs => [ 'blue' ],
) or die $graph->error;
my $gd = $graph->plot(\@data) or die $graph->error;
open my $fh, '>', 'yellowstone-sequence.png';
binmode $fh;
print $fh $gd->png();
close $fh; | 20Yellowstone sequence
| 2perl
| qyx6 |
import java.math.BigInteger;
class IntegerPower {
public static void main(String[] args) {
BigInteger power = BigInteger.valueOf(5).pow(BigInteger.valueOf(4).pow(BigInteger.valueOf(3).pow(2).intValueExact()).intValueExact());
String str = power.toString();
int len = str.length();
System.out.printf("5**4**3**2 =%s...%s and has%d digits%n",
str.substring(0, 20), str.substring(len - 20), len);
}
} | 18Arbitrary-precision integers (included)
| 9java
| a31y |
void draw_yinyang(int trans, double scale)
{
printf(,
trans, trans, scale);
}
int main()
{ printf(
);
draw_yinyang(20, .05);
draw_yinyang(8, .02);
printf();
return 0;
} | 26Yin and yang
| 5c
| 5kuk |
int main(int c, char **v)
{
int i, j, m, n, *s;
if (c < 2 || ((m = atoi(v[1]))) <= 0) m = 5;
s = malloc(sizeof(int) * m * m);
for (i = n = 0; i < m * 2; i++)
for (j = (i < m) ? 0 : i-m+1; j <= i && j < m; j++)
s[(i&1)? j*(m-1)+i : (i-j)*m+j ] = n++;
for (i = 0; i < m * m; putchar((++i % m) ? ' ':'\n'))
printf(, s[i]);
return 0;
} | 27Zig-zag matrix
| 5c
| qnxc |
package YahooSearch;
use Encode;
use HTTP::Cookies;
use WWW::Mechanize;
sub apply (&$)
{my $f = shift; local $_ = shift; $f->(); return $_;}
my $search_prefs = 'v=1&n=100&sm=' .
apply {s/([^a-zA-Z0-9])/sprintf '%%%02X', ord $1/ge}
join '|',
map {'!' . $_}
qw(hsb Zq0 XbM sss dDO VFM RQh uZ0 Fxe yCl GP4 FZK yNC mEG niH);
my $cookies = HTTP::Cookies->new;
$cookies->set_cookie(0, 'sB', $search_prefs, '/', 'search.yahoo.com');
my $mech = new WWW::Mechanize
(cookie_jar => $cookies,
stack_depth => 0);
sub read_page
{my ($next, $page, @results) =
($mech->find_link(text => 'Next >')->url,
decode 'iso-8859-1', $mech->content);
while ($page =~ m
{<h3> <a \s class="yschttl \s spt" \s
href=" ([^"]+) " \s* >
(.+?) </a>
.+?
<div \s class="abstr">
(.+?) </div>}xg)
{push @results, {url => $1, title => $2, content => $3};
foreach ( @{$results[-1]}{qw(title content)} )
{s/<.+?>//g;
$_ = encode 'utf8', $_;}}
return $next, \@results;}
sub new
{my $invocant = shift;
my $class = ref($invocant) || $invocant;
$mech->get('http://search.yahoo.com/search?p=' . apply
{s/([^a-zA-Z0-9 ])/sprintf '%%%02X', ord $1/ge;
s/ /+/g;}
shift);
my ($next, $results) = read_page();
return bless {link_to_next => $next, results => $results}, $class;}
sub results
{@{shift()->{results}};}
sub next_page
{my $invocant = shift;
my $next = $invocant->{link_to_next};
unless ($next)
{$invocant->{results} = [];
return undef;}
$mech->get($next);
($next, my $results) = read_page();
$invocant->{link_to_next} = $next;
$invocant->{results} = $results;
return 1;} | 22Yahoo! search interface
| 2perl
| gw4e |
>>> const y = (5n**4n**3n**2n).toString();
>>> console.log(`5**4**3**2 = ${y.slice(0,20)}...${y.slice(-20)} and has ${y.length} digits`);
5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits | 18Arbitrary-precision integers (included)
| 10javascript
| scqz |
(ns zebra.core
(:refer-clojure:exclude [==])
(:use [clojure.core.logic]
[clojure.tools.macro:as macro]))
(defne lefto [x y l]
([_ _ [x y .?r]])
([_ _ [_ .?r]] (lefto x y?r)))
(defn nexto [x y l]
(conde
((lefto x y l))
((lefto y x l))))
(defn zebrao [hs]
(macro/symbol-macrolet [_ (lvar)]
(all
(== [_ _ _ _ _] hs)
(membero ['englishman _ _ _ 'red] hs)
(membero ['swede _ _ 'dog _] hs)
(membero ['dane _ 'tea _ _] hs)
(lefto [_ _ _ _ 'green] [_ _ _ _ 'white] hs)
(membero [_ _ 'coffee _ 'green] hs)
(membero [_ 'pallmall _ 'birds _] hs)
(membero [_ 'dunhill _ _ 'yellow] hs)
(== [_ _ [_ _ 'milk _ _] _ _ ] hs)
(firsto hs ['norwegian _ _ _ _])
(nexto [_ 'blend _ _ _] [_ _ _ 'cats _ ] hs)
(nexto [_ _ _ 'horse _] [_ 'dunhill _ _ _] hs)
(membero [_ 'bluemaster 'beer _ _] hs)
(membero ['german 'prince _ _ _] hs)
(nexto ['norwegian _ _ _ _] [_ _ _ _ 'blue] hs)
(nexto [_ _ 'water _ _] [_ 'blend _ _ _] hs)
(membero [_ _ _ 'zebra _] hs))))
(let [solns (run* [q] (zebrao q))
soln (first solns)
zebra-owner (->> soln (filter #(= 'zebra (% 3))) first (#(% 0)))]
(println "solution count:" (count solns))
(println "zebra owner is the" zebra-owner)
(println "full solution (in house order):")
(doseq [h soln] (println " " h))) | 24Zebra puzzle
| 6clojure
| vk2f |
import java.math.BigInteger
fun main(args: Array<String>) {
val x = BigInteger.valueOf(5).pow(Math.pow(4.0, 3.0 * 3.0).toInt())
val y = x.toString()
val len = y.length
println("5^4^3^2 = ${y.substring(0, 20)}...${y.substring(len - 20)} and has $len digits")
} | 18Arbitrary-precision integers (included)
| 11kotlin
| hnj3 |
null | 16Zeckendorf number representation
| 1lua
| tjfn |
'''Yellowstone permutation OEIS A098550'''
from itertools import chain, count, islice
from operator import itemgetter
from math import gcd
from matplotlib import pyplot
def yellowstone():
'''A non-finite stream of terms from
the Yellowstone permutation.
OEIS A098550.
'''
def relativelyPrime(a):
return lambda b: 1 == gcd(a, b)
def nextWindow(triple):
p2, p1, rest = triple
[rp2, rp1] = map(relativelyPrime, [p2, p1])
def match(xxs):
x, xs = uncons(xxs)['Just']
return (x, xs) if rp1(x) and not rp2(x) else (
second(cons(x))(
match(xs)
)
)
n, residue = match(rest)
return (p1, n, residue)
return chain(
range(1, 3),
map(
itemgetter(1),
iterate(nextWindow)(
(2, 3, count(4))
)
)
)
def main():
'''Terms of the Yellowstone permutation.'''
print(showList(
take(30)(yellowstone())
))
pyplot.plot(
take(100)(yellowstone())
)
pyplot.xlabel(main.__doc__)
pyplot.show()
def Just(x):
'''Constructor for an inhabited Maybe (option type) value.
Wrapper containing the result of a computation.
'''
return {'type': 'Maybe', 'Nothing': False, 'Just': x}
def Nothing():
'''Constructor for an empty Maybe (option type) value.
Empty wrapper returned where a computation is not possible.
'''
return {'type': 'Maybe', 'Nothing': True}
def cons(x):
'''Construction of a list from x as head,
and xs as tail.
'''
return lambda xs: [x] + xs if (
isinstance(xs, list)
) else x + xs if (
isinstance(xs, str)
) else chain([x], xs)
def iterate(f):
'''An infinite list of repeated
applications of f to x.
'''
def go(x):
v = x
while True:
yield v
v = f(v)
return go
def second(f):
'''A simple function lifted to a function over a tuple,
with f applied only to the second of two values.
'''
return lambda xy: (xy[0], f(xy[1]))
def showList(xs):
'''Stringification of a list.'''
return '[' + ','.join(repr(x) for x in xs) + ']'
def take(n):
'''The prefix of xs of length n,
or xs itself if n > length xs.
'''
return lambda xs: (
xs[0:n]
if isinstance(xs, (list, tuple))
else list(islice(xs, n))
)
def uncons(xs):
'''The deconstruction of a non-empty list
(or generator stream) into two parts:
a head value, and the remaining values.
'''
if isinstance(xs, list):
return Just((xs[0], xs[1:])) if xs else Nothing()
else:
nxt = take(1)(xs)
return Just((nxt[0], xs)) if nxt else Nothing()
if __name__ == '__main__':
main() | 20Yellowstone sequence
| 3python
| smq9 |
import urllib
import re
def fix(x):
p = re.compile(r'<[^<]*?>')
return p.sub('', x).replace('&', '&')
class YahooSearch:
def __init__(self, query, page=1):
self.query = query
self.page = page
self.url = %(self.query, ((self.page - 1) * 10 + 1))
self.content = urllib.urlopen(self.url).read()
def getresults(self):
self.results = []
for i in re.findall('<a class= href=>(.+?)</a></h3></div>(.+?)</div>.*?<span class=url>(.+?)</span>', self.content):
title = fix(i[0])
content = fix(i[1])
url = fix(i[2])
self.results.append(YahooResult(title, content, url))
return self.results
def getnextpage(self):
return YahooSearch(self.query, self.page+1)
search_results = property(fget=getresults)
nextpage = property(fget=getnextpage)
class YahooResult:
def __init__(self,title,content,url):
self.title = title
self.content = content
self.url = url
x = YahooSearch()
for result in x.search_results:
print result.title | 22Yahoo! search interface
| 3python
| rxgq |
(defn Y [f]
((fn [x] (x x))
(fn [x]
(f (fn [& args]
(apply (x x) args))))))
(def fac
(fn [f]
(fn [n]
(if (zero? n) 1 (* n (f (dec n)))))))
(def fib
(fn [f]
(fn [n]
(condp = n
0 0
1 1
(+ (f (dec n))
(f (dec (dec n)))))))) | 25Y combinator
| 6clojure
| hxjr |
(defn partitions [sizes coll]
(lazy-seq
(when-let [n (first sizes)]
(when-let [s (seq coll)]
(cons (take n coll)
(partitions (next sizes) (drop n coll)))))))
(defn take-from [n colls]
(lazy-seq
(when-let [s (seq colls)]
(let [[first-n rest-n] (split-at n s)]
(cons (map first first-n)
(take-from n (concat (filter seq (map rest first-n)) rest-n)))))))
(defn zig-zag [n]
(->> (partitions (concat (range 1 (inc n)) (range (dec n) 0 -1)) (range (* n n)))
(map #(%1 %2) (cycle [reverse identity]) ,)
(take-from n ,)))
user> (zig-zag 5)
(( 0 1 5 6 14)
( 2 4 7 13 15)
( 3 8 12 16 21)
( 9 11 17 20 22)
(10 18 19 23 24))
user> (zig-zag 6)
(( 0 1 5 6 14 15)
( 2 4 7 13 16 25)
( 3 8 12 17 24 26)
( 9 11 18 23 27 32)
(10 19 22 28 31 33)
(20 21 29 30 34 35)) | 27Zig-zag matrix
| 6clojure
| i3om |
YahooSearch <- function(query, page=1, .opts=list(), ignoreMarkUpErrors=TRUE)
{
if(!require(RCurl) ||!require(XML))
{
stop("Could not load required packages")
}
query <- curlEscape(query)
b <- 10*(page-1)+1
theurl <- paste("http://uk.search.yahoo.com/search?p=",
query, "&b=", b, sep="")
webpage <- getURL(theurl, .opts=.opts)
.Search <- list(query=query, page=page, .opts=.opts,
ignoreMarkUpErrors=ignoreMarkUpErrors)
assign(".Search", .Search, envir=globalenv())
webpage <- readLines(tc <- textConnection(webpage)); close(tc)
if(ignoreMarkUpErrors)
{
pagetree <- htmlTreeParse(webpage, error=function(...){})
} else
{
pagetree <- htmlTreeParse(webpage)
}
findbyattr <- function(x, id, type="id")
{
ids <- sapply(x, function(x) x$attributes[type])
x[ids==id]
}
body <- pagetree$children$html$children$body
bd <- findbyattr(body$children$div$children, "bd")
left <- findbyattr(bd$div$children$div$children, "left")
web <- findbyattr(left$div$children$div$children, "web")
resol <- web$div$children$ol
gettextfromnode <- function(x)
{
un <- unlist(x$children)
paste(un[grep("value", names(un))], collapse=" ")
}
n <- length(resol)
results <- list()
length(results) <- n
for(i in 1:n)
{
mainlink <- resol[[i]]$children$div$children[1]$div$children$h3$children$a
url <- mainlink$attributes["href"]
title <- gettextfromnode(mainlink)
contenttext <- findbyattr(resol[[i]]$children$div$children[2], "abstr", type="class")
if(length(contenttext)==0)
{
contenttext <- findbyattr(resol[[i]]$children$div$children[2]$div$children$div$children,
"sm-abs", type="class")
}
content <- gettextfromnode(contenttext$div)
results[[i]] <- list(url=url, title=title, content=content)
}
names(results) <- as.character(seq(b, b+n-1))
results
}
nextpage <- function()
{
if(exists(".Search", envir=globalenv()))
{
.Search <- get(".Search", envir=globalenv())
.Search$page <- .Search$page + 1L
do.call(YahooSearch, .Search)
} else
{
message("No search has been performed yet")
}
}
YahooSearch("rosetta code")
nextpage() | 22Yahoo! search interface
| 13r
| u1vx |
bc = require("bc") | 18Arbitrary-precision integers (included)
| 1lua
| kdh2 |
print 0 ** 0, "\n";
use Math::Complex;
print cplx(0,0) ** cplx(0,0), "\n"; | 14Zero to the zero power
| 2perl
| gn4e |
package main
import (
"fmt"
)
func main() { | 13Arrays
| 0go
| 19p5 |
public struct Complex {
public let real: Double
public let imaginary: Double
public init(real inReal:Double, imaginary inImaginary:Double) {
real = inReal
imaginary = inImaginary
}
public static var i: Complex = Complex(real:0, imaginary: 1)
public static var zero: Complex = Complex(real: 0, imaginary: 0)
public var negate: Complex {
return Complex(real: -real, imaginary: -imaginary)
}
public var invert: Complex {
let d = (real*real + imaginary*imaginary)
return Complex(real: real/d, imaginary: -imaginary/d)
}
public var conjugate: Complex {
return Complex(real: real, imaginary: -imaginary)
}
}
public func + (left: Complex, right: Complex) -> Complex {
return Complex(real: left.real+right.real, imaginary: left.imaginary+right.imaginary)
}
public func * (left: Complex, right: Complex) -> Complex {
return Complex(real: left.real*right.real - left.imaginary*right.imaginary,
imaginary: left.real*right.imaginary+left.imaginary*right.real)
}
public prefix func - (right:Complex) -> Complex {
return right.negate
} | 9Arithmetic/Complex
| 17swift
| fadk |
def yellow(n)
a = [1, 2, 3]
b = { 1 => true, 2 => true, 3 => true }
i = 4
while n > a.length
if!b[i] && i.gcd(a[-1]) == 1 && i.gcd(a[-2]) > 1
a << i
b[i] = true
i = 4
end
i += 1
end
a
end
p yellow(30) | 20Yellowstone sequence
| 14ruby
| 8c01 |
null | 20Yellowstone sequence
| 15rust
| ol83 |
require 'open-uri'
require 'hpricot'
SearchResult = Struct.new(:url, :title, :content)
class SearchYahoo
@@urlinfo = [nil, 'ca.search.yahoo.com', 80, '/search', nil, nil]
def initialize(term)
@term = term
@page = 1
@results = nil
@url = URI::HTTP.build(@@urlinfo)
end
def next_result
if not @results
@results = []
fetch_results
elsif @results.empty?
next_page
end
@results.shift
end
def fetch_results
@url.query = URI.escape( % [@term, @page])
doc = open(@url) { |f| Hpricot(f) }
parse_html(doc)
end
def next_page
@page += 10
fetch_results
end
def parse_html(doc)
doc.search().search().each do |div|
next unless div.has_attribute?() and div.get_attribute().index() == 0
result = SearchResult.new
div.search().each do |link|
next unless link.has_attribute?() and link.get_attribute() ==
result.url = link.get_attribute()
result.title = link.inner_text
end
div.search().each do |abstract|
next unless abstract.has_attribute?() and abstract.get_attribute().index()
result.content = abstract.inner_text
end
@results << result
end
end
end
s = SearchYahoo.new()
15.times do |i|
result = s.next_result
puts i+1
puts result.title
puts result.url
puts result.content
puts
end | 22Yahoo! search interface
| 14ruby
| js7x |
my @fib;
sub fib {
my $n = shift;
return 1 if $n < 2;
return $fib[$n] //= fib($n-1)+fib($n-2);
}
sub zeckendorf {
my $n = shift;
return "0" unless $n;
my $i = 1;
$i++ while fib($i) <= $n;
my $z = '';
while( --$i ) {
$z .= "0", next if fib( $i ) > $n;
$z .= "1";
$n -= fib( $i );
}
return $z;
}
printf "%4d:%8s\n", $_, zeckendorf($_) for 0..20; | 16Zeckendorf number representation
| 2perl
| hfjl |
<?php
echo pow(0,0);
echo 0 ** 0;
?> | 14Zero to the zero power
| 12php
| n7ig |
def aa = [ 1, 25, 31, -3 ] | 13Arrays
| 7groovy
| jz7o |
package main
import (
"fmt"
"os"
"text/template"
)
var tmpl = `<?xml version="1.0"?>
<svg xmlns="http: | 26Yin and yang
| 0go
| 8z0g |
<?php
$m = 20;
$F = array(1,1);
while ($F[count($F)-1] <= $m)
$F[] = $F[count($F)-1] + $F[count($F)-2];
while ($n = $m--) {
while ($F[count($F)-1] > $n) array_pop($F);
$l = count($F)-1;
print ;
while ($n) {
if ($n >= $F[$l]) {
$n = $n - $F[$l];
print '1';
} else print '0';
--$l;
}
print str_repeat('0',$l);
print ;
}
?> | 16Zeckendorf number representation
| 12php
| zht1 |
package main
import (
"encoding/xml"
"fmt"
"log"
"os"
)
type Inventory struct {
XMLName xml.Name `xml:"inventory"`
Title string `xml:"title,attr"`
Sections []struct {
XMLName xml.Name `xml:"section"`
Name string `xml:"name,attr"`
Items []struct {
XMLName xml.Name `xml:"item"`
Name string `xml:"name"`
UPC string `xml:"upc,attr"`
Stock int `xml:"stock,attr"`
Price float64 `xml:"price"`
Description string `xml:"description"`
} `xml:"item"`
} `xml:"section"`
} | 23XML/XPath
| 0go
| eda6 |
import Diagrams.Prelude
import Diagrams.Backend.Cairo.CmdLine
yinyang = lw 0 $
perim # lw 0.003 <>
torus white black # xform id <>
torus black white # xform negate <>
clipBy perim base
where perim = arc 0 (360 :: Deg) # scale (1/2)
torus c c' = circle (1/3) # fc c' <> circle 1 # fc c
xform f = translateY (f (1/4)) . scale (1/4)
base = rect (1/2) 1 # fc white ||| rect (1/2) 1 # fc black
main = defaultMain $
pad 1.1 $
beside (2,-1) yinyang (yinyang # scale (1/4)) | 26Yin and yang
| 8haskell
| lrch |
from decimal import Decimal
from fractions import Fraction
from itertools import product
zeroes = [0, 0.0, 0j, Decimal(0), Fraction(0, 1), -0.0, -0.0j, Decimal(-0.0)]
for i, j in product(zeroes, repeat=2):
try:
ans = i**j
except:
ans = '<Exception raised>'
print(f'{i!r:>15} ** {j!r:<15} = {ans!r}') | 14Zero to the zero power
| 3python
| rdgq |
def inventory = new XmlSlurper().parseText("<inventory...") | 23XML/XPath
| 7groovy
| k0h7 |
import Data.List
import Control.Arrow
import Control.Monad
takeWhileIncl :: (a -> Bool) -> [a] -> [a]
takeWhileIncl _ [] = []
takeWhileIncl p (x:xs)
| p x = x: takeWhileIncl p xs
| otherwise = [x]
getmultiLineItem n = takeWhileIncl(not.isInfixOf ("</" ++ n)). dropWhile(not.isInfixOf ('<': n))
getsingleLineItems n = map (takeWhile(/='<'). drop 1. dropWhile(/='>')). filter (isInfixOf ('<': n))
main = do
xml <- readFile "./Rosetta/xmlpath.xml"
let xmlText = lines xml
putStrLn "\n== First item ==\n"
mapM_ putStrLn $ head $ unfoldr (Just. liftM2 (id &&&) (\\) (getmultiLineItem "item")) xmlText
putStrLn "\n== Prices ==\n"
mapM_ putStrLn $ getsingleLineItems "price" xmlText
putStrLn "\n== Names ==\n"
print $ getsingleLineItems "name" xmlText | 23XML/XPath
| 8haskell
| 35zj |
print(0^0) | 14Zero to the zero power
| 13r
| u8vx |
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
public class XMLParser {
final static String xmlStr =
"<inventory title=\"OmniCorp Store #45x10^3\">"
+ " <section name=\"health\">"
+ " <item upc=\"123456789\" stock=\"12\">"
+ " <name>Invisibility Cream</name>"
+ " <price>14.50</price>"
+ " <description>Makes you invisible</description>"
+ " </item>"
+ " <item upc=\"445322344\" stock=\"18\">"
+ " <name>Levitation Salve</name>"
+ " <price>23.99</price>"
+ " <description>Levitate yourself for up to 3 hours per application</description>"
+ " </item>"
+ " </section>"
+ " <section name=\"food\">"
+ " <item upc=\"485672034\" stock=\"653\">"
+ " <name>Blork and Freen Instameal</name>"
+ " <price>4.95</price>"
+ " <description>A tasty meal in a tablet; just add water</description>"
+ " </item>"
+ " <item upc=\"132957764\" stock=\"44\">"
+ " <name>Grob winglets</name>"
+ " <price>3.56</price>"
+ " <description>Tender winglets of Grob. Just add priwater</description>"
+ " </item>"
+ " </section>"
+ "</inventory>";
public static void main(String[] args) {
try {
Document doc = DocumentBuilderFactory.newInstance()
.newDocumentBuilder()
.parse(new InputSource(new StringReader(xmlStr)));
XPath xpath = XPathFactory.newInstance().newXPath(); | 23XML/XPath
| 9java
| i9os |
null | 23XML/XPath
| 10javascript
| zut2 |
package org.rosettacode.yinandyang;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class YinYangGenerator
{
private final int size;
public YinYangGenerator(final int size)
{
this.size = size;
}
public void drawYinYang(final Graphics graphics)
{ | 26Yin and yang
| 9java
| 32zg |
def fib():
memo = [1, 2]
while True:
memo.append(sum(memo))
yield memo.pop(0)
def sequence_down_from_n(n, seq_generator):
seq = []
for s in seq_generator():
seq.append(s)
if s >= n: break
return seq[::-1]
def zeckendorf(n):
if n == 0: return [0]
seq = sequence_down_from_n(n, fib)
digits, nleft = [], n
for s in seq:
if s <= nleft:
digits.append(1)
nleft -= s
else:
digits.append(0)
assert nleft == 0, 'Check all of n is accounted for'
assert sum(x*y for x,y in zip(digits, seq)) == n, 'Assert digits are correct'
while digits[0] == 0:
digits.pop(0)
return digits
n = 20
print('Fibonacci digit multipliers:%r'% sequence_down_from_n(n, fib))
for i in range(n + 1):
print('%3i:%8s'% (i, ''.join(str(d) for d in zeckendorf(i)))) | 16Zeckendorf number representation
| 3python
| kthf |
main() {
for (var k = 1, x = new List(101); k <= 100; k++) {
for (int i = k; i <= 100; i += k)
x[i] =!x[i];
if (x[k]) print("$k open");
}
} | 21100 doors
| 18dart
| x3wh |
import Data.Array.IO
main = do arr <- newArray (1,10) 37 :: IO (IOArray Int Int)
a <- readArray arr 1
writeArray arr 1 64
b <- readArray arr 1
print (a,b) | 13Arrays
| 8haskell
| tbf7 |
package main
import (
"fmt"
"log"
"strings"
) | 24Zebra puzzle
| 0go
| ai1f |
null | 23XML/XPath
| 11kotlin
| qzx1 |
function Arc(posX,posY,radius,startAngle,endAngle,color){ | 26Yin and yang
| 10javascript
| cg9j |
use Math::BigInt;
my $x = Math::BigInt->new('5') ** Math::BigInt->new('4') ** Math::BigInt->new('3') ** Math::BigInt->new('2');
my $y = "$x";
printf("5**4**3**2 =%s...%s and has%i digits\n", substr($y,0,20), substr($y,-20), length($y)); | 18Arbitrary-precision integers (included)
| 2perl
| z7tb |
require 'bigdecimal'
[0, 0.0, Complex(0), Rational(0), BigDecimal()].each do |n|
printf % [n.class, n**n]
end | 14Zero to the zero power
| 14ruby
| jt7x |
fn main() {
println!("{}",0u32.pow(0));
} | 14Zero to the zero power
| 15rust
| hzj2 |
module Main where
import Control.Applicative ((<$>), (<*>))
import Control.Monad (foldM, forM_)
import Data.List ((\\))
data House = House
{ color :: Color
, man :: Man
, pet :: Pet
, drink :: Drink
, smoke :: Smoke
}
deriving (Eq, Show)
data Color = Red | Green | Blue | Yellow | White
deriving (Eq, Show, Enum, Bounded)
data Man = Eng | Swe | Dan | Nor | Ger
deriving (Eq, Show, Enum, Bounded)
data Pet = Dog | Birds | Cats | Horse | Zebra
deriving (Eq, Show, Enum, Bounded)
data Drink = Coffee | Tea | Milk | Beer | Water
deriving (Eq, Show, Enum, Bounded)
data Smoke = PallMall | Dunhill | Blend | BlueMaster | Prince
deriving (Eq, Show, Enum, Bounded)
type Solution = [House]
main :: IO ()
main = do
forM_ solutions $ \sol -> mapM_ print sol
>> putStrLn "
putStrLn "No More Solutions"
solutions :: [Solution]
solutions = filter finalCheck . map reverse $ foldM next [] [1..5]
where
next :: Solution -> Int -> [Solution]
next sol pos = [h:sol | h <- newHouses sol, consistent h pos]
newHouses :: Solution -> Solution
newHouses sol =
House <$> new color <*> new man <*> new pet <*> new drink <*> new smoke
where
new trait = [minBound ..] \\ map trait sol
consistent :: House -> Int -> Bool
consistent house pos = and
[ man `is` Eng <=> color `is` Red
, man `is` Swe <=> pet `is` Dog
, man `is` Dan <=> drink `is` Tea
, color `is` Green <=> drink `is` Coffee
, pet `is` Birds <=> smoke `is` PallMall
, color `is` Yellow <=> smoke `is` Dunhill
, const (pos == 3) <=> drink `is` Milk
, const (pos == 1) <=> man `is` Nor
, drink `is` Beer <=> smoke `is` BlueMaster
, man `is` Ger <=> smoke `is` Prince
]
where
infix 4 <=>
p <=> q = p house == q house
is :: Eq a => (House -> a) -> a -> House -> Bool
(trait `is` value) house = trait house == value
finalCheck :: [House] -> Bool
finalCheck solution = and
[ (color `is` Green) `leftOf` (color `is` White)
, (smoke `is` Blend ) `nextTo` (pet `is` Cats )
, (smoke `is` Dunhill) `nextTo` (pet `is` Horse)
, (color `is` Blue ) `nextTo` (man `is` Nor )
, (smoke `is` Blend ) `nextTo` (drink `is` Water)
]
where
nextTo :: (House -> Bool) -> (House -> Bool) -> Bool
nextTo p q = leftOf p q || leftOf q p
leftOf p q
| (_:h:_) <- dropWhile (not . p) solution = q h
| otherwise = False | 24Zebra puzzle
| 8haskell
| zvt0 |
<?php
$y = bcpow('5', bcpow('4', bcpow('3', '2')));
printf(, substr($y,0,20), substr($y,-20), strlen($y));
?> | 18Arbitrary-precision integers (included)
| 12php
| bfk9 |
zeckendorf <- function(number) {
indexOfFibonacciNumber <- function(n) {
if (n < 1) {
2
} else {
Phi <- (1 + sqrt(5)) / 2
invertClosedFormula <- log(n * sqrt(5)) / log(Phi)
ceiling(invertClosedFormula)
}
}
upperLimit <- indexOfFibonacciNumber(number)
fibonacciSequenceDigits <- function(n) {
fibGenerator <- function(f, ...) { c(f[2], sum(f)) }
fibSeq <- Reduce(fibGenerator, 1:n, c(0,1), accumulate=TRUE)
fibNums <- unlist(lapply(fibSeq, head, n=1))
rev(fibNums[-2:-1])
}
digits <- fibonacciSequenceDigits(upperLimit)
isInNumber <- function(digit) {
if (number >= digit) {
number <<- number - digit
1
} else {
0
}
}
zeckSeq <- Map(isInNumber, digits)
gsub("^0+1", "1", paste(zeckSeq, collapse=""))
}
print(unlist(lapply(0:20, zeckendorf))) | 16Zeckendorf number representation
| 13r
| rigj |
assert(math.pow(0, 0) == 1, "Scala blunder, should go back to school!") | 14Zero to the zero power
| 16scala
| pybj |
require 'lxp'
data = [[<inventory title="OmniCorp Store #45x10^3">
<section name="health">
<item upc="123456789" stock="12">
<name>Invisibility Cream</name>
<price>14.50</price>
<description>Makes you invisible</description>
</item>
<item upc="445322344" stock="18">
<name>Levitation Salve</name>
<price>23.99</price>
<description>Levitate yourself for up to 3 hours per application</description>
</item>
</section>
<section name="food">
<item upc="485672034" stock="653">
<name>Blork and Freen Instameal</name>
<price>4.95</price>
<description>A tasty meal in a tablet; just add water</description>
</item>
<item upc="132957764" stock="44">
<name>Grob winglets</name>
<price>3.56</price>
<description>Tender winglets of Grob. Just add water</description>
</item>
</section>
</inventory>]]
local first = true
local names, prices = {}, {}
p = lxp.new({StartElement = function (parser, name)
local a, b, c = parser:pos() | 23XML/XPath
| 1lua
| s3q8 |
null | 26Yin and yang
| 11kotlin
| nyij |
package org.rosettacode.zebra;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Objects;
import java.util.Set;
public class Zebra {
private static final int[] orders = {1, 2, 3, 4, 5};
private static final String[] nations = {"English", "Danish", "German", "Swedish", "Norwegian"};
private static final String[] animals = {"Zebra", "Horse", "Birds", "Dog", "Cats"};
private static final String[] drinks = {"Coffee", "Tea", "Beer", "Water", "Milk"};
private static final String[] cigarettes = {"Pall Mall", "Blend", "Blue Master", "Prince", "Dunhill"};
private static final String[] colors = {"Red", "Green", "White", "Blue", "Yellow"};
static class Solver {
private final PossibleLines puzzleTable = new PossibleLines();
void solve() {
PossibleLines constraints = new PossibleLines();
constraints.add(new PossibleLine(null, "English", "Red", null, null, null));
constraints.add(new PossibleLine(null, "Swedish", null, "Dog", null, null));
constraints.add(new PossibleLine(null, "Danish", null, null, "Tea", null));
constraints.add(new PossibleLine(null, null, "Green", null, "Coffee", null));
constraints.add(new PossibleLine(null, null, null, "Birds", null, "Pall Mall"));
constraints.add(new PossibleLine(null, null, "Yellow", null, null, "Dunhill"));
constraints.add(new PossibleLine(3, null, null, null, "Milk", null));
constraints.add(new PossibleLine(1, "Norwegian", null, null, null, null));
constraints.add(new PossibleLine(null, null, null, null, "Beer", "Blue Master"));
constraints.add(new PossibleLine(null, "German", null, null, null, "Prince"));
constraints.add(new PossibleLine(2, null, "Blue", null, null, null)); | 24Zebra puzzle
| 9java
| oy8d |
function circle(x, y, c, r)
return (r * r) >= (x * x) / 4 + ((y - c) * (y - c))
end
function pixel(x, y, r)
if circle(x, y, -r / 2, r / 6) then
return '#'
end
if circle(x, y, r / 2, r / 6) then
return '.'
end
if circle(x, y, -r / 2, r / 2) then
return '.'
end
if circle(x, y, r / 2, r / 2) then
return '#'
end
if circle(x, y, 0, r) then
if x < 0 then
return '.'
else
return '#'
end
end
return ' '
end
function yinYang(r)
for y=-r,r do
for x=-2*r,2*r do
io.write(pixel(x, y, r))
end
print()
end
end
yinYang(18) | 26Yin and yang
| 1lua
| dmnq |
>>> y = str( 5**4**3**2 )
>>> print (% (y[:20], y[-20:], len(y)))
5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits | 18Arbitrary-precision integers (included)
| 3python
| 3jzc |
SQL> SELECT POWER(0,0) FROM dual; | 14Zero to the zero power
| 19sql
| ecau |
library(gmp)
large <- pow.bigz(5, pow.bigz(4, pow.bigz(3, 2)))
largestr <- as.character(large)
cat("first 20 digits:", substr(largestr, 1, 20), "\n",
"last 20 digits:", substr(largestr, nchar(largestr) - 19, nchar(largestr)), "\n",
"number of digits: ", nchar(largestr), "\n") | 18Arbitrary-precision integers (included)
| 13r
| d4nt |
def zeckendorf
return to_enum(__method__) unless block_given?
x = 0
loop do
bin = x.to_s(2)
yield bin unless bin.include?()
x += 1
end
end
zeckendorf.take(21).each_with_index{|x,i| puts % [i, x]} | 16Zeckendorf number representation
| 14ruby
| p3bh |
import Darwin
print(pow(0.0,0.0)) | 14Zero to the zero power
| 17swift
| 7frq |
null | 24Zebra puzzle
| 11kotlin
| xfws |