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 < count:
for num1 in elem1:
for num2 in matrix2[counter]:
sub_list.append(num1 * num2)
counter += 1
final_list.append(sub_list)
sub_list = []
check +=1
return final_list
result1 = kronecker(a1, b1)
for elem in result1:
print(elem)
print()
result2 = kronecker(a2, b2)
for elem in result2:
print(elem) | 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 that Mrs. Bennet, however, with the assistance of her five\
daughters, could ask on the subject, was sufficient to draw from her\
husband any satisfactory description of Mr. Bingley. They attacked him\
in various ways--with barefaced questions, ingenious suppositions, and\
distant surmises; but he eluded the skill of them all, and they were at\
last obliged to accept the second-hand intelligence of their neighbour,\
Lady Lucas. Her report was highly favourable. Sir William had been\
delighted with him. He was quite young, wonderfully handsome, extremely\
agreeable, and, to crown the whole, he meant to be at the next assembly\
with a large party. Nothing could be more delightful! To be fond of\
dancing was a certain step towards falling in love; and very lively\
hopes of Mr. Bingley's heart were entertained."); | 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, t )
)
end
print(leven("kitten", "sitting"))
print(leven("rosettacode", "raisethysword")) | 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()) {
if (!mon.isEmpty()) {
int totalDaysOfMonth = c.getActualMaximum(Calendar.DAY_OF_MONTH);
c.set(Calendar.DAY_OF_MONTH, totalDaysOfMonth);
int daysToRollBack = (c.get(Calendar.DAY_OF_WEEK) + 1) % 7;
int day = totalDaysOfMonth - daysToRollBack;
c.set(Calendar.DAY_OF_MONTH, day);
System.out.printf("%d%s%d\n", year, mon, day);
c.set(year, c.get(Calendar.MONTH) + 1, 1);
}
}
}
} | 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 = function(year) {
var month, results;
results = [];
for (month = 1; month <= 12; ++month) {
results.push(console.log(last_friday_of_month(year, month)));
}
return results;
};
(function() {
var year;
year = parseInt(process.argv[2]);
return print_last_fridays_of_month(year);
})(); | 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");
for i in a {
println!("{:?}", i);
}
println!("\nand\n");
for i in b {
println!("{:?}", i);
}
println!("\nis\n");
for i in ab {
println!("{:?}", i);
}
println!("\n\n");
let mut a = vec![vec![0., 1., 0.],
vec![1., 1., 1.],
vec![0., 1., 0.]];
let mut b = vec![vec![1., 1., 1., 1.],
vec![1., 0., 0., 1.],
vec![1., 1., 1., 1.]];
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");
for i in a {
println!("{:?}", i);
}
println!("\nand\n");
for i in b {
println!("{:?}", i);
}
println!("\nis\n");
for i in ab {
println!("{:?}", i);
}
println!("\n\n");
}
fn kronecker_product(a: &mut Vec<Vec<f64>>, b: &mut Vec<Vec<f64>>) -> Vec<Vec<f64>> {
let m = a.len();
let n = a[0].len();
let p = b.len();
let q = b[0].len();
let rtn = m * p;
let ctn = n * q;
let mut r = zero_matrix(rtn, ctn);
for i in 0..m {
for j in 0..n {
for k in 0..p {
for l in 0..q {
r[p * i + k][q * j + l] = a[i][j] * b[k][l];
}
}
}
}
r
}
fn zero_matrix(rows: usize, cols: usize) -> Vec<Vec<f64>> {
let mut matrix = Vec::with_capacity(cols);
for _ in 0..rows {
let mut col: Vec<f64> = Vec::with_capacity(rows);
for _ in 0..cols {
col.push(0.0);
}
matrix.push(col);
}
matrix
} | 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(matrix1)
val (r2,c2) = getDimensions(matrix2)
val res = Array.ofDim[Int](r1*r2, c1*c2)
for(
i <- 0 until r1;
j <- 0 until c1;
k <- 0 until r2;
l <- 0 until c2
){
res(r2 * i + k)(c2 * j + l) = matrix1(i)(j) * matrix2(k)(l)
}
res
}
def main(args: Array[String]): Unit = {
val m1 = Array(Array(1, 2), Array(3, 4))
val m2 = Array(Array(0, 5), Array(6, 7))
println(kroneckerProduct(m1,m2).map(_.mkString("|")).mkString("\n"))
println("----------")
val m3 = Array(Array(0, 1, 0), Array(1, 1, 1), Array(0, 1, 0))
val m4 = Array(Array(1, 1, 1, 1), Array(1, 0, 0, 1), Array(1, 1, 1, 1))
println(kroneckerProduct(m3,m4).map(_.mkString("|")).mkString("\n"))
}
} | 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(sorted((str(n) for n in x),
key=cmp_to_key(lambda x,y:cmp(y+x, x+y))))
for numbers in [(1, 34, 3, 98, 9, 76, 45, 4), (54, 546, 548, 60)]:
print('Numbers:%r\n Largest integer:%15s'% (numbers, maxnum(numbers))) | 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 {
for l in 0..<q {
res[p * i + k][q * j + l] = m1[i][j] * m2[k][l]
}
}
}
}
return res
}
func printMatrix<T>(_ matrix: [[T]]) {
guard!matrix.isEmpty else {
print()
return
}
let rows = matrix.count
let cols = matrix[0].count
for i in 0..<rows {
for j in 0..<cols {
print(matrix[i][j], terminator: " ")
}
print()
}
}
func printProducts(a: [[Int]], b: [[Int]]) {
print("Matrix A:")
printMatrix(a)
print("Matrix B:")
printMatrix(b)
print("kronecker a b:")
printMatrix(kronecker(m1: a, m2: b))
print()
}
let a = [
[1, 2],
[3, 4]
]
let b = [
[0, 5],
[6, 7]
]
printProducts(a: a, b: b)
let a2 = [
[0, 1, 0],
[1, 1, 1],
[0, 1, 0]
]
let b2 = [
[1, 1, 1, 1],
[1, 0, 0, 1],
[1, 1, 1, 1]
]
printProducts(a: a2, b: b2) | 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.numeric(apply(permutations, 1, paste, collapse = ""))
return(max(concat))
}
Largest_int_from_concat_ints(c(54, 546, 548, 60))
Largest_int_from_concat_ints(c(1, 34, 3, 98, 9, 76, 45, 4))
Largest_int_from_concat_ints(c(93, 4, 89, 21, 73)) | 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 isLeapYear(year) then monthLength[2] = 29 end
for month = 1, 12 do
day = monthLength[month]
while dayOfWeek(year, month, day) ~= wday do day = day - 1 end
print(year .. "-" .. month .. "-" .. day)
end
end
lastWeekdays("Friday", tonumber(arg[1])) | 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, bounds, image.NewUniform(gWhite), image.ZP, draw.Src)
pos := image.Point{50, 50}
dir := up
for pos.In(bounds) {
switch im.At(pos.X, pos.Y).(color.Gray).Y {
case gBlack.Y:
im.SetGray(pos.X, pos.Y, gWhite)
dir--
case gWhite.Y:
im.SetGray(pos.X, pos.Y, gBlack)
dir++
}
if dir&1 == 1 {
pos.X += 1 - dir&2
} else {
pos.Y -= 1 - dir&2
}
}
f, err := os.Create("ant.png")
if err != nil {
fmt.Println(err)
return
}
if err = png.Encode(f, im); err != nil {
fmt.Println(err)
}
if err = f.Close(); err != nil {
fmt.Println(err)
}
} | 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, 548, 60]);
} | 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)
: 1 + min(
leven($s1, $t1),
leven($s, $t1),
leven($s1, $t ),
);
};
}
print leven('rosettacode', 'raisethysword'), "\n"; | 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 g) {
for(int y = 0; y < plane.length;y++){
for(int x = 0; x < plane[0].length;x++){
g.setColor(plane[y][x] ? Color.BLACK : Color.WHITE);
g.fillRect(x * ZOOM, y * ZOOM, ZOOM, ZOOM);
}
} | 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) {
echo last_friday_of_month($year, $month), ;
}
}
date_default_timezone_set();
$year = 2012;
print_last_fridays_of_month($year);
?> | 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)) => {
let (x, y) = (min(x, y), max(x, y));
gcd((y - x) >> 1, x)
}
_ => unreachable!(),
}
}
fn lcm(a: usize, b: usize) -> usize {
a * b / gcd(a, b)
}
fn main() {
println!("{}", lcm(6324, 234))
} | 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:
substitutionCost = 1
d[i].insert(j, min(d[i - 1][j] + 1,
d[i][j - 1] + 1,
d[i - 1][j - 1] + substitutionCost))
return d[-1][-1]
print(levenshteinDistance(,))
print(levenshteinDistance(,)) | 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
end
costs[b.length]
end
def self.test
%w{kitten sitting saturday sunday rosettacode raisethysword}.each_slice(2) do |a, b|
puts
end
end
end
Levenshtein.test | 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<_>>();
let w2 = word2.chars().collect::<Vec<_>>();
let word1_length = w1.len() + 1;
let word2_length = w2.len() + 1;
let mut matrix = vec![vec![0; word1_length]; word2_length];
for i in 1..word1_length { matrix[0][i] = i; }
for j in 1..word2_length { matrix[j][0] = j; }
for j in 1..word2_length {
for i in 1..word1_length {
let x: usize = if w1[i-1] == w2[j-1] {
matrix[j-1][i-1]
} else {
1 + std::cmp::min(
std::cmp::min(matrix[j][i-1], matrix[j-1][i])
, matrix[j-1][i-1])
};
matrix[j][i] = x;
}
}
matrix[word2_length-1][word1_length-1]
} | 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} dist(j)(i) =
if (s2(j - 1) == s1(i - 1)) dist(j - 1)(i - 1)
else minimum(dist(j - 1)(i) + 1, dist(j)(i - 1) + 1, dist(j - 1)(i - 1) + 1)
dist(s2.length)(s1.length)
}
def printDistance(s1: String, s2: String) {
println("%s ->%s:%d".format(s1, s2, distance(s1, s2)))
}
printDistance("kitten", "sitting")
printDistance("rosettacode", "raisethysword")
} | 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][$y] ||= 0)) {
$dir = ($dir - 1) % @dirs;
} else {
$dir = ($dir + 1) % @dirs;
}
$x += $dirs[$dir][0];
$y += $dirs[$dir][1];
}
print "Out of bounds after $move moves at ($x, $y)\n";
for (my $y=0; $y<$size; ++$y) {
for (my $x=0; $x<$size; ++$x) {
print $plane[$x][$y] ? '
}
print "\n";
} | 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;
$dir = ($dir + 1) % 4;
}
switch($dir){
case 0: $y++; break;
case 1: $x--; break;
case 2: $y--; break;
case 3: $x++; break;
}
$step_count++;
}
$img = imagecreatetruecolor(width, height);
$white = imagecolorallocate($img, 255, 255, 255);
for($x = 0; $x < width; $x++){
for($y = 0; $y < height; $y++){
if(isset($field[$x][$y])){
imagesetpixel($img, $x, $y, $white);
}
}
}
$color = array();
$color[0] = imagecolorallocate($img, 255, 0, 0);
$color[1] = imagecolorallocate($img, 0, 255, 0);
$color[2] = imagecolorallocate($img, 0, 0, 255);
$print_array = array(
0 => 'Langton`s Ant', 1=>'PHP Version', 2=>'Steps: ' . $step_count
);
foreach($print_array as $key => $line){
imagestring($img, 3, 3, 3 + $key*11, $line, $color[$key]);
}
imagepng($img, dest_name); | 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,
DefaultRootWindow(d), True, GrabModeAsync, GrabModeAsync);
for(;;)
{
XNextEvent(d, &event);
if ( event.type == KeyPress ) {
KeySym s = XLookupKeysym(&event.xkey, 0);
if ( s == XK_F7 ) {
printf();
} else if ( s == XK_F6 ) {
break;
}
}
}
XUngrabKey(d, XKeysymToKeycode(d, XStringToKeysym()), Mod1Mask, DefaultRootWindow(d));
XUngrabKey(d, XKeysymToKeycode(d, XStringToKeysym()), Mod1Mask, DefaultRootWindow(d));
}
return EXIT_SUCCESS;
} | 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 =
Duration::days(((date.weekday().number_from_sunday() as i64)% 7) + 1);
println!("{}", date - 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, -1)
cal.getTime
}
def fridaysOfYear(year:Int)=for(month <- 0 to 11) yield lastFridayOfMonth(year, month)
def main(args:Array[String]){
val year=args(0).toInt
val formatter=new SimpleDateFormat("yyyy-MMM-dd")
fridaysOfYear(year).foreach{date=>
println(formatter.format(date))
}
}
} | 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] = tLett == sLett?
mat[i][j]: min(mat[i][j], mat[i][j + 1], mat[i + 1][j]).successor()
}
}
return mat.last!.last!
} | 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))),
C.Mod1Mask,
C.DefaultRootWindow_macro(d), C.True, C.GrabModeAsync, C.GrabModeAsync)
C.XGrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f6))),
C.Mod1Mask,
C.DefaultRootWindow_macro(d), C.True, C.GrabModeAsync, C.GrabModeAsync)
var event C.XEvent
for {
C.XNextEvent(d, &event)
if C.getXEvent_type(event) == C.KeyPress {
xkeyEvent := C.getXEvent_xkey(event)
s := C.XLookupKeysym(&xkeyEvent, 0)
if s == C.XK_F7 {
fmt.Println("something's happened")
} else if s == C.XK_F6 {
break
}
}
}
C.XUngrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f7))), C.Mod1Mask, C.DefaultRootWindow_macro(d))
C.XUngrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f6))), C.Mod1Mask, C.DefaultRootWindow_macro(d))
} else {
fmt.Println("XOpenDisplay did not succeed")
}
} | 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_direction(grid, x, y, direction):
if grid[y][x] == Color.BLACK:
turn_right = False
else:
turn_right = True
direction_index = direction.value
if turn_right:
direction_index = (direction_index + 1)% 4
else:
direction_index = (direction_index - 1)% 4
directions = [Dir.UP, Dir.RIGHT, Dir.DOWN, Dir.LEFT]
direction = directions[direction_index]
return direction
def next_position(x, y, direction):
if direction == Dir.UP:
y -= 1
elif direction == Dir.RIGHT:
x -= 1
elif direction == Dir.DOWN:
y += 1
elif direction == Dir.LEFT:
x += 1
return x, y
def print_grid(grid):
print(80 * )
print(.join(.join(v.value for v in row) for row in grid))
def ant(width, height, max_nb_steps):
grid = [[Color.WHITE] * width for _ in range(height)]
x = width
y = height
direction = Dir.UP
i = 0
while i < max_nb_steps and 0 <= x < width and 0 <= y < height:
invert_color(grid, x, y)
direction = next_direction(grid, x, y, direction)
x, y = next_position(x, y, direction)
print_grid(grid)
i += 1
if __name__ == :
ant(width=75, height=52, max_nb_steps=12000) | 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 + 1)
} else {
map[p[1], p[2]] = 1
p = p + switch(d, c(0, -1), c(1, 0), c(0, 1), c(-1, 0))
d = ifelse(d == 1, 4, d - 1)
}
}
return(map)
}
image(langton.ant(), xaxt = "n", yaxt = "n", bty = "n") | 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_set fs;
tv.tv_usec = tv.tv_sec = 0;
FD_ZERO(&fs);
FD_SET(STDIN_FILENO, &fs);
select(STDIN_FILENO + 1, &fs, 0, 0, no_timeout ? 0 : &tv);
if (FD_ISSET(STDIN_FILENO, &fs)) {
c = getchar();
set_mode(0);
}
return c;
}
int main()
{
int c;
while(1) {
set_mode(1);
while (get_key(0));
printf();
fflush(stdout);
c = get_key(1);
if (c == 'Y' || c == 'y') {
printf();
continue;
}
if (c == 'N' || c == 'n') {
printf();
break;
}
printf();
}
return 0;
} | 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 show frame title<br>"
+"<b>Ctrl-H</b> to hide it</html>";
frame.add( new JLabel(directions));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.addKeyListener( new KeyAdapter(){
public void keyReleased( KeyEvent e ) {
if( e.isControlDown() && e.getKeyCode() == KeyEvent.VK_S){
frame.setTitle("Hello there");
}else if( e.isControlDown() && e.getKeyCode() == KeyEvent.VK_H){
frame.setTitle("");
}
}
});
frame.pack();
frame.setVisible(true);
}
} | 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();
let mut count = BTreeMap::new();
File::open(&filename)
.unwrap_or_else(|e| exit_err(e, 2))
.read_to_string(&mut buf)
.unwrap_or_else(|e| exit_err(e, 3));
for c in buf.chars() {
*count.entry(c).or_insert(0) += 1;
}
println!("Number of occurences per character");
for (ch, count) in &count {
println!("{:?}: {}", ch, count);
}
}
#[inline]
fn exit_err<T>(msg: T, code: i32) ->! where T: Display {
writeln!(&mut io::stderr(), "{}", msg).expect("Could not write to stderr");
process::exit(code)
} | 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[j]? t[j]: Math.min(t[j], t[j + 1], u[j]) + 1;
}
t = u;
}
return u[n];
} | 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 = b->v / b->w;
return ua < ub ? -1 : ua > ub;
}
int main()
{
struct item *it;
double space = 15;
qsort(items, 9, sizeof(struct item), item_cmp);
for (it = items + 9; it---items && space > 0; space -= it->w)
if (space >= it->w)
printf(, it->name);
else
printf(,
space, it->w, it->name);
return 0;
} | 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,
day: 0,
hour: 12)
let date = calendar.date(from: lastDayOfMonth)!
let isFriday = calendar.component(.weekday, from: date) == 6
if isFriday {
dates.append(calendar.date(from: lastDayOfMonth)!)
} else {
let lastWeekofMonth = calendar.ordinality(of: .weekOfMonth,
in: .month,
for: date)!
let lastWithFriday = lastWeekofMonth - (calendar.component(.weekday, from: date) > 6? 0: 1)
let lastFridayOfMonth = DateComponents(calendar: calendar,
year: year,
month: month - 1,
hour: 12,
weekday: 6,
weekOfMonth: lastWithFriday)
dates.append(calendar.date(from: lastFridayOfMonth)!)
}
}
return dates
}
var dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
print(lastFridays(of: 2013).map(dateFormatter.string).joined(separator: "\n")) | 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},
{, 68, 45, 3},
{, 27, 60, 3},
{, 39, 40, 3},
{, 23, 30, 1},
{, 52, 10, 3},
{, 11, 70, 1},
{, 32, 30, 1},
{, 24, 15, 2},
{, 48, 10, 2},
{, 73, 40, 1},
{, 42, 70, 1},
{, 43, 75, 1},
{, 22, 80, 1},
{, 7, 20, 1},
{, 18, 12, 2},
{, 4, 50, 1},
{, 30, 10, 2},
};
int n = sizeof (items) / sizeof (item_t);
int *knapsack (int w) {
int i, j, k, v, *mm, **m, *s;
mm = calloc((n + 1) * (w + 1), sizeof (int));
m = malloc((n + 1) * sizeof (int *));
m[0] = mm;
for (i = 1; i <= n; i++) {
m[i] = &mm[i * (w + 1)];
for (j = 0; j <= w; j++) {
m[i][j] = m[i - 1][j];
for (k = 1; k <= items[i - 1].count; k++) {
if (k * items[i - 1].weight > j) {
break;
}
v = m[i - 1][j - k * items[i - 1].weight] + k * items[i - 1].value;
if (v > m[i][j]) {
m[i][j] = v;
}
}
}
}
s = calloc(n, sizeof (int));
for (i = n, j = w; i > 0; i--) {
int v = m[i][j];
for (k = 0; v != m[i - 1][j] + k * items[i - 1].value; k++) {
s[i - 1]++;
j -= items[i - 1].weight;
}
}
free(mm);
free(m);
return s;
}
int main () {
int i, tc = 0, tw = 0, tv = 0, *s;
s = knapsack(400);
for (i = 0; i < n; i++) {
if (s[i]) {
printf(, items[i].name, s[i], s[i] * items[i].weight, s[i] * items[i].value);
tc += s[i];
tw += s[i] * items[i].weight;
tv += s[i] * items[i].value;
}
}
printf(, , tc, tw, tv);
return 0;
} | 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, py)? :black: :white)
end
def check_bounds(px, py)
unless (0 <= px and px < @size_x) and (0 <= py and py < @size_y)
raise OutOfBoundsException,
end
end
def to_s
@cells.collect {|row|
row.collect {|cell| cell == :white? : }.join +
}.join
end
end
dir_move = [[:north, [0,-1]], [:east, [1,0]], [:south, [0,1]], [:west, [-1,0]]]
Move = Hash[dir_move]
directions = dir_move.map{|dir, move| dir}
Right = Hash[ directions.zip(directions.rotate).to_a ]
Left = Right.invert
def initialize(size_x, size_y, pos_x=size_x/2, pos_y=size_y/2)
@plane = Plane.new(size_x, size_y)
@pos_x, @pos_y = pos_x, pos_y
@direction = :south
@plane.check_bounds(@pos_x, @pos_y)
end
def run
moves = 0
loop do
begin
moves += 1
move
rescue OutOfBoundsException
break
end
end
moves
end
def move
@plane.toggle_colour(@pos_x, @pos_y)
advance
if @plane.white?(@pos_x, @pos_y)
@direction = Right[@direction]
else
@direction = Left[@direction]
end
end
def advance
dx, dy = Move[@direction]
@pos_x += dx
@pos_y += dy
@plane.check_bounds(@pos_x, @pos_y)
end
def position
end
def to_s
@plane.to_s
end
end
ant = Ant.new(100, 100)
moves = ant.run
puts
puts ant | 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") { logger "up" }
elsif ($c eq "h") { logger "left" }
elsif ($c eq "l") { logger "right" }
elsif ($c eq "J") { logger "DOWN" }
elsif ($c eq "K") { logger "UP" }
elsif ($c eq "H") { logger "LEFT" }
elsif ($c eq "L") { logger "RIGHT" }
elsif ($c eq "\e") {
my $esc = ReadKey 0;
$esc .= ReadKey 0;
if ($esc eq "[A") { logger "up" }
elsif ($esc eq "[B") { logger "down" }
elsif ($esc eq "[C") { logger "right" }
elsif ($esc eq "[D") { logger "left" }
elsif ($esc eq "[5") { logger "page up" }
elsif ($esc eq "[6") { logger "page down" }
else { logger "Unrecognized escape: $esc"; }
}
else { logger "you typed: $c"; }
}
}
ReadMode 0; | 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 (items key )))))
compare-items
(fn[key1 key2]
(compare (val-item key1) (val-item key2)))
sorted (into (sorted-map-by compare-items) items)]
(loop [current (first sorted)
array (rest sorted)
value 0
weight 0]
(let[new-weight (first (val current))
new-value (second (val current))]
(if (> (- maxW weight new-weight) 0)
(do
(println "Take all " (key current))
(recur
(first array)
(rest array)
(+ value new-value)
(+ weight new-weight)))
(let [t (- maxW weight)]
(println
"Take " t " of "
(key current) "\n"
"Total Value is:"
(+ value (* t (/ new-value new-weight))))))))))
(rob items maxW) | 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]
["banana", 27, 60, 3]
["apple", 39, 40, 3]
["cheese", 23, 30, 1]
["beer", 52, 10, 3]
["suntan cream", 11, 70, 1]
["camera", 32, 30, 1]
["t-shirt", 24, 15, 2]
["trousers", 48, 10, 2]
["umbrella", 73, 40, 1]
["waterproof trousers", 42, 70, 1]
["waterproof overclothes", 43, 75, 1]
["note-case", 22, 80, 1]
["sunglasses", 7, 20, 1]
["towel", 18, 12, 2]
["socks", 4, 50, 1]
["book", 30, 10, 2]
])
(defstruct item :name :weight :value)
(def items (->> (for [[item wt val n] groupeditems]
(repeat n [item wt val]))
(mapcat identity)
(map #(apply struct item %))
(vec)))
(declare mm)
(defn m [i w]
(cond
(< i 0) [0 []]
(= w 0) [0 []]
:else
(let [{wi :weight vi :value} (get items i)]
(if (> wi w)
(mm (dec i) w)
(let [[vn sn :as no] (mm (dec i) w)
[vy sy :as yes] (mm (dec i) (- w wi))]
(if (> (+ vy vi) vn)
[(+ vy vi) (conj sy i)]
no))))))
(def mm (memoize m))
(let [[value indexes] (mm (-> items count dec) 400)
names (map (comp :name items) indexes)]
(println "Items to pack:")
(doseq [[k v] (frequencies names)]
(println (format "%d%s" v k)))
(println "Total value:" value)
(println "Total weight:" (reduce + (map (comp :weight items) indexes)))) | 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, double value, double weight, double volume) {
int j, m1, m2, m;
if (i == n) {
if (value > best_value) {
best_value = value;
for (j = 0; j < n; j++) {
best[j] = count[j];
}
}
return;
}
m1 = weight / items[i].weight;
m2 = volume / items[i].volume;
m = m1 < m2 ? m1 : m2;
for (count[i] = m; count[i] >= 0; count[i]--) {
knapsack(
i + 1,
value + count[i] * items[i].value,
weight - count[i] * items[i].weight,
volume - count[i] * items[i].volume
);
}
}
int main () {
count = malloc(n * sizeof (int));
best = malloc(n * sizeof (int));
best_value = 0;
knapsack(0, 0.0, 25.0, 0.25);
int i;
for (i = 0; i < n; i++) {
printf(, best[i], items[i].name);
}
printf(, best_value);
free(count); free(best);
return 0;
} | 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 evolve():Langton={
val (newCol, newAnt)=if(isBlack) (WHITE, ant.turnLeft) else (BLACK, ant.turnRight)
new Langton(changeColor(newCol), newAnt.move)
}
override def toString()=matrix map (_.mkString("")) mkString "\n"
}
case class Ant(row:Int, col:Int, d:Int=0) {
def turnLeft=Ant(row,col,(d-1)&3)
def turnRight=Ant(row,col,(d+1)&3)
def move=d match {
case 0 => Ant(row-1,col,d) | 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;
tv.tv_usec = tv.tv_sec = 0;
FD_ZERO(&fs);
FD_SET(STDIN_FILENO, &fs);
select(STDIN_FILENO + 1, &fs, 0, 0, &tv);
if (FD_ISSET(STDIN_FILENO, &fs)) {
c = getchar();
set_mode(0);
}
return c;
}
int main()
{
int c;
while(1) {
set_mode(1);
while (!(c = get_key())) usleep(10000);
printf(, c);
}
} | 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.nocbreak()
stdscr.keypad(0)
curses.echo()
curses.endwin() | 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.components(separatedBy: "\n")
let counts = words.flatMap({ $0.map({ ($0, 1) }) }).reduce(into: [:], { $0[$1.0, default: 0] += $1.1 })
for (char, count) in counts {
print("\(char): \(count)")
} | 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, Direction.North, Direction.West]
let xInc = [0, 1,-1, 0]
let yInc = [-1, 0, 0, 1]
var isBlack:[[Bool]]
var origin:Point
var antPosition = Point(x:0, y:0)
var outOfBounds = false
var antDirection = Direction.East
init(width:Int, height:Int) {
self.origin = Point(x:width / 2, y:height / 2)
self.isBlack = Array(count: width, repeatedValue: Array(count: height, repeatedValue: false))
}
func moveAnt() {
self.antPosition.x += xInc[self.antDirection.rawValue]
self.antPosition.y += yInc[self.antDirection.rawValue]
}
func step() -> Point {
if self.outOfBounds {
println("Ant tried to move while out of bounds.")
exit(0)
}
var ptCur = Point(x:self.antPosition.x + self.origin.x, y:self.antPosition.y + self.origin.y)
let black = self.isBlack[ptCur.x][ptCur.y]
let direction = self.antDirection.rawValue
self.antDirection = (black? self.leftTurn: self.rightTurn)[direction]
self.isBlack[ptCur.x][ptCur.y] =!self.isBlack[ptCur.x][ptCur.y]
self.moveAnt()
ptCur = Point(x:self.antPosition.x + self.origin.x, y:self.antPosition.y + self.origin.y)
self.outOfBounds =
ptCur.x < 0 ||
ptCur.x >= self.isBlack.count ||
ptCur.y < 0 ||
ptCur.y >= self.isBlack[0].count
return self.antPosition
}
}
let ant = Langton(width: WIDTH, height: HEIGHT)
while!ant.outOfBounds {
ant.step()
}
for row in 0 ..< WIDTH {
for col in 0 ..< HEIGHT {
print(ant.isBlack[col][row]? "#": " ")
}
println()
} | 674Langton's ant
| 17swift
| hn9j0 |
$ lein trampoline run | 680Keyboard input/Keypress check
| 6clojure
| trhfv |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.