code stringlengths 1 46.1k ⌀ | label class label 1.18k
classes | domain_label class label 21
classes | index stringlengths 4 5 |
|---|---|---|---|
a1 = [[1, 2], [3, 4]]
b1 = [[0, 5], [6, 7]]
a2 = [[0, 1, 0], [1, 1, 1], [0, 1, 0]]
b2 = [[1, 1, 1, 1], [1, 0, 0, 1], [1, 1, 1, 1]]
def kronecker(matrix1, matrix2):
final_list = []
sub_list = []
count = len(matrix2)
for elem1 in matrix1:
counter = 0
check = 0
while check < co... | 673Kronecker product | 3python | hncjw |
sub maxnum {
join '', sort { "$b$a" cmp "$a$b" } @_
}
print maxnum(1, 34, 3, 98, 9, 76, 45, 4), "\n";
print maxnum(54, 546, 548, 60), "\n"; | 666Largest int from concatenated ints | 2perl | z7ntb |
(function(txt) {
var cs = txt.split(''),
i = cs.length,
dct = {},
c = '',
keys;
while (i--) {
c = cs[i];
dct[c] = (dct[c] || 0) + 1;
}
keys = Object.keys(dct);
keys.sort();
return keys.map(function (c) { return [c, dct[c]]; });
})("Not all tha... | 662Letter frequency | 10javascript | mp9yv |
fun isLeapYear(year: Int) = year% 400 == 0 || (year% 100!= 0 && year% 4 == 0) | 657Leap year | 11kotlin | g8b4d |
null | 672Koch curve | 15rust | 4s65u |
a <- matrix(c(1,1,1,1), ncol=2, nrow=2, byrow=TRUE);
b <- matrix(c(0,1,1,0), ncol=2, nrow=2, byrow=TRUE);
a%x% b | 673Kronecker product | 13r | g0647 |
function gcd( m, n )
while n ~= 0 do
local q = m
m = n
n = q % n
end
return m
end
function lcm( m, n )
return ( m ~= 0 and n ~= 0 ) and m * n / gcd( m, n ) or 0
end
print( lcm(12,18) ) | 667Least common multiple | 1lua | 6hd39 |
function leven(s,t)
if s == '' then return t:len() end
if t == '' then return s:len() end
local s1 = s:sub(2, -1)
local t1 = t:sub(2, -1)
if s:sub(0, 1) == t:sub(0, 1) then
return leven(s1, t1)
end
return 1 + math.min(
leven(s1, t1),
leven(s, t1),
leven(s1... | 656Levenshtein distance | 1lua | pzsbw |
import java.text.*;
import java.util.*;
public class LastFridays {
public static void main(String[] args) throws Exception {
int year = Integer.parseInt(args[0]);
GregorianCalendar c = new GregorianCalendar(year, 0, 1);
for (String mon: new DateFormatSymbols(Locale.US).getShortMonths()) {... | 671Last Friday of each month | 9java | iuaos |
function maxnum($nums) {
usort($nums, function ($x, $y) { return strcmp(, ); });
return implode('', $nums);
}
echo maxnum(array(1, 34, 3, 98, 9, 76, 45, 4)), ;
echo maxnum(array(54, 546, 548, 60)), ; | 666Largest int from concatenated ints | 12php | bf7k9 |
var last_friday_of_month, print_last_fridays_of_month;
last_friday_of_month = function(year, month) {
var i, last_day;
i = 0;
while (true) {
last_day = new Date(year, month, i);
if (last_day.getDay() === 5) {
return last_day.toDateString();
}
i -= 1;
}
};
print_last_fridays_of_month = fu... | 671Last Friday of each month | 10javascript | z7st2 |
null | 662Letter frequency | 11kotlin | oui8z |
fn main() {
let mut a = vec![vec![1., 2.], vec![3., 4.]];
let mut b = vec![vec![0., 5.], vec![6., 7.]];
let mut a_ref = &mut a;
let a_rref = &mut a_ref;
let mut b_ref = &mut b;
let b_rref = &mut b_ref;
let ab = kronecker_product(a_rref, b_rref);
println!("Kronecker product of\n");
... | 673Kronecker product | 15rust | ptvbu |
object KroneckerProduct
{
def getDimensions(matrix : Array[Array[Int]]) : (Int,Int) = {
val dimensions = matrix.map(x => x.size)
(dimensions.size, dimensions(0))
}
def kroneckerProduct(matrix1 : Array[Array[Int]], matrix2 : Array[Array[Int]]) : Array[Array[Int]] = {
val (r1,c1) = getDimensions(... | 673Kronecker product | 16scala | e64ab |
null | 671Last Friday of each month | 11kotlin | q9hx1 |
try:
cmp
def maxnum(x):
return ''.join(sorted((str(n) for n in x),
cmp=lambda x,y:cmp(y+x, x+y)))
except NameError:
from functools import cmp_to_key
def cmp(x, y):
return -1 if x<y else ( 0 if x==y else 1)
def maxnum(x):
return ''.join(... | 666Largest int from concatenated ints | 3python | 3jdzc |
function isLeapYear(year)
return year%4==0 and (year%100~=0 or year%400==0)
end | 657Leap year | 1lua | ropga |
func kronecker(m1: [[Int]], m2: [[Int]]) -> [[Int]] {
let m = m1.count
let n = m1[0].count
let p = m2.count
let q = m2[0].count
let rtn = m * p
let ctn = n * q
var res = Array(repeating: Array(repeating: 0, count: ctn), count: rtn)
for i in 0..<m {
for j in 0..<n {
for k in 0..<p {
f... | 673Kronecker product | 17swift | kdlhx |
Largest_int_from_concat_ints <- function(vec){
perm <- function(vec) {
n <- length(vec)
if (n == 1)
return(vec)
else {
x <- NULL
for (i in 1:n){
x <- rbind(x, cbind(vec[i], perm(vec[-i])))
}
return(x)
}
}
permutations <- perm(vec)
concat <- as.numer... | 666Largest int from concatenated ints | 13r | d48nt |
null | 662Letter frequency | 1lua | i5not |
function isLeapYear (y)
return (y % 4 == 0 and y % 100 ~=0) or y % 400 == 0
end
function dayOfWeek (y, m, d)
local t = os.time({year = y, month = m, day = d})
return os.date("%A", t)
end
function lastWeekdays (wday, year)
local monthLength, day = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
if... | 671Last Friday of each month | 1lua | sckq8 |
def icsort nums
nums.sort { |x, y| <=> }
end
[[54, 546, 548, 60], [1, 34, 3, 98, 9, 76, 45, 4]].each do |c|
p c
puts icsort(c).join
end | 666Largest int from concatenated ints | 14ruby | ykt6n |
package main
import (
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"os"
)
const (
up = iota
rt
dn
lt
)
func main() {
bounds := image.Rect(0, 0, 100, 100)
im := image.NewGray(bounds)
gBlack := color.Gray{0}
gWhite := color.Gray{255}
draw.Draw(im, bou... | 674Langton's ant | 0go | 82h0g |
fn maxcat(a: &mut [u32]) {
a.sort_by(|x, y| {
let xy = format!("{}{}", x, y);
let yx = format!("{}{}", y, x);
xy.cmp(&yx).reverse()
});
for x in a {
print!("{}", x);
}
println!();
}
fn main() {
maxcat(&mut [1, 34, 3, 98, 9, 76, 45, 4]);
maxcat(&mut [54, 546, ... | 666Largest int from concatenated ints | 15rust | mbzya |
import Data.Set (member,insert,delete,Set) | 674Langton's ant | 8haskell | laich |
object LIFCI extends App {
def lifci(list: List[Long]) = list.permutations.map(_.mkString).max
println(lifci(List(1, 34, 3, 98, 9, 76, 45, 4)))
println(lifci(List(54, 546, 548, 60)))
} | 666Largest int from concatenated ints | 16scala | laycq |
sub gcd {
my ($x, $y) = @_;
while ($x) { ($x, $y) = ($y % $x, $x) }
$y
}
sub lcm {
my ($x, $y) = @_;
($x && $y) and $x / gcd($x, $y) * $y or 0
}
print lcm(1001, 221); | 667Least common multiple | 2perl | pt7b0 |
echo lcm(12, 18) == 36;
function lcm($m, $n) {
if ($m == 0 || $n == 0) return 0;
$r = ($m * $n) / gcd($m, $n);
return abs($r);
}
function gcd($a, $b) {
while ($b != 0) {
$t = $b;
$b = $a % $b;
$a = $t;
}
return $a;
} | 667Least common multiple | 12php | ykf61 |
use List::Util qw(min);
my %cache;
sub leven {
my ($s, $t) = @_;
return length($t) if $s eq '';
return length($s) if $t eq '';
$cache{$s}{$t} //=
do {
my ($s1, $t1) = (substr($s, 1), substr($t, 1));
(substr($s, 0, 1) eq substr($t, 0, 1))
? leven($s1, $t1)
... | 656Levenshtein distance | 2perl | 6kv36 |
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Langton extends JFrame{
private JPanel planePanel;
private static final int ZOOM = 4;
public Langton(final boolean[][] plane){
planePanel = new JPanel(){
@Override
public void paint(Graphics... | 674Langton's ant | 9java | 3jxzg |
null | 674Langton's ant | 10javascript | c1o9j |
echo levenshtein('kitten','sitting');
echo levenshtein('rosettacode', 'raisethysword'); | 656Levenshtein distance | 12php | 130pq |
>>> import fractions
>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0
>>> lcm(12, 18)
36
>>> lcm(-6, 14)
42
>>> assert lcm(0, 2) == lcm(2, 0) == 0
>>> | 667Least common multiple | 3python | 1zjpc |
null | 674Langton's ant | 11kotlin | n5pij |
"%gcd%" <- function(u, v) {ifelse(u%% v!= 0, v%gcd% (u%%v), v)}
"%lcm%" <- function(u, v) { abs(u*v)/(u%gcd% v)}
print (50%lcm% 75) | 667Least common multiple | 13r | hn4jj |
use strict ;
use DateTime ;
use feature qw( say ) ;
foreach my $month ( 1..12 ) {
my $dt = DateTime->last_day_of_month( year => $ARGV[ 0 ] , month => $month ) ;
while ( $dt->day_of_week != 5 ) {
$dt->subtract( days => 1 ) ;
}
say $dt->ymd ;
} | 671Last Friday of each month | 2perl | vwz20 |
sub isleap {
my $year = shift;
if ($year % 100 == 0) {
return ($year % 400 == 0);
}
return ($year % 4 == 0);
} | 657Leap year | 2perl | n46iw |
<?php
function last_friday_of_month($year, $month) {
$day = 0;
while(True) {
$last_day = mktime(0, 0, 0, $month+1, $day, $year);
if (date(, $last_day) == 5) {
return date(, $last_day);
}
$day -= 1;
}
}
function print_last_fridays_of_month($year) {
foreach(range(1, 12) as $month) {
ec... | 671Last Friday of each month | 12php | 0lbsp |
irb(main):001:0> 12.lcm 18
=> 36 | 667Least common multiple | 14ruby | e6kax |
while (<>) { $cnt{lc chop}++ while length }
print "$_: ", $cnt{$_}//0, "\n" for 'a' .. 'z'; | 662Letter frequency | 2perl | g8r4e |
<?php
function isLeapYear($year) {
if ($year % 100 == 0) {
return ($year % 400 == 0);
}
return ($year % 4 == 0);
} | 657Leap year | 12php | 7i1rp |
use std::cmp::{max, min};
fn gcd(a: usize, b: usize) -> usize {
match ((a, b), (a & 1, b & 1)) {
((x, y), _) if x == y => y,
((0, x), _) | ((x, 0), _) => x,
((x, y), (0, 1)) | ((y, x), (1, 0)) => gcd(x >> 1, y),
((x, y), (0, 0)) => gcd(x >> 1, y >> 1) << 1,
((x, y), (1, 1)) ... | 667Least common multiple | 15rust | wybe4 |
local socket = require 'socket' | 674Langton's ant | 1lua | d41nq |
def gcd(a: Int, b: Int):Int=if (b==0) a.abs else gcd(b, a%b)
def lcm(a: Int, b: Int)=(a*b).abs/gcd(a,b) | 667Least common multiple | 16scala | scaqo |
def levenshteinDistance(str1, str2):
m = len(str1)
n = len(str2)
d = [[i] for i in range(1, m + 1)]
d.insert(0, list(range(0, n + 1)))
for j in range(1, n + 1):
for i in range(1, m + 1):
if str1[i - 1] == str2[j - 1]:
substitutionCost = 0
else... | 656Levenshtein distance | 3python | ybu6q |
<?php
print_r(array_count_values(str_split(file_get_contents($argv[1]))));
?> | 662Letter frequency | 12php | n4dig |
func lcm(a:Int, b:Int) -> Int {
return abs(a * b) / gcd_rec(a, b)
} | 667Least common multiple | 17swift | a3h1i |
import calendar
calendar.isleap(year) | 657Leap year | 3python | dgyn1 |
import calendar
def last_fridays(year):
for month in range(1, 13):
last_friday = max(week[calendar.FRIDAY]
for week in calendar.monthcalendar(year, month))
print('{:4d}-{:02d}-{:02d}'.format(year, month, last_friday)) | 671Last Friday of each month | 3python | ux3vd |
module Levenshtein
def self.distance(a, b)
a, b = a.downcase, b.downcase
costs = Array(0..b.length)
(1..a.length).each do |i|
costs[0], nw = i, i - 1
(1..b.length).each do |j|
costs[j], nw = [costs[j] + 1, costs[j-1] + 1, a[i-1] == b[j-1]? nw: nw + 1].min, costs[j]
end
en... | 656Levenshtein distance | 14ruby | 914mz |
isLeapYear <- function(year) {
ifelse(year%%100==0, year%%400==0, year%%4==0)
}
for (y in c(1900, 1994, 1996, 1997, 2000)) {
cat(y, ifelse(isLeapYear(y), "is", "isn't"), "a leap year.\n")
} | 657Leap year | 13r | 8vt0x |
null | 667Least common multiple | 20typescript | z7it8 |
year = commandArgs(T)
d = as.Date(paste0(year, "-01-01"))
fridays = d + seq(by = 7,
(5 - as.POSIXlt(d)$wday) %% 7,
364 + (months(d + 30 + 29) == "February"))
message(paste(collapse = "\n", fridays[tapply(
seq_along(fridays), as.POSIXlt(fridays)$mon, max)])) | 671Last Friday of each month | 13r | c1d95 |
fn main() {
println!("{}", levenshtein_distance("kitten", "sitting"));
println!("{}", levenshtein_distance("saturday", "sunday"));
println!("{}", levenshtein_distance("rosettacode", "raisethysword"));
}
fn levenshtein_distance(word1: &str, word2: &str) -> usize {
let w1 = word1.chars().collect::<Vec<_>... | 656Levenshtein distance | 15rust | cag9z |
object Levenshtein0 extends App {
def distance(s1: String, s2: String): Int = {
val dist = Array.tabulate(s2.length + 1, s1.length + 1) { (j, i) => if (j == 0) i else if (i == 0) j else 0 }
@inline
def minimum(i: Int*): Int = i.min
for {j <- dist.indices.tail
i <- dist(0).indices.tail} dis... | 656Levenshtein distance | 16scala | vxj2s |
import collections, sys
def filecharcount(openfile):
return sorted(collections.Counter(c for l in openfile for c in l).items())
f = open(sys.argv[1])
print(filecharcount(f)) | 662Letter frequency | 3python | ro7gq |
use strict;
my @dirs = ( [1,0], [0,-1], [-1,0], [0,1] );
my $size = 100;
my @plane;
for (0..$size-1) { $plane[$_] = [] };
my ($x, $y) = ($size/2, $size/2);
my $dir = int rand @dirs;
my $move;
for ($move = 0; $x >= 0 && $x < $size && $y >= 0 && $y < $size; $move++) {
if ($plane[$x][$y] = 1 - ($plane[$x]... | 674Langton's ant | 2perl | 7oyrh |
require 'date'
Date.leap?(year) | 657Leap year | 14ruby | t79f2 |
fn is_leap(year: i32) -> bool {
let factor = |x| year% x == 0;
factor(4) && (!factor(100) || factor(400))
} | 657Leap year | 15rust | zjcto |
define('dest_name', 'output.png');
define('width', 100);
define('height', 100);
$x = 50;
$y = 70;
$dir = 0;
$field = array();
$step_count = 0;
while(0 <= $x && $x <= width && 0 <= $y && $y <= height){
if(isset($field[$x][$y])){
unset($field[$x][$y]);
$dir = ($dir + 3) % 4;
}else{
$field[$x][$y] = true;
... | 674Langton's ant | 12php | fgadh |
letter.frequency <- function(filename)
{
file <- paste(readLines(filename), collapse = '')
chars <- strsplit(file, NULL)[[1]]
summary(factor(chars))
} | 662Letter frequency | 13r | uq5vx |
null | 657Leap year | 16scala | ybv63 |
require 'date'
def last_friday(year, month)
d = Date.new(year, month, -1)
d -= (d.wday - 5) % 7
end
year = Integer(ARGV.shift)
(1..12).each {|month| puts last_friday(year, month)} | 671Last Friday of each month | 14ruby | 4sy5p |
int main()
{
Display *d;
XEvent event;
d = XOpenDisplay(NULL);
if ( d != NULL ) {
XGrabKey(d, XKeysymToKeycode(d, XStringToKeysym()),
Mod1Mask,
DefaultRootWindow(d), True, GrabModeAsync, GrabModeAsync);
XGrabKey(d, XKeysymToKeycode(d, XStringToKeysym()),
Mod1Mask,... | 675Keyboard macros | 5c | q9gxc |
use std::env::args;
use time::{Date, Duration};
fn main() {
let year = args().nth(1).unwrap().parse::<i32>().unwrap();
(1..=12)
.map(|month| Date::try_from_ymd(year + month / 12, ((month% 12) + 1) as u8, 1))
.filter_map(|date| date.ok())
.for_each(|date| {
let days_back =
... | 671Last Friday of each month | 15rust | g0m4o |
(ns hello-seesaw.core
(:use seesaw.core))
(defn -main [& args]
(invoke-later
(-> (frame
:listen [:key-pressed (fn [e] (println (.getKeyChar e) " key pressed"))]
:on-close:exit)
pack!
show!))) | 675Keyboard macros | 6clojure | iukom |
import java.util.Calendar
import java.text.SimpleDateFormat
object Fridays {
def lastFridayOfMonth(year:Int, month:Int)={
val cal=Calendar.getInstance
cal.set(Calendar.YEAR, year)
cal.set(Calendar.MONTH, month)
cal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY)
cal.set(Calendar.DAY_OF_WEEK_IN_MONTH,... | 671Last Friday of each month | 16scala | jil7i |
func levDis(w1: String, w2: String) -> Int {
let (t, s) = (w1.characters, w2.characters)
let empty = Repeat(count: s.count, repeatedValue: 0)
var mat = [[Int](0...s.count)] + (1...t.count).map{[$0] + empty}
for (i, tLett) in t.enumerate() {
for (j, sLett) in s.enumerate() {
mat[i + 1][j + 1] = tLet... | 656Levenshtein distance | 17swift | mp5yk |
func isLeapYear(year: Int) -> Bool {
return year.isMultiple(of: 100)? year.isMultiple(of: 400): year.isMultiple(of: 4)
}
[1900, 1994, 1996, 1997, 2000].forEach { year in
print("\(year): \(isLeapYear(year: year)? "YES": "NO")")
} | 657Leap year | 17swift | frmdk |
package main
import "C"
import "fmt"
import "unsafe"
func main() {
d := C.XOpenDisplay(nil)
f7, f6 := C.CString("F7"), C.CString("F6")
defer C.free(unsafe.Pointer(f7))
defer C.free(unsafe.Pointer(f6))
if d != nil {
C.XGrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f7))),
... | 675Keyboard macros | 0go | 2eil7 |
from enum import Enum, IntEnum
class Dir(IntEnum):
UP = 0
RIGHT = 1
DOWN = 2
LEFT = 3
class Color(Enum):
WHITE =
BLACK =
def invert_color(grid, x, y):
if grid[y][x] == Color.BLACK:
grid[y][x] = Color.WHITE
else:
grid[y][x] = Color.BLACK
def next... | 674Langton's ant | 3python | jim7p |
def letter_frequency(file)
letters = 'a' .. 'z'
File.read(file) .
split(
group_by {|letter| letter.downcase} .
select {|key, val| letters.include? key} .
collect {|key, val| [key, val.length]}
end
letter_frequency(ARGV[0]).sort_by {|key, val| -val}.each {|pair| p pair} | 662Letter frequency | 14ruby | jnh7x |
langton.ant = function(n = 100) {
map = matrix(data = 0, nrow = n, ncol = n)
p = floor(c(n/2, n/2))
d = sample(1:4, 1)
i = 1
while(p[1] > 0 & p[1] <= n & p[2] > 0 & p[2] <= n) {
if(map[p[1], p[2]] == 1) {
map[p[1], p[2]] = 0
p = p + switch(d, c(0, 1), c(-1, 0), c(0, -1), c(1, 0))
d = ifelse(d == 4, 1, d... | 674Langton's ant | 13r | 4sz5y |
void set_mode(int want_key)
{
static struct termios old, new;
if (!want_key) {
tcsetattr(STDIN_FILENO, TCSANOW, &old);
return;
}
tcgetattr(STDIN_FILENO, &old);
new = old;
new.c_lflag &= ~(ICANON);
tcsetattr(STDIN_FILENO, TCSANOW, &new);
}
int get_key(int no_timeout)
{
int c = 0;
struct timeval tv;
fd_se... | 676Keyboard input/Obtain a Y or N response | 5c | 3jeza |
package keybord.macro.demo;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
class KeyboardMacroDemo {
public static void main( String [] args ) {
final JFrame frame = new JFrame();
String directions = "<html><b>Ctrl-S</b> to ... | 675Keyboard macros | 9java | jiy7c |
use std::collections::btree_map::BTreeMap;
use std::{env, process};
use std::io::{self, Read, Write};
use std::fmt::Display;
use std::fs::File;
fn main() {
let filename = env::args().nth(1)
.ok_or("Please supply a file name")
.unwrap_or_else(|e| exit_err(e, 1));
let mut buf = String::new();
... | 662Letter frequency | 15rust | hdkj2 |
SELECT to_char( next_day( last_day( add_months( to_date(
:yr||'01','yyyymm' ),level-1))-7,'Fri') ,'yyyy-mm-dd Dy') lastfriday
FROM dual
CONNECT BY level <= 12; | 671Last Friday of each month | 19sql | bfuks |
function levenshtein(a: string, b: string): number {
const m: number = a.length,
n: number = b.length;
let t: number[] = [...Array(n + 1).keys()],
u: number[] = [];
for (let i: number = 0; i < m; i++) {
u = [i + 1];
for (let j: number = 0; j < n; j++) {
u[j + 1] = a[i] === b[... | 656Levenshtein distance | 20typescript | kfxhe |
document.onkeydown = function(evt) {
if (evt.keyCode === 118) {
alert("You pressed F7!");
return false;
}
} | 675Keyboard macros | 10javascript | 1z2p7 |
$ lein trampoline run | 676Keyboard input/Obtain a Y or N response | 6clojure | c109b |
null | 675Keyboard macros | 11kotlin | 5qfua |
struct item { double w, v; const char *name; } items[] = {
{ 3.8, 36, },
{ 5.4, 43, },
{ 3.6, 90, },
{ 2.4, 45, },
{ 4.0, 30, },
{ 2.5, 56, },
{ 3.7, 67, },
{ 3.0, 95, },
{ 5.9, 98, },
};
int item_cmp(const void *aa, const void *bb)
{
const struct item *a = aa, *b = bb;
double ua = a->v / a->w, ub ... | 677Knapsack problem/Continuous | 5c | r8tg7 |
import io.Source.fromFile
def letterFrequencies(filename: String) =
fromFile(filename).mkString groupBy (c => c) mapValues (_.length) | 662Letter frequency | 16scala | pz1bj |
import Foundation
func lastFridays(of year: Int) -> [Date] {
let calendar = Calendar.current
var dates = [Date]()
for month in 2...13 {
let lastDayOfMonth = DateComponents(calendar: calendar,
year: year,
month: month,
... | 671Last Friday of each month | 17swift | 5q6u8 |
typedef struct {
char *name;
int weight;
int value;
int count;
} item_t;
item_t items[] = {
{, 9, 150, 1},
{, 13, 35, 1},
{, 153, 200, 2},
{, 50, 60, 2},
{, 15, 60, 2},
{,... | 678Knapsack problem/Bounded | 5c | 82g04 |
class Ant
class OutOfBoundsException < StandardError; end
class Plane
def initialize(x, y)
@size_x, @size_y = x, y
@cells = Array.new(y) {Array.new(x, :white)}
end
def white?(px, py)
@cells[py][px] == :white
end
def toggle_colour(px, py)
@cells[py][px] = (white?(px, p... | 674Langton's ant | 14ruby | kdchg |
use strict;
use warnings;
use Term::ReadKey;
ReadMode 4;
sub logger { my($message) = @_; print "$message\n" }
while (1) {
if (my $c = ReadKey 0) {
if ($c eq 'q') { logger "QUIT"; last }
elsif ($c =~ /\n|\r/) { logger "CR" }
elsif ($c eq "j") { logger "down" }
elsif ($c eq "k") {... | 675Keyboard macros | 2perl | ovh8x |
(def maxW 15.0)
(def items
{:beef [3.8 36]
:pork [5.4 43]
:ham [3.6 90]
:greaves [2.4 45]
:flitch [4.0 30]
:brawn [2.5 56]
:welt [3.7 67]
:salami [3.0 95]
:sausage [5.9 98]})
(defn rob [items maxW]
(let[
val-item
(fn[key]
(- (/ (second (items key)) (first (it... | 677Knapsack problem/Continuous | 6clojure | bfmkz |
struct Ant {
x: usize,
y: usize,
dir: Direction
}
#[derive(Clone,Copy)]
enum Direction {
North,
East,
South,
West
}
use Direction::*;
impl Ant {
fn mv(&mut self, vec: &mut Vec<Vec<u8>>) {
let pointer = &mut vec[self.y][self.x]; | 674Langton's ant | 15rust | bflkx |
(ns knapsack
(:gen-class))
(def groupeditems [
["map", 9, 150, 1]
["compass", 13, 35, 1]
["water", 153, 200, 3]
["sandwich", 50, 60, 2]
["glucose", 15, 60, 2]
["tin", 68, 45, 3]
["bana... | 678Knapsack problem/Bounded | 6clojure | fgkdm |
typedef struct {
char *name;
double value;
double weight;
double volume;
} item_t;
item_t items[] = {
{, 3000.0, 0.3, 0.025},
{, 1800.0, 0.2, 0.015},
{, 2500.0, 2.0, 0.002},
};
int n = sizeof (items) / sizeof (item_t);
int *count;
int *best;
double best_value;
void knapsack (int i, d... | 679Knapsack problem/Unbounded | 5c | scuq5 |
class Langton(matrix:Array[Array[Char]], ant:Ant) {
import Langton._
val rows=matrix.size
val cols=matrix(0).size
def isValid = 0 <= ant.row && ant.row < cols && 0 <= ant.col && ant.col < rows
def isBlack=matrix(ant.row)(ant.col)==BLACK
def changeColor(c:Char)={matrix(ant.row)(ant.col)=c; matrix}
def e... | 674Langton's ant | 16scala | a3u1n |
void set_mode(int want_key)
{
static struct termios old, new;
if (!want_key) {
tcsetattr(STDIN_FILENO, TCSANOW, &old);
return;
}
tcgetattr(STDIN_FILENO, &old);
new = old;
new.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &new);
}
int get_key()
{
int c = 0;
struct timeval tv;
fd_set fs;
... | 680Keyboard input/Keypress check | 5c | ov480 |
while read -t 0.01; do
true
done | 681Keyboard input/Flush the keyboard buffer | 4bash | bfzkn |
int main(int argc, char* argv[])
{
char text[256];
getchar();
fseek(stdin, 0, SEEK_END);
fgets(text, sizeof(text), stdin);
puts(text);
return EXIT_SUCCESS;
} | 681Keyboard input/Flush the keyboard buffer | 5c | 1z6pj |
(defstruct item :value :weight :volume)
(defn total [key items quantities]
(reduce + (map * quantities (map key items))))
(defn max-count [item max-weight max-volume]
(let [mcw (/ max-weight (:weight item))
mcv (/ max-volume (:volume item))]
(min mcw mcv))) | 679Knapsack problem/Unbounded | 6clojure | n57ik |
import curses
def print_message():
stdscr.addstr('This is the message.\n')
stdscr = curses.initscr()
curses.noecho()
curses.cbreak()
stdscr.keypad(1)
stdscr.addstr('CTRL+P for message or q to quit.\n')
while True:
c = stdscr.getch()
if c == 16: print_message()
elif c == ord('q'): break
curses.nocbre... | 675Keyboard macros | 3python | iukof |
import Foundation
let dictPath: String
switch CommandLine.arguments.count {
case 2:
dictPath = CommandLine.arguments[1]
case _:
dictPath = "/usr/share/dict/words"
}
let wordsData = FileManager.default.contents(atPath: dictPath)!
let allWords = String(data: wordsData, encoding: .utf8)!
let words = allWords.compon... | 662Letter frequency | 17swift | 7ijrq |
import Foundation
let WIDTH = 100
let HEIGHT = 100
struct Point {
var x:Int
var y:Int
}
enum Direction: Int {
case North = 0, East, West, South
}
class Langton {
let leftTurn = [Direction.West, Direction.North, Direction.South, Direction.East]
let rightTurn = [Direction.East, Direction.South, Di... | 674Langton's ant | 17swift | hn9j0 |
$ lein trampoline run | 680Keyboard input/Keypress check | 6clojure | trhfv |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.