code stringlengths 1 46.1k ⌀ | label class label 1.18k
classes | domain_label class label 21
classes | index stringlengths 4 5 |
|---|---|---|---|
from math import gcd
def (n):
return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)
if __name__ == '__main__':
def is_prime(n):
return (n) == n - 1
for n in range(1, 26):
print(f)
count = 0
for n in range(1, 10_000 + 1):
count += is_prime(n)
if n in {100, 1000,... | 108Totient function | 3python | xpbwr |
def f(x) x.abs ** 0.5 + 5 * x ** 3 end
puts
nums = 11.times.map{ gets.to_f }
nums.reverse_each do |n|
print
res = f(n)
puts res > 400? : res
end | 106Trabb Pardo–Knuth algorithm | 14ruby | c369k |
sub tokenize {
my ($string, $sep, $esc) = (shift, quotemeta shift, quotemeta shift);
my @fields = split /$esc . (*SKIP)(*FAIL) | $sep/sx, $string, -1;
return map { s/$esc(.)/$1/gsr } @fields;
} | 112Tokenize a string with escaping | 2perl | mtoyz |
use std::io::{self, BufRead};
fn op(x: f32) -> Option<f32> {
let y = x.abs().sqrt() + 5.0 * x * x * x;
if y < 400.0 {
Some(y)
} else {
None
}
}
fn main() {
println!("Please enter 11 numbers (one number per line)");
let stdin = io::stdin();
let xs = stdin
.lock()
... | 106Trabb Pardo–Knuth algorithm | 15rust | l6ycc |
object TPKa extends App {
final val numbers = scala.collection.mutable.MutableList[Double]()
final val in = new java.util.Scanner(System.in)
while (numbers.length < CAPACITY) {
print("enter a number: ")
try {
numbers += in.nextDouble()
}
catch {
case _... | 106Trabb Pardo–Knuth algorithm | 16scala | u9cv8 |
void move(int n, int from, int via, int to)
{
if (n > 1) {
move(n - 1, from, to, via);
printf(, from, to);
move(n - 1, via, from, to);
} else {
printf(, from, to);
}
}
int main()
{
move(4, 1,2,3);
return 0;
} | 119Towers of Hanoi | 5c | ekcav |
import Foundation
print("Enter 11 numbers for the TrabbPardoKnuth algorithm:")
let f: (Double) -> Double = { sqrt(fabs($0)) + 5 * pow($0, 3) }
(1...11)
.generate()
.map { i -> Double in
print("\(i): ", terminator: "")
guard let s = readLine(), let n = Double(s) else { return 0 }
retur... | 106Trabb Pardo–Knuth algorithm | 17swift | 9z3mj |
sub complement
{
my $s = shift;
$s =~ tr/01/10/;
return $s;
}
my $str = '0';
for (0..6) {
say $str;
$str .= complement($str);
} | 114Thue-Morse | 2perl | 5ctu2 |
null | 110Topological sort | 11kotlin | sabq7 |
from __future__ import print_function
def run_utm(
state = None,
blank = None,
rules = [],
tape = [],
halt = None,
pos = 0):
st = state
if not tape: tape = [blank]
if pos < 0: pos += len(tape)
if pos >= len(tape) or pos < 0: raise Error( )
rules = dic... | 103Universal Turing machine | 3python | n0niz |
public class Trig {
public static void main(String[] args) { | 111Trigonometric functions | 9java | d0wn9 |
def left_truncatable?(n)
truncatable?(n) {|i| i.to_s[1..-1].to_i}
end
def right_truncatable?(n)
truncatable?(n) {|i| i/10}
end
def truncatable?(n, &trunc_func)
return false if n.to_s.include?
loop do
n = trunc_func.call(n)
return true if n.zero?
return false unless Prime.prime?(n)
end
end
req... | 102Truncatable primes | 14ruby | zn3tw |
<?php
function thueMorseSequence($length) {
$sequence = '';
for ($digit = $n = 0 ; $n < $length ; $n++) {
$x = $n ^ ($n - 1);
if (($x ^ ($x >> 1)) & 0x55555555) {
$digit = 1 - $digit;
}
$sequence .= $digit;
}
return $sequence;
}
for ($n = 10 ; $n <= 100 ; $n... | 114Thue-Morse | 12php | oxk85 |
def token_with_escape(a, escape = '^', separator = '|'):
'''
Issue python -m doctest thisfile.py to run the doctests.
>>> print(token_with_escape('one^|uno||three^^^^|four^^^|^cuatro|'))
['one|uno', '', 'three^^', 'four^|cuatro', '']
'''
result = []
token = ''
state = 0
... | 112Tokenize a string with escaping | 3python | 9zimf |
var
radians = Math.PI / 4, | 111Trigonometric functions | 10javascript | 6d838 |
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;
}
let mut p = 5;
while p * p <= n {
if n% p == 0 {
return false;
}
p += 2;
if n% p == 0 {
... | 102Truncatable primes | 15rust | 3d6z8 |
package empty
func Empty() {}
func Count() { | 118Time a function | 0go | 7utr2 |
import java.lang.management.ManagementFactory
import java.lang.management.ThreadMXBean
def threadMX = ManagementFactory.threadMXBean
assert threadMX.currentThreadCpuTimeSupported
threadMX.threadCpuTimeEnabled = true
def clockCpuTime = { Closure c ->
def start = threadMX.currentThreadCpuTime
c.call()
(thre... | 118Time a function | 7groovy | u9ov9 |
(defn towers-of-hanoi [n from to via]
(when (pos? n)
(towers-of-hanoi (dec n) from via to)
(printf "Move from%s to%s\n" from to)
(recur (dec n) via to from))) | 119Towers of Hanoi | 6clojure | 0e5sj |
require
def (n)
n.prime_division.inject(1) {|res, (pr, exp)| res *= (pr-1) * pr**(exp-1) }
end
1.upto 25 do |n|
tot = (n)
puts prime
end
[100, 1_000, 10_000, 100_000].each do |u|
puts
end | 108Totient function | 14ruby | sa1qw |
object TruncatablePrimes {
def main(args: Array[String]): Unit = {
val max = 1000000
println(
s"""|ltPrime: ${ltPrimes.takeWhile(_ <= max).last}
|rtPrime: ${rtPrimes.takeWhile(_ <= max).last}
|""".stripMargin)
}
def ltPrimes: LazyList[Int] = 2 #:: LazyList.from(3, 2).filter(isL... | 102Truncatable primes | 16scala | mz9yc |
import System.CPUTime (getCPUTime)
timeIt :: (Fractional c) => (a -> IO b) -> a -> IO c
timeIt action arg = do
startTime <- getCPUTime
action arg
finishTime <- getCPUTime
return $ fromIntegral (finishTime - startTime) / 1000000000000
timeIt_ :: (Fractional c) => (a -> b) -> a -> IO c
timeIt_ f = timeIt ((`s... | 118Time a function | 8haskell | 8wg0z |
m='0'
print(m)
for i in range(0,6):
m0=m
m=m.replace('0','a')
m=m.replace('1','0')
m=m.replace('a','1')
m=m0+m
print(m) | 114Thue-Morse | 3python | 4lz5k |
def tokenize(string, sep, esc)
sep = Regexp.escape(sep)
esc = Regexp.escape(esc)
string.scan(/\G (?:^ |
m.gsub(/
end
end
p tokenize('one^|uno||three^^^^|four^^^|^cuatro|', '|', '^') | 112Tokenize a string with escaping | 14ruby | l6dcl |
use num::integer::gcd;
fn main() { | 108Totient function | 15rust | 0easl |
package main
import (
"fmt"
"sort"
) | 115Top rank per group | 0go | d0pne |
thue_morse <- function(steps) {
sb1 <- "0"
sb2 <- "1"
for (idx in 1:steps) {
tmp <- sb1
sb1 <- paste0(sb1, sb2)
sb2 <- paste0(sb2, tmp)
}
sb1
}
cat(thue_morse(6), "\n") | 114Thue-Morse | 13r | 2ynlg |
const SEPARATOR: char = '|';
const ESCAPE: char = '^';
const STRING: &str = "one^|uno||three^^^^|four^^^|^cuatro|";
fn tokenize(string: &str) -> Vec<String> {
let mut token = String::new();
let mut tokens: Vec<String> = Vec::new();
let mut chars = string.chars();
while let Some(ch) = chars.next() {
... | 112Tokenize a string with escaping | 15rust | 2yflt |
object TokenizeStringWithEscaping0 extends App {
val (markerSpE,markerSpF) = ("\ufffe" , "\uffff")
def tokenize(str: String, sep: String, esc: String): Array[String] = {
val s0 = str.replace( esc + esc, markerSpE).replace(esc + sep, markerSpF)
val s = if (s0.last.toString == esc) s0.replace(esc, "") + es... | 112Tokenize a string with escaping | 16scala | 5c3ut |
class Turing
class Tape
def initialize(symbols, blank, starting_tape)
@symbols = symbols
@blank = blank
@tape = starting_tape
@index = 0
end
def read
retval = @tape[@index]
unless retval
retval = @tape[@i... | 103Universal Turing machine | 14ruby | fofdr |
func isPrime(_ n: Int) -> Bool {
if n < 2 {
return false
}
if n% 2 == 0 {
return n == 2
}
if n% 3 == 0 {
return n == 3
}
var p = 5
while p * p <= n {
if n% p == 0 {
return false
}
p += 2
if n% p == 0 {
return... | 102Truncatable primes | 17swift | tizfl |
def displayRank(employees, number) {
employees.groupBy { it.Department }.sort().each { department, staff ->
println "Department $department"
println " Name ID Salary"
staff.sort { e1, e2 -> e2.Salary <=> e1.Salary }
staff[0..<Math.min(number, staff.size())].eac... | 115Top rank per group | 7groovy | 0e7sh |
use std::collections::VecDeque;
use std::fmt::{Display, Formatter, Result};
fn main() {
println!("Simple incrementer");
let rules_si = vec!(
Rule::new("q0", '1', '1', Direction::Right, "q0"),
Rule::new("q0", 'B', '1', Direction::Stay, "qf")
);
let states_si = vec!("q0", "qf");
let t... | 103Universal Turing machine | 15rust | titfd |
@tailrec
def gcd(a: Int, b: Int): Int = if(b == 0) a else gcd(b, a%b)
def totientLaz(num: Int): Int = LazyList.range(2, num).count(gcd(num, _) == 1) + 1 | 108Totient function | 16scala | iqxox |
null | 111Trigonometric functions | 11kotlin | 0ebsf |
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
public class TimeIt {
public static void main(String[] args) {
final ThreadMXBean threadMX = ManagementFactory.getThreadMXBean();
assert threadMX.isCurrentThreadCpuTimeSupported();
threadMX.setThreadCpuTimeEnabled(true);
... | 118Time a function | 9java | ekla5 |
import Data.List (sortBy, groupBy)
import Text.Printf (printf)
import Data.Ord (comparing)
import Data.Function (on)
type ID = Int
type DEP = String
type NAME = String
type SALARY = Double
data Employee = Employee
{ nr :: ID
, dep :: DEP
, name :: NAME
, sal :: SALARY
}
employees :: [Employee]
employ... | 115Top rank per group | 8haskell | 5cfug |
puts s =
6.times{puts s << s.tr(,)} | 114Thue-Morse | 14ruby | rv6gs |
const ITERATIONS: usize = 8;
fn neg(sequence: &String) -> String {
sequence.chars()
.map(|ch| {
(1 - ch.to_digit(2).unwrap()).to_string()
})
.collect::<String>()
}
fn main() {
let mut sequence: String = String::from("0");
for i in 0..ITERATIONS {
println!("{}: {... | 114Thue-Morse | 15rust | 7uyrc |
package utm.scala
import scala.annotation.tailrec
import scala.language.implicitConversions
class UniversalTuringMachine[S](
val rules: List[UTMRule[S]],
val initialState: S,
val finalStates: Set[S],
val blankSymbol: String,
val inputTapeVals: Iterable[String],
printEveryIter: Int = 1
) {
... | 103Universal Turing machine | 16scala | 6f631 |
function test() {
let n = 0
for(let i = 0; i < 1000000; i++){
n += i
}
}
let start = new Date().valueOf()
test()
let end = new Date().valueOf()
console.log('test() took ' + ((end - start) / 1000) + ' seconds') | 118Time a function | 10javascript | 0e4sz |
def thueMorse(n: Int): String = {
val (sb0, sb1) = (new StringBuilder("0"), new StringBuilder("1"))
(0 until n).foreach { _ =>
val tmp = sb0.toString()
sb0.append(sb1)
sb1.append(tmp)
}
sb0.toString()
}
(0 to 6).foreach(i => println(s"$i: ${thueMorse(i)}")) | 114Thue-Morse | 16scala | kgchk |
extension String {
func tokenize(separator: Character, escape: Character) -> [String] {
var token = ""
var tokens = [String]()
var chars = makeIterator()
while let char = chars.next() {
switch char {
case separator:
tokens.append(token)
token = ""
case escape:
... | 112Tokenize a string with escaping | 17swift | c3n9t |
null | 118Time a function | 11kotlin | kg6h3 |
package main
import (
"bufio"
"fmt"
"math/rand"
"os"
"strings"
)
var b []byte
func printBoard() {
fmt.Printf("%s\n%s\n%s\n", b[0:3], b[3:6], b[6:9])
}
var pScore, cScore int
var pMark, cMark byte = 'X', 'O'
var in = bufio.NewReader(os.Stdin)
func main() {
b = make([]byte, 9)
fmt.Pri... | 117Tic-tac-toe | 0go | u9ivt |
main() {
moveit(from,to) {
print("move ${from} ---> ${to}");
}
hanoi(height,toPole,fromPole,usePole) {
if (height>0) {
hanoi(height-1,usePole,fromPole,toPole);
moveit(fromPole,toPole);
hanoi(height-1,toPole,usePole,fromPole);
}
}
hanoi(3,3,1,2);
} | 119Towers of Hanoi | 18dart | h4zjb |
WITH recursive a(a) AS (SELECT '0' UNION ALL SELECT REPLACE(REPLACE(hex(a),'30','01'),'31','10') FROM a) SELECT * FROM a; | 114Thue-Morse | 19sql | 1jvpg |
package main
import "fmt"
type node struct {
value int
left, right *node
}
func (n *node) iterPreorder(visit func(int)) {
if n == nil {
return
}
visit(n.value)
n.left.iterPreorder(visit)
n.right.iterPreorder(visit)
}
func (n *node) iterInorder(visit func(int)) {
if n ==... | 113Tree traversal | 0go | p7vbg |
package main
import (
"fmt"
"strings"
)
func main() {
s := "Hello,How,Are,You,Today"
fmt.Println(strings.Join(strings.Split(s, ","), "."))
} | 116Tokenize a string | 0go | j567d |
println 'Hello,How,Are,You,Today'.split(',').join('.') | 116Tokenize a string | 7groovy | 5cduv |
class Main {
def input = new Scanner(System.in)
static main(args) {
Main main = new Main();
main.play();
}
public void play() {
TicTackToe game = new TicTackToe();
game.init()
def gameOver = false
def player = game.player1
println "Players take turns marking a square. Only squares \n"+
"not... | 117Tic-tac-toe | 7groovy | 9zqm4 |
def preorder;
preorder = { Node node ->
([node] + node.children().collect { preorder(it) }).flatten()
}
def postorder;
postorder = { Node node ->
(node.children().collect { postorder(it) } + [node]).flatten()
}
def inorder;
inorder = { Node node ->
def kids = node.children()
if (kids.empty) [node]
... | 113Tree traversal | 7groovy | 7umrz |
import Data.Text (splitOn,intercalate)
import qualified Data.Text.IO as T (putStrLn)
main = T.putStrLn . intercalate "." $ splitOn "," "Hello,How,Are,You,Today" | 116Tokenize a string | 8haskell | oxj8p |
function Test_Function()
for i = 1, 10000000 do
local s = math.log( i )
s = math.sqrt( s )
end
end
t1 = os.clock()
Test_Function()
t2 = os.clock()
print( os.difftime( t2, t1 ) ) | 118Time a function | 1lua | bryka |
module Main where
import System.Random
import Data.List (intercalate, find, minimumBy)
import System.Environment (getArgs)
import Data.Char (digitToInt)
import Data.Maybe (listToMaybe, mapMaybe)
import Control.Monad (guard)
import Data.Ord (comparing)
tictactoe :: String -> Bool
tictactoe a = tictactoeFor 'X' a /= ... | 117Tic-tac-toe | 8haskell | wbved |
sub print_topo_sort {
my %deps = @_;
my %ba;
while ( my ( $before, $afters_aref ) = each %deps ) {
for my $after ( @{ $afters_aref } ) {
$ba{$before}{$after} = 1 if $before ne $after;
$ba{$after} ||= {};
}
}
while ( my @afters = sort grep { ! %{ $ba{$_} } } ... | 110Topological sort | 2perl | u96vr |
print(math.cos(1), math.sin(1), math.tan(1), math.atan(1), math.atan2(3, 4)) | 111Trigonometric functions | 1lua | 8wp0e |
data Tree a
= Empty
| Node
{ value :: a,
left :: Tree a,
right :: Tree a
}
preorder, inorder, postorder, levelorder :: Tree a -> [a]
preorder Empty = []
preorder (Node v l r) = v: preorder l <> preorder r
inorder Empty = []
inorder (Node v l r) = inorder l <> (v: inorder r)
postorder ... | 113Tree traversal | 8haskell | f8ed1 |
import java.io.File;
import java.util.*;
public class TopRankPerGroup {
private static class Employee {
final String name;
final String id;
final String department;
final int salary;
Employee(String[] rec) {
name = rec[0];
id = rec[1];
s... | 115Top rank per group | 9java | 9z0mu |
var data = [
{name: "Tyler Bennett", id: "E10297", salary: 32000, dept: "D101"},
{name: "John Rappl", id: "E21437", salary: 47000, dept: "D050"},
{name: "George Woltman", id: "E00127", salary: 53500, dept: "D101"},
{name: "Adam Smith", id: "E63535", salary: 18000, dept: "D202"},
{name: ... | 115Top rank per group | 10javascript | u9dvb |
String toTokenize = "Hello,How,Are,You,Today";
System.out.println(String.join(".", toTokenize.split(","))); | 116Tokenize a string | 9java | wbuej |
alert( "Hello,How,Are,You,Today".split(",").join(".") ); | 116Tokenize a string | 10javascript | 8w70l |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Hashtable;
public class TicTacToe
{
public static void main(String[] args)
{
TicTacToe now=new TicTacToe();
now.startMatch();
}
private int[][] marks;
private int[][] wins;
private int[] weights;
private char[][] grid;
priva... | 117Tic-tac-toe | 9java | kgyhm |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>TicTacToe</title>
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script> | 117Tic-tac-toe | 10javascript | ek2ao |
import java.util.*;
public class TreeTraversal {
static class Node<T> {
T value;
Node<T> left;
Node<T> right;
Node(T value) {
this.value = value;
}
void visit() {
System.out.print(this.value + " ");
}
}
static enum ORDER {
PREORDER, INORDER, POSTORDER, LEVEL
}
static <T> v... | 113Tree traversal | 9java | 0ehse |
use Benchmark;
use Memoize;
sub fac1 {
my $n = shift;
return $n == 0 ? 1 : $n * fac1($n - 1);
}
sub fac2 {
my $n = shift;
return $n == 0 ? 1 : $n * fac2($n - 1);
}
memoize('fac2');
my $result = timethese(100000, {
'fac1' => sub { fac1(50) },
'fac2' => sub { fac2(50) },
});
Benchmark::cmpthese(... | 118Time a function | 2perl | 3n1zs |
function BinaryTree(value, left, right) {
this.value = value;
this.left = left;
this.right = right;
}
BinaryTree.prototype.preorder = function(f) {this.walk(f,['this','left','right'])}
BinaryTree.prototype.inorder = function(f) {this.walk(f,['left','this','right'])}
BinaryTree.prototype.postorder = funct... | 113Tree traversal | 10javascript | d0anu |
fun main(args: Array<String>) {
val input = "Hello,How,Are,You,Today"
println(input.split(',').joinToString("."))
} | 116Tokenize a string | 11kotlin | br9kb |
null | 115Top rank per group | 11kotlin | ziets |
null | 117Tic-tac-toe | 11kotlin | g2f4d |
try:
from functools import reduce
except:
pass
data = {
'des_system_lib': set('std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee'.split()),
'dw01': set('ieee dw01 dware gtech'.split()),
'dw02': set('ieee dw02 dware'.split()),
'dw03': set('std s... | 110Topological sort | 3python | 5cyux |
deps <- list(
"des_system_lib" = c("std", "synopsys", "std_cell_lib", "des_system_lib", "dw02", "dw01", "ramlib", "ieee"),
"dw01" = c("ieee", "dw01", "dware", "gtech", "dw04"),
"dw02" = c("ieee", "dw02", "dware"),
"dw03" = c("std", "synopsys", "dware", "dw03", "dw02", "dw01", "ieee", "gtech"),
"dw04" = c("dw04", "ieee"... | 110Topological sort | 13r | l6tce |
N = 2
lst = { { "Tyler Bennett","E10297",32000,"D101" },
{ "John Rappl","E21437",47000,"D050" },
{ "George Woltman","E00127",53500,"D101" },
{ "Adam Smith","E63535",18000,"D202" },
{ "Claire Buckman","E39876",27800,"D202" },
{ "David McClellan","E04242",41500,"D101" },
{ "Rich Holcomb","E01234"... | 115Top rank per group | 1lua | 3nwzo |
data class Node(val v: Int, var left: Node? = null, var right: Node? = null) {
override fun toString() = "$v"
}
fun preOrder(n: Node?) {
n?.let {
print("$n ")
preOrder(n.left)
preOrder(n.right)
}
}
fun inorder(n: Node?) {
n?.let {
inorder(n.left)
print("$n ")
... | 113Tree traversal | 11kotlin | ek4a4 |
#!/usr/bin/env luajit
ffi=require"ffi"
local function printf(fmt,...) io.write(string.format(fmt, ...)) end
local board="123456789" | 117Tic-tac-toe | 1lua | rvtga |
import sys, timeit
def usec(function, arguments):
modname, funcname = __name__, function.__name__
timer = timeit.Timer(stmt='%(funcname)s(*args)'% vars(),
setup='from%(modname)s import%(funcname)s; args=%(arguments)r'% vars())
try:
t, N = 0, 1
while t < 0.2: ... | 118Time a function | 3python | 6da3w |
foo <- function()
{
for(i in 1:10)
{
mat <- matrix(rnorm(1e6), nrow=1e3)
mat^-0.5
}
}
timer <- system.time(foo())
timer["user.self"] | 118Time a function | 13r | f8kdc |
require 'tsort'
class Hash
include TSort
alias tsort_each_node each_key
def tsort_each_child(node, &block)
fetch(node).each(&block)
end
end
depends = {}
DATA.each do |line|
key, *libs = line.split
depends[key] = libs
libs.each {|lib| depends[lib] ||= []}
end
begin
p depends.tsort
depends[] <<
... | 110Topological sort | 14ruby | g294q |
function string:split (sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
self:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
local str = "Hello,How,Are,You,Today"
print(table.concat(str:split(","), ".")) | 116Tokenize a string | 1lua | p7cbw |
use std::boxed::Box;
use std::collections::{HashMap, HashSet};
#[derive(Debug, PartialEq, Eq, Hash)]
struct Library<'a> {
name: &'a str,
children: Vec<&'a str>,
num_parents: usize,
}
fn build_libraries(input: Vec<&str>) -> HashMap<&str, Box<Library>> {
let mut libraries: HashMap<&str, Box<Library>> = ... | 110Topological sort | 15rust | rvcg5 |
require 'benchmark'
Benchmark.bm(8) do |x|
x.report() { }
x.report() { (1..1_000_000).inject(4) {|sum, x| sum + x} }
end | 118Time a function | 14ruby | mtwyj |
null | 113Tree traversal | 1lua | wbgea |
null | 118Time a function | 15rust | 9zxmm |
def time(f: => Unit)={
val s = System.currentTimeMillis
f
System.currentTimeMillis - s
} | 118Time a function | 16scala | 2y0lb |
let libs = [
("des_system_lib", ["std", "synopsys", "std_cell_lib", "des_system_lib", "dw02", "dw01", "ramlib", "ieee"]),
("dw01", ["ieee", "dw01", "dware", "gtech"]),
("dw02", ["ieee", "dw02", "dware"]),
("dw03", ["std", "synopsys", "dware", "dw03", "dw02", "dw01", "ieee", "gtech"]),
("dw04", ["dw04", "ieee"... | 110Topological sort | 17swift | 4lm5g |
import Foundation
public struct TimeResult {
public var seconds: Double
public var nanoSeconds: Double
public var duration: Double { seconds + (nanoSeconds / 1e9) }
@usableFromInline
init(seconds: Double, nanoSeconds: Double) {
self.seconds = seconds
self.nanoSeconds = nanoSeconds
}
}
extension ... | 118Time a function | 17swift | yfe6e |
sub zip {
my @a = @{shift()};
my @b = @{shift()};
my @l;
push @l, shift @a, shift @b while @a and @b;
return @l;
}
sub uniq {
my %h;
grep {!$h{$_}++} @_;
}
my @data =
map {{ zip [qw(name id salary dept)], [split ','] }}
split "\n",
<<'EOF';
Tyler Bennett,E10297,32000,D101
John ... | 115Top rank per group | 2perl | brck4 |
use warnings;
use strict;
my $initial = join ",", qw(abc def ghi);
my %reverse = qw(X O O X);
my %cache;
sub best_move {
my ($b, $me) = @_;
if( exists $cache{$b,$me,wantarray} ) {
return $cache{$b,$me,wantarray};
} elsif( my $s = score( $b, $me ) ) {
return $cache{$b,$me,wantarray} = (wantarray ? undef : $s)... | 117Tic-tac-toe | 2perl | nshiw |
$data = Array(
Array(,,32000,),
Array(,,47000,),
Array(,,53500,),
Array(,,18000,),
Array(,,27800,),
Array(,,41500,),
Array(,,49500,),
Array(,,21900,),
Array(,,15900,),
Array(,,19250,),
Arr... | 115Top rank per group | 12php | 6dx3g |
use Math::Trig;
my $angle_degrees = 45;
my $angle_radians = pi / 4;
print sin($angle_radians), ' ', sin(deg2rad($angle_degrees)), "\n";
print cos($angle_radians), ' ', cos(deg2rad($angle_degrees)), "\n";
print tan($angle_radians), ' ', tan(deg2rad($angle_degrees)), "\n";
print cot($angle_radians), ' ', cot(deg2rad($a... | 111Trigonometric functions | 2perl | 5c6u2 |
<?php
const BOARD_NUM = 9;
const ROW_NUM = 3;
$EMPTY_BOARD_STR = str_repeat('.', BOARD_NUM);
function isGameOver($board, $pin) {
$pat =
'/X{3}|' .
'X..X..X..|' .
'.X..X..X.|' .
'..X..X..X|' .
'..X.X.X..|' .
'X...X...X|' .
'[^\.]{9}/i';
if ($pin == 'O') $pat = str_replace('X', 'O', $pat);
retur... | 117Tic-tac-toe | 12php | 7uzrp |
$radians = M_PI / 4;
$degrees = 45 * M_PI / 180;
echo sin($radians) . . sin($degrees);
echo cos($radians) . . cos($degrees);
echo tan($radians) . . tan($degrees);
echo asin(sin($radians)) . . asin(sin($radians)) * 180 / M_PI;
echo acos(cos($radians)) . . acos(cos($radians)) * 180 / M_PI;
echo atan(tan($radians)) .... | 111Trigonometric functions | 12php | ox185 |
package main
import "fmt" | 119Towers of Hanoi | 0go | 9zwmt |
'''
Tic-tac-toe game player.
Input the index of where you wish to place your mark at your turn.
'''
import random
board = list('123456789')
wins = ((0,1,2), (3,4,5), (6,7,8),
(0,3,6), (1,4,7), (2,5,8),
(0,4,8), (2,4,6))
def printboard():
print('\n'.join(' '.join(board[x:x+3]) for x in(0,3... | 117Tic-tac-toe | 3python | d0kn1 |
def tail = { list, n -> def m = list.size(); list.subList([m - n, 0].max(),m) }
final STACK = [A:[],B:[],C:[]].asImmutable()
def report = { it -> }
def check = { it -> }
def moveRing = { from, to -> to << from.pop(); report(); check(to) }
def moveStack
moveStack = { from, to, using = STACK.values().find { !(it.is... | 119Towers of Hanoi | 7groovy | zibt5 |
sub preorder
{
my $t = shift or return ();
return ($t->[0], preorder($t->[1]), preorder($t->[2]));
}
sub inorder
{
my $t = shift or return ();
return (inorder($t->[1]), $t->[0], inorder($t->[2]));
}
sub postorder
{
my $t = shift or return ();
return (postorder($t->[1]), postorder($t->[2]), $t->[0]);
}
sub dept... | 113Tree traversal | 2perl | c3i9a |
rm(list=ls())
library(RColorBrewer)
tic.tac.toe <- function(name="Name", mode=0, type=0){
place.na <<- matrix(1:9, 3, 3)
value <<- matrix(-3, 3, 3)
k <<- 1; r <<- 0
image(1:3, 1:3, matrix(sample(9), 3, 3), asp=c(1, 1),
xaxt="n", yaxt="n", xlab="", ylab="", frame=F, col=brewer.pal(9, "Set3"... | 117Tic-tac-toe | 13r | 8wr0x |
hanoi :: Integer -> a -> a -> a -> [(a, a)]
hanoi 0 _ _ _ = []
hanoi n a b c = hanoi (n-1) a c b ++ [(a,b)] ++ hanoi (n-1) c b a | 119Towers of Hanoi | 8haskell | br6k2 |
class Node {
private $left;
private $right;
private $value;
function __construct($value) {
$this->value = $value;
}
public function getLeft() {
return $this->left;
}
public function getRight() {
return $this->right;
}
public function getValue() {
... | 113Tree traversal | 12php | xprw5 |
print join('.', split /,/, 'Hello,How,Are,You,Today'), "\n"; | 116Tokenize a string | 2perl | 6dw36 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.