code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
use Gtk3 '-init';
my $window = Gtk3::Window->new();
$window->set_default_size(320, 240);
$window->set_border_width(10);
$window->set_title("Draw a Pixel");
$window->set_app_paintable(TRUE);
my $da = Gtk3::DrawingArea->new();
$da->signal_connect('draw' => \&draw_in_drawingarea);
$window->add($da);
$window->show_all();
Gtk3->main;
sub draw_in_drawingarea
{
my ($widget, $cr, $data) = @_;
$cr->set_source_rgb(1, 0, 0);
$cr->set_line_width(1);
$cr->rectangle( 100, 100, 1, 1);
$cr->stroke;
} | 918Draw a pixel
| 2perl
| z2xtb |
def egyptian_divmod(dividend, divisor)
table = [[1, divisor]]
table << table.last.map{|e| e*2} while table.last.first * 2 <= dividend
answer, accumulator = 0, 0
table.reverse_each do |pow, double|
if accumulator + double <= dividend
accumulator += double
answer += pow
end
end
[answer, dividend - accumulator]
end
puts % egyptian_divmod(580, 34) | 914Egyptian division
| 14ruby
| jwv7x |
fn egyptian_divide(dividend: u32, divisor: u32) -> (u32, u32) {
let dividend = dividend as u64;
let divisor = divisor as u64;
let pows = (0..32).map(|p| 1 << p);
let doublings = (0..32).map(|p| divisor << p);
let (answer, sum) = doublings
.zip(pows)
.rev()
.skip_while(|(i, _)| i > ÷nd )
.fold((0, 0), |(answer, sum), (double, power)| {
if sum + double < dividend {
(answer + power, sum + double)
} else {
(answer, sum)
}
});
(answer as u32, (dividend - sum) as u32)
}
fn main() {
let (div, rem) = egyptian_divide(580, 34);
println!("580 divided by 34 is {} remainder {}", div, rem);
} | 914Egyptian division
| 15rust
| hxuj2 |
def ef(fr)
ans = []
if fr >= 1
return [[fr.to_i], Rational(0, 1)] if fr.denominator == 1
intfr = fr.to_i
ans, fr = [intfr], fr - intfr
end
x, y = fr.numerator, fr.denominator
while x!= 1
ans << Rational(1, (1/fr).ceil)
fr = Rational(-y % x, y * (1/fr).ceil)
x, y = fr.numerator, fr.denominator
end
ans << fr
end
for fr in [Rational(43, 48), Rational(5, 121), Rational(2014, 59)]
puts '%s =>%s' % [fr, ef(fr).join(' + ')]
end
lenmax = denommax = [0]
for b in 2..99
for a in 1...b
fr = Rational(a,b)
e = ef(fr)
elen, edenom = e.length, e[-1].denominator
lenmax = [elen, fr] if elen > lenmax[0]
denommax = [edenom, fr] if edenom > denommax[0]
end
end
puts 'Term max is%s with%i terms' % [lenmax[1], lenmax[0]]
dstr = denommax[0].to_s
puts 'Denominator max is%s with%i digits' % [denommax[1], dstr.size], dstr | 913Egyptian fractions
| 14ruby
| ukmvz |
require 'socket'
server = TCPServer.new(12321)
while (connection = server.accept)
Thread.new(connection) do |conn|
port, host = conn.peeraddr[1,2]
client =
puts
begin
loop do
line = conn.readline
puts
conn.puts(line)
end
rescue EOFError
conn.close
puts
end
end
end | 907Echo server
| 14ruby
| aie1s |
local abs,atan,cos,floor,pi,sin,sqrt = math.abs,math.atan,math.cos,math.floor,math.pi,math.sin,math.sqrt
local bitmap = {
init = function(self, w, h, value)
self.w, self.h, self.pixels = w, h, {}
for y=1,h do self.pixels[y]={} end
self:clear(value)
end,
clear = function(self, value)
for y=1,self.h do
for x=1,self.w do
self.pixels[y][x] = value or " "
end
end
end,
set = function(self, x, y, value)
x,y = floor(x),floor(y)
if x>0 and y>0 and x<=self.w and y<=self.h then
self.pixels[y][x] = value or "#"
end
end,
line = function(self, x1, y1, x2, y2, c)
x1,y1,x2,y2 = floor(x1),floor(y1),floor(x2),floor(y2)
local dx, sx = abs(x2-x1), x1<x2 and 1 or -1
local dy, sy = abs(y2-y1), y1<y2 and 1 or -1
local err = floor((dx>dy and dx or -dy)/2)
while(true) do
self:set(x1, y1, c)
if (x1==x2 and y1==y2) then break end
if (err > -dx) then
err, x1 = err-dy, x1+sx
if (x1==x2 and y1==y2) then
self:set(x1, y1, c)
break
end
end
if (err < dy) then
err, y1 = err+dx, y1+sy
end
end
end,
render = function(self)
for y=1,self.h do
print(table.concat(self.pixels[y]))
end
end,
}
screen = {
clear = function()
os.execute("cls") | 919Draw a rotating cube
| 1lua
| 6uq39 |
mat <- matrix(1:4, 2, 2)
mat + 2
mat * 2
mat ^ 2
mat + mat
mat * mat
mat ^ mat | 912Element-wise operations
| 13r
| qf1xs |
DoublyLinkedList.prototype.insertAfter = function(searchValue, nodeToInsert) {
if (this._value == searchValue) {
var after = this.next();
this.next(nodeToInsert);
nodeToInsert.prev(this);
nodeToInsert.next(after);
after.prev(nodeToInsert);
}
else if (this.next() == null)
throw new Error(0, "value '" + searchValue + "' not found in linked list.")
else
this.next().insertAfter(searchValue, nodeToInsert);
}
var list = createDoublyLinkedListFromArray(['A','B']);
list.insertAfter('A', new DoublyLinkedList('C', null, null)); | 920Doubly-linked list/Element insertion
| 10javascript
| hxmjh |
package main
import "fmt"
type dlNode struct {
string
next, prev *dlNode
}
type dlList struct {
head, tail *dlNode
}
func (list *dlList) String() string {
if list.head == nil {
return fmt.Sprint(list.head)
}
r := "[" + list.head.string
for p := list.head.next; p != nil; p = p.next {
r += " " + p.string
}
return r + "]"
}
func (list *dlList) insertTail(node *dlNode) {
if list.tail == nil {
list.head = node
} else {
list.tail.next = node
}
node.next = nil
node.prev = list.tail
list.tail = node
}
func (list *dlList) insertAfter(existing, insert *dlNode) {
insert.prev = existing
insert.next = existing.next
existing.next.prev = insert
existing.next = insert
if existing == list.tail {
list.tail = insert
}
}
func main() {
dll := &dlList{}
fmt.Println(dll)
a := &dlNode{string: "A"}
dll.insertTail(a)
dll.insertTail(&dlNode{string: "B"})
fmt.Println(dll)
dll.insertAfter(a, &dlNode{string: "C"})
fmt.Println(dll) | 921Doubly-linked list/Traversal
| 0go
| g1t4n |
(use 'quil.core)
(def w 500)
(def h 400)
(defn setup []
(background 0))
(defn draw []
(push-matrix)
(translate (/ w 2) (/ h 2) 0)
(rotate-x 0.7)
(rotate-z 0.5)
(box 100 150 200)
(pop-matrix))
(defsketch main
:title "cuboid"
:setup setup
:size [w h]
:draw draw
:renderer:opengl) | 924Draw a cuboid
| 6clojure
| vh02f |
object EgyptianDivision extends App {
private def divide(dividend: Int, divisor: Int): Unit = {
val powersOf2, doublings = new collection.mutable.ListBuffer[Integer] | 914Egyptian division
| 16scala
| p0gbj |
use num_bigint::BigInt;
use num_integer::Integer;
use num_traits::{One, Zero};
use std::fmt;
#[derive(Debug, Clone, PartialEq, PartialOrd)]
struct Rational {
nominator: BigInt,
denominator: BigInt,
}
impl Rational {
fn new(n: &BigInt, d: &BigInt) -> Rational {
assert!(!d.is_zero(), "denominator cannot be 0"); | 913Egyptian fractions
| 15rust
| 5b9uq |
use std::net::{TcpListener, TcpStream};
use std::io::{BufReader, BufRead, Write};
use std::thread;
fn main() {
let listener = TcpListener::bind("127.0.0.1:12321").unwrap();
println!("server is running on 127.0.0.1:12321 ...");
for stream in listener.incoming() {
let stream = stream.unwrap();
thread::spawn(move || handle_client(stream));
}
}
fn handle_client(stream: TcpStream) {
let mut stream = BufReader::new(stream);
loop {
let mut buf = String::new();
if stream.read_line(&mut buf).is_err() {
break;
}
stream
.get_ref()
.write(buf.as_bytes())
.unwrap();
}
} | 907Echo server
| 15rust
| enwaj |
const char *shades = ;
double light[3] = { 30, 30, -50 };
void normalize(double * v)
{
double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);
v[0] /= len; v[1] /= len; v[2] /= len;
}
double dot(double *x, double *y)
{
double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];
return d < 0 ? -d : 0;
}
void draw_sphere(double R, double k, double ambient)
{
int i, j, intensity;
double b;
double vec[3], x, y;
for (i = floor(-R); i <= ceil(R); i++) {
x = i + .5;
for (j = floor(-2 * R); j <= ceil(2 * R); j++) {
y = j / 2. + .5;
if (x * x + y * y <= R * R) {
vec[0] = x;
vec[1] = y;
vec[2] = sqrt(R * R - x * x - y * y);
normalize(vec);
b = pow(dot(light, vec), k) + ambient;
intensity = (1 - b) * (sizeof(shades) - 1);
if (intensity < 0) intensity = 0;
if (intensity >= sizeof(shades) - 1)
intensity = sizeof(shades) - 2;
putchar(shades[intensity]);
} else
putchar(' ');
}
putchar('\n');
}
}
int main()
{
normalize(light);
draw_sphere(20, 4, .1);
draw_sphere(10, 2, .4);
return 0;
} | 925Draw a sphere
| 5c
| 4po5t |
null | 920Doubly-linked list/Element insertion
| 11kotlin
| l7ocp |
ds = CreateDataStructure["DoublyLinkedList"];
ds["Append", "A"];
ds["Append", "B"];
ds["Append", "C"];
ds["SwapPart", 2, 3];
ds["Elements"] | 920Doubly-linked list/Element insertion
| 1lua
| 2jil3 |
class DoubleLinkedListTraversing {
static void main(args) {
def linkedList = (1..9).collect() as LinkedList
linkedList.each {
print it
}
println()
linkedList.reverseEach {
print it
}
}
} | 921Doubly-linked list/Traversal
| 7groovy
| 2jolv |
main = print . traverse True $ create [10,20,30,40]
data DList a = Leaf | Node { prev::(DList a), elt::a, next::(DList a) }
create = go Leaf
where go _ [] = Leaf
go prev (x:xs) = current
where current = Node prev x next
next = go current xs
isLeaf Leaf = True
isLeaf _ = False
lastNode Leaf = Leaf
lastNode dl = until (isLeaf.next) next dl
traverse _ Leaf = []
traverse True (Node l v Leaf) = v: v: traverse False l
traverse dir (Node l v r) = v: traverse dir (if dir then r else l) | 921Doubly-linked list/Traversal
| 8haskell
| stgqk |
type dlNode struct {
string
next, prev *dlNode
} | 923Doubly-linked list/Element definition
| 0go
| eila6 |
data DList a = Leaf | Node (DList a) a (DList a)
updateLeft _ Leaf = Leaf
updateLeft Leaf (Node _ v r) = Node Leaf v r
updateLeft new@(Node nl _ _) (Node _ v r) = current
where current = Node prev v r
prev = updateLeft nl new
updateRight _ Leaf = Leaf
updateRight Leaf (Node l v _) = Node l v Leaf
updateRight new@(Node _ _ nr) (Node l v _) = current
where current = Node l v next
next = updateRight nr new | 923Doubly-linked list/Element definition
| 8haskell
| 3v1zj |
from PIL import Image
img = Image.new('RGB', (320, 240))
pixels = img.load()
pixels[100,100] = (255,0,0)
img.show() | 918Draw a pixel
| 3python
| 3vqzc |
extension BinaryInteger {
@inlinable
public func egyptianDivide(by divisor: Self) -> (quo: Self, rem: Self) {
let table =
(0...).lazy
.map({i -> (Self, Self) in
let power = Self(2).power(Self(i))
return (power, power * divisor)
})
.prefix(while: { $0.1 <= self })
.reversed()
let (answer, acc) = table.reduce((Self(0), Self(0)), {cur, row in
let ((ans, acc), (power, doubling)) = (cur, row)
return acc + doubling <= self? (ans + power, doubling + acc): cur
})
return (answer, Self((acc - self).magnitude))
}
@inlinable
public func power(_ n: Self) -> Self {
return stride(from: 0, to: n, by: 1).lazy.map({_ in self }).reduce(1, *)
}
}
let dividend = 580
let divisor = 34
let (quo, rem) = dividend.egyptianDivide(by: divisor)
print("\(dividend) divided by \(divisor) = \(quo) rem \(rem)") | 914Egyptian division
| 17swift
| 7e2rq |
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.{ArrayBuffer, ListBuffer}
abstract class Frac extends Comparable[Frac] {
val num: BigInt
val denom: BigInt
def toEgyptian: List[Frac] = {
if (num == 0) {
return List(this)
}
val fracs = new ArrayBuffer[Frac]
if (num.abs >= denom.abs) {
val div = Frac(num / denom, 1)
val rem = this - div
fracs += div
egyptian(rem.num, rem.denom, fracs)
} else {
egyptian(num, denom, fracs)
}
fracs.toList
}
@tailrec
private def egyptian(n: BigInt, d: BigInt, fracs: mutable.Buffer[Frac]): Unit = {
if (n == 0) {
return
}
val n2 = BigDecimal.apply(n)
val d2 = BigDecimal.apply(d)
val (divbd, rembd) = d2./%(n2)
var div = divbd.toBigInt()
if (rembd > 0) {
div = div + 1
}
fracs += Frac(1, div)
var n3 = -d % n
if (n3 < 0) {
n3 = n3 + n
}
val d3 = d * div
val f = Frac(n3, d3)
if (f.num == 1) {
fracs += f
return
}
egyptian(f.num, f.denom, fracs)
}
def unary_-(): Frac = {
Frac(-num, denom)
}
def +(rhs: Frac): Frac = {
Frac(
num * rhs.denom + rhs.num * denom,
denom * rhs.denom
)
}
def -(rhs: Frac): Frac = {
Frac(
num * rhs.denom - rhs.num * denom,
denom * rhs.denom
)
}
override def compareTo(rhs: Frac): Int = {
val ln = num * rhs.denom
val rn = rhs.num * denom
ln.compare(rn)
}
def canEqual(other: Any): Boolean = other.isInstanceOf[Frac]
override def equals(other: Any): Boolean = other match {
case that: Frac =>
(that canEqual this) &&
num == that.num &&
denom == that.denom
case _ => false
}
override def hashCode(): Int = {
val state = Seq(num, denom)
state.map(_.hashCode()).foldLeft(0)((a, b) => 31 * a + b)
}
override def toString: String = {
if (denom == 1) {
return s"$num"
}
s"$num/$denom"
}
}
object Frac {
def apply(n: BigInt, d: BigInt): Frac = {
if (d == 0) {
throw new IllegalArgumentException("Parameter d may not be zero.")
}
var nn = n
var dd = d
if (nn == 0) {
dd = 1
} else if (dd < 0) {
nn = -nn
dd = -dd
}
val g = nn.gcd(dd)
if (g > 0) {
nn /= g
dd /= g
}
new Frac {
val num: BigInt = nn
val denom: BigInt = dd
}
}
}
object EgyptianFractions {
def main(args: Array[String]): Unit = {
val fracs = List.apply(
Frac(43, 48),
Frac(5, 121),
Frac(2014, 59)
)
for (frac <- fracs) {
val list = frac.toEgyptian
val it = list.iterator
print(s"$frac -> ")
if (it.hasNext) {
val value = it.next()
if (value.denom == 1) {
print(s"[$value]")
} else {
print(value)
}
}
while (it.hasNext) {
val value = it.next()
print(s" + $value")
}
println()
}
for (r <- List(98, 998)) {
println()
if (r == 98) {
println("For proper fractions with 1 or 2 digits:")
} else {
println("For proper fractions with 1, 2 or 3 digits:")
}
var maxSize = 0
var maxSizeFracs = new ListBuffer[Frac]
var maxDen = BigInt(0)
var maxDenFracs = new ListBuffer[Frac]
val sieve = Array.ofDim[Boolean](r + 1, r + 2)
for (i <- 0 until r + 1) {
for (j <- i + 1 until r + 1) {
if (!sieve(i)(j)) {
val f = Frac(i, j)
val list = f.toEgyptian
val listSize = list.size
if (listSize > maxSize) {
maxSize = listSize
maxSizeFracs.clear()
maxSizeFracs += f
} else if (listSize == maxSize) {
maxSizeFracs += f
}
val listDen = list.last.denom
if (listDen > maxDen) {
maxDen = listDen
maxDenFracs.clear()
maxDenFracs += f
} else if (listDen == maxDen) {
maxDenFracs += f
}
if (i < r / 2) {
var k = 2
while (j * k <= r + 1) {
sieve(i * k)(j * k) = true
k = k + 1
}
}
}
}
}
println(s" largest number of items = $maxSize")
println(s"fraction(s) with this number: ${maxSizeFracs.toList}")
val md = maxDen.toString()
print(s" largest denominator = ${md.length} digits, ")
println(s"${md.substring(0, 20)}...${md.substring(md.length - 20)}")
println(s"fraction(s) with this denominator: ${maxDenFracs.toList}")
}
}
} | 913Egyptian fractions
| 16scala
| ra2gn |
import java.io.PrintWriter
import java.net.{ServerSocket, Socket}
import scala.io.Source
object EchoServer extends App {
private val serverSocket = new ServerSocket(23)
private var numConnections = 0
class ClientHandler(clientSocket: Socket) extends Runnable {
private val (connectionId, closeCmd) = ({numConnections += 1; numConnections}, ":exit")
override def run(): Unit =
new PrintWriter(clientSocket.getOutputStream, true) {
println(s"Connection opened, close with entering '$closeCmd'.")
Source.fromInputStream(clientSocket.getInputStream).getLines
.takeWhile(!_.toLowerCase.startsWith(closeCmd))
.foreach { line =>
Console.println(s"Received on #$connectionId: $line")
println(line) | 907Echo server
| 16scala
| qtsxw |
public class Node<T> {
private T element;
private Node<T> next, prev;
public Node<T>(){
next = prev = element = null;
}
public Node<T>(Node<T> n, Node<T> p, T elem){
next = n;
prev = p;
element = elem;
}
public void setNext(Node<T> n){
next = n;
}
public Node<T> getNext(){
return next;
}
public void setElem(T elem){
element = elem;
}
public T getElem(){
return element;
}
public void setNext(Node<T> n){
next = n;
}
public Node<T> setPrev(Node<T> p){
prev = p;
}
public getPrev(){
return prev;
}
} | 923Doubly-linked list/Element definition
| 9java
| iy7os |
p
x = + gets.chomp!
instance_variable_set x, 42
p | 917Dynamic variable names
| 14ruby
| 7e9ri |
use strict;
use warnings;
use Tk;
use Time::HiRes qw( time );
my $size = 600;
my $wait = int 1000 / 30;
my ($height, $width) = ($size, $size * sqrt 8/9);
my $mid = $width / 2;
my $rot = atan2(0, -1) / 3;
my $mw = MainWindow->new;
my $c = $mw->Canvas(-width => $width, -height => $height)->pack;
$c->Tk::bind('<ButtonRelease>' => sub {$mw->destroy});
draw();
MainLoop;
sub draw
{
my $angle = time - $^T;
my @points = map { $mid + $mid * cos $angle + $_ * $rot,
$height * ($_ % 2 + 1) / 3 } 0 .. 5;
$c->delete('all');
$c->createLine( @points[-12 .. 1], $mid, 0, -width => 5,);
$c->createLine( @points[4, 5], $mid, 0, @points[8, 9], -width => 5,);
$c->createLine( @points[2, 3], $mid, $height, @points[6, 7], -width => 5,);
$c->createLine( $mid, $height, @points[10, 11], -width => 5,);
$mw->after($wait, \&draw);
} | 919Draw a rotating cube
| 2perl
| p02b0 |
require 'matrix'
class Matrix
def element_wise( operator, other )
Matrix.build(row_size, column_size) do |row, col|
self[row, col].send(operator, other[row, col])
end
end
end
m1, m2 = Matrix[[3,1,4],[1,5,9]], Matrix[[2,7,1],[8,2,2]]
puts
[:+,:-,:*,:/, :fdiv,:**,:%].each do |op|
puts % [op, m1.element_wise(op, m2)]
end | 912Element-wise operations
| 14ruby
| nmsit |
package com.rosettacode;
import java.util.LinkedList;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class DoubleLinkedListTraversing {
public static void main(String[] args) {
final LinkedList<String> doubleLinkedList =
IntStream.range(1, 10)
.mapToObj(String::valueOf)
.collect(Collectors.toCollection(LinkedList::new));
doubleLinkedList.iterator().forEachRemaining(System.out::print);
System.out.println();
doubleLinkedList.descendingIterator().forEachRemaining(System.out::print);
}
} | 921Doubly-linked list/Traversal
| 9java
| 18lp2 |
DoublyLinkedList.prototype.getTail = function() {
var tail;
this.traverse(function(node){tail = node;});
return tail;
}
DoublyLinkedList.prototype.traverseBackward = function(func) {
func(this);
if (this.prev() != null)
this.prev().traverseBackward(func);
}
DoublyLinkedList.prototype.printBackward = function() {
this.traverseBackward( function(node) {print(node.value())} );
}
var head = createDoublyLinkedListFromArray([10,20,30,40]);
head.print();
head.getTail().printBackward(); | 921Doubly-linked list/Traversal
| 10javascript
| qf4x8 |
function DoublyLinkedList(value, next, prev) {
this._value = value;
this._next = next;
this._prev = prev;
} | 923Doubly-linked list/Element definition
| 10javascript
| z2pt2 |
struct Matrix {
elements: Vec<f32>,
pub height: u32,
pub width: u32,
}
impl Matrix {
fn new(elements: Vec<f32>, height: u32, width: u32) -> Matrix { | 912Element-wise operations
| 15rust
| d90ny |
(use 'quil.core)
(def w 500)
(def h 400)
(defn setup []
(background 0))
(defn draw []
(push-matrix)
(translate 250 200 0)
(sphere 100)
(pop-matrix))
(defsketch main
:title "sphere"
:setup setup
:size [w h]
:draw draw
:renderer:opengl) | 925Draw a sphere
| 6clojure
| hxtjr |
null | 921Doubly-linked list/Traversal
| 11kotlin
| jw67r |
null | 923Doubly-linked list/Element definition
| 11kotlin
| qfux1 |
local node = { data=data, prev=nil, next=nil } | 923Doubly-linked list/Element definition
| 1lua
| st5q8 |
package main
import (
"fmt"
"math/rand"
"time"
) | 922Dutch national flag problem
| 0go
| st4qa |
my %node_model = (
data => 'something',
prev => undef,
next => undef,
);
sub insert
{
my ($anchor, $newlink) = @_;
$newlink->{next} = $anchor->{next};
$newlink->{prev} = $anchor;
$newlink->{next}->{prev} = $newlink;
$anchor->{next} = $newlink;
}
my $node_a = { %node_model };
my $node_b = { %node_model };
$node_a->{next} = $node_b;
$node_b->{prev} = $node_a;
my $node_c = { %node_model };
insert($node_a, $node_c); | 920Doubly-linked list/Element insertion
| 2perl
| qfgx6 |
const char * shades = ;
double dist(double x, double y, double x0, double y0) {
double l = (x * x0 + y * y0) / (x0 * x0 + y0 * y0);
if (l > 1) {
x -= x0;
y -= y0;
} else if (l >= 0) {
x -= l * x0;
y -= l * y0;
}
return sqrt(x * x + y * y);
}
enum { sec = 0, min, hur };
void draw(int size)
{
double angle, cx = size / 2.;
double sx[3], sy[3], sw[3];
double fade[] = { 1, .35, .35 };
struct timeval tv;
struct tm *t;
sw[sec] = size * .02;
sw[min] = size * .03;
sw[hur] = size * .05;
every_second:
gettimeofday(&tv, 0);
t = localtime(&tv.tv_sec);
angle = t->tm_sec * PI / 30;
sy[sec] = -cx * cos(angle);
sx[sec] = cx * sin(angle);
angle = (t->tm_min + t->tm_sec / 60.) / 30 * PI;
sy[min] = -cx * cos(angle) * .8;
sx[min] = cx * sin(angle) * .8;
angle = (t->tm_hour + t->tm_min / 60.) / 6 * PI;
sy[hur] = -cx * cos(angle) * .6;
sx[hur] = cx * sin(angle) * .6;
printf();
for_i {
printf(, i);
double y = i - cx;
for_j {
double x = (j - 2 * cx) / 2;
int pix = 0;
for (int k = hur; k >= sec; k--) {
double d = dist(x, y, sx[k], sy[k]);
if (d < sw[k] - .5)
pix = 10 * fade[k];
else if (d < sw[k] + .5)
pix = (5 + (sw[k] - d) * 10) * fade[k];
}
putchar(shades[pix]);
}
}
printf();
fflush(stdout);
sleep(1);
goto every_second;
}
int main(int argc, char *argv[])
{
int s;
if (argc <= 1 || (s = atoi(argv[1])) <= 0) s = 20;
draw(s);
return 0;
} | 926Draw a clock
| 5c
| 5b0uk |
null | 921Doubly-linked list/Traversal
| 1lua
| hxyj8 |
import Data.List (sort)
import System.Random (randomRIO)
import System.IO.Unsafe (unsafePerformIO)
data Color = Red | White | Blue deriving (Show, Eq, Ord, Enum)
dutch :: [Color] -> [Color]
dutch = sort
isDutch :: [Color] -> Bool
isDutch x = x == dutch x
randomBalls :: Int -> [Color]
randomBalls 0 = []
randomBalls n = toEnum (unsafePerformIO (randomRIO (fromEnum Red,
fromEnum Blue))): randomBalls (n - 1)
main :: IO ()
main = do
let a = randomBalls 20
case isDutch a of
True -> putStrLn $ "The random sequence " ++ show a ++
" is already in the order of the Dutch national flag!"
False -> do
putStrLn $ "The starting random sequence is " ++ show a ++ "\n"
putStrLn $ "The ordered sequence is " ++ show (dutch a) | 922Dutch national flag problem
| 8haskell
| 9gqmo |
from visual import *
scene.title =
scene.range = 2
scene.autocenter = True
print
print
deg45 = math.radians(45.0)
cube = box()
cube.rotate( angle=deg45, axis=(1,0,0) )
cube.rotate( angle=deg45, axis=(0,0,1) )
while True:
rate(50)
cube.rotate( angle=0.005, axis=(0,1,0) ) | 919Draw a rotating cube
| 3python
| 18vpc |
require 'gtk3'
Width, Height = 320, 240
PosX, PosY = 100, 100
window = Gtk::Window.new
window.set_default_size(Width, Height)
window.title = 'Draw a pixel'
window.signal_connect(:draw) do |widget, context|
context.set_antialias(Cairo::Antialias::NONE)
context.set_source_rgb(1.0, 0.0, 0.0)
context.fill do
context.rectangle(PosX, PosY, 1, 1)
end
end
window.signal_connect(:destroy) { Gtk.main_quit }
window.show
Gtk.main | 918Draw a pixel
| 14ruby
| y506n |
extern crate piston_window;
extern crate image;
use piston_window::*;
fn main() {
let (width, height) = (320, 240);
let mut window: PistonWindow =
WindowSettings::new("Red Pixel", [width, height])
.exit_on_esc(true).build().unwrap(); | 918Draw a pixel
| 15rust
| m48ya |
def insert(anchor, new):
new.next = anchor.next
new.prev = anchor
anchor.next.prev = new
anchor.next = new | 920Doubly-linked list/Element insertion
| 3python
| strq9 |
my %node = (
data => 'say what',
next => \%foo_node,
prev => \%bar_node,
);
$node{next} = \%quux_node; | 923Doubly-linked list/Element definition
| 2perl
| vh820 |
import java.util.Arrays;
import java.util.Random;
public class DutchNationalFlag {
enum DutchColors {
RED, WHITE, BLUE
}
public static void main(String[] args){
DutchColors[] balls = new DutchColors[12];
DutchColors[] values = DutchColors.values();
Random rand = new Random();
for (int i = 0; i < balls.length; i++)
balls[i]=values[rand.nextInt(values.length)];
System.out.println("Before: " + Arrays.toString(balls));
Arrays.sort(balls);
System.out.println("After: " + Arrays.toString(balls));
boolean sorted = true;
for (int i = 1; i < balls.length; i++ ){
if (balls[i-1].compareTo(balls[i]) > 0){
sorted=false;
break;
}
}
System.out.println("Correctly sorted: " + sorted);
}
} | 922Dutch national flag problem
| 9java
| tlpf9 |
package main
import "fmt"
func cuboid(dx, dy, dz int) {
fmt.Printf("cuboid%d%d%d:\n", dx, dy, dz)
cubLine(dy+1, dx, 0, "+-")
for i := 1; i <= dy; i++ {
cubLine(dy-i+1, dx, i-1, "/ |")
}
cubLine(0, dx, dy, "+-|")
for i := 4*dz - dy - 2; i > 0; i-- {
cubLine(0, dx, dy, "| |")
}
cubLine(0, dx, dy, "| +")
for i := 1; i <= dy; i++ {
cubLine(0, dx, dy-i, "| /")
}
cubLine(0, dx, 0, "+-\n")
}
func cubLine(n, dx, dy int, cde string) {
fmt.Printf("%*s", n+1, cde[:1])
for d := 9*dx - 1; d > 0; d-- {
fmt.Print(cde[1:2])
}
fmt.Print(cde[:1])
fmt.Printf("%*s\n", dy+1, cde[2:])
}
func main() {
cuboid(2, 3, 4)
cuboid(1, 1, 1)
cuboid(6, 2, 1)
} | 924Draw a cuboid
| 0go
| ao91f |
import java.awt.image.BufferedImage
import java.awt.Color
import scala.language.reflectiveCalls
object RgbBitmap extends App {
class RgbBitmap(val dim: (Int, Int)) {
def width = dim._1
def height = dim._2
private val image = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR)
def apply(x: Int, y: Int) = new Color(image.getRGB(x, y))
def update(x: Int, y: Int, c: Color) = image.setRGB(x, y, c.getRGB)
def fill(c: Color) = {
val g = image.getGraphics
g.setColor(c)
g.fillRect(0, 0, width, height)
}
}
object RgbBitmap {
def apply(width: Int, height: Int) = new RgbBitmap(width, height)
}
private val img0 = new RgbBitmap(50, 60) { | 918Draw a pixel
| 16scala
| l7ncq |
import java.awt.event.ActionEvent
import java.awt._
import javax.swing.{JFrame, JPanel, Timer}
import scala.math.{Pi, atan, cos, sin, sqrt}
object RotatingCube extends App {
class RotatingCube extends JPanel {
private val vertices: Vector[Array[Double]] =
Vector(Array(-1, -1, -1), Array(-1, -1, 1), Array(-1, 1, -1),
Array(-1, 1, 1), Array(1, -1, -1), Array(1, -1, 1), Array(1, 1, -1), Array(1, 1, 1))
private val edges: Vector[(Int, Int)] =
Vector((0, 1), (1, 3), (3, 2), (2, 0), (4, 5), (5, 7),
(7, 6), (6, 4), (0, 4), (1, 5), (2, 6), (3, 7))
setPreferredSize(new Dimension(640, 640))
setBackground(Color.white)
scale(100)
rotateCube(Pi / 4, atan(sqrt(2)))
new Timer(17, (_: ActionEvent) => {
rotateCube(Pi / 180, 0)
repaint()
}).start()
override def paintComponent(gg: Graphics): Unit = {
def drawCube(g: Graphics2D): Unit = {
g.translate(getWidth / 2, getHeight / 2)
for {edge <- edges
xy1: Array[Double] = vertices(edge._1)
xy2: Array[Double] = vertices(edge._2)
} {
g.drawLine(xy1(0).toInt, xy1(1).toInt, xy2(0).toInt, xy2(1).toInt)
g.fillOval(xy1(0).toInt -4, xy1(1).toInt - 4, 8, 8)
g.setColor(Color.black)
}
}
super.paintComponent(gg)
val g: Graphics2D = gg.asInstanceOf[Graphics2D]
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
drawCube(g)
}
private def scale(s: Double): Unit = {
for {node <- vertices
i <- node.indices
} node(i) *= s
}
private def rotateCube(angleX: Double, angleY: Double): Unit = {
def sinCos(x: Double) = (sin(x), cos(x))
val ((sinX, cosX), (sinY, cosY)) = (sinCos(angleX), sinCos(angleY))
for {
node <- vertices
x: Double = node(0)
y: Double = node(1)
} {
def f(p: Double, q: Double)(a: Double, b: Double) = a * p + b * q
def fx(a: Double, b: Double) = f(cosX, sinX)(a, b)
def fy(a: Double, b: Double) = f(cosY, sinY)(a, b)
node(0) = fx(x, -node(2))
val z = fx(node(2), x)
node(1) = fy(y, -z)
node(2) = fy(z, y)
}
}
}
new JFrame("Rotating Cube") {
add(new RotatingCube(), BorderLayout.CENTER)
pack()
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE)
setLocationRelativeTo(null)
setResizable(false)
setVisible(true)
}
} | 919Draw a rotating cube
| 16scala
| st7qo |
const dutchNationalFlag = () => {
const name = e => e > 1 ? 'Blue' : e > 0 ? 'White' : 'Red';
const isSorted = arr => arr.every((e,i) => e >= arr[Math.max(i-1, 0)]);
function* randomGen (max, n) {
let i = 0;
while (i < n) {
i += 1;
yield Math.floor(Math.random() * max);
}
}
const mixedBalls = [...(randomGen(3, 22))];
const sortedBalls = mixedBalls
.reduce((p,c) => p[c].push(c) && p, [[],[],[]])
.reduce((p,c) => p.concat(c), []);
const dutchSort = (A, mid) => {
let i = 0;
let j = 0;
let n = A.length - 1;
while(j <= n) {
if (A[j] < mid) {
[A[i], A[j]] = [A[j], A[i]];
i += 1;
j += 1;
} else if (A[j] > mid) {
[A[j], A[n]] = [A[n], A[j]];
n -= 1
} else {
j += 1;
}
}
};
console.log(`Mixed balls : ${mixedBalls.map(name).join()}`);
console.log(`Is sorted: ${isSorted(mixedBalls)}`);
console.log(`Sorted balls : ${sortedBalls.map(name).join()}`);
console.log(`Is sorted: ${isSorted(sortedBalls)}`); | 922Dutch national flag problem
| 10javascript
| m4xyv |
import Graphics.Rendering.OpenGL
import Graphics.UI.GLUT
type Fl = GLfloat
cuboid :: IO ()
cuboid = do
color red ; render front
color green; render side
color blue ; render top
red,green,blue :: Color4 GLfloat
red = Color4 1 0 0 1
green = Color4 0 1 0 1
blue = Color4 0 0 1 1
render :: [(Fl, Fl, Fl)] -> IO ()
render = renderPrimitive TriangleStrip . mapM_ toVertex
where toVertex (x,y,z) = vertex $ Vertex3 x y z
front,side,top :: [(Fl,Fl,Fl)]
front = vertices [0,1,2,3]
side = vertices [4,1,5,3]
top = vertices [3,2,5,6]
vertices :: [Int] -> [(Fl,Fl,Fl)]
vertices = map (verts !!)
verts :: [(Fl,Fl,Fl)]
verts = [(0,0,1), (1,0,1), (0,1,1), (1,1,1), (1,0,0), (1,1,0), (0,1,0)]
transform :: IO ()
transform = do
translate $ Vector3 0 0 (-10 :: Fl)
rotate (-14) $ Vector3 0 0 (1 :: Fl)
rotate (-30) $ Vector3 0 1 (0 :: Fl)
rotate 25 $ Vector3 1 0 (0 :: Fl)
scale 2 3 (4 :: Fl)
translate $ Vector3 (-0.5) (-0.5) (-0.5 :: Fl)
display :: IO ()
display = do
clear [ColorBuffer]
perspective 40 1 1 (15 :: GLdouble)
transform
cuboid
flush
main :: IO ()
main = do
let name = "Cuboid"
initialize name []
createWindow name
displayCallback $= display
mainLoop | 924Draw a cuboid
| 8haskell
| z2bt0 |
class Node(object):
def __init__(self, data = None, prev = None, next = None):
self.prev = prev
self.next = next
self.data = data
def __str__(self):
return str(self.data)
def __repr__(self):
return repr(self.data)
def iter_forward(self):
c = self
while c != None:
yield c
c = c.next
def iter_backward(self):
c = self
while c != None:
yield c
c = c.prev | 923Doubly-linked list/Element definition
| 3python
| ukovd |
null | 922Dutch national flag problem
| 11kotlin
| o678z |
class DListNode
def insert_after(search_value, new_value)
if search_value == value
new_node = self.class.new(new_value, nil, nil)
next_node = self.succ
self.succ = new_node
new_node.prev = self
new_node.succ = next_node
next_node.prev = new_node
elsif self.succ.nil?
raise StandardError,
else
self.succ.insert_after(search_value, new_value)
end
end
end
head = DListNode.from_array([:a, :b])
head.insert_after(:a, :c) | 920Doubly-linked list/Element insertion
| 14ruby
| 83j01 |
use std::collections::LinkedList;
fn main() {
let mut list = LinkedList::new();
list.push_front(8);
} | 920Doubly-linked list/Element insertion
| 15rust
| o6h83 |
typealias NodePtr<T> = UnsafeMutablePointer<Node<T>>
class Node<T> {
var value: T
fileprivate var prev: NodePtr<T>?
fileprivate var next: NodePtr<T>?
init(value: T, prev: NodePtr<T>? = nil, next: NodePtr<T>? = nil) {
self.value = value
self.prev = prev
self.next = next
}
}
@discardableResult
func insert<T>(_ val: T, after: Node<T>? = nil, list: NodePtr<T>? = nil) -> NodePtr<T> {
let node = NodePtr<T>.allocate(capacity: 1)
node.initialize(to: Node(value: val))
var n = list
while n!= nil {
if n?.pointee!== after {
n = n?.pointee.next
continue
}
node.pointee.prev = n
node.pointee.next = n?.pointee.next
n?.pointee.next?.pointee.prev = node
n?.pointee.next = node
break
}
return node
} | 920Doubly-linked list/Element insertion
| 17swift
| 0z7s6 |
import java.awt.*;
import java.awt.event.*;
import static java.lang.Math.*;
import javax.swing.*;
public class Cuboid extends JPanel {
double[][] nodes = {{-1, -1, -1}, {-1, -1, 1}, {-1, 1, -1}, {-1, 1, 1},
{1, -1, -1}, {1, -1, 1}, {1, 1, -1}, {1, 1, 1}};
int[][] edges = {{0, 1}, {1, 3}, {3, 2}, {2, 0}, {4, 5}, {5, 7}, {7, 6},
{6, 4}, {0, 4}, {1, 5}, {2, 6}, {3, 7}};
int mouseX, prevMouseX, mouseY, prevMouseY;
public Cuboid() {
setPreferredSize(new Dimension(640, 640));
setBackground(Color.white);
scale(80, 120, 160);
rotateCube(PI / 5, PI / 9);
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
mouseX = e.getX();
mouseY = e.getY();
}
});
addMouseMotionListener(new MouseAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
prevMouseX = mouseX;
prevMouseY = mouseY;
mouseX = e.getX();
mouseY = e.getY();
double incrX = (mouseX - prevMouseX) * 0.01;
double incrY = (mouseY - prevMouseY) * 0.01;
rotateCube(incrX, incrY);
repaint();
}
});
}
private void scale(double sx, double sy, double sz) {
for (double[] node : nodes) {
node[0] *= sx;
node[1] *= sy;
node[2] *= sz;
}
}
private void rotateCube(double angleX, double angleY) {
double sinX = sin(angleX);
double cosX = cos(angleX);
double sinY = sin(angleY);
double cosY = cos(angleY);
for (double[] node : nodes) {
double x = node[0];
double y = node[1];
double z = node[2];
node[0] = x * cosX - z * sinX;
node[2] = z * cosX + x * sinX;
z = node[2];
node[1] = y * cosY - z * sinY;
node[2] = z * cosY + y * sinY;
}
}
void drawCube(Graphics2D g) {
g.translate(getWidth() / 2, getHeight() / 2);
for (int[] edge : edges) {
double[] xy1 = nodes[edge[0]];
double[] xy2 = nodes[edge[1]];
g.drawLine((int) round(xy1[0]), (int) round(xy1[1]),
(int) round(xy2[0]), (int) round(xy2[1]));
}
for (double[] node : nodes) {
g.fillOval((int) round(node[0]) - 4, (int) round(node[1]) - 4, 8, 8);
}
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawCube(g);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Cuboid");
f.setResizable(false);
f.add(new Cuboid(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
} | 924Draw a cuboid
| 9java
| o6g8d |
class List:
def __init__(self, data, next=None, prev=None):
self.data = data
self.next = next
self.prev = prev
def append(self, data):
if self.next == None:
self.next = List(data, None, self)
return self.next
else:
return self.next.append(data)
tail = head = List(10)
for i in [ 20, 30, 40 ]:
tail = tail.append(i)
node = head
while node != None:
print(node.data)
node = node.next
node = tail
while node != None:
print(node.data)
node = node.prev | 921Doubly-linked list/Traversal
| 3python
| z2att |
class DListNode < ListNode
attr_accessor :prev
def initialize(value, prev=nil, succ=nil)
@value = value
@prev = prev
@prev.succ = self if prev
@succ = succ
@succ.prev = self if succ
end
def self.from_values(*ary)
ary << (f = ary.pop)
ary.map! {|i| new i }
ary.inject(f) {|p, c| p.succ = c; c.prev = p; c }
end
end
list = DListNode.from_values 1,2,3,4 | 923Doubly-linked list/Element definition
| 14ruby
| 4pn5p |
use std::collections::LinkedList;
fn main() { | 923Doubly-linked list/Element definition
| 15rust
| g1d4o |
null | 922Dutch national flag problem
| 1lua
| iyjot |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
canvas {
background-color: black;
}
</style>
</head>
<body>
<canvas></canvas>
<script>
var canvas = document.querySelector("canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var g = canvas.getContext("2d");
canvas.addEventListener("mousemove", function (event) {
prevMouseX = mouseX;
prevMouseY = mouseY;
mouseX = event.x;
mouseY = event.y;
var incrX = (mouseX - prevMouseX) * 0.01;
var incrY = (mouseY - prevMouseY) * 0.01;
rotateCuboid(incrX, incrY);
drawCuboid();
});
var nodes = [[-1, -1, -1], [-1, -1, 1], [-1, 1, -1], [-1, 1, 1],
[1, -1, -1], [1, -1, 1], [1, 1, -1], [1, 1, 1]];
var edges = [[0, 1], [1, 3], [3, 2], [2, 0], [4, 5], [5, 7], [7, 6],
[6, 4], [0, 4], [1, 5], [2, 6], [3, 7]];
var mouseX = 0, prevMouseX, mouseY = 0, prevMouseY;
function scale(factor0, factor1, factor2) {
nodes.forEach(function (node) {
node[0] *= factor0;
node[1] *= factor1;
node[2] *= factor2;
});
}
function rotateCuboid(angleX, angleY) {
var sinX = Math.sin(angleX);
var cosX = Math.cos(angleX);
var sinY = Math.sin(angleY);
var cosY = Math.cos(angleY);
nodes.forEach(function (node) {
var x = node[0];
var y = node[1];
var z = node[2];
node[0] = x * cosX - z * sinX;
node[2] = z * cosX + x * sinX;
z = node[2];
node[1] = y * cosY - z * sinY;
node[2] = z * cosY + y * sinY;
});
}
function drawCuboid() {
g.save();
g.clearRect(0, 0, canvas.width, canvas.height);
g.translate(canvas.width / 2, canvas.height / 2);
g.strokeStyle = "#FFFFFF";
g.beginPath();
edges.forEach(function (edge) {
var p1 = nodes[edge[0]];
var p2 = nodes[edge[1]];
g.moveTo(p1[0], p1[1]);
g.lineTo(p2[0], p2[1]);
});
g.closePath();
g.stroke();
g.restore();
}
scale(80, 120, 160);
rotateCuboid(Math.PI / 5, Math.PI / 9);
</script>
</body>
</html> | 924Draw a cuboid
| 10javascript
| tlkfm |
long long x, y, dx, dy, scale, clen;
typedef struct { double r, g, b; } rgb;
rgb ** pix;
void sc_up()
{
long long tmp = dx - dy; dy = dx + dy; dx = tmp;
scale *= 2; x *= 2; y *= 2;
}
void h_rgb(long long x, long long y)
{
rgb *p = &pix[y][x];
double h = 6.0 * clen / scale;
double VAL = 1 - (cos(3.141592653579 * 64 * clen / scale) - 1) / 4;
double c = SAT * VAL;
double X = c * (1 - fabs(fmod(h, 2) - 1));
switch((int)h) {
case 0: p->r += c; p->g += X; return;
case 1: p->r += X; p->g += c; return;
case 2: p->g += c; p->b += X; return;
case 3: p->g += X; p->b += c; return;
case 4: p->r += X; p->b += c; return;
default:
p->r += c; p->b += X;
}
}
void iter_string(const char * str, int d)
{
long tmp;
while (*str != '\0') {
switch(*(str++)) {
case 'X': if (d) iter_string(, d - 1); continue;
case 'Y': if (d) iter_string(, d - 1); continue;
case '+': RIGHT; continue;
case '-': LEFT; continue;
case 'F':
clen ++;
h_rgb(x/scale, y/scale);
x += dx; y += dy;
continue;
}
}
}
void dragon(long leng, int depth)
{
long i, d = leng / 3 + 1;
long h = leng + 3, w = leng + d * 3 / 2 + 2;
rgb *buf = malloc(sizeof(rgb) * w * h);
pix = malloc(sizeof(rgb *) * h);
for (i = 0; i < h; i++)
pix[i] = buf + w * i;
memset(buf, 0, sizeof(rgb) * w * h);
x = y = d; dx = leng; dy = 0; scale = 1; clen = 0;
for (i = 0; i < depth; i++) sc_up();
iter_string(, depth);
unsigned char *fpix = malloc(w * h * 3);
double maxv = 0, *dbuf = (double*)buf;
for (i = 3 * w * h - 1; i >= 0; i--)
if (dbuf[i] > maxv) maxv = dbuf[i];
for (i = 3 * h * w - 1; i >= 0; i--)
fpix[i] = 255 * dbuf[i] / maxv;
printf(, w, h);
fflush(stdout);
fwrite(fpix, h * w * 3, 1, stdout);
}
int main(int c, char ** v)
{
int size, depth;
depth = (c > 1) ? atoi(v[1]) : 10;
size = 1 << depth;
fprintf(stderr, , size, depth);
dragon(size, depth * 2);
return 0;
} | 927Dragon curve
| 5c
| qfcxc |
typealias NodePtr<T> = UnsafeMutablePointer<Node<T>>
class Node<T> {
var value: T
fileprivate var prev: NodePtr<T>?
fileprivate var next: NodePtr<T>?
init(value: T, prev: NodePtr<T>? = nil, next: NodePtr<T>? = nil) {
self.value = value
self.prev = prev
self.next = next
}
} | 923Doubly-linked list/Element definition
| 17swift
| 5biu8 |
class DListNode
def get_tail
self.find {|node| node.succ.nil?}
end
def each_previous(&b)
yield self
self.prev.each_previous(&b) if self.prev
end
end
head = DListNode.from_array([:a, :b, :c])
head.each {|node| p node.value}
head.get_tail.each_previous {|node| p node.value} | 921Doubly-linked list/Traversal
| 14ruby
| 6uw3t |
null | 924Draw a cuboid
| 11kotlin
| xd2ws |
import java.util
object DoublyLinkedListTraversal extends App {
private val ll = new util.LinkedList[String]
private def traverse(iter: util.Iterator[String]) =
while (iter.hasNext) iter.next
traverse(ll.iterator)
traverse(ll.descendingIterator)
} | 921Doubly-linked list/Traversal
| 16scala
| cr093 |
use warnings;
use strict;
use 5.010;
use List::Util qw( shuffle );
my @colours = qw( blue white red );
sub are_ordered {
my $balls = shift;
my $last = 0;
for my $ball (@$balls) {
return if $ball < $last;
$last = $ball;
}
return 1;
}
sub show {
my $balls = shift;
print join(' ', map $colours[$_], @$balls), "\n";
}
sub debug {
return unless $ENV{DEBUG};
my ($pos, $top, $bottom, $balls) = @_;
for my $i (0 .. $
my ($prefix, $suffix) = (q()) x 2;
($prefix, $suffix) = qw/( )/ if $i == $pos;
$prefix .= '>' if $i == $top;
$suffix .= '<' if $i == $bottom;
print STDERR " $prefix$colours[$balls->[$i]]$suffix";
}
print STDERR "\n";
}
my $count = shift // 10;
die "$count: Not enough balls\n" if $count < 3;
my $balls = [qw( 2 1 0 )];
push @$balls, int rand 3 until @$balls == $count;
do { @$balls = shuffle @$balls } while are_ordered($balls);
show($balls);
my $top = 0;
my $bottom = $
my $i = 0;
while ($i <= $bottom) {
debug($i, $top, $bottom, $balls);
my $col = $colours[ $balls->[$i] ];
if ('red' eq $col and $i < $bottom) {
@{$balls}[$bottom, $i] = @{$balls}[$i, $bottom];
$bottom--;
} elsif ('blue' eq $col and $i > $top) {
@{$balls}[$top, $i] = @{$balls}[$i, $top];
$top++;
} else {
$i++;
}
}
debug($i, $top, $bottom, $balls);
show($balls);
are_ordered($balls) or die "Incorrect\n"; | 922Dutch national flag problem
| 2perl
| g1f4e |
package main
import (
"fmt"
"image"
"image/color"
"image/png"
"math"
"os"
)
type vector [3]float64
func normalize(v *vector) {
invLen := 1 / math.Sqrt(dot(v, v))
v[0] *= invLen
v[1] *= invLen
v[2] *= invLen
}
func dot(x, y *vector) float64 {
return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]
}
func drawSphere(r int, k, amb float64, dir *vector) *image.Gray {
w, h := r*4, r*3
img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2))
vec := new(vector)
for x := -r; x < r; x++ {
for y := -r; y < r; y++ {
if z := r*r - x*x - y*y; z >= 0 {
vec[0] = float64(x)
vec[1] = float64(y)
vec[2] = math.Sqrt(float64(z))
normalize(vec)
s := dot(dir, vec)
if s < 0 {
s = 0
}
lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)
if lum < 0 {
lum = 0
} else if lum > 255 {
lum = 255
}
img.SetGray(x, y, color.Gray{uint8(lum)})
}
}
}
return img
}
func main() {
dir := &vector{-30, -30, 50}
normalize(dir)
img := drawSphere(200, 1.5, .2, dir)
f, err := os.Create("sphere.png")
if err != nil {
fmt.Println(err)
return
}
if err = png.Encode(f, img); err != nil {
fmt.Println(err)
}
if err = f.Close(); err != nil {
fmt.Println(err)
}
} | 925Draw a sphere
| 0go
| o648q |
package main
import (
"golang.org/x/net/websocket"
"flag"
"fmt"
"html/template"
"io"
"math"
"net/http"
"time"
)
var (
Portnum string
Hostsite string
)
type PageSettings struct {
Host string
Port string
}
const (
Canvaswidth = 512
Canvasheight = 512 | 926Draw a clock
| 0go
| 83u0g |
null | 924Draw a cuboid
| 1lua
| qfvx0 |
import Graphics.Rendering.OpenGL.GL
import Graphics.UI.GLUT.Objects
import Graphics.UI.GLUT
setProjection :: IO ()
setProjection = do
matrixMode $= Projection
ortho (-1) 1 (-1) 1 0 (-1)
grey1,grey9,red,white :: Color4 GLfloat
grey1 = Color4 0.1 0.1 0.1 1
grey9 = Color4 0.9 0.9 0.9 1
red = Color4 1 0 0 1
white = Color4 1 1 1 1
setLights :: IO ()
setLights = do
let l = Light 0
ambient l $= grey1
diffuse l $= white
specular l $= white
position l $= Vertex4 (-4) 4 3 (0 :: GLfloat)
light l $= Enabled
lighting $= Enabled
setMaterial :: IO ()
setMaterial = do
materialAmbient Front $= grey1
materialDiffuse Front $= red
materialSpecular Front $= grey9
materialShininess Front $= (32 :: GLfloat)
display :: IO()
display = do
clear [ColorBuffer]
renderObject Solid $ Sphere' 0.8 64 64
swapBuffers
main:: IO()
main = do
_ <- getArgsAndInitialize
_ <- createWindow "Sphere"
clearColor $= Color4 0.0 0.0 0.0 0.0
setProjection
setLights
setMaterial
displayCallback $= display
mainLoop | 925Draw a sphere
| 8haskell
| 2jqll |
import Control.Concurrent
import Data.List
import System.Time
import System.Console.ANSI
number :: (Integral a) => a -> [String]
number 0 =
[""
," "
," "
," "
,""]
number 1 =
[" "
," "
," "
," "
," "]
number 2 =
[""
," "
,""
," "
,""]
number 3 =
[""
," "
,""
," "
,""]
number 4 =
[" "
," "
,""
," "
," "]
number 5 =
[""
," "
,""
," "
,""]
number 6 =
[""
," "
,""
," "
,""]
number 7 =
[""
," "
," "
," "
," "]
number 8 =
[""
," "
,""
," "
,""]
number 9 =
[""
," "
,""
," "
,""]
colon :: [String]
colon =
[" "
," "
," "
," "
," "]
newline :: [String]
newline =
["\n"
,"\n"
,"\n"
,"\n"
,"\n"]
space :: [String]
space =
[" "
," "
," "
," "
," "]
leadingZero :: (Integral a) => a -> [[String]]
leadingZero num =
let (tens, ones) = divMod num 10
in [number tens, space, number ones]
fancyTime :: CalendarTime -> String
fancyTime time =
let hour = leadingZero $ ctHour time
minute = leadingZero $ ctMin time
second = leadingZero $ ctSec time
nums = hour ++ [colon] ++ minute ++ [colon] ++ second ++ [newline]
in concat $ concat $ transpose nums
main :: IO ()
main = do
time <- getClockTime >>= toCalendarTime
putStr $ fancyTime time
threadDelay 1000000
setCursorColumn 0
cursorUp 5
main | 926Draw a clock
| 8haskell
| l7wch |
import random
colours_in_order = 'Red White Blue'.split()
def dutch_flag_sort(items, order=colours_in_order):
'return sort of items using the given order'
reverse_index = dict((x,i) for i,x in enumerate(order))
return sorted(items, key=lambda x: reverse_index[x])
def dutch_flag_check(items, order=colours_in_order):
'Return True if each item of items is in the given order'
reverse_index = dict((x,i) for i,x in enumerate(order))
order_of_items = [reverse_index[item] for item in items]
return all(x <= y for x, y in zip(order_of_items, order_of_items[1:]))
def random_balls(mx=5):
'Select from 1 to mx balls of each colour, randomly'
balls = sum([[colour] * random.randint(1, mx)
for colour in colours_in_order], [])
random.shuffle(balls)
return balls
def main():
while True:
balls = random_balls()
if not dutch_flag_check(balls):
break
print(, balls)
sorted_balls = dutch_flag_sort(balls)
print(, sorted_balls)
assert dutch_flag_check(sorted_balls), 'Whoops. Not sorted!'
if __name__ == '__main__':
main() | 922Dutch national flag problem
| 3python
| ratgq |
public class Sphere{
static char[] shades = {'.', ':', '!', '*', 'o', 'e', '&', '#', '%', '@'};
static double[] light = { 30, 30, -50 };
private static void normalize(double[] v){
double len = Math.sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);
v[0] /= len; v[1] /= len; v[2] /= len;
}
private static double dot(double[] x, double[] y){
double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];
return d < 0 ? -d : 0;
}
public static void drawSphere(double R, double k, double ambient){
double[] vec = new double[3];
for(int i = (int)Math.floor(-R); i <= (int)Math.ceil(R); i++){
double x = i + .5;
for(int j = (int)Math.floor(-2 * R); j <= (int)Math.ceil(2 * R); j++){
double y = j / 2. + .5;
if(x * x + y * y <= R * R) {
vec[0] = x;
vec[1] = y;
vec[2] = Math.sqrt(R * R - x * x - y * y);
normalize(vec);
double b = Math.pow(dot(light, vec), k) + ambient;
int intensity = (b <= 0) ?
shades.length - 2 :
(int)Math.max((1 - b) * (shades.length - 1), 0);
System.out.print(shades[intensity]);
} else
System.out.print(' ');
}
System.out.println();
}
}
public static void main(String[] args){
normalize(light);
drawSphere(20, 4, .1);
drawSphere(10, 2, .4);
}
} | 925Draw a sphere
| 9java
| 6up3z |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Draw a sphere</title>
<script>
var light=[30,30,-50],gR,gk,gambient;
function normalize(v){
var len=Math.sqrt(v[0]*v[0]+v[1]*v[1]+v[2]*v[2]);
v[0]/=len;
v[1]/=len;
v[2]/=len;
return v;
}
function dot(x,y){
var d=x[0]*y[0]+x[1]*y[1]+x[2]*y[2];
return d<0?-d:0;
}
function draw_sphere(R,k,ambient){
var i,j,intensity,b,vec,x,y,cvs,ctx,imgdata,idx;
cvs=document.getElementById("c");
ctx=cvs.getContext("2d");
cvs.width=cvs.height=2*Math.ceil(R)+1;
imgdata=ctx.createImageData(2*Math.ceil(R)+1,2*Math.ceil(R)+1);
idx=0;
for(i=Math.floor(-R);i<=Math.ceil(R);i++){
x=i+.5;
for(j=Math.floor(-R);j<=Math.ceil(R);j++){
y=j+.5;
if(x*x+y*y<=R*R){
vec=[x,y,Math.sqrt(R*R-x*x-y*y)];
vec=normalize(vec);
b=Math.pow(dot(light,vec),k)+ambient;
intensity=(1-b)*256;
if(intensity<0)intensity=0;
if(intensity>=256)intensity=255;
imgdata.data[idx++]=imgdata.data[idx++]=255-~~(intensity); | 925Draw a sphere
| 10javascript
| l7xcf |
import java.awt.*;
import java.awt.event.*;
import static java.lang.Math.*;
import java.time.LocalTime;
import javax.swing.*;
class Clock extends JPanel {
final float degrees06 = (float) (PI / 30);
final float degrees30 = degrees06 * 5;
final float degrees90 = degrees30 * 3;
final int size = 590;
final int spacing = 40;
final int diameter = size - 2 * spacing;
final int cx = diameter / 2 + spacing;
final int cy = diameter / 2 + spacing;
public Clock() {
setPreferredSize(new Dimension(size, size));
setBackground(Color.white);
new Timer(1000, (ActionEvent e) -> {
repaint();
}).start();
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawFace(g);
final LocalTime time = LocalTime.now();
int hour = time.getHour();
int minute = time.getMinute();
int second = time.getSecond();
float angle = degrees90 - (degrees06 * second);
drawHand(g, angle, diameter / 2 - 30, Color.red);
float minsecs = (minute + second / 60.0F);
angle = degrees90 - (degrees06 * minsecs);
drawHand(g, angle, diameter / 3 + 10, Color.black);
float hourmins = (hour + minsecs / 60.0F);
angle = degrees90 - (degrees30 * hourmins);
drawHand(g, angle, diameter / 4 + 10, Color.black);
}
private void drawFace(Graphics2D g) {
g.setStroke(new BasicStroke(2));
g.setColor(Color.white);
g.fillOval(spacing, spacing, diameter, diameter);
g.setColor(Color.black);
g.drawOval(spacing, spacing, diameter, diameter);
}
private void drawHand(Graphics2D g, float angle, int radius, Color color) {
int x = cx + (int) (radius * cos(angle));
int y = cy - (int) (radius * sin(angle));
g.setColor(color);
g.drawLine(cx, cy, x, y);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Clock");
f.setResizable(false);
f.add(new Clock(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
} | 926Draw a clock
| 9java
| 3vkzg |
class Ball
FLAG = {red: 1, white: 2, blue: 3}
def initialize
@color = FLAG.keys.sample
end
def color
@color
end
def <=>(other)
FLAG[self.color] <=> FLAG[other.color]
end
def inspect
@color
end
end
balls = []
balls = Array.new(8){Ball.new} while balls == balls.sort
puts
puts | 922Dutch national flag problem
| 14ruby
| jw37x |
var sec_old = 0;
function update_clock() {
var t = new Date();
var arms = [t.getHours(), t.getMinutes(), t.getSeconds()];
if (arms[2] == sec_old) return;
sec_old = arms[2];
var c = document.getElementById('clock');
var ctx = c.getContext('2d');
ctx.fillStyle = "rgb(0,200,200)";
ctx.fillRect(0, 0, c.width, c.height);
ctx.fillStyle = "white";
ctx.fillRect(3, 3, c.width - 6, c.height - 6);
ctx.lineCap = 'round';
var orig = { x: c.width / 2, y: c.height / 2 };
arms[1] += arms[2] / 60;
arms[0] += arms[1] / 60;
draw_arm(ctx, orig, arms[0] * 30, c.width/2.5 - 15, c.width / 20, "green");
draw_arm(ctx, orig, arms[1] * 6, c.width/2.2 - 10, c.width / 30, "navy");
draw_arm(ctx, orig, arms[2] * 6, c.width/2.0 - 6, c.width / 100, "maroon");
}
function draw_arm(ctx, orig, deg, len, w, style)
{
ctx.save();
ctx.lineWidth = w;
ctx.lineCap = 'round';
ctx.translate(orig.x, orig.y);
ctx.rotate((deg - 90) * Math.PI / 180);
ctx.strokeStyle = style;
ctx.beginPath();
ctx.moveTo(-len / 10, 0);
ctx.lineTo(len, 0);
ctx.stroke();
ctx.restore();
}
function init_clock() {
var clock = document.createElement('canvas');
clock.width = 100;
clock.height = 100;
clock.id = "clock";
document.body.appendChild(clock);
window.setInterval(update_clock, 200);
} | 926Draw a clock
| 10javascript
| cre9j |
extern crate rand;
use rand::Rng; | 922Dutch national flag problem
| 15rust
| hx6j2 |
object FlagColor extends Enumeration {
type FlagColor = Value
val Red, White, Blue = Value
}
val genBalls = (1 to 10).map(i => FlagColor(scala.util.Random.nextInt(FlagColor.maxId)))
val sortedBalls = genBalls.sorted
val sorted = if (genBalls == sortedBalls) "sorted" else "not sorted"
println(s"Generated balls (${genBalls mkString " "}) are $sorted.")
println(s"Sorted balls (${sortedBalls mkString " "}) are sorted.") | 922Dutch national flag problem
| 16scala
| p09bj |
-- Create and populate tables
CREATE TABLE colours (id INTEGER PRIMARY KEY, name VARCHAR(5));
INSERT INTO colours (id, name) VALUES ( 1, 'red' );
INSERT INTO colours (id, name) VALUES ( 2, 'white');
INSERT INTO colours (id, name) VALUES ( 3, 'blue' );
CREATE TABLE balls ( colour INTEGER REFERENCES colours );
INSERT INTO balls ( colour ) VALUES ( 2 );
INSERT INTO balls ( colour ) VALUES ( 2 );
INSERT INTO balls ( colour ) VALUES ( 3 );
INSERT INTO balls ( colour ) VALUES ( 2 );
INSERT INTO balls ( colour ) VALUES ( 1 );
INSERT INTO balls ( colour ) VALUES ( 3 );
INSERT INTO balls ( colour ) VALUES ( 3 );
INSERT INTO balls ( colour ) VALUES ( 2 );
-- Show the balls are unsorted
SELECT
colours.name
FROM
balls
JOIN colours ON balls.colour = colours.id;
-- Show the balls in dutch flag order
SELECT
colours.name
FROM
balls
JOIN colours ON balls.colour = colours.id
ORDER BY
colours.id;
-- Tidy up
DROP TABLE balls;
DROP TABLE colours; | 922Dutch national flag problem
| 19sql
| ei2au |
null | 925Draw a sphere
| 11kotlin
| d97nz |
null | 926Draw a clock
| 11kotlin
| nmgij |
sub cubLine ($$$$) {
my ($n, $dx, $dy, $cde) = @_;
printf '%*s', $n + 1, substr($cde, 0, 1);
for (my $d = 9 * $dx - 1 ; $d > 0 ; --$d) {
print substr($cde, 1, 1);
}
print substr($cde, 0, 1);
printf "%*s\n", $dy + 1, substr($cde, 2, 1);
}
sub cuboid ($$$) {
my ($dx, $dy, $dz) = @_;
printf "cuboid%d%d%d:\n", $dx, $dy, $dz;
cubLine $dy + 1, $dx, 0, '+-';
for (my $i = 1 ; $i <= $dy ; ++$i) {
cubLine $dy - $i + 1, $dx, $i - 1, '/ |';
}
cubLine 0, $dx, $dy, '+-|';
for (my $i = 4 * $dz - $dy - 2 ; $i > 0 ; --$i) {
cubLine 0, $dx, $dy, '| |';
}
cubLine 0, $dx, $dy, '| +';
for (my $i = 1 ; $i <= $dy ; ++$i) {
cubLine 0, $dx, $dy - $i, '| /';
}
cubLine 0, $dx, 0, "+-\n";
}
cuboid 2, 3, 4;
cuboid 1, 1, 1;
cuboid 6, 2, 1; | 924Draw a cuboid
| 2perl
| 2jslf |
require ("math")
shades = {'.', ':', '!', '*', 'o', 'e', '&', '#', '%', '@'}
function normalize (vec)
len = math.sqrt(vec[1]^2 + vec[2]^2 + vec[3]^2)
return {vec[1]/len, vec[2]/len, vec[3]/len}
end
light = normalize{30, 30, -50}
function dot (vec1, vec2)
d = vec1[1]*vec2[1] + vec1[2]*vec2[2] + vec1[3]*vec2[3]
return d < 0 and -d or 0
end
function draw_sphere (radius, k, ambient)
for i = math.floor(-radius),-math.floor(-radius) do
x = i + .5
local line = ''
for j = math.floor(-2*radius),-math.floor(-2*radius) do
y = j / 2 + .5
if x^2 + y^2 <= radius^2 then
vec = normalize{x, y, math.sqrt(radius^2 - x^2 - y^2)}
b = dot(light,vec) ^ k + ambient
intensity = math.floor ((1 - b) * #shades)
line = line .. (shades[intensity] or shades[1])
else
line = line .. ' '
end
end
print (line)
end
end
draw_sphere (20, 4, 0.1)
draw_sphere (10, 2, 0.4) | 925Draw a sphere
| 1lua
| fcjdp |
Dynamic[ClockGauge[], UpdateInterval -> 1] | 926Draw a clock
| 1lua
| d9rnq |
package main
import (
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"math"
"os"
) | 927Dragon curve
| 0go
| 2jwl7 |
def _pr(t, x, y, z):
txt = '\n'.join(''.join(t[(n,m)] for n in range(3+x+z)).rstrip()
for m in reversed(range(3+y+z)))
return txt
def cuboid(x,y,z):
t = {(n,m):' ' for n in range(3+x+z) for m in range(3+y+z)}
xrow = ['+'] + ['%i'% (i% 10) for i in range(x)] + ['+']
for i,ch in enumerate(xrow):
t[(i,0)] = t[(i,1+y)] = t[(1+z+i,2+y+z)] = ch
if _debug: print(_pr(t, x, y, z))
ycol = ['+'] + ['%i'% (j% 10) for j in range(y)] + ['+']
for j,ch in enumerate(ycol):
t[(0,j)] = t[(x+1,j)] = t[(2+x+z,1+z+j)] = ch
zdepth = ['+'] + ['%i'% (k% 10) for k in range(z)] + ['+']
if _debug: print(_pr(t, x, y, z))
for k,ch in enumerate(zdepth):
t[(k,1+y+k)] = t[(1+x+k,1+y+k)] = t[(1+x+k,k)] = ch
return _pr(t, x, y, z)
_debug = False
if __name__ == '__main__':
for dim in ((2,3,4), (3,4,2), (4,2,3)):
print(% (dim,), cuboid(*dim), sep='\n') | 924Draw a cuboid
| 3python
| vh029 |
import Data.List
import Graphics.Gnuplot.Simple
pl = [[0,0],[0,1]]
r_90 = [[0,1],[-1,0]]
ip :: [Int] -> [Int] -> Int
ip xs = sum . zipWith (*) xs
matmul xss yss = map (\xs -> map (ip xs ). transpose $ yss) xss
vmoot xs = (xs++).map (zipWith (+) lxs). flip matmul r_90.
map (flip (zipWith (-)) lxs) .reverse . init $ xs
where lxs = last xs
dragoncurve = iterate vmoot pl | 927Dragon curve
| 8haskell
| ao61g |
import java.awt.Color;
import java.awt.Graphics;
import java.util.*;
import javax.swing.JFrame;
public class DragonCurve extends JFrame {
private List<Integer> turns;
private double startingAngle, side;
public DragonCurve(int iter) {
super("Dragon Curve");
setBounds(100, 100, 800, 600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
turns = getSequence(iter);
startingAngle = -iter * (Math.PI / 4);
side = 400 / Math.pow(2, iter / 2.);
}
public List<Integer> getSequence(int iterations) {
List<Integer> turnSequence = new ArrayList<Integer>();
for (int i = 0; i < iterations; i++) {
List<Integer> copy = new ArrayList<Integer>(turnSequence);
Collections.reverse(copy);
turnSequence.add(1);
for (Integer turn : copy) {
turnSequence.add(-turn);
}
}
return turnSequence;
}
@Override
public void paint(Graphics g) {
g.setColor(Color.BLACK);
double angle = startingAngle;
int x1 = 230, y1 = 350;
int x2 = x1 + (int) (Math.cos(angle) * side);
int y2 = y1 + (int) (Math.sin(angle) * side);
g.drawLine(x1, y1, x2, y2);
x1 = x2;
y1 = y2;
for (Integer turn : turns) {
angle += turn * (Math.PI / 2);
x2 = x1 + (int) (Math.cos(angle) * side);
y2 = y1 + (int) (Math.sin(angle) * side);
g.drawLine(x1, y1, x2, y2);
x1 = x2;
y1 = y2;
}
}
public static void main(String[] args) {
new DragonCurve(14).setVisible(true);
}
} | 927Dragon curve
| 9java
| jwn7c |
use utf8;
binmode STDOUT, ':utf8';
$|++;
my ($rows, $cols) = split /\s+/, `stty size`;
my $x = int($rows / 2 - 1);
my $y = int($cols / 2 - 16);
my @chars = map {[ /(...)/g ]}
(" ",
" : ",
" ");
while (1) {
my @indices = map { ord($_) - ord('0') } split //,
sprintf("%02d:%02d:%02d", (localtime(time))[2,1,0]);
clear();
for (0 .. $
position($x + $_, $y);
print "@{$chars[$_]}[@indices]";
}
position(1, 1);
sleep 1;
}
sub clear { print "\e[H\e[J" }
sub position { printf "\e[%d;%dH", shift, shift } | 926Draw a clock
| 2perl
| 7enrh |
var DRAGON = (function () { | 927Dragon curve
| 10javascript
| 183p7 |
X, Y, Z = 6, 2, 3
DIR = { => [1,0], => [0,1], => [1,1]}
def cuboid(nx, ny, nz)
puts % [nx, ny, nz]
x, y, z = X*nx, Y*ny, Z*nz
area = Array.new(y+z+1){ * (x+y+1)}
draw_line = lambda do |n, sx, sy, c|
dx, dy = DIR[c]
(n+1).times do |i|
xi, yi = sx+i*dx, sy+i*dy
area[yi][xi] = (area[yi][xi]==? c: )
end
end
nz .times {|i| draw_line[x, 0, Z*i, ]}
(ny+1).times {|i| draw_line[x, Y*i, z+Y*i, ]}
nx .times {|i| draw_line[z, X*i, 0, ]}
(ny+1).times {|i| draw_line[z, x+Y*i, Y*i, ]}
nz .times {|i| draw_line[y, x, Z*i, ]}
(nx+1).times {|i| draw_line[y, X*i, z, ]}
puts area.reverse
end
cuboid(2, 3, 4)
cuboid(1, 1, 1)
cuboid(6, 2, 1)
cuboid(2, 4, 1) | 924Draw a cuboid
| 14ruby
| 5bouj |
use strict;
use warnings;
my $x = my $y = 255;
$x |= 1;
my $depth = 255;
my $light = Vector->new(rand, rand, rand)->normalized;
print "P2\n$x $y\n$depth\n";
my ($r, $ambient) = (($x - 1)/2, 0);
my ($r2) = $r ** 2;
{
for my $x (-$r .. $r) {
my $x2 = $x**2;
for my $y (-$r .. $r) {
my $y2 = $y**2;
my $pixel = 0;
if ($x2 + $y2 < $r2) {
my $v = Vector->new($x, $y, sqrt($r2 - $x2 - $y2))->normalized;
my $I = $light . $v + $ambient;
$I = $I < 0 ? 0 : $I > 1 ? 1 : $I;
$pixel = int($I * $depth);
}
print $pixel;
print $y == $r ? "\n" : " ";
}
}
}
package Vector {
sub new {
my $class = shift;
bless ref($_[0]) eq 'Array' ? $_[0] : [ @_ ], $class;
}
sub normalized {
my $this = shift;
my $norm = sqrt($this . $this);
ref($this)->new( map $_/$norm, @$this );
}
use overload q{.} => sub {
my ($a, $b) = @_;
my $sum = 0;
for (0 .. @$a - 1) {
$sum += $a->[$_] * $b->[$_]
}
return $sum;
},
q{""} => sub { sprintf "Vector:[%s]", join ' ', @{shift()} };
} | 925Draw a sphere
| 2perl
| jwf7f |
import java.awt._
import java.awt.event.{MouseAdapter, MouseEvent}
import javax.swing._
import scala.math.{Pi, cos, sin}
object Cuboid extends App {
SwingUtilities.invokeLater(() => {
class Cuboid extends JPanel {
private val nodes: Array[Array[Double]] =
Array(Array(-1, -1, -1), Array(-1, -1, 1), Array(-1, 1, -1), Array(-1, 1, 1),
Array(1, -1, -1), Array(1, -1, 1), Array(1, 1, -1), Array(1, 1, 1))
private var mouseX, prevMouseX, mouseY, prevMouseY: Int = _
private def edges =
Seq(Seq(0, 1), Seq(1, 3), Seq(3, 2), Seq(2, 0),
Seq(4, 5), Seq(5, 7), Seq(7, 6), Seq(6, 4),
Seq(0, 4), Seq(1, 5), Seq(2, 6), Seq(3, 7))
override def paintComponent(gg: Graphics): Unit = {
val g = gg.asInstanceOf[Graphics2D]
def drawCube(g: Graphics2D): Unit = {
g.translate(getWidth / 2, getHeight / 2)
for (edge <- edges) {
g.drawLine(nodes(edge.head)(0).round.toInt, nodes(edge.head)(1).round.toInt,
nodes(edge(1))(0).round.toInt, nodes(edge(1))(1).round.toInt)
}
for (node <- nodes) g.fillOval(node(0).round.toInt - 4, node(1).round.toInt - 4, 8, 8)
}
super.paintComponent(gg)
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
drawCube(g)
}
private def scale(sx: Double, sy: Double, sz: Double): Unit = {
for (node <- nodes) {
node(0) *= sx
node(1) *= sy
node(2) *= sz
}
}
private def rotateCube(angleX: Double, angleY: Double): Unit = {
val (sinX, cosX, sinY, cosY) = (sin(angleX), cos(angleX), sin(angleY), cos(angleY))
for (node <- nodes) {
val (x, y, z) = (node.head, node(1), node(2))
node(0) = x * cosX - z * sinX
node(2) = z * cosX + x * sinX
node(1) = y * cosY - node(2) * sinY
node(2) = node(2) * cosY + y * sinY
}
}
addMouseListener(new MouseAdapter() {
override def mousePressed(e: MouseEvent): Unit = {
mouseX = e.getX
mouseY = e.getY
}
})
addMouseMotionListener(new MouseAdapter() {
override def mouseDragged(e: MouseEvent): Unit = {
prevMouseX = mouseX
prevMouseY = mouseY
mouseX = e.getX
mouseY = e.getY
rotateCube((mouseX - prevMouseX) * 0.01, (mouseY - prevMouseY) * 0.01)
repaint()
}
})
scale(80, 120, 160)
rotateCube(Pi / 5, Pi / 9)
setPreferredSize(new Dimension(640, 640))
setBackground(Color.white)
}
new JFrame("Cuboid") {
add(new Cuboid, BorderLayout.CENTER)
pack()
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
setLocationRelativeTo(null)
setResizable(false)
setVisible(true)
}
})
} | 924Draw a cuboid
| 16scala
| 7efr9 |
null | 927Dragon curve
| 11kotlin
| 5bsua |
import time
def chunks(l, n=5):
return [l[i:i+n] for i in range(0, len(l), n)]
def binary(n, digits=8):
n=int(n)
return '{0:0{1}b}'.format(n, digits)
def secs(n):
n=int(n)
h='x' * n
return .join(chunks(h))
def bin_bit(h):
h=h.replace(,)
h=h.replace(,)
return .join(list(h))
x=str(time.ctime()).split()
y=x[3].split()
s=y[-1]
y=map(binary,y[:-1])
print bin_bit(y[0])
print
print bin_bit(y[1])
print
print secs(s) | 926Draw a clock
| 3python
| jwd7p |
function dragon()
local l = "l"
local r = "r"
local inverse = {l = r, r = l}
local field = {r}
local num = 1
local loop_limit = 6 | 927Dragon curve
| 1lua
| 4p05c |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.