code stringlengths 1 46.1k ⌀ | label class label 1.18k
classes | domain_label class label 21
classes | index stringlengths 4 5 |
|---|---|---|---|
char nonblocking_getch();
void positional_putch(int x, int y, char ch);
void millisecond_sleep(int n);
void init_screen();
void update_screen();
void close_screen();
char nonblocking_getch() { return getch(); }
void positional_putch(int x, int y, char ch) { mvaddch(x, y, ch); }
void millisecond_sleep(int n) {
... | 262Snake | 5c | dwgnv |
package KT_Locations;
use strict;
use overload '""' => "as_string";
use English;
use Class::Tiny qw(N locations);
use List::Util qw(all);
sub BUILD {
my $self = shift;
$self->{N} //= 8;
$self->{N} >= 3 or die "N must be at least 3";
all {ref($ARG) eq 'ARRAY' && scalar(@{$ARG}) == 2} @{$self->{loca... | 256Solve a Holy Knight's tour | 2perl | miqyz |
use strict;
use warnings;
my $gap = qr/.{3}/s;
find( <<terminator );
-AB-
CDEF
-GH-
terminator
sub find
{
my $p = shift;
$p =~ /(\d)$gap.{0,2}(\d)(??{abs $1 - $2 <= 1? '': '(*F)'})/ ||
$p =~ /^.*\n.*(\d)(\d)(??{abs $1 - $2 <= 1? '': '(*F)'})/ and return;
if( $p =~ /[A-H]/ )
{
find( $p =~ s/[A-H]/... | 251Solve the no connection puzzle | 2perl | 4yy5d |
package main
import "fmt"
import "sort"
func main() {
nums := []int {2, 4, 3, 1, 2}
sort.Ints(nums)
fmt.Println(nums)
} | 252Sort an integer array | 0go | 6803p |
import Foundation
public struct OID {
public var val: String
public init(_ val: String) {
self.val = val
}
}
extension OID: CustomStringConvertible {
public var description: String {
return val
}
}
extension OID: Comparable {
public static func < (lhs: OID, rhs: OID) -> Bool {
let split1 = l... | 248Sort a list of object identifiers | 17swift | zsotu |
package main
import (
"fmt"
"net"
)
func main() {
conn, err := net.Dial("tcp", "localhost:256")
if err != nil {
fmt.Println(err)
return
}
defer conn.Close()
_, err = conn.Write([]byte("hello socket world"))
if err != nil {
fmt.Println(err)
}
} | 258Sockets | 0go | xjvwf |
s = new java.net.Socket("localhost", 256)
s << "hello socket world"
s.close() | 258Sockets | 7groovy | p5mbo |
let experiments = 1000000
var heads = 0
var wakenings = 0
for _ in (1...experiments) {
wakenings += 1
switch (Int.random(in: 0...1)) {
case 0:
heads += 1
default:
wakenings += 1
}
}
print("Wakenings over \(experiments) experiments: \(wakenings)")
print("Sleeping Beauty should estimat... | 260Sleeping Beauty problem | 17swift | miayk |
null | 259Smarandache prime-digital sequence | 1lua | 30pzo |
from array import array
from collections import deque
import psyco
data = []
nrows = 0
px = py = 0
sdata =
ddata =
def init(board):
global data, nrows, sdata, ddata, px, py
data = filter(None, board.splitlines())
nrows = max(len(r) for r in data)
maps = {' ':' ', '.': '.', '@':' ', '
mapd = {' ... | 257Sokoban | 3python | lf0cv |
package main
import (
"fmt"
"sort"
)
type pair struct {
name, value string
}
type csArray []pair | 255Sort an array of composite structures | 0go | xj4wf |
println ([2,4,0,3,1,2,-12].sort()) | 252Sort an integer array | 7groovy | dwen3 |
use feature 'say';
@strings = qw/Here are some sample strings to be sorted/;
sub mycmp { length $b <=> length $a || lc $a cmp lc $b }
say join ' ', sort mycmp @strings;
say join ' ', sort {length $b <=> length $a || lc $a cmp lc $b} @strings
say join ' ', map { $_->[0] }
sort { $b->[1] <=> $a->[1] ... | 243Sort using a custom comparator | 2perl | oao8x |
use strict;
use warnings;
use feature 'say';
sub cocktail_sort {
my @a = @_;
while (1) {
my $swapped_forward = 0;
for my $i (0..$
if ($a[$i] gt $a[$i+1]) {
@a[$i, $i+1] = @a[$i+1, $i];
$swapped_forward = 1;
}
}
last if not ... | 240Sorting algorithms/Cocktail sort | 2perl | 2z5lf |
import Network
main = withSocketsDo $ sendTo "localhost" (PortNumber $ toEnum 256) "hello socket world" | 258Sockets | 8haskell | yoe66 |
class Holiday {
def date
def name
Holiday(dateStr, name) { this.name = name; this.date = format.parse(dateStr) }
String toString() { "${format.format date}: ${name}" }
static format = new java.text.SimpleDateFormat("yyyy-MM-dd")
}
def holidays = [ new Holiday("2009-12-25", "Christmas Day"),
... | 255Sort an array of composite structures | 7groovy | p5lbo |
nums = [2,4,3,1,2] :: [Int]
sorted = List.sort nums | 252Sort an integer array | 8haskell | jlc7g |
package main
import "fmt"
func main() {
list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}
fmt.Println("unsorted:", list)
bubblesort(list)
fmt.Println("sorted! ", list)
}
func bubblesort(a []int) {
for itemCount := len(a) - 1; ; itemCount-- {
hasChanged := false
for index := ... | 246Sorting algorithms/Bubble sort | 0go | 56lul |
use strict;
use warnings;
use feature 'say';
use feature 'state';
use ntheory qw<is_prime>;
use Lingua::EN::Numbers qw(num2en_ordinal);
my @prime_digits = <2 3 5 7>;
my @spds = grep { is_prime($_) && /^[@{[join '',@prime_digits]}]+$/ } 1..100;
my @p = map { $_+3, $_+7 } map { 10*$_ } @prime_digits;
while ($
st... | 259Smarandache prime-digital sequence | 2perl | bu6k4 |
package main
import (
"errors"
"fmt"
"log"
"math/rand"
"time"
termbox "github.com/nsf/termbox-go"
)
func main() {
rand.Seed(time.Now().UnixNano())
score, err := playSnake()
if err != nil {
log.Fatal(err)
}
fmt.Println("Final score:", score)
}
type snake struct {
body []position | 262Snake | 0go | 7cir2 |
int numPrimeFactors(unsigned x) {
unsigned p = 2;
int pf = 0;
if (x == 1)
return 1;
else {
while (true) {
if (!(x % p)) {
pf++;
x /= p;
if (x == 1)
return pf;
}
else
++... | 263Smith numbers | 5c | er6av |
package main
import (
"fmt"
"sort"
"strconv"
"strings"
)
var board [][]int
var start, given []int
func setup(input []string) {
puzzle := make([][]string, len(input))
for i := 0; i < len(input); i++ {
puzzle[i] = strings.Fields(input[i])
}
nCols := len(puzzle[0])
nRows... | 261Solve a Hidato puzzle | 0go | u3svt |
from sys import stdout
moves = [
[-1, -2], [1, -2], [-1, 2], [1, 2],
[-2, -1], [-2, 1], [2, -1], [2, 1]
]
def solve(pz, sz, sx, sy, idx, cnt):
if idx > cnt:
return 1
for i in range(len(moves)):
x = sx + moves[i][0]
y = sy + moves[i][1]
if sz > x > -1 and sz > y > -1 an... | 256Solve a Holy Knight's tour | 3python | 9nsmf |
import Data.List
import Data.Function (on)
data Person =
P String
Int
deriving (Eq)
instance Show Person where
show (P name val) = "Person " ++ name ++ " with value " ++ show val
instance Ord Person where
compare (P a _) (P b _) = compare a b
pVal :: Person -> Int
pVal (P _ x) = x
people :: [Person]
pe... | 255Sort an array of composite structures | 8haskell | yoq66 |
from __future__ import print_function
from itertools import permutations
from enum import Enum
A, B, C, D, E, F, G, H = Enum('Peg', 'A, B, C, D, E, F, G, H')
connections = ((A, C), (A, D), (A, E),
(B, D), (B, E), (B, F),
(G, C), (G, D), (G, E),
(H, D), (H, E), (H, F),
... | 251Solve the no connection puzzle | 3python | gmm4h |
<?php
function mycmp($s1, $s2)
{
if ($d = strlen($s2) - strlen($s1))
return $d;
return strcasecmp($s1, $s2);
}
$strings = array(, , , , , , , );
usort($strings, );
?> | 243Sort using a custom comparator | 12php | g9g42 |
def makeSwap = { a, i, j = i+1 -> print "."; a[[i,j]] = a[[j,i]] }
def checkSwap = { a, i, j = i+1 -> [(a[i] > a[j])].find { it }.each { makeSwap(a, i, j) } }
def bubbleSort = { list ->
boolean swapped = true
while (swapped) { swapped = (1..<list.size()).any { checkSwap(list, it-1) } }
list
} | 246Sorting algorithms/Bubble sort | 7groovy | cd69i |
function cocktailSort($arr){
if (is_string($arr)) $arr = str_split(preg_replace('/\s+/','',$arr));
do{
$swapped = false;
for($i=0;$i<count($arr);$i++){
if(isset($arr[$i+1])){
if($arr[$i] > $arr[$i+1]){
list($arr[$i], $arr[$i+1]) = array($arr[$i+1], $arr[$i]);
$swapped = true;
}
}
}
... | 240Sorting algorithms/Cocktail sort | 12php | sboqs |
import java.io.IOException;
import java.net.*;
public class SocketSend {
public static void main(String args[]) throws IOException {
sendData("localhost", "hello socket world");
}
public static void sendData(String host, String msg) throws IOException {
Socket sock = new Socket( host, 256 );
sock.get... | 258Sockets | 9java | dwhn9 |
import Control.Monad.Random (getRandomRs)
import Graphics.Gloss.Interface.Pure.Game
import Lens.Micro ((%~), (^.), (&), set)
import Lens.Micro.TH (makeLenses)
data Snake = Snake { _body :: [Point], _direction :: Point }
makeLenses ''Snake
data World = World { _snake :: Snake , _food :: [Point]
,... | 262Snake | 8haskell | 8pv0z |
import qualified Data.IntMap as I
import Data.IntMap (IntMap)
import Data.List
import Data.Maybe
import Data.Time.Clock
data BoardProblem = Board
{ cells :: IntMap (IntMap Int)
, endVal :: Int
, onePos :: (Int, Int)
, givens :: [Int]
} deriving (Show, Eq)
tupIns x y v m = I.insert x (I.insert y v (I.findWit... | 261Solve a Hidato puzzle | 8haskell | w79ed |
require 'set'
class Sokoban
def initialize(level)
board = level.each_line.map(&:rstrip)
@nrows = board.map(&:size).max
board.map!{|line| line.ljust(@nrows)}
board.each_with_index do |row, r|
row.each_char.with_index do |ch, c|
@px, @py = c, r if ch == '@' or ch == '+'
end
end... | 257Sokoban | 14ruby | vzo2n |
bsort :: Ord a => [a] -> [a]
bsort s = case _bsort s of
t | t == s -> t
| otherwise -> bsort t
where _bsort (x:x2:xs) | x > x2 = x2:(_bsort (x:xs))
| otherwise = x:(_bsort (x2:xs))
_bsort s = s | 246Sorting algorithms/Bubble sort | 8haskell | xj1w4 |
>>> def gnomesort(a):
i,j,size = 1,2,len(a)
while i < size:
if a[i-1] <= a[i]:
i,j = j, j+1
else:
a[i-1],a[i] = a[i],a[i-1]
i -= 1
if i == 0:
i,j = j, j+1
return a
>>> gnomesort([3,4,2,5,1,6])
[1, 2, 3, 4, 5, 6]
>>> | 238Sorting algorithms/Gnome sort | 3python | rcbgq |
null | 258Sockets | 11kotlin | 0b4sf |
def divisors(n):
divs = [1]
for ii in range(2, int(n ** 0.5) + 3):
if n% ii == 0:
divs.append(ii)
divs.append(int(n / ii))
divs.append(n)
return list(set(divs))
def is_prime(n):
return len(divisors(n)) == 2
def digit_check(n):
if len(str(n))<2:
return ... | 259Smarandache prime-digital sequence | 3python | p5ybm |
import java.util.Arrays;
import java.util.Comparator;
public class SortComp {
public static class Pair {
public String name;
public String value;
public Pair(String n, String v) {
name = n;
value = v;
}
}
public static void main(String[] args) {
... | 255Sort an array of composite structures | 9java | dwpn9 |
socket = require "socket"
host, port = "127.0.0.1", 256
sid = socket.udp()
sid:sendto( "hello socket world", host, port )
sid:close() | 258Sockets | 1lua | 8pg0e |
const L = 1, R = 2, D = 4, U = 8;
var block = 24, wid = 30, hei = 20, frameR = 7, fruit, snake;
function Snake() {
this.length = 1;
this.alive = true;
this.pos = createVector( 1, 1 );
this.posArray = [];
this.posArray.push( createVector( 1, 1 ) );
this.dir = R;
this.draw = function() {
... | 262Snake | 9java | erya5 |
(defn divisible? [a b]
(zero? (mod a b)))
(defn prime? [n]
(and (> n 1) (not-any? (partial divisible? n) (range 2 n))))
(defn prime-factors
([n] (prime-factors n 2 '()))
([n candidate acc]
(cond
(<= n 1) (reverse acc)
(zero? (rem n candidate)) (recur
(/ n cand... | 263Smith numbers | 6clojure | 0blsj |
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Hidato {
private static int[][] board;
private static int[] given, start;
public static void main(String[] args) {
String[] input = {"_ 33 35 _ _ . . .",
"_ _ 24 22 _ . . .",
"_ _... | 261Solve a Hidato puzzle | 9java | kvthm |
require 'HLPsolver'
ADJACENT = [[-1,-2],[-2,-1],[-2,1],[-1,2],[1,2],[2,1],[2,-1],[1,-2]]
boardy = <<EOS
. . 0 0 0
. . 0 . 0 0
. 0 0 0 0 0 0 0
0 0 0 . . 0 . 0
0 . 0 . . 0 0 0
1 0 0 0 0 0 0
. . 0 0 . 0
. . . 0 0 0
EOS
t0 = Time.now
HLPsolver.new(boardy).solve
puts | 256Solve a Holy Knight's tour | 14ruby | lf8cl |
var arr = [
{id: 3, value: "foo"},
{id: 2, value: "bar"},
{id: 4, value: "baz"},
{id: 1, value: 42},
{id: 5, something: "another string"} | 255Sort an array of composite structures | 10javascript | 68x38 |
require 'HLPSolver'
ADJACENT = [[0,0]]
A,B,C,D,E,F,G,H = [0,1],[0,2],[1,0],[1,1],[1,2],[1,3],[2,1],[2,2]
board1 = <<EOS
. 0 0 .
0 0 1 0
. 0 0 .
EOS
g = HLPsolver.new(board1)
g.board[A[0]][A[1]].adj = [B,G,H,F]
g.board[B[0]][B[1]].adj = [A,C,G,H]
g.board[C[0]][C[1]].adj = [B,E,F,H] ... | 251Solve the no connection puzzle | 14ruby | 7ccri |
import java.util.Arrays;
public class Example {
public static void main(String[] args)
{
int[] nums = {2,4,3,1,2};
Arrays.sort(nums);
}
} | 252Sort an integer array | 9java | u3zvv |
function int_arr(a, b) {
return a - b;
}
var numbers = [20, 7, 65, 10, 3, 0, 8, -60];
numbers.sort(int_arr);
document.write(numbers); | 252Sort an integer array | 10javascript | 7c9rd |
use strict ;
sub disjointSort {
my ( $values , @indices ) = @_ ;
@{$values}[ sort @indices ] = sort @{$values}[ @indices ] ;
}
my @values = ( 7 , 6 , 5 , 4 , 3 , 2 , 1 , 0 ) ;
my @indices = ( 6 , 1 , 7 ) ;
disjointSort( \@values , @indices ) ;
print "[@values]\n" ; | 247Sort disjoint sublist | 2perl | iaqo3 |
gnomesort <- function(x)
{
i <- 1
j <- 1
while(i < length(x))
{
if(x[i] <= x[i+1])
{
i <- j
j <- j+1
} else
{
temp <- x[i]
x[i] <- x[i+1]
x[i+1] <- temp
i <- i - 1
if(i == 0)
{
i <- j
j <... | 238Sorting algorithms/Gnome sort | 13r | u67vx |
const L = 1, R = 2, D = 4, U = 8;
var block = 24, wid = 30, hei = 20, frameR = 7, fruit, snake;
function Snake() {
this.length = 1;
this.alive = true;
this.pos = createVector( 1, 1 );
this.posArray = [];
this.posArray.push( createVector( 1, 1 ) );
this.dir = R;
this.draw = function() {
... | 262Snake | 10javascript | 0b2sz |
null | 255Sort an array of composite structures | 11kotlin | 0b7sf |
object NoConnection extends App {
private def links = Seq(
Seq(2, 3, 4), | 251Solve the no connection puzzle | 16scala | buuk6 |
strings = .split()
def mykey(x):
return -len(x), x.upper()
print sorted(strings, key=mykey) | 243Sort using a custom comparator | 3python | ieiof |
fn is_prime(n: u32) -> bool {
if n < 2 {
return false;
}
if n% 2 == 0 {
return n == 2;
}
if n% 3 == 0 {
return n == 3;
}
if n% 5 == 0 {
return n == 5;
}
let mut p = 7;
const WHEEL: [u32; 8] = [4, 2, 4, 2, 4, 6, 2, 6];
loop {
for w in &W... | 259Smarandache prime-digital sequence | 15rust | ercaj |
require
smarandache = Enumerator.new do|y|
prime_digits = [2,3,5,7]
prime_digits.each{|pr| y << pr}
(1..).each do |n|
prime_digits.repeated_permutation(n).each do |perm|
c = perm.join.to_i * 10
y << c + 3 if (c+3).prime?
y << c + 7 if (c+7).prime?
end
end
end
seq = smarandache.tak... | 259Smarandache prime-digital sequence | 14ruby | ag91s |
null | 261Solve a Hidato puzzle | 11kotlin | gmo4d |
v = c("Here", "are", "some", "sample", "strings", "to", "be", "sorted")
print(v[order(-nchar(v), tolower(v))]) | 243Sort using a custom comparator | 13r | sbsqy |
func isPrime(number: Int) -> Bool {
if number < 2 {
return false
}
if number% 2 == 0 {
return number == 2
}
if number% 3 == 0 {
return number == 3
}
if number% 5 == 0 {
return number == 5
}
var p = 7
let wheel = [4,2,4,2,4,6,2,6]
while true {
... | 259Smarandache prime-digital sequence | 17swift | 14mpt |
null | 262Snake | 11kotlin | kvfh3 |
null | 252Sort an integer array | 11kotlin | 9nimh |
def cocktailSort(A):
up = range(len(A)-1)
while True:
for indices in (up, reversed(up)):
swapped = False
for i in indices:
if A[i] > A[i+1]:
A[i], A[i+1] = A[i+1], A[i]
swapped = True
if not swapped:
... | 240Sorting algorithms/Cocktail sort | 3python | v3429 |
UP, RIGHT, DOWN, LEFT = 1, 2, 3, 4
UpdateTime=0.200
Timer = 0
GridSize = 30
GridWidth, GridHeight = 20, 10
local directions = {
[UP] = {x= 0, y=-1},
[RIGHT] = {x= 1, y= 0},
[DOWN] = {x= 0, y= 1},
[LEFT] = {x=-1, y= 0},
}
local function isPositionInBody(x, y)
for i = 1, #Body-3, 2 do | 262Snake | 1lua | butka |
function sorting( a, b )
return a[1] < b[1]
end
tab = { {"C++", 1979}, {"Ada", 1983}, {"Ruby", 1995}, {"Eiffel", 1985} }
table.sort( tab, sorting )
for _, v in ipairs( tab ) do
print( unpack(v) )
end | 255Sort an array of composite structures | 1lua | 8pj0e |
cocktailSort <- function(A)
{
repeat
{
swapped <- FALSE
for(i in seq_len(length(A) - 1))
{
if(A[i] > A[i + 1])
{
A[c(i, i + 1)] <- A[c(i + 1, i)]
swapped <- TRUE
}
}
if(!swapped) break
swapped <- FALSE
for(i in (length(A)-1):1)
{
if(A[i] > A[... | 240Sorting algorithms/Cocktail sort | 13r | 9d2mg |
>>> def sort_disjoint_sublist(data, indices):
indices = sorted(indices)
values = sorted(data[i] for i in indices)
for index, value in zip(indices, values):
data[index] = value
>>> d = [7, 6, 5, 4, 3, 2, 1, 0]
>>> i = set([6, 1, 7])
>>> sort_disjoint_sublist(d, i)
>>> d
[7, 0, 5, 4, 3, 2, 1, 6]
>>>
>>> def sort... | 247Sort disjoint sublist | 3python | nesiz |
words = %w(Here are some sample strings to be sorted)
p words.sort_by {|word| [-word.size, word.downcase]} | 243Sort using a custom comparator | 14ruby | dxdns |
public static <E extends Comparable<? super E>> void bubbleSort(E[] comparable) {
boolean changed = false;
do {
changed = false;
for (int a = 0; a < comparable.length - 1; a++) {
if (comparable[a].compareTo(comparable[a + 1]) > 0) {
E tmp = comparable[a];
... | 246Sorting algorithms/Bubble sort | 9java | bu7k3 |
use strict;
use List::Util 'max';
our (@grid, @known, $n);
sub show_board {
for my $r (@grid) {
print map(!defined($_) ? ' ' : $_
? sprintf("%3d", $_)
: ' __'
, @$r), "\n"
}
}
sub parse_board {
@grid = map{[map(/^_/ ? 0 : /^\./ ? undef: $_, split ' ')]}
split "\n", shift();
for my $y (0 .. $
... | 261Solve a Hidato puzzle | 2perl | negiw |
t = {4, 5, 2}
table.sort(t)
print(unpack(t)) | 252Sort an integer array | 1lua | cdn92 |
values=c(7,6,5,4,3,2,1,0)
indices=c(7,2,8)
values[sort(indices)]=sort(values[indices])
print(values) | 247Sort disjoint sublist | 13r | 0besg |
fn main() {
let mut words = ["Here", "are", "some", "sample", "strings", "to", "be", "sorted"];
words.sort_by(|l, r| Ord::cmp(&r.len(), &l.len()).then(Ord::cmp(l, r)));
println!("{:?}", words);
} | 243Sort using a custom comparator | 15rust | fqfd6 |
Array.prototype.bubblesort = function() {
var done = false;
while (!done) {
done = true;
for (var i = 1; i<this.length; i++) {
if (this[i-1] > this[i]) {
done = false;
[this[i-1], this[i]] = [this[i], this[i-1]]
}
}
}
return... | 246Sorting algorithms/Bubble sort | 10javascript | w7pe2 |
class Array
def gnomesort!
i, j = 1, 2
while i < length
if self[i-1] <= self[i]
i, j = j, j+1
else
self[i-1], self[i] = self[i], self[i-1]
i -= 1
if i == 0
i, j = j, j+1
end
end
end
self
end
end
ary = [7,6,5,9,8,4,3,1,2,0]
ary.gnome... | 238Sorting algorithms/Gnome sort | 14ruby | j217x |
use utf8;
use Time::HiRes qw(sleep);
use Term::ANSIColor qw(colored);
use Term::ReadKey qw(ReadMode ReadLine);
binmode(STDOUT, ':utf8');
use constant {
VOID => 0,
HEAD => 1,
BODY => 2,
TAIL => 3,
FOOD => 4,
};
use constant {
... | 262Snake | 2perl | 30hzs |
List("Here", "are", "some", "sample", "strings", "to", "be", "sorted").sortWith{(a,b) =>
val cmp=a.size-b.size
(if (cmp==0) -a.compareTo(b) else cmp) > 0
} | 243Sort using a custom comparator | 16scala | 383zy |
fn gnome_sort<T: PartialOrd>(a: &mut [T]) {
let len = a.len();
let mut i: usize = 1;
let mut j: usize = 2;
while i < len {
if a[i - 1] <= a[i] { | 238Sorting algorithms/Gnome sort | 15rust | hvaj2 |
package main
import "fmt"
func numPrimeFactors(x uint) int {
var p uint = 2
var pf int
if x == 1 {
return 1
}
for {
if (x % p) == 0 {
pf++
x /= p
if x == 1 {
return pf
}
} else {
p++
}
}
}
func primeFactors(x uint, arr []uint) {
var p uint = 2
var pf int
if x == 1 {
arr[pf] = 1
... | 263Smith numbers | 0go | 9npmt |
object GnomeSort {
def gnomeSort(a: Array[Int]): Unit = {
var (i, j) = (1, 2)
while ( i < a.length)
if (a(i - 1) <= a(i)) { i = j; j += 1 }
else {
val tmp = a(i - 1)
a(i - 1) = a(i)
a({i -= 1; i + 1}) = tmp
i = if (i == 0) {j += 1; j - 1} else i
}
}
} | 238Sorting algorithms/Gnome sort | 16scala | p4xbj |
use Socket;
$host = gethostbyname('localhost');
$in = sockaddr_in(256, $host);
$proto = getprotobyname('tcp');
socket(Socket_Handle, AF_INET, SOCK_STREAM, $proto);
connect(Socket_Handle, $in);
send(Socket_Handle, 'hello socket world', 0, $in);
close(Socket_Handle); | 258Sockets | 2perl | 56iu2 |
from __future__ import annotations
import itertools
import random
from enum import Enum
from typing import Any
from typing import Tuple
import pygame as pg
from pygame import Color
from pygame import Rect
from pygame.surface import Surface
from pygame.sprite import AbstractGroup
from pygame.sprite import Group
f... | 262Snake | 3python | 68k3w |
import Data.Numbers.Primes (primeFactors)
import Data.List (unfoldr)
import Data.Tuple (swap)
import Data.Bool (bool)
isSmith :: Int -> Bool
isSmith n = pfs /= [n] && sumDigits n == foldr ((+) . sumDigits) 0 pfs
where
sumDigits = sum . baseDigits 10
pfs = primeFactors n
baseDigits :: Int -> Int -> [Int]
bas... | 263Smith numbers | 8haskell | bufk2 |
def sort_disjoint_sublist!(ar, indices)
values = ar.values_at(*indices).sort
indices.sort.zip(values).each{ |i,v| ar[i] = v }
ar
end
values = [7, 6, 5, 4, 3, 2, 1, 0]
indices = [6, 1, 7]
p sort_disjoint_sublist!(values, indices) | 247Sort disjoint sublist | 14ruby | fx8dr |
import java.util.Comparator
fun <T> bubbleSort(a: Array<T>, c: Comparator<T>) {
var changed: Boolean
do {
changed = false
for (i in 0..a.size - 2) {
if (c.compare(a[i], a[i + 1]) > 0) {
val tmp = a[i]
a[i] = a[i + 1]
a[i + 1] = tmp
... | 246Sorting algorithms/Bubble sort | 11kotlin | r9ugo |
class Array
def cocktailsort!
begin
swapped = false
0.upto(length - 2) do |i|
if self[i] > self[i + 1]
self[i], self[i + 1] = self[i + 1], self[i]
swapped = true
end
end
break unless swapped
swapped = false
(length - 2).downto(0) do |i|
... | 240Sorting algorithms/Cocktail sort | 14ruby | 5yruj |
$socket = fsockopen('localhost', 256);
fputs($socket, 'hello socket world');
fclose($socket); | 258Sockets | 12php | o1r85 |
import java.util.*;
public class SmithNumbers {
public static void main(String[] args) {
for (int n = 1; n < 10_000; n++) {
List<Integer> factors = primeFactors(n);
if (factors.size() > 1) {
int sum = sumDigits(n);
for (int f : factors)
... | 263Smith numbers | 9java | gm04m |
use std::collections::BTreeSet;
fn disjoint_sort(array: &mut [impl Ord], indices: &[usize]) {
let mut sorted = indices.to_owned();
sorted.sort_unstable_by_key(|k| &array[*k]);
indices
.iter()
.zip(sorted.iter())
.map(|(&a, &b)| if a > b { (b, a) } else { (a, b) })
.collect::... | 247Sort disjoint sublist | 15rust | tqofd |
import Foundation
var list = ["this",
"is",
"a",
"set",
"of",
"strings",
"to",
"sort",
"This",
"Is",
"A",
"Set",
"Of",
"Strings",
"To",
"Sort"]
list.sortInPlace {lhs, rhs in
let lhsCount = lhs.characters.count
let rhsCount = rhs.characters.count
let result = rhsCount - lhsCount
... | 243Sort using a custom comparator | 17swift | nwnil |
#![windows_subsystem = "windows"]
use rand::Rng;
use std::{cell::RefCell, rc::Rc};
use winsafe::{co, gui, prelude::*, COLORREF, HBRUSH, HPEN, SIZE};
const STEP: i32 = 3; | 262Snake | 15rust | 9n1mm |
(() => {
'use strict'; | 263Smith numbers | 10javascript | kvdhq |
board = []
given = []
start = None
def setup(s):
global board, given, start
lines = s.splitlines()
ncols = len(lines[0].split())
nrows = len(lines)
board = [[-1] * (ncols + 2) for _ in xrange(nrows + 2)]
for r, row in enumerate(lines):
for c, cell in enumerate(row.split()):
... | 261Solve a Hidato puzzle | 3python | dwrn1 |
import scala.compat.Platform
object SortedDisjointSubList extends App {
val (list, subListIndex) = (List(7, 6, 5, 4, 3, 2, 1, 0), List(6, 1, 7))
def sortSubList[T: Ordering](indexList: List[Int], list: List[T]) = {
val subListIndex = indexList.sorted
val sortedSubListMap = subListIndex.zip(subListIndex.ma... | 247Sort disjoint sublist | 16scala | 68d31 |
fn cocktail_sort<T: PartialOrd>(a: &mut [T]) {
let len = a.len();
loop {
let mut swapped = false;
let mut i = 0;
while i + 1 < len {
if a[i] > a[i + 1] {
a.swap(i, i + 1);
swapped = true;
}
i += 1;
}
if s... | 240Sorting algorithms/Cocktail sort | 15rust | 4m75u |
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((, 256))
sock.sendall()
sock.close() | 258Sockets | 3python | 4yn5k |
object CocktailSort extends App {
def sort(arr: Array[Int]) = {
var swapped = false
do {
def swap(i: Int) {
val temp = arr(i)
arr(i) = arr(i + 1)
arr(i + 1) = temp
swapped = true
}
swapped = false
for (i <- 0 to (arr.length - 2)) if (arr(i) > arr(i + 1)... | 240Sorting algorithms/Cocktail sort | 16scala | 7lkr9 |
s <- make.socket(port = 256)
write.socket(s, "hello socket world")
close.socket(s) | 258Sockets | 13r | 2t0lg |
null | 263Smith numbers | 11kotlin | 2teli |
function bubbleSort(A)
local itemCount=#A
local hasChanged
repeat
hasChanged = false
itemCount=itemCount - 1
for i = 1, itemCount do
if A[i] > A[i + 1] then
A[i], A[i + 1] = A[i + 1], A[i]
hasChanged = true
end
end
until hasChanged == false
end | 246Sorting algorithms/Bubble sort | 1lua | 7c5ru |
func gnomeSort<T: Comparable>(_ a: inout [T]) {
var i = 1
var j = 2
while i < a.count {
if a[i - 1] <= a[i] {
i = j
j += 1
} else {
a.swapAt(i - 1, i)
i -= 1
if i == 0 {
i = j
j += 1
}
... | 238Sorting algorithms/Gnome sort | 17swift | 7lprq |
null | 263Smith numbers | 1lua | vzw2x |
@people = (['joe', 120], ['foo', 31], ['bar', 51]);
@people = sort { $a->[0] cmp $b->[0] } @people; | 255Sort an array of composite structures | 2perl | 56fu2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.