code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
struct DisjointSublistView<T>: MutableCollectionType {
let array: UnsafeMutablePointer<T>
let indexes: [Int]
subscript (position: Int) -> T {
get {
return array[indexes[position]]
}
set {
array[indexes[position]] = newValue
}
}
var startIndex: Int { return 0 }
var endIndex: Int { return indexes.count }
func generate() -> IndexingGenerator<DisjointSublistView<T>> { return IndexingGenerator(self) }
}
func sortDisjointSublist<T: Comparable>(inout array: [T], indexes: [Int]) {
var d = DisjointSublistView(array: &array, indexes: sorted(indexes))
sort(&d)
}
var a = [7, 6, 5, 4, 3, 2, 1, 0]
let ind = [6, 1, 7]
sortDisjointSublist(&a, ind)
println(a) | 247Sort disjoint sublist
| 17swift
| dw0nh |
require 'socket'
sock = TCPSocket.open(, 256)
sock.write()
sock.close | 258Sockets
| 14ruby
| r9fgs |
class Hidato
Cell = Struct.new(:value, :used, :adj)
ADJUST = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]]
def initialize(board, pout=true)
@board = []
board.each_line do |line|
@board << line.split.map{|n| Cell[Integer(n), false] rescue nil} + [nil]
end
@board << []
@board.each_with_index do |row, x|
row.each_with_index do |cell, y|
if cell
@sx, @sy = x, y if cell.value==1
cell.adj = ADJUST.map{|dx,dy| [x+dx,y+dy]}.select{|xx,yy| @board[xx][yy]}
end
end
end
@xmax = @board.size - 1
@ymax = @board.map(&:size).max - 1
@end = @board.flatten.compact.size
puts to_s('Problem:') if pout
end
def solve
@zbl = Array.new(@end+1, false)
@board.flatten.compact.each{|cell| @zbl[cell.value] = true}
puts (try(@board[@sx][@sy], 1)? to_s('Solution:'): )
end
def try(cell, seq_num)
return true if seq_num > @end
return false if cell.used
value = cell.value
return false if value > 0 and value!= seq_num
return false if value == 0 and @zbl[seq_num]
cell.used = true
cell.adj.each do |x, y|
if try(@board[x][y], seq_num+1)
cell.value = seq_num
return true
end
end
cell.used = false
end
def to_s(msg=nil)
str = (0...@xmax).map do |x|
(0...@ymax).map{|y| % ((c=@board[x][y])? c.value: c)}.join
end
(msg? [msg]: []) + str + []
end
end | 261Solve a Hidato puzzle
| 14ruby
| tqjf2 |
use std::io::prelude::*;
use std::net::TcpStream;
fn main() { | 258Sockets
| 15rust
| 7ctrc |
import java.net.Socket
object sendSocketData {
def sendData(host: String, msg: String) {
val sock = new Socket(host, 256)
sock.getOutputStream().write(msg.getBytes())
sock.getOutputStream().flush()
sock.close()
}
sendData("localhost", "hello socket world")
} | 258Sockets
| 16scala
| kv6hk |
use std::cmp::{max, min};
use std::fmt;
use std::ops;
#[derive(Debug, Clone, PartialEq)]
struct Board {
cells: Vec<Vec<Option<u32>>>,
}
impl Board {
fn new(initial_board: Vec<Vec<u32>>) -> Self {
let b = initial_board
.iter()
.map(|r| {
r.iter()
.map(|c| if *c == u32::MAX { None } else { Some(*c) })
.collect()
})
.collect();
Board { cells: b }
}
fn height(&self) -> usize {
self.cells.len()
}
fn width(&self) -> usize {
self.cells[0].len()
}
}
impl ops::Index<(usize, usize)> for Board {
type Output = Option<u32>;
fn index(&self, (y, x): (usize, usize)) -> &Self::Output {
&self.cells[y][x]
}
}
impl ops::IndexMut<(usize, usize)> for Board { | 261Solve a Hidato puzzle
| 15rust
| zshto |
people = [('joe', 120), ('foo', 31), ('bar', 51)]
sorted(people) | 255Sort an array of composite structures
| 3python
| 4yt5k |
sortbyname <- function(x, ...) x[order(names(x), ...)]
x <- c(texas=68.9, ohio=87.8, california=76.2, "new york"=88.2)
sortbyname(x) | 255Sort an array of composite structures
| 13r
| 2tilg |
extension Collection where Element: Comparable {
public func cocktailSorted() -> [Element] {
var swapped = false
var ret = Array(self)
guard count > 1 else {
return ret
}
repeat {
for i in 0...ret.count-2 where ret[i] > ret[i + 1] {
(ret[i], ret[i + 1]) = (ret[i + 1], ret[i])
swapped = true
}
guard swapped else {
break
}
swapped = false
for i in stride(from: ret.count - 2, through: 0, by: -1) where ret[i] > ret[i + 1] {
(ret[i], ret[i + 1]) = (ret[i + 1], ret[i])
swapped = true
}
} while swapped
return ret
}
}
let arr = (1...10).shuffled()
print("Before: \(arr)")
print("Cocktail sort: \(arr.cocktailSorted())") | 240Sorting algorithms/Cocktail sort
| 17swift
| u6gvg |
use ntheory qw/:all/;
my @smith;
forcomposites {
push @smith, $_ if sumdigits($_) == sumdigits(join("",factor($_)));
} 10000-1;
say scalar(@smith), " Smith numbers below 10000.";
say "@smith"; | 263Smith numbers
| 2perl
| skcq3 |
@nums = (2,4,3,1,2);
@sorted = sort {$a <=> $b} @nums; | 252Sort an integer array
| 2perl
| w7re6 |
Person = Struct.new(:name,:value) do
def to_s; end
end
list = [Person.new(,3),
Person.new(,4),
Person.new(,20),
Person.new(,3)]
puts list.sort_by{|x|x.name}
puts
puts list.sort_by(&:value) | 255Sort an array of composite structures
| 14ruby
| r93gs |
use std::cmp::Ordering;
#[derive(Debug)]
struct Employee {
name: String,
category: String,
}
impl Employee {
fn new(name: &str, category: &str) -> Self {
Employee {
name: name.into(),
category: category.into(),
}
}
}
impl PartialEq for Employee {
fn eq(&self, other: &Self) -> bool {
self.name == other.name
}
}
impl Eq for Employee {}
impl PartialOrd for Employee {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Employee {
fn cmp(&self, other: &Self) -> Ordering {
self.name.cmp(&other.name)
}
}
fn main() {
let mut employees = vec![
Employee::new("David", "Manager"),
Employee::new("Alice", "Sales"),
Employee::new("Joanna", "Director"),
Employee::new("Henry", "Admin"),
Employee::new("Tim", "Sales"),
Employee::new("Juan", "Admin"),
];
employees.sort();
for e in employees {
println!("{:<6}: {}", e.name, e.category);
}
} | 255Sort an array of composite structures
| 15rust
| 7c6rc |
<?php
$nums = array(2,4,3,1,2);
sort($nums);
?> | 252Sort an integer array
| 12php
| lfdcj |
case class Pair(name:String, value:Double)
val input = Array(Pair("Krypton", 83.798), Pair("Beryllium", 9.012182), Pair("Silicon", 28.0855))
input.sortBy(_.name) | 255Sort an array of composite structures
| 16scala
| kv9hk |
from sys import stdout
def factors(n):
rt = []
f = 2
if n == 1:
rt.append(1);
else:
while 1:
if 0 == ( n% f ):
rt.append(f);
n
if n == 1:
return rt
else:
f += 1
return rt
def sum_digits(n):
sum = 0
while n > 0:
m = n% 10
sum += m
n -= m
n
return sum
def add_all_digits(lst):
sum = 0
for i in range (len(lst)):
sum += sum_digits(lst[i])
return sum
def list_smith_numbers(cnt):
for i in range(4, cnt):
fac = factors(i)
if len(fac) > 1:
if sum_digits(i) == add_all_digits(fac):
stdout.write(.format(i) )
list_smith_numbers(10_000) | 263Smith numbers
| 3python
| 0blsq |
-- setup
CREATE TABLE pairs (name VARCHAR(16), VALUE VARCHAR(16));
INSERT INTO pairs VALUES ('Fluffy', 'cat');
INSERT INTO pairs VALUES ('Fido', 'dog');
INSERT INTO pairs VALUES ('Francis', 'fish');
-- order them by name
SELECT * FROM pairs ORDER BY name; | 255Sort an array of composite structures
| 19sql
| 142pg |
extension Sequence {
func sorted<Value>(
on: KeyPath<Element, Value>,
using: (Value, Value) -> Bool
) -> [Element] where Value: Comparable {
return withoutActuallyEscaping(using, do: {using -> [Element] in
return self.sorted(by: { using($0[keyPath: on], $1[keyPath: on]) })
})
}
}
struct Person {
var name: String
var role: String
}
let a = Person(name: "alice", role: "manager")
let b = Person(name: "bob", role: "worker")
let c = Person(name: "charlie", role: "driver")
print([c, b, a].sorted(on: \.name, using: <)) | 255Sort an array of composite structures
| 17swift
| gmz49 |
require
class Integer
def smith?
return false if prime?
digits.sum == prime_division.map{|pr,n| pr.digits.sum * n}.sum
end
end
n = 10_000
res = 1.upto(n).select(&:smith?)
puts , , | 263Smith numbers
| 14ruby
| o1v8v |
nums = [2,4,3,1,2]
nums.sort() | 252Sort an integer array
| 3python
| xj7wr |
fn main () { | 263Smith numbers
| 15rust
| iauod |
object SmithNumbers extends App {
def sumDigits(_n: Int): Int = {
var n = _n
var sum = 0
while (n > 0) {
sum += (n % 10)
n /= 10
}
sum
}
def primeFactors(_n: Int): List[Int] = {
var n = _n
val result = new collection.mutable.ListBuffer[Int]
val i = 2
while (n % i == 0) {
result += i
n /= i
}
var j = 3
while (j * j <= n) {
while (n % j == 0) {
result += i
n /= j
}
j += 2
}
if (n != 1) result += n
result.toList
}
for (n <- 1 until 10000) {
val factors = primeFactors(n)
if (factors.size > 1) {
var sum = sumDigits(n)
for (f <- factors) sum -= sumDigits(f)
if (sum == 0) println(n)
}
}
} | 263Smith numbers
| 16scala
| fxgd4 |
nums <- c(2,4,3,1,2)
sorted <- sort(nums) | 252Sort an integer array
| 13r
| 145pn |
extension BinaryInteger {
@inlinable
public var isSmith: Bool {
guard self > 3 else {
return false
}
let primeFactors = primeDecomposition()
guard primeFactors.count!= 1 else {
return false
}
return primeFactors.map({ $0.sumDigits() }).reduce(0, +) == sumDigits()
}
@inlinable
public func primeDecomposition() -> [Self] {
guard self > 1 else { return [] }
func step(_ x: Self) -> Self {
return 1 + (x << 2) - ((x >> 1) << 1)
}
let maxQ = Self(Double(self).squareRoot())
var d: Self = 1
var q: Self = self & 1 == 0? 2: 3
while q <= maxQ && self% q!= 0 {
q = step(d)
d += 1
}
return q <= maxQ? [q] + (self / q).primeDecomposition(): [self]
}
@inlinable
public func sumDigits() -> Self {
return String(self).lazy.map({ Self(Int(String($0))!) }).reduce(0, +)
}
}
let smiths = (0..<10_000).filter({ $0.isSmith })
print("Num Smith numbers below 10,000: \(smiths.count)")
print("First 10 smith numbers: \(Array(smiths.prefix(10)))")
print("Last 10 smith numbers below 10,000: \(Array(smiths.suffix(10)))") | 263Smith numbers
| 17swift
| 8p20v |
nums = [2,4,3,1,2]
sorted = nums.sort
p sorted
p nums
nums.sort!
p nums | 252Sort an integer array
| 14ruby
| skhqw |
fn main() {
let mut a = vec!(9, 8, 7, 6, 5, 4, 3, 2, 1, 0);
a.sort();
println!("{:?}", a);
} | 252Sort an integer array
| 15rust
| 0bksl |
import scala.compat.Platform
object Sort_an_integer_array extends App {
val array = Array((for (i <- 0 to 10) yield scala.util.Random.nextInt()):
_* )
def isSorted[T](arr: Array[T]) = array.sliding(2).forall(pair => pair(0) <= pair(1))
assert(!isSorted(array), "Not random")
scala.util.Sorting.quickSort(array)
assert(isSorted(array), "Not sorted")
println(s"Array in sorted order.\nSuccessfully completed without errors. [total ${Platform.currentTime - executionStart} ms]")
} | 252Sort an integer array
| 16scala
| ia1ox |
var nums = [2, 4, 3, 1, 2]
nums.sortInPlace()
print(nums) | 252Sort an integer array
| 17swift
| qhjxg |
extern void JumpOverTheDog( int numberOfTimes);
extern int PlayFetchWithDog( float weightOfStick); | 264Singleton
| 5c
| xjywu |
sub bubble_sort {
for my $i (0 .. $
for my $j ($i + 1 .. $
$_[$j] < $_[$i] and @_[$i, $j] = @_[$j, $i];
}
}
} | 246Sorting algorithms/Bubble sort
| 2perl
| dw8nw |
function bubbleSort(array $array){
foreach($array as $i => &$val){
foreach($array as $k => &$val2){
if($k <= $i)
continue;
if($val > $val2) {
list($val, $val2) = [$val2, $val];
break;
}
}
}
return $array;
} | 246Sorting algorithms/Bubble sort
| 12php
| jl47z |
package main
import (
"log"
"math/rand"
"sync"
"time"
)
var (
instance string
once sync.Once | 264Singleton
| 0go
| lf1cw |
def bubble_sort(seq):
changed = True
while changed:
changed = False
for i in range(len(seq) - 1):
if seq[i] > seq[i+1]:
seq[i], seq[i+1] = seq[i+1], seq[i]
changed = True
return seq
if __name__ == :
from random import shuffle
testset = [_ for _ in range(100)]
testcase = testset.copy()
shuffle(testcase)
assert testcase != testset
bubble_sort(testcase)
assert testcase == testset | 246Sorting algorithms/Bubble sort
| 3python
| fxode |
@Singleton
class SingletonClass {
def invokeMe() {
println 'invoking method of a singleton class'
}
static void main(def args) {
SingletonClass.instance.invokeMe()
}
} | 264Singleton
| 7groovy
| 68j3o |
class Singleton
{
private static Singleton myInstance;
public static Singleton getInstance()
{
if (myInstance == null)
{
synchronized(Singleton.class)
{
if (myInstance == null)
{
myInstance = new Singleton();
}
}
}
return myInstance;
}
protected Singleton()
{ | 264Singleton
| 9java
| 7c8rj |
function Singleton() {
if(Singleton._instance) return Singleton._instance;
this.set("");
Singleton._instance = this;
}
Singleton.prototype.set = function(msg) { this.msg = msg; }
Singleton.prototype.append = function(msg) { this.msg += msg; }
Singleton.prototype.get = function() { return this.msg; }
var a = new Singleton();
var b = new Singleton();
var c = new Singleton();
a.set("Hello");
b.append(" World");
c.append("!!!");
document.write( (new Singleton()).get() ); | 264Singleton
| 10javascript
| p5fb7 |
bubbleSort <- function(items)
{
repeat
{
if((itemCount <- length(items)) <= 1) return(items)
hasChanged <- FALSE
itemCount <- itemCount - 1
for(i in seq_len(itemCount))
{
if(items[i] > items[i + 1])
{
items[c(i, i + 1)] <- items[c(i + 1, i)]
hasChanged <- TRUE
}
}
if(!hasChanged) break
}
items
}
ints <- c(1, 10, 2, 5, -1, 5, -19, 4, 23, 0)
numerics <- c(1, -3.2, 5.2, 10.8, -5.7, 7.3, 3.5, 0, -4.1, -9.5)
strings <- c("We", "hold", "these", "truths", "to", "be", "self-evident", "that", "all", "men", "are", "created", "equal") | 246Sorting algorithms/Bubble sort
| 13r
| o1q84 |
null | 264Singleton
| 11kotlin
| u3wvc |
int main()
{
int maxX = GetSystemMetrics(SM_CXSCREEN), maxY = GetSystemMetrics(SM_CYSCREEN);
int x = maxX/2, y = maxY/2;
double factorX = 65536.0 / maxX,factorY = 65536.0 / maxY;
INPUT ip;
ZeroMemory(&ip,sizeof(ip));
ip.type = INPUT_MOUSE;
while(x > 5 || y < maxY-5){
ip.mi.mouseData = 0;
ip.mi.dx = x * factorX;
ip.mi.dy = y * factorY;
ip.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE;
SendInput(1,&ip,sizeof(ip));
Sleep(1);
if(x>3)
x-=1;
if(y<maxY-3)
y+=1;
}
ip.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP;
SendInput(1,&ip,sizeof(ip));
return 0;
} | 265Simulate input/Mouse
| 5c
| yoj6f |
gcc -o simkeypress -L/usr/X11R6/lib -lX11 simkeypress.c | 266Simulate input/Keyboard
| 5c
| vz12o |
(import java.awt.Robot)
(import java.awt.event.KeyEvent)
(defn keytype [str]
(let [robot (new Robot)]
(doseq [ch str]
(if (Character/isUpperCase ch)
(doto robot
(.keyPress (. KeyEvent VK_SHIFT))
(.keyPress (int ch))
(.keyRelease (int ch))
(.keyRelease (. KeyEvent VK_SHIFT)))
(let [upCh (Character/toUpperCase ch)]
(doto robot
(.keyPress (int upCh))
(.keyRelease (int upCh)))))))) | 266Simulate input/Keyboard
| 6clojure
| r9qg2 |
class Array
def bubblesort1!
length.times do |j|
for i in 1...(length - j)
if self[i] < self[i - 1]
self[i], self[i - 1] = self[i - 1], self[i]
end
end
end
self
end
def bubblesort2!
each_index do |index|
(length - 1).downto( index ) do |i|
self[i-1], self[i] = self[i], self[i-1] if self[i-1] < self[i]
end
end
self
end
end
ary = [3, 78, 4, 23, 6, 8, 6]
ary.bubblesort1!
p ary | 246Sorting algorithms/Bubble sort
| 14ruby
| zsntw |
package main
import (
"github.com/micmonay/keybd_event"
"log"
"runtime"
"time"
)
func main() {
kb, err := keybd_event.NewKeyBonding()
if err != nil {
log.Fatal(err)
} | 266Simulate input/Keyboard
| 0go
| skyqa |
package Singleton;
use strict;
use warnings;
my $Instance;
sub new {
my $class = shift;
$Instance ||= bless {}, $class;
}
sub name {
my $self = shift;
$self->{name};
}
sub set_name {
my ($self, $name) = @_;
$self->{name} = $name;
}
package main;
my $s1 = Singleton->new;
$s1->set_name('Bob');
printf "name:%s, ref:%s\n", $s1->name, $s1;
my $s2 = Singleton->new;
printf "name:%s, ref:%s\n", $s2->name, $s2; | 264Singleton
| 2perl
| 8pl0w |
import java.awt.Robot
public static void type(String str){
Robot robot = new Robot();
for(char ch:str.toCharArray()){
if(Character.isUpperCase(ch)){
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress((int)ch);
robot.keyRelease((int)ch);
robot.keyRelease(KeyEvent.VK_SHIFT);
}else{
char upCh = Character.toUpperCase(ch);
robot.keyPress((int)upCh);
robot.keyRelease((int)upCh);
}
}
} | 266Simulate input/Keyboard
| 9java
| tq5f9 |
package main
import "github.com/go-vgo/robotgo"
func main() {
robotgo.MouseClick("left", false) | 265Simulate input/Mouse
| 0go
| 14fp5 |
fn bubble_sort<T: Ord>(values: &mut[T]) {
let mut n = values.len();
let mut swapped = true;
while swapped {
swapped = false;
for i in 1..n {
if values[i - 1] > values[i] {
values.swap(i - 1, i);
swapped = true;
}
}
n = n - 1;
}
}
fn main() { | 246Sorting algorithms/Bubble sort
| 15rust
| 30dz8 |
class Singleton {
protected static $instance = null;
public $test_var;
private function __construct(){
}
public static function getInstance(){
if (is_null(self::$instance)){
self::$instance = new self();
}
return self::$instance;
}
}
$foo = Singleton::getInstance();
$foo->test_var = 'One';
$bar = Singleton::getInstance();
echo $bar->test_var;
$fail = new Singleton(); | 264Singleton
| 12php
| 4yq5n |
null | 266Simulate input/Keyboard
| 11kotlin
| o1c8z |
Point p = component.getLocation();
Robot robot = new Robot();
robot.mouseMove(p.getX(), p.getY()); | 265Simulate input/Mouse
| 9java
| 8pc06 |
null | 265Simulate input/Mouse
| 11kotlin
| w73ek |
def bubbleSort[T](arr: Array[T])(implicit o: Ordering[T]) {
import o._
val consecutiveIndices = (arr.indices, arr.indices drop 1).zipped
var hasChanged = true
do {
hasChanged = false
consecutiveIndices foreach { (i1, i2) =>
if (arr(i1) > arr(i2)) {
hasChanged = true
val tmp = arr(i1)
arr(i1) = arr(i2)
arr(i2) = tmp
}
}
} while(hasChanged)
} | 246Sorting algorithms/Bubble sort
| 16scala
| mizyc |
>>> class Borg(object):
__state = {}
def __init__(self):
self.__dict__ = self.__state
>>> b1 = Borg()
>>> b2 = Borg()
>>> b1 is b2
False
>>> b1.datum = range(5)
>>> b1.datum
[0, 1, 2, 3, 4]
>>> b2.datum
[0, 1, 2, 3, 4]
>>> b1.datum is b2.datum
True
>>> | 264Singleton
| 3python
| o1281 |
$target = "/dev/pts/51";
$TIOCSTI = 0x5412 ;
open(TTY,">$target") or die "cannot open $target" ;
$b="sleep 99334 &\015";
@c=split("",$b);
sleep(2);
foreach $a ( @c ) { ioctl(TTY,$TIOCSTI,$a); select(undef,undef,undef,0.1);} ;
print "DONE\n"; | 266Simulate input/Keyboard
| 2perl
| gmx4e |
require 'singleton'
class MySingleton
include Singleton
end
a = MySingleton.instance
b = MySingleton.instance
puts a.equal?(b) | 264Singleton
| 14ruby
| neuit |
object Singleton { | 264Singleton
| 16scala
| zsrtr |
import ctypes
def click():
ctypes.windll.user32.mouse_event(0x2, 0,0,0,0)
ctypes.windll.user32.mouse_event(0x4, 0,0,0,0)
click() | 265Simulate input/Mouse
| 3python
| 2t1lz |
import autopy
autopy.key.type_string()
autopy.key.type_string(, wpm=60)
autopy.key.tap(autopy.key.Code.RETURN)
autopy.key.tap(autopy.key.Code.F1)
autopy.key.tap(autopy.key.Code.LEFT_ARROW) | 266Simulate input/Keyboard
| 3python
| r9qgq |
use strict;
use warnings;
use Tk;
use List::Util qw( max );
my $c;
my $pen = 1;
my @location = (0, 0);
my $direction = 0;
my @stack;
my $radian = 180 / atan2 0, -1;
sub dsin { sin $_[0] / $radian }
sub dcos { cos $_[0] / $radian }
sub save { push @stack, [ $direction, @location ] }
sub restore { ($direction, @location) = @{ pop @stack } }
sub turn { $direction += shift }
sub right { turn shift }
sub left { turn -shift }
sub forward
{
my $x = $location[0] + $_[0] * dcos $direction;
my $y = $location[1] + $_[0] * dsin $direction;
$pen and $c->createLine( @location, $x, $y, -width => 3 );
@location = ($x, $y);
}
sub back { turn 180; forward shift; turn 180 }
sub penup { $pen = 0 }
sub pendown { $pen = 1 }
sub text { $c->createText( @location, -text => shift ) }
my $mw = MainWindow->new;
$c = $mw->Canvas(
-width => 900, -height => 900,
)->pack;
$mw->Button(-text => 'Exit', -command => sub {$mw->destroy},
)->pack(-fill => 'x');
$mw->after(0, \&run);
MainLoop;
-M $0 < 0 and exec $0;
sub box
{
my ($w, $h) = @_;
for (1 .. 2)
{
forward $w;
left 90;
forward $h;
left 90;
}
}
sub house
{
my $size = shift;
box $size, $size;
right 90;
for ( 1 .. 3 )
{
right 120;
forward $size;
}
penup;
left 90;
forward $size;
left 90;
save;
forward $size * 1 / 4;
pendown;
box $size / 4, $size / 2;
penup;
forward $size * 3 / 8;
left 90;
forward $size / 4;
right 90;
pendown;
box $size / 4, $size / 4;
penup;
restore;
save;
forward $size / 2;
left 90;
forward $size + 40;
right 90;
pendown;
for (1 .. 8)
{
forward 15;
left 45;
forward 15;
}
restore;
penup;
}
sub graph
{
save;
my $size = shift;
my $width = $size / @_;
my $hscale = $size / max @_;
for ( @_ )
{
box $width, $hscale * $_;
save;
penup;
forward $width / 2;
left 90;
forward 10;
text $_;
pendown;
restore;
forward $width;
}
restore;
}
sub run
{
penup;
forward 50;
right 90;
forward 400;
pendown;
house(300);
penup;
forward 400;
pendown;
graph( 400, 2,7,4,5,1,8,6 );
} | 267Simple turtle graphics
| 2perl
| r9xgd |
from turtle import *
def rectangle(width, height):
for _ in range(2):
forward(height)
left(90)
forward(width)
left(90)
def square(size):
rectangle(size, size)
def triangle(size):
for _ in range(3):
forward(size)
right(120)
def house(size):
right(180)
square(size)
triangle(size)
right(180)
def barchart(lst, size):
scale = size/max(lst)
width = size/len(lst)
for i in lst:
rectangle(i*scale, width)
penup()
forward(width)
pendown()
penup()
back(size)
pendown()
clearscreen()
hideturtle()
house(150)
penup()
forward(10)
pendown()
barchart([0.5, (1/3), 2, 1.3, 0.5], 200)
penup()
back(10)
pendown() | 267Simple turtle graphics
| 3python
| 7cqrm |
extern crate autopilot;
extern crate rand;
use rand::Rng; | 265Simulate input/Mouse
| 15rust
| 56wuq |
class SingletonClass {
static let sharedInstance = SingletonClass() | 264Singleton
| 17swift
| iavo0 |
extern crate autopilot;
fn main() {
autopilot::key::type_string("Hello, world!", None, None, &[]);
} | 266Simulate input/Keyboard
| 15rust
| h28j2 |
val (p , robot)= (component.location, new Robot())
robot.mouseMove(p.getX().toInt, p.getY().toInt) | 265Simulate input/Mouse
| 16scala
| r9sgn |
import java.awt.Robot
import java.awt.event.KeyEvent
object Keystrokes extends App {
def keystroke(str: String) {
val robot = new Robot()
for (ch <- str) {
if (Character.isUpperCase(ch)) {
robot.keyPress(KeyEvent.VK_SHIFT)
robot.keyPress(ch)
robot.keyRelease(ch)
robot.keyRelease(KeyEvent.VK_SHIFT)
} else {
val upCh = Character.toUpperCase(ch)
robot.keyPress(upCh)
robot.keyRelease(upCh)
}
}
}
keystroke(args(0))
} | 266Simulate input/Keyboard
| 16scala
| p5nbj |
struct link {
struct link *next;
int data;
}; | 268Singly-linked list/Element definition
| 5c
| gme45 |
(cons 1 (cons 2 (cons 3 nil))) | 268Singly-linked list/Element definition
| 6clojure
| kv0hs |
struct link *first;
struct link *iter;
for(iter = first; iter != NULL; iter = iter->next) {
} | 269Singly-linked list/Traversal
| 5c
| 2thlo |
(doseq [x xs] (println x)) | 269Singly-linked list/Traversal
| 6clojure
| gma4f |
void insert_append (struct link *anchor, struct link *newlink) {
newlink->next = anchor->next;
anchor->next = newlink;
} | 270Singly-linked list/Element insertion
| 5c
| nemi6 |
func bubbleSort<T:Comparable>(list:inout[T]) {
var done = false
while!done {
done = true
for i in 1..<list.count {
if list[i - 1] > list[i] {
(list[i], list[i - 1]) = (list[i - 1], list[i])
done = false
}
}
}
}
var list1 = [3, 1, 7, 5, 2, 5, 3, 8, 4]
print(list1)
bubbleSort(list: &list1)
print(list1) | 246Sorting algorithms/Bubble sort
| 17swift
| tqifl |
(defn insert-after [new old ls]
(cond (empty? ls) ls
(= (first ls) old) (cons old (cons new (rest ls)))
:else (cons (first ls) (insert-after new old (rest ls))))) | 270Singly-linked list/Element insertion
| 6clojure
| 30vzr |
type Ele struct {
Data interface{}
Next *Ele
}
func (e *Ele) Append(data interface{}) *Ele {
if e.Next == nil {
e.Next = &Ele{data, nil}
} else {
tmp := &Ele{data, e.Next}
e.Next = tmp
}
return e.Next
}
func (e *Ele) String() string {
return fmt.Sprintf("Ele:%v", e.Data)
} | 268Singly-linked list/Element definition
| 0go
| ia9og |
class ListNode {
Object payload
ListNode next
String toString() { "${payload} -> ${next}" }
} | 268Singly-linked list/Element definition
| 7groovy
| qhzxp |
int main()
{
unsigned int seconds;
scanf(, &seconds);
printf();
sleep(seconds);
printf();
return 0;
} | 271Sleep
| 5c
| jle70 |
data List a = Nil | Cons a (List a) | 268Singly-linked list/Element definition
| 8haskell
| vzb2k |
class Link
{
Link next;
int data;
} | 268Singly-linked list/Element definition
| 9java
| yog6g |
function LinkedList(value, next) {
this._value = value;
this._next = next;
}
LinkedList.prototype.value = function() {
if (arguments.length == 1)
this._value = arguments[0];
else
return this._value;
}
LinkedList.prototype.next = function() {
if (arguments.length == 1)
this._next = arguments[0];
else
return this._next;
} | 268Singly-linked list/Element definition
| 10javascript
| 2tklr |
(defn sleep [ms]
(println "Sleeping...")
(Thread/sleep ms)
(println "Awake!"))
(sleep 1000) | 271Sleep
| 6clojure
| 140py |
null | 268Singly-linked list/Element definition
| 11kotlin
| fx2do |
start := &Ele{"tacos", nil}
end := start.Append("burritos")
end = end.Append("fajitas")
end = end.Append("enchilatas")
for iter := start; iter != nil; iter = iter.Next {
fmt.Println(iter)
} | 269Singly-linked list/Traversal
| 0go
| qhtxz |
map (>5) [1..10]
map (++ "s") ["Apple", "Orange", "Mango", "Pear"]
foldr (+) 0 [1..10]
traverse :: [a] -> [a]
traverse list = map func list
where func a = | 269Singly-linked list/Traversal
| 8haskell
| migyf |
package main
import "fmt"
type Ele struct {
Data interface{}
Next *Ele
}
func (e *Ele) insert(data interface{}) {
if e == nil {
panic("attept to modify nil")
}
e.Next = &Ele{data, e.Next}
}
func (e *Ele) printList() {
if e == nil {
fmt.Println(nil)
return
}
fmt.Printf("(%v", e.Data)
for {
e = e.Next
if e == nil {
fmt.Println(")")
return
}
fmt.Print(" ", e.Data)
}
}
func main() {
h := &Ele{"A", &Ele{"B", nil}}
h.printList()
h.insert("C")
h.printList()
} | 270Singly-linked list/Element insertion
| 0go
| r9agm |
LinkedList<Type> list = new LinkedList<Type>();
for(Type i: list){ | 269Singly-linked list/Traversal
| 9java
| fxldv |
LinkedList.prototype.traverse = function(func) {
func(this);
if (this.next() != null)
this.next().traverse(func);
}
LinkedList.prototype.print = function() {
this.traverse( function(node) {print(node.value())} );
}
var head = createLinkedListFromArray([10,20,30,40]);
head.print(); | 269Singly-linked list/Traversal
| 10javascript
| yo46r |
class NodeList {
private enum Flag { FRONT }
private ListNode head
void insert(value, insertionPoint=Flag.FRONT) {
if (insertionPoint == Flag.FRONT) {
head = new ListNode(payload: value, next: head)
} else {
def node = head
while (node.payload != insertionPoint) {
node = node.next
if (node == null) {
throw new IllegalArgumentException(
"Insertion point ${afterValue} not already contained in list")
}
}
node.next = new ListNode(payload:value, next:node.next)
}
}
String toString() { "${head}" }
} | 270Singly-linked list/Element insertion
| 7groovy
| vzh28 |
insertAfter a b (c:cs) | a==c = a: b: cs
| otherwise = c: insertAfter a b cs
insertAfter _ _ [] = error "Can't insert" | 270Singly-linked list/Element insertion
| 8haskell
| 0bzs7 |
my %node = (
data => 'say what',
next => \%foo_node,
);
$node{next} = \%bar_node; | 268Singly-linked list/Element definition
| 2perl
| h2sjl |
fun main(args: Array<String>) {
val list = IntRange(1, 50).toList() | 269Singly-linked list/Traversal
| 11kotlin
| 8p60q |
void insertNode(Node<T> anchor_node, Node<T> new_node)
{
new_node.next = anchor_node.next;
anchor_node.next = new_node;
} | 270Singly-linked list/Element insertion
| 9java
| ago1y |
LinkedList.prototype.insertAfter = function(searchValue, nodeToInsert) {
if (this._value == searchValue) {
nodeToInsert.next(this.next());
this.next(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 = createLinkedListFromArray(['A','B']);
list.insertAfter('A', new LinkedList('C', null)); | 270Singly-linked list/Element insertion
| 10javascript
| sktqz |
const gchar *clickme = ;
guint counter = 0;
void clickedme(GtkButton *o, gpointer d)
{
GtkLabel *l = GTK_LABEL(d);
char nt[MAXLEN];
counter++;
snprintf(nt, MAXLEN, , counter);
gtk_label_set_text(l, nt);
}
int main(int argc, char **argv)
{
GtkWindow *win;
GtkButton *button;
GtkLabel *label;
GtkVBox *vbox;
gtk_init(&argc, &argv);
win = (GtkWindow*)gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(win, clickme);
button = (GtkButton*)gtk_button_new_with_label(clickme);
label = (GtkLabel*)gtk_label_new();
gtk_label_set_single_line_mode(label, TRUE);
vbox = (GtkVBox*)gtk_vbox_new(TRUE, 1);
gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(label));
gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(button));
gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(vbox));
g_signal_connect(G_OBJECT(win), , (GCallback)gtk_main_quit, NULL);
g_signal_connect(G_OBJECT(button), , (GCallback)clickedme, label);
gtk_widget_show_all(GTK_WIDGET(win));
gtk_main();
return 0;
} | 272Simple windowed application
| 5c
| ag011 |
null | 270Singly-linked list/Element insertion
| 11kotlin
| h2xj3 |
class LinkedList(object):
class Node(object):
def __init__(self, item):
self.value = item
self.next = None
def __init__(self, item=None):
if item is not None:
self.head = Node(item); self.tail = self.head
else:
self.head = None; self.tail = None
def append(self, item):
if not self.head:
self.head = Node(item)
self.tail = self.head
elif self.tail:
self.tail.next = Node(item)
self.tail = self.tail.next
else:
self.tail = Node(item)
def __iter__(self):
cursor = self.head
while cursor:
yield cursor.value
cursor = cursor.next | 268Singly-linked list/Element definition
| 3python
| kv0hf |
class ListNode
attr_accessor :value, :succ
def initialize(value, succ=nil)
self.value = value
self.succ = succ
end
def each(&b)
yield self
succ.each(&b) if succ
end
include Enumerable
def self.from_array(ary)
head = self.new(ary[0], nil)
prev = head
ary[1..-1].each do |val|
node = self.new(val, nil)
prev.succ = node
prev = node
end
head
end
end
list = ListNode.from_array([1,2,3,4]) | 268Singly-linked list/Element definition
| 14ruby
| p5obh |
(ns counter-window
(:import (javax.swing JFrame JLabel JButton)))
(defmacro on-action [component event & body]
`(. ~component addActionListener
(proxy [java.awt.event.ActionListener] []
(actionPerformed [~event] ~@body))))
(defn counter-app []
(let [counter (atom 0)
label (JLabel. "There have been no clicks yet")
button (doto (JButton. "Click me!")
(on-action evnt
(.setText label
(str "Counter: " (swap! counter inc)))))
panel (doto (JPanel.)
(.setOpaque true)
(.add label)
(.add button))]
(doto (JFrame. "Counter App")
(.setContentPane panel)
(.setSize 300 100)
(.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE)
(.setVisible true)))) | 272Simple windowed application
| 6clojure
| skdqr |
struct Node<T> {
elem: T,
next: Option<Box<Node<T>>>,
} | 268Singly-linked list/Element definition
| 15rust
| 14ipu |
sealed trait List[+A]
case class Cons[+A](head: A, tail: List[A]) extends List[A]
case object Nil extends List[Nothing]
object List {
def apply[A](as: A*): List[A] =
if (as.isEmpty) Nil else Cons(as.head, apply(as.tail: _*))
} | 268Singly-linked list/Element definition
| 16scala
| w7fes |
my @l = ($A, $B);
push @l, $C, splice @l, 1; | 270Singly-linked list/Element insertion
| 2perl
| zs2tb |
class Node<T>{
var data:T?=nil
var next:Node?=nil
init(input:T){
data=input
next=nil
}
} | 268Singly-linked list/Element definition
| 17swift
| bu8kd |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.