code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
import 'dart:convert' show jsonDecode, jsonEncode; main(){ var json_string = ''' { "rosetta_code": { "task": "json", "language": "dart", "descriptions": [ "fun!", "easy to learn!", "awesome!" ] } } ''';
691JSON
18dart
vwj2j
import Foundation guard let path = Array(CommandLine.arguments.dropFirst()).first else { fatalError() } let fileData = FileManager.default.contents(atPath: path)! let eventData = String(data: fileData, encoding: .utf8)! for line in eventData.components(separatedBy: "\n") { guard let lastSpace = line.lastIndex(of: " "),
682Kernighans large earthquake problem
17swift
9p1mj
my (@names, @val, @weight, @vol, $max_vol, $max_weight, $vsc, $wsc); if (1) { @names = qw(panacea icor gold); @val = qw(3000 1800 2500); @weight = qw(3 2 20 ); @vol = qw(25 15 2 ); $max_weight = 250; $max_vol = 250; $vsc = 1000; $wsc = 10; } else { @names = qw(panacea icor gold banana monkey ); @val = qw(17 11 5 3 34 ); @weight = qw(14 3 2 2 10 ); @vol = qw(3 4 2 1 12 ); $max_weight = 150; $max_vol = 100; $vsc = $wsc = 1; } my @cache; my ($hits, $misses) = (0, 0); sub solu { my ($i, $w, $v) = @_; return [0, []] if $i < 0; if ($cache[$i][$w][$v]) { $hits ++; return $cache[$i][$w][$v] } $misses ++; my $x = solu($i - 1, $w, $v); my ($w1, $v1); for (my $t = 1; ; $t++) { last if ($w1 = $w - $t * $weight[$i]) < 0; last if ($v1 = $v - $t * $vol[$i]) < 0; my $y = solu($i - 1, $w1, $v1); if ( (my $tmp = $y->[0] + $val[$i] * $t) > $x->[0] ) { $x = [ $tmp, [ @{$y->[1]}, [$i, $t] ] ]; } } $cache[$i][$w][$v] = $x } my $x = solu($ print "Max value $x->[0], with:\n", " Item\tQty\tWeight Vol Value\n", '-'x 50, "\n"; my ($wtot, $vtot) = (0, 0); for (@{$x->[1]}) { my $i = $_->[0]; printf " $names[$i]:\t% 3d % 8d% 8g% 8d\n", $_->[1], $weight[$i] * $_->[1] / $wsc, $vol[$i] * $_->[1] / $vsc, $val[$i] * $_->[1]; $wtot += $weight[$i] * $_->[1]; $vtot += $vol[$i] * $_->[1]; } print "-" x 50, "\n"; printf " Total:\t % 8d% 8g% 8d\n", $wtot/$wsc, $vtot/$vsc, $x->[0]; print "\nCache hit: $hits\tmiss: $misses\n";
679Knapsack problem/Unbounded
2perl
iuro3
Struct.new('Item', :name, :weight, :value, :count) $items = [ Struct::Item.new('map', 9, 150, 1), Struct::Item.new('compass', 13, 35, 1), Struct::Item.new('water', 153, 200, 3), Struct::Item.new('sandwich', 50, 60, 2), Struct::Item.new('glucose', 15, 60, 2), Struct::Item.new('tin', 68, 45, 3), Struct::Item.new('banana', 27, 60, 3), Struct::Item.new('apple', 39, 40, 3), Struct::Item.new('cheese', 23, 30, 1), Struct::Item.new('beer', 52, 10, 3), Struct::Item.new('suntan cream', 11, 70, 1), Struct::Item.new('camera', 32, 30, 1), Struct::Item.new('t-shirt', 24, 15, 2), Struct::Item.new('trousers', 48, 10, 2), Struct::Item.new('umbrella', 73, 40, 1), Struct::Item.new('w-trousers', 42, 70, 1), Struct::Item.new('w-overcoat', 43, 75, 1), Struct::Item.new('note-case', 22, 80, 1), Struct::Item.new('sunglasses', 7, 20, 1), Struct::Item.new('towel', 18, 12, 2), Struct::Item.new('socks', 4, 50, 1), Struct::Item.new('book', 30, 10, 2) ] def choose_item(weight, id, cache) return 0, [] if id < 0 k = [weight, id] return cache[k] unless cache[k].nil? value = $items[id].value best_v = 0 best_list = [] ($items[id].count+1).times do |i| wlim = weight - i * $items[id].weight break if wlim < 0 val, taken = choose_item(wlim, id - 1, cache) if val + i * value > best_v best_v = val + i * value best_list = taken + [i] end end cache[k] = [best_v, best_list] return [best_v, best_list] end val, list = choose_item(400, $items.length - 1, {}) w = 0 list.each_with_index do |cnt, i| if cnt > 0 print w += $items[i][1] * cnt end end p
678Knapsack problem/Bounded
14ruby
z7ptw
(def item-data [ "map" 9 150 "compass" 13 35 "water" 153 200 "sandwich" 50 160 "glucose" 15 60 "tin" 68 45 "banana" 27 60 "apple" 39 40 "cheese" 23 30 "beer" 52 10 "suntan cream" 11 70 "camera" 32 30 "t-shirt" 24 15 "trousers" 48 10 "umbrella" 73 40 "waterproof trousers" 42 70 "waterproof overclothes" 43 75 "note-case" 22 80 "sunglasses" 7 20 "towel" 18 12 "socks" 4 50 "book" 30 10]) (defstruct item:name:weight:value) (def items (vec (map #(apply struct item %) (partition 3 item-data))))
692Knapsack problem/0-1
6clojure
ykv6b
import sys import pygame pygame.init() clk = pygame.time.Clock() if pygame.joystick.get_count() == 0: raise IOError() joy = pygame.joystick.Joystick(0) joy.init() size = width, height = 600, 600 screen = pygame.display.set_mode(size) pygame.display.set_caption() frameRect = pygame.Rect((45, 45), (510, 510)) crosshair = pygame.surface.Surface((10, 10)) crosshair.fill(pygame.Color()) pygame.draw.circle(crosshair, pygame.Color(), (5,5), 5, 0) crosshair.set_colorkey(pygame.Color(), pygame.RLEACCEL) crosshair = crosshair.convert() writer = pygame.font.Font(pygame.font.get_default_font(), 15) buttons = {} for b in range(joy.get_numbuttons()): buttons[b] = [ writer.render( hex(b)[2:].upper(), 1, pygame.Color(), pygame.Color() ).convert(), ((15*b)+45, 560) ] while True: pygame.event.pump() for events in pygame.event.get(): if events.type == pygame.QUIT: pygame.quit() sys.exit() screen.fill(pygame.Color()) x = joy.get_axis(0) y = joy.get_axis(1) screen.blit(crosshair, ((x*250)+300-5, (y*250)+300-5)) pygame.draw.rect(screen, pygame.Color(), frameRect, 1) for b in range(joy.get_numbuttons()): if joy.get_button(b): screen.blit(buttons[b][0], buttons[b][1]) pygame.display.flip() clk.tick(40)
689Joystick position
3python
lajcv
package main import ( "image" "image/color" "image/png" "log" "os" "sync" ) func main() { const ( width, height = 800.0, 600.0 maxIter = 255 cX, cY = -0.7, 0.27015 fileName = "julia.png" ) img := image.NewNRGBA(image.Rect(0, 0, width, height)) var wg sync.WaitGroup wg.Add(width) for x := 0; x < width; x++ { thisx := float64(x) go func() { var tmp, zx, zy float64 var i uint8 for y := 0.0; y < height; y++ { zx = 1.5 * (thisx - width/2) / (0.5 * width) zy = (y - height/2) / (0.5 * height) i = maxIter for zx*zx+zy*zy < 4.0 && i > 0 { tmp = zx*zx - zy*zy + cX zy = 2.0*zx*zy + cY zx = tmp i-- } img.Set(int(thisx), int(y), color.RGBA{i, i, i << 3, 255}) } wg.Done() }() } wg.Wait() imgFile, err := os.Create(fileName) if err != nil { log.Fatal(err) } defer imgFile.Close() if err := png.Encode(imgFile, img); err != nil { imgFile.Close() log.Fatal(err) } }
688Julia set
0go
kd0hz
loop1: while (x != 0) { loop2: for (int i = 0; i < 10; i++) { loop3: do {
684Jump anywhere
9java
uxwvv
import System.Environment (getArgs) plotChar :: Int -> Float -> Float -> Float -> Float -> Char plotChar iter cReal cImag y x | zReal^2 > 10000 = ' ' | iter == 1 = '#' | otherwise = plotChar (pred iter) cReal cImag zImag zReal where zReal = x * x - y * y + cReal zImag = x * y * 2 + cImag parseArgs :: [String] -> (Float, Float) parseArgs [] = (-0.8, 0.156) parseArgs [cReal, cImag] = (read cReal :: Float, read cImag :: Float) parseArgs _ = error "Invalid arguments" main :: IO () main = do args <- getArgs let (cReal, cImag) = parseArgs args print (cReal, cImag) mapM_ putStrLn $ [-100,-96..100] >>= \y -> [[-280,-276..280] >>= \x -> [plotChar 50 cReal cImag (y/100) (x/200)]]
688Julia set
8haskell
n5cie
import 'dart:math'; void main() { int x1; for(x1=1;x1<1000000;x1++){ int x; int i,y,y1,l1,z,l; double o,o1,o2,o3; x=pow(x1,2); for(i=0;;i++) {z=pow(10,i); if(x%z==x)break;} if(i.isEven) { y=pow(10,i/2); l=x%y; o=x/y; o=o-l/y; o3=o; for(int j=0;j<4;j++) { if(o%10==0) o=o/10; if(o%10!=0) break; } if(o+l==x1 ||o3+l==x1 ) print('$x1'); } else { y1=pow(10,i/2+0.5); l1=x%y1; o1=x/y1; o1=o1-l1/y1; o2=o1; for(int j=0;j<4;j++) { if(o1%10==0) o1=o1/10; else break; } if(o1+l1==x1 ||o2+l1==x1 ) print('$x1'); } } }
693Kaprekar numbers
18dart
a3s1h
from math import pi, sin, cos from collections import namedtuple from random import random, choice from copy import copy try: import psyco psyco.full() except ImportError: pass FLOAT_MAX = 1e100 class Point: __slots__ = [, , ] def __init__(self, x=0.0, y=0.0, group=0): self.x, self.y, self.group = x, y, group def generate_points(npoints, radius): points = [Point() for _ in xrange(npoints)] for p in points: r = random() * radius ang = random() * 2 * pi p.x = r * cos(ang) p.y = r * sin(ang) return points def nearest_cluster_center(point, cluster_centers): def sqr_distance_2D(a, b): return (a.x - b.x) ** 2 + (a.y - b.y) ** 2 min_index = point.group min_dist = FLOAT_MAX for i, cc in enumerate(cluster_centers): d = sqr_distance_2D(cc, point) if min_dist > d: min_dist = d min_index = i return (min_index, min_dist) def kpp(points, cluster_centers): cluster_centers[0] = copy(choice(points)) d = [0.0 for _ in xrange(len(points))] for i in xrange(1, len(cluster_centers)): sum = 0 for j, p in enumerate(points): d[j] = nearest_cluster_center(p, cluster_centers[:i])[1] sum += d[j] sum *= random() for j, di in enumerate(d): sum -= di if sum > 0: continue cluster_centers[i] = copy(points[j]) break for p in points: p.group = nearest_cluster_center(p, cluster_centers)[0] def lloyd(points, nclusters): cluster_centers = [Point() for _ in xrange(nclusters)] kpp(points, cluster_centers) lenpts10 = len(points) >> 10 changed = 0 while True: for cc in cluster_centers: cc.x = 0 cc.y = 0 cc.group = 0 for p in points: cluster_centers[p.group].group += 1 cluster_centers[p.group].x += p.x cluster_centers[p.group].y += p.y for cc in cluster_centers: cc.x /= cc.group cc.y /= cc.group changed = 0 for p in points: min_i = nearest_cluster_center(p, cluster_centers)[0] if min_i != p.group: changed += 1 p.group = min_i if changed <= lenpts10: break for i, cc in enumerate(cluster_centers): cc.group = i return cluster_centers def print_eps(points, cluster_centers, W=400, H=400): Color = namedtuple(, ); colors = [] for i in xrange(len(cluster_centers)): colors.append(Color((3 * (i + 1)% 11) / 11.0, (7 * i% 11) / 11.0, (9 * i% 11) / 11.0)) max_x = max_y = -FLOAT_MAX min_x = min_y = FLOAT_MAX for p in points: if max_x < p.x: max_x = p.x if min_x > p.x: min_x = p.x if max_y < p.y: max_y = p.y if min_y > p.y: min_y = p.y scale = min(W / (max_x - min_x), H / (max_y - min_y)) cx = (max_x + min_x) / 2 cy = (max_y + min_y) / 2 print % (W + 10, H + 10) print ( + + + + ) for i, cc in enumerate(cluster_centers): print (% (colors[i].r, colors[i].g, colors[i].b)) for p in points: if p.group != i: continue print (% ((p.x - cx) * scale + W / 2, (p.y - cy) * scale + H / 2)) print (% ((cc.x - cx) * scale + W / 2, (cc.y - cy) * scale + H / 2)) print def main(): npoints = 30000 k = 7 points = generate_points(npoints, 10) cluster_centers = lloyd(points, k) print_eps(points, cluster_centers) main()
685K-means++ clustering
3python
82c0o
import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; public class JuliaSet extends JPanel { private static final int MAX_ITERATIONS = 300; private static final double ZOOM = 1; private static final double CX = -0.7; private static final double CY = 0.27015; private static final double MOVE_X = 0; private static final double MOVE_Y = 0; public JuliaSet() { setPreferredSize(new Dimension(800, 600)); setBackground(Color.white); } void drawJuliaSet(Graphics2D g) { int w = getWidth(); int h = getHeight(); BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < w; x++) { for (int y = 0; y < h; y++) { double zx = 1.5 * (x - w / 2) / (0.5 * ZOOM * w) + MOVE_X; double zy = (y - h / 2) / (0.5 * ZOOM * h) + MOVE_Y; float i = MAX_ITERATIONS; while (zx * zx + zy * zy < 4 && i > 0) { double tmp = zx * zx - zy * zy + CX; zy = 2.0 * zx * zy + CY; zx = tmp; i--; } int c = Color.HSBtoRGB((MAX_ITERATIONS / i) % 1, 1, i > 0 ? 1 : 0); image.setRGB(x, y, c); } } g.drawImage(image, 0, 0, null); } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); drawJuliaSet(g); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Julia Set"); f.setResizable(false); f.add(new JuliaSet(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
688Julia set
9java
q9zxa
public struct KnapsackItem: Hashable { public var name: String public var weight: Int public var value: Int public init(name: String, weight: Int, value: Int) { self.name = name self.weight = weight self.value = value } } public func knapsack(items: [KnapsackItem], limit: Int) -> [KnapsackItem] { var table = Array(repeating: Array(repeating: 0, count: limit + 1), count: items.count + 1) for j in 1...items.count { let item = items[j-1] for w in 1...limit { if item.weight > w { table[j][w] = table[j-1][w] } else { table[j][w] = max(table[j-1][w], table[j-1][w-item.weight] + item.value) } } } var result = [KnapsackItem]() var w = limit for j in stride(from: items.count, to: 0, by: -1) where table[j][w]!= table[j-1][w] { let item = items[j-1] result.append(item) w -= item.weight } return result } typealias GroupedItem = (name: String, weight: Int, val: Int, n: Int) let groupedItems: [GroupedItem] = [ ("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) ] let items = groupedItems.flatMap({item in (0..<item.n).map({_ in KnapsackItem(name: item.name, weight: item.weight, value: item.val) }) }) let bagged = knapsack(items: items, limit: 400) let (totalVal, totalWeight) = bagged.reduce((0, 0), {cur, item in (cur.0 + item.value, cur.1 + item.weight) }) print("Bagged the following \(bagged.count) items:") for item in bagged { print("\t\(item.name)") } print("For a total value of \(totalVal) and weight of \(totalWeight)")
678Knapsack problem/Bounded
17swift
trbfl
null
684Jump anywhere
11kotlin
9pbmh
var maxIterations = 450, minX = -.5, maxX = .5, minY = -.5, maxY = .5, wid, hei, ctx, jsX = 0.285, jsY = 0.01; function remap( x, t1, t2, s1, s2 ) { var f = ( x - t1 ) / ( t2 - t1 ), g = f * ( s2 - s1 ) + s1; return g; } function getColor( c ) { var r, g, b, p = c / 32, l = ~~( p * 6 ), o = p * 6 - l, q = 1 - o; switch( l % 6 ) { case 0: r = 1; g = o; b = 0; break; case 1: r = q; g = 1; b = 0; break; case 2: r = 0; g = 1; b = o; break; case 3: r = 0; g = q; b = 1; break; case 4: r = o; g = 0; b = 1; break; case 5: r = 1; g = 0; b = q; break; } var c = "#" + ( "00" + ( ~~( r * 255 ) ).toString( 16 ) ).slice( -2 ) + ( "00" + ( ~~( g * 255 ) ).toString( 16 ) ).slice( -2 ) + ( "00" + ( ~~( b * 255 ) ).toString( 16 ) ).slice( -2 ); return (c); } function drawFractal() { var a, as, za, b, bs, zb, cnt, clr for( var j = 0; j < hei; j++ ) { for( var i = 0; i < wid; i++ ) { a = remap( i, 0, wid, minX, maxX ) b = remap( j, 0, hei, minY, maxY ) cnt = 0; while( ++cnt < maxIterations ) { za = a * a; zb = b * b; if( za + zb > 4 ) break; as = za - zb; bs = 2 * a * b; a = as + jsX; b = bs + jsY; } if( cnt < maxIterations ) { ctx.fillStyle = getColor( cnt ); } ctx.fillRect( i, j, 1, 1 ); } } } function init() { var canvas = document.createElement( "canvas" ); wid = hei = 800; canvas.width = wid; canvas.height = hei; ctx = canvas.getContext( "2d" ); ctx.fillStyle = "black"; ctx.fillRect( 0, 0, wid, hei ); document.body.appendChild( canvas ); drawFractal(); }
688Julia set
10javascript
iu9ol
List solveKnapsack(items, maxWeight) { int MIN_VALUE=-100; int N = items.length;
692Knapsack problem/0-1
18dart
0lfsb
items = [(, 3.8, 36.0), (, 5.4, 43.0), (, 3.6, 90.0), (, 2.4, 45.0), (, 4.0, 30.0), (, 2.5, 56.0), (, 3.7, 67.0), (, 3.0, 95.0), (, 5.9, 98.0)] MAXWT = 15.0 sorted_items = sorted(((value/amount, amount, name) for name, amount, value in items), reverse = True) wt = val = 0 bagged = [] for unit_value, amount, name in sorted_items: portion = min(MAXWT - wt, amount) wt += portion addval = portion * unit_value val += addval bagged += [(name, portion, addval)] if wt >= MAXWT: break print() print(.join(% item for item in bagged)) print(% (wt, val))
677Knapsack problem/Continuous
3python
bfmkr
null
684Jump anywhere
1lua
c1p92
extern crate csv; extern crate getopts; extern crate gnuplot; extern crate nalgebra; extern crate num; extern crate rand; extern crate rustc_serialize; extern crate test; use getopts::Options; use gnuplot::{Axes2D, AxesCommon, Color, Figure, Fix, PointSize, PointSymbol}; use nalgebra::{DVector, Iterable}; use rand::{Rng, SeedableRng, StdRng}; use rand::distributions::{IndependentSample, Range}; use std::f64::consts::PI; use std::env; type Point = DVector<f64>; struct Cluster<'a> { members: Vec<&'a Point>, center: Point, } struct Stats { centroids: Vec<Point>, mean_d_from_centroid: DVector<f64>, }
685K-means++ clustering
15rust
n5vi4
import java.awt.* import java.awt.image.BufferedImage import javax.swing.JFrame import javax.swing.JPanel class JuliaPanel : JPanel() { init { preferredSize = Dimension(800, 600) background = Color.white } private val maxIterations = 300 private val zoom = 1 private val moveX = 0.0 private val moveY = 0.0 private val cX = -0.7 private val cY = 0.27015 public override fun paintComponent(graphics: Graphics) { super.paintComponent(graphics) with(graphics as Graphics2D) { setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) val image = BufferedImage(width, height, BufferedImage.TYPE_INT_RGB) (0 until width).forEach { x -> (0 until height).forEach { y -> var zx = 1.5 * (x - width / 2) / (0.5 * zoom * width) + moveX var zy = (y - height / 2) / (0.5 * zoom * height) + moveY var i = maxIterations.toFloat() while (zx * zx + zy * zy < 4 && i > 0) { val tmp = zx * zx - zy * zy + cX zy = 2.0 * zx * zy + cY zx = tmp i-- } image.setRGB(x, y, Color.HSBtoRGB(maxIterations / i % 1, 1f, (if (i > 0) 1 else 0).toFloat())) } } drawImage(image, 0, 0, null) } } } fun main() { with(JFrame()) { defaultCloseOperation = JFrame.EXIT_ON_CLOSE title = "Julia Set" isResizable = false add(JuliaPanel(), BorderLayout.CENTER) pack() setLocationRelativeTo(null) isVisible = true } }
688Julia set
11kotlin
1zipd
weights <- c(panacea=0.3, ichor=0.2, gold=2.0) volumes <- c(panacea=0.025, ichor=0.015, gold=0.002) values <- c(panacea=3000, ichor=1800, gold=2500) sack.weight <- 25 sack.volume <- 0.25 max.items <- floor(pmin(sack.weight/weights, sack.volume/volumes)) getTotalValue <- function(n) sum(n*values) getTotalWeight <- function(n) sum(n*weights) getTotalVolume <- function(n) sum(n*volumes) willFitInSack <- function(n) getTotalWeight(n) <= sack.weight && getTotalVolume(n) <= sack.volume knapsack <- expand.grid(lapply(max.items, function(n) seq.int(0, n))) ok <- apply(knapsack, 1, willFitInSack) knapok <- knapsack[ok,] vals <- apply(knapok, 1, getTotalValue) knapok[vals == max(vals),]
679Knapsack problem/Unbounded
3python
n57iz
weights <- c(panacea=0.3, ichor=0.2, gold=2.0) volumes <- c(panacea=0.025, ichor=0.015, gold=0.002) values <- c(panacea=3000, ichor=1800, gold=2500) sack.weight <- 25 sack.volume <- 0.25 max.items <- floor(pmin(sack.weight/weights, sack.volume/volumes)) getTotalValue <- function(n) sum(n*values) getTotalWeight <- function(n) sum(n*weights) getTotalVolume <- function(n) sum(n*volumes) willFitInSack <- function(n) getTotalWeight(n) <= sack.weight && getTotalVolume(n) <= sack.volume knapsack <- expand.grid(lapply(max.items, function(n) seq.int(0, n))) ok <- apply(knapsack, 1, willFitInSack) knapok <- knapsack[ok,] vals <- apply(knapok, 1, getTotalValue) knapok[vals == max(vals),]
679Knapsack problem/Unbounded
13r
0l5sg
knapsack<- function(Value, Weight, Objects, Capacity){ Fraction = rep(0, length(Value)) Cost = Value/Weight W = Weight[order(Cost, decreasing = TRUE)] Obs = Objects[order(Cost, decreasing = TRUE)] Val = Value[order(Cost, decreasing = TRUE)] RemainCap = Capacity i = 1 n = length(Cost) if (W[1] <= Capacity){ Fits <- TRUE } else{ Fits <- FALSE } while (Fits && i <= n ){ Fraction[i] <- 1 RemainCap <- RemainCap - W[i] i <- i+1 if (W[i] <= RemainCap){ Fits <- TRUE } else{ Fits <- FALSE } } if (i <= n){ Fraction[i] <- RemainCap/W[i] } names(Fraction) = Obs Quantity_to_take = W*Fraction Total_Value = sum(Val*Fraction) print("Fraction of available quantity to take:") print(round(Fraction, 3)) print("KG of each to take:") print(Quantity_to_take) print("Total value of tasty meats:") print(Total_Value) }
677Knapsack problem/Continuous
13r
7ozry
local cmap = { [0]=" ", ".", ":", "-", "=", "+", "*", "#", "%", "$", "@" } for y = -1.0, 1.0, 0.05 do for x = -1.5, 1.5, 0.025 do local zr, zi, i = x, y, 0 while i < 100 do zr, zi = zr*zr - zi*zi - 0.79, zr * zi * 2 + 0.15 if (zr*zr + zi*zi > 4) then break else i = i + 1 end end io.write(cmap[math.floor(i/10)]) end print() end
688Julia set
1lua
a3n1v
package main import "encoding/json" import "fmt" func main() { var data interface{} err := json.Unmarshal([]byte(`{"foo":1, "bar":[10, "apples"]}`), &data) if err == nil { fmt.Println(data) } else { fmt.Println(err) } sample := map[string]interface{}{ "blue": []interface{}{1, 2}, "ocean": "water", } json_string, err := json.Marshal(sample) if err == nil { fmt.Println(string(json_string)) } else { fmt.Println(err) } }
691JSON
0go
d4mne
package main import ( "fmt" "math/rand" "time" )
690Knight's tour
0go
xmdwf
package main import ( "fmt" "strconv" ) func kaprekar(n uint64, base uint64) (bool, int) { order := 0 if n == 1 { return true, -1 } nn, power := n*n, uint64(1) for power <= nn { power *= base order++ } power /= base order-- for ; power > 1; power /= base { q, r := nn/power, nn%power if q >= n { return false, -1 } if q+r == n { return true, order } order-- } return false, -1 } func main() { max := uint64(10000) fmt.Printf("Kaprekar numbers <%d:\n", max) for m := uint64(0); m < max; m++ { if is, _ := kaprekar(m, 10); is { fmt.Println(" ", m) } }
693Kaprekar numbers
0go
ux7vt
def slurper = new groovy.json.JsonSlurper() def result = slurper.parseText(''' { "people":[ {"name":{"family":"Flintstone","given":"Frederick"},"age":35,"relationships":{"wife":"people[1]","child":"people[4]"}}, {"name":{"family":"Flintstone","given":"Wilma"},"age":32,"relationships":{"husband":"people[0]","child":"people[4]"}}, {"name":{"family":"Rubble","given":"Barnard"},"age":30,"relationships":{"wife":"people[3]","child":"people[5]"}}, {"name":{"family":"Rubble","given":"Elisabeth"},"age":32,"relationships":{"husband":"people[2]","child":"people[5]"}}, {"name":{"family":"Flintstone","given":"Pebbles"},"age":1,"relationships":{"mother":"people[1]","father":"people[0]"}}, {"name":{"family":"Rubble","given":"Bam-Bam"},"age":1,"relationships":{"mother":"people[3]","father":"people[2]"}}, ] } ''')
691JSON
7groovy
0ltsh
import Data.Bifunctor (bimap) import Data.Char (chr, ord) import Data.List (intercalate, minimumBy, sort, (\\)) import Data.Ord (comparing) import Control.Monad (join) type Square = (Int, Int) knightTour :: [Square] -> [Square] knightTour moves | null possibilities = reverse moves | otherwise = knightTour $ newSquare: moves where newSquare = minimumBy (comparing (length . findMoves)) possibilities possibilities = findMoves $ head moves findMoves = (\\ moves) . knightOptions knightOptions :: Square -> [Square] knightOptions (x, y) = knightMoves >>= go . bimap (+ x) (+ y) where go move | uncurry (&&) (both onBoard move) = [move] | otherwise = [] knightMoves :: [(Int, Int)] knightMoves = ((>>=) <*> (\deltas n -> deltas >>= go n)) [1, 2, -1, -2] where go i x | abs i /= abs x = [(i, x)] | otherwise = [] onBoard :: Int -> Bool onBoard = (&&) . (0 <) <*> (9 >) both :: (a -> b) -> (a, a) -> (b, b) both = join bimap startPoint :: String startPoint = "e5" algebraic :: (Int, Int) -> String algebraic (x, y) = [chr (x + 96), chr (y + 48)] main :: IO () main = printTour $ algebraic <$> knightTour [(\[x, y] -> (ord x - 96, ord y - 48)) startPoint] where printTour [] = return () printTour tour = do putStrLn $ intercalate " -> " $ take 8 tour printTour $ drop 8 tour
690Knight's tour
8haskell
yk566
use Imager; my($w, $h, $zoom) = (800, 600, 1); my $img = Imager->new(xsize => $w, ysize => $h, channels => 3); my $maxIter = 255; my ($cX, $cY) = (-0.7, 0.27015); my ($moveX, $moveY) = (0, 0); my $color = Imager::Color->new(' foreach my $x (0 .. $w - 1) { foreach my $y (0 .. $h - 1) { my $zx = (1.5 * ($x - $w / 2) / (0.5 * $zoom * $w) + $moveX); my $zy = (($y - $h / 2) / (0.5 * $zoom * $h) + $moveY); my $i = $maxIter; while ($zx**2 + $zy**2 < 4 and --$i >= 0) { ($zy, $zx) = (2 * $zx * $zy + $cY, $zx**2 - $zy**2 + $cX); } $color->set(hsv => [$i / $maxIter * 360, 1, $i > 0 ? 1 : 0]); $img->setpixel(x => $x, y => $y, color => $color); } } $img->write(file => 'julia_set.png');
688Julia set
2perl
mbryz
KnapsackItem = Struct.new(:volume, :weight, :value) panacea = KnapsackItem.new(0.025, 0.3, 3000) ichor = KnapsackItem.new(0.015, 0.2, 1800) gold = KnapsackItem.new(0.002, 2.0, 2500) maximum = KnapsackItem.new(0.25, 25, 0) max_items = {} for item in [panacea, ichor, gold] max_items[item] = [(maximum.volume/item.volume).to_i, (maximum.weight/item.weight).to_i].min end maxval = 0 solutions = [] 0.upto(max_items[ichor]) do |i| 0.upto(max_items[panacea]) do |p| 0.upto(max_items[gold]) do |g| break if i*ichor.weight + p*panacea.weight + g*gold.weight > maximum.weight break if i*ichor.volume + p*panacea.volume + g*gold.volume > maximum.volume val = i*ichor.value + p*panacea.value + g*gold.value if val > maxval maxval = val solutions = [[i, p, g]] elsif val == maxval solutions << [i, p, g] end end end end puts solutions.each do |i, p, g| printf , i, p, g, i*ichor.weight + p*panacea.weight + g*gold.weight, i*ichor.volume + p*panacea.volume + g*gold.volume end
679Knapsack problem/Unbounded
14ruby
fghdr
class Kaprekar { private static String[] splitAt(String str, int idx) { String[] ans = new String[2] ans[0] = str.substring(0, idx) if (ans[0] == "") ans[0] = "0"
693Kaprekar numbers
7groovy
9pum4
import Data.Aeson import Data.Attoparsec (parseOnly) import Data.Text import qualified Data.ByteString.Lazy.Char8 as B import qualified Data.ByteString.Char8 as S testdoc = object [ "foo" .= (1 :: Int), "bar" .= ([1.3, 1.6, 1.9] :: [Double]), "baz" .= ("some string" :: Text), "other" .= object [ "yes" .= ("sir" :: Text) ] ] main = do let out = encode testdoc B.putStrLn out case parseOnly json (S.concat $ B.toChunks out) of Left e -> error $ "strange error re-parsing json: " ++ (show e) Right v | v /= testdoc -> error "documents not equal!" Right v | otherwise -> print v
691JSON
8haskell
5qkug
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] ].sort_by{|item, weight, price| -price / weight} maxW, value = 15.0, 0 items.each do |item, weight, price| if (maxW -= weight) > 0 puts value += price else puts % [t=weight+maxW, item], , % (value+(price/weight)*t) break end end
677Knapsack problem/Continuous
14ruby
1zcpw
import Text.Printf (printf) import Data.Maybe (mapMaybe) import Numeric (showIntAtBase) kaprekars :: Integer -> Integer -> [(Integer, Integer, Integer)] kaprekars base top = (1, 0, 1): mapMaybe kap (filter res [2 .. top]) where res x = x * (x - 1) `mod` (base - 1) == 0 kap n = getSplit $ takeWhile (<= nn) $ dropWhile (< n) $ iterate (* toInteger base) 1 where nn = n * n getSplit [] = Nothing getSplit (p:ps) | p == n = Nothing | q + r == n = Just (n, q, r) | r > n = Nothing | otherwise = getSplit ps where (q, r) = nn `divMod` p heading :: Int -> String heading = printf (h ++ d) where h = " # Value (base 10) Sum (base%d) Square\n" d = " - printKap :: Integer -> (Int, (Integer, Integer, Integer)) -> String printKap b (i, (n, l, r)) = printf "%2d%13s%26s%16s" i (show n) ss (base b (n * n)) where ss = base b n ++ " = " ++ base b l ++ " + " ++ base b r base b n = showIntAtBase b (("0123456789" ++ ['a' .. 'z']) !!) n "" main :: IO () main = do putStrLn $ heading 10 mapM_ (putStrLn . printKap 10) $ zip [1 ..] (kaprekars 10 1000000) putStrLn "" putStrLn $ heading 17 mapM_ (putStrLn . printKap 17) $ zip [1 ..] (kaprekars 17 1000000)
693Kaprekar numbers
8haskell
wy8ed
set_time_limit(300); header(); class Julia { static private $started = false; public static function start() { if (!self::$started) { self::$started = true; new self; } } const AXIS_REAL = 0; const AXIS_IMAGINARY = 1; const C = [-0.75, 0.1]; const RADII = [1, 0.5]; const CENTER = [0, 0]; const MAX_ITERATIONS = 100; const TICK_SPACING = 0.001; private $maxDistance; private $imageResource; private $whiteColorResource; private $z0 = []; private function __construct() { $this->maxDistance = max($this->distance(self::C), 2); $this->imageResource = imagecreate( $this->coordinateToPixel(self::RADII[self::AXIS_REAL], self::AXIS_REAL), $this->coordinateToPixel(self::RADII[self::AXIS_IMAGINARY], self::AXIS_IMAGINARY) ); imagecolorallocate($this->imageResource, 0, 0, 0); $this->whiteColorResource = imagecolorallocate($this->imageResource, 255, 255, 255); for ($x = self::CENTER[self::AXIS_REAL] - self::RADII[self::AXIS_REAL]; $x <= self::CENTER[self::AXIS_REAL] + self::RADII[self::AXIS_REAL]; $x += self::TICK_SPACING) { $z0[self::AXIS_REAL] = $x; for ($y = self::CENTER[self::AXIS_IMAGINARY] - self::RADII[self::AXIS_IMAGINARY]; $y <= self::CENTER[self::AXIS_IMAGINARY] + self::RADII[self::AXIS_IMAGINARY]; $y += self::TICK_SPACING) { $z0[self::AXIS_IMAGINARY] = $y; $iterations = 1; do { $z0 = $this->q($z0); $iterations++; } while($iterations < self::MAX_ITERATIONS && $this->distance($z0) <= $this->maxDistance); if ($iterations !== self::MAX_ITERATIONS) { imagesetpixel( $this->imageResource, $this->coordinateToPixel($x, self::AXIS_REAL), $this->coordinateToPixel($y, self::AXIS_IMAGINARY), $this->whiteColorResource ); } $z0[self::AXIS_REAL] = $x; } } } public function __destruct() { imagepng($this->imageResource); imagedestroy($this->imageResource); } private function q($z) { return [ ($z[self::AXIS_REAL] ** 2) - ($z[self::AXIS_IMAGINARY] ** 2) + self::C[self::AXIS_REAL], (2 * $z[self::AXIS_REAL] * $z[self::AXIS_IMAGINARY]) + self::C[self::AXIS_IMAGINARY] ]; } private function distance($z) { return sqrt( ($z[self::AXIS_REAL] ** 2) + ($z[self::AXIS_IMAGINARY] ** 2) ); } private function coordinateToPixel($coordinate, $axis) { return ($coordinate + self::RADII[$axis]) * (self::TICK_SPACING ** -1); } } Julia::start();
688Julia set
12php
e6da9
import scala.annotation.tailrec object UnboundedKnapsack extends App { private val (maxWeight, maxVolume) = (BigDecimal(25.0), BigDecimal(0.25)) private val items = Seq(Item("panacea", 3000, 0.3, 0.025), Item("ichor", 1800, 0.2, 0.015), Item("gold", 2500, 2.0, 0.002)) @tailrec private def packer(notPacked: Seq[Knapsack], packed: Seq[Knapsack]): Seq[Knapsack] = { def fill(knapsack: Knapsack): Seq[Knapsack] = items.map(i => Knapsack(i +: knapsack.bagged)) def stuffer(Seq: Seq[Knapsack]): Seq[Knapsack] =
679Knapsack problem/Unbounded
16scala
6h131
import com.google.gson.Gson; public class JsonExample { public static void main(String[] args) { Gson gson = new Gson(); String json = "{ \"foo\": 1, \"bar\": [ \"10\", \"apples\"] }"; MyJsonObject obj = gson.fromJson(json, MyJsonObject.class); System.out.println(obj.getFoo()); for(String bar : obj.getBar()) { System.out.println(bar); } obj = new MyJsonObject(2, new String[] { "20", "oranges" }); json = gson.toJson(obj); System.out.println(json); } } class MyJsonObject { private int foo; private String[] bar; public MyJsonObject(int foo, String[] bar) { this.foo = foo; this.bar = bar; } public int getFoo() { return foo; } public String[] getBar() { return bar; } }
691JSON
9java
9p4mu
import java.util.*; public class KnightsTour { private final static int base = 12; private final static int[][] moves = {{1,-2},{2,-1},{2,1},{1,2},{-1,2}, {-2,1},{-2,-1},{-1,-2}}; private static int[][] grid; private static int total; public static void main(String[] args) { grid = new int[base][base]; total = (base - 4) * (base - 4); for (int r = 0; r < base; r++) for (int c = 0; c < base; c++) if (r < 2 || r > base - 3 || c < 2 || c > base - 3) grid[r][c] = -1; int row = 2 + (int) (Math.random() * (base - 4)); int col = 2 + (int) (Math.random() * (base - 4)); grid[row][col] = 1; if (solve(row, col, 2)) printResult(); else System.out.println("no result"); } private static boolean solve(int r, int c, int count) { if (count > total) return true; List<int[]> nbrs = neighbors(r, c); if (nbrs.isEmpty() && count != total) return false; Collections.sort(nbrs, new Comparator<int[]>() { public int compare(int[] a, int[] b) { return a[2] - b[2]; } }); for (int[] nb : nbrs) { r = nb[0]; c = nb[1]; grid[r][c] = count; if (!orphanDetected(count, r, c) && solve(r, c, count + 1)) return true; grid[r][c] = 0; } return false; } private static List<int[]> neighbors(int r, int c) { List<int[]> nbrs = new ArrayList<>(); for (int[] m : moves) { int x = m[0]; int y = m[1]; if (grid[r + y][c + x] == 0) { int num = countNeighbors(r + y, c + x); nbrs.add(new int[]{r + y, c + x, num}); } } return nbrs; } private static int countNeighbors(int r, int c) { int num = 0; for (int[] m : moves) if (grid[r + m[1]][c + m[0]] == 0) num++; return num; } private static boolean orphanDetected(int cnt, int r, int c) { if (cnt < total - 1) { List<int[]> nbrs = neighbors(r, c); for (int[] nb : nbrs) if (countNeighbors(nb[0], nb[1]) == 0) return true; } return false; } private static void printResult() { for (int[] row : grid) { for (int i : row) { if (i == -1) continue; System.out.printf("%2d ", i); } System.out.println(); } } }
690Knight's tour
9java
d49n9
fn main() { let items: [(&str, f32, u8); 9] = [ ("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), ]; let mut weight: f32 = 15.0; let mut values: Vec<(&str, f32, f32)> = Vec::new(); for item in &items { values.push((item.0, f32::from(item.2) / item.1, item.1)); } values.sort_by(|a, b| (a.1).partial_cmp(&b.1).unwrap()); values.reverse(); for choice in values { if choice.2 <= weight { println!("Grab {:.1} kgs of {}", choice.2, choice.0); weight -= choice.2; if (choice.2 - weight).abs() < std::f32::EPSILON { return; } } else { println!("Grab {:.1} kgs of {}", weight, choice.0); return; } } }
677Knapsack problem/Continuous
15rust
a3l14
sub outer { print "In outer, calling inner:\n"; inner(); OUTER: print "at label OUTER\n"; } sub inner { print "In inner\n"; goto SKIP; print "This should be skipped\n"; SKIP: print "at label SKIP\n"; goto OUTER; print "Inner should never reach here\n"; } sub disguise { goto &outer; print "Can't reach this statement\n"; } print "Calling outer:\n"; outer(); print "\nCalling disguise:\n"; disguise(); print "\nCalling inner:\n"; inner();
684Jump anywhere
2perl
wy6e6
public class Kaprekar { private static String[] splitAt(String str, int idx){ String[] ans = new String[2]; ans[0] = str.substring(0, idx); if(ans[0].equals("")) ans[0] = "0";
693Kaprekar numbers
9java
kdehm
var data = JSON.parse('{ "foo": 1, "bar": [10, "apples"] }'); var sample = { "blue": [1,2], "ocean": "water" }; var json_string = JSON.stringify(sample);
691JSON
10javascript
uxhvb
class KnightTour { constructor() { this.width = 856; this.height = 856; this.cellCount = 8; this.size = 0; this.knightPiece = "\u2658"; this.knightPos = { x: 0, y: 0 }; this.ctx = null; this.step = this.width / this.cellCount; this.lastTime = 0; this.wait; this.delay; this.success; this.jumps; this.directions = []; this.visited = []; this.path = []; document.getElementById("start").addEventListener("click", () => { this.startHtml(); }); this.init(); this.drawBoard(); } drawBoard() { let a = false, xx, yy; for (let y = 0; y < this.cellCount; y++) { for (let x = 0; x < this.cellCount; x++) { if (a) { this.ctx.fillStyle = "#607db8"; } else { this.ctx.fillStyle = "#aecaf0"; } a = !a; xx = x * this.step; yy = y * this.step; this.ctx.fillRect(xx, yy, xx + this.step, yy + this.step); } if (!(this.cellCount & 1)) a = !a; } if (this.path.length) { const s = this.step >> 1; this.ctx.lineWidth = 3; this.ctx.fillStyle = "black"; this.ctx.beginPath(); this.ctx.moveTo(this.step * this.knightPos.x + s, this.step * this.knightPos.y + s); let a, b, v = this.path.length - 1; for (; v > -1; v--) { a = this.path[v].pos.x * this.step + s; b = this.path[v].pos.y * this.step + s; this.ctx.lineTo(a, b); this.ctx.fillRect(a - 5, b - 5, 10, 10); } this.ctx.stroke(); } } createMoves(pos) { const possibles = []; let x = 0, y = 0, m = 0, l = this.directions.length; for (; m < l; m++) { x = pos.x + this.directions[m].x; y = pos.y + this.directions[m].y; if (x > -1 && x < this.cellCount && y > -1 && y < this.cellCount && !this.visited[x + y * this.cellCount]) { possibles.push({ x, y }) } } return possibles; } warnsdorff(pos) { const possibles = this.createMoves(pos); if (possibles.length < 1) return []; const moves = []; for (let p = 0, l = possibles.length; p < l; p++) { let ps = this.createMoves(possibles[p]); moves.push({ len: ps.length, pos: possibles[p] }); } moves.sort((a, b) => { return b.len - a.len; }); return moves; } startHtml() { this.cellCount = parseInt(document.getElementById("cellCount").value); this.size = Math.floor(this.width / this.cellCount) this.wait = this.delay = parseInt(document.getElementById("delay").value); this.step = this.width / this.cellCount; this.ctx.font = this.size + "px Arial"; document.getElementById("log").innerText = ""; document.getElementById("path").innerText = ""; this.path = []; this.jumps = 1; this.success = true; this.visited = []; const cnt = this.cellCount * this.cellCount; for (let a = 0; a < cnt; a++) { this.visited.push(false); } const kx = parseInt(document.getElementById("knightx").value), ky = parseInt(document.getElementById("knighty").value); this.knightPos = { x: (kx > this.cellCount || kx < 0) ? Math.floor(Math.random() * this.cellCount) : kx, y: (ky > this.cellCount || ky < 0) ? Math.floor(Math.random() * this.cellCount) : ky }; this.mainLoop = (time = 0) => { const dif = time - this.lastTime; this.lastTime = time; this.wait -= dif; if (this.wait > 0) { requestAnimationFrame(this.mainLoop); return; } this.wait = this.delay; let moves; if (this.success) { moves = this.warnsdorff(this.knightPos); } else { if (this.path.length > 0) { const path = this.path[this.path.length - 1]; moves = path.m; if (moves.length < 1) this.path.pop(); this.knightPos = path.pos this.visited[this.knightPos.x + this.knightPos.y * this.cellCount] = false; this.jumps--; this.wait = this.delay; } else { document.getElementById("log").innerText = "Can't find a solution!"; return; } } this.drawBoard(); const ft = this.step - (this.step >> 3); this.ctx.fillStyle = "#000"; this.ctx.fillText(this.knightPiece, this.knightPos.x * this.step, this.knightPos.y * this.step + ft); if (moves.length < 1) { if (this.jumps === this.cellCount * this.cellCount) { document.getElementById("log").innerText = "Tour finished!"; let str = ""; for (let z of this.path) { str += `${1 + z.pos.x + z.pos.y * this.cellCount}, `; } str += `${1 + this.knightPos.x + this.knightPos.y * this.cellCount}`; document.getElementById("path").innerText = str; return; } else { this.success = false; } } else { this.visited[this.knightPos.x + this.knightPos.y * this.cellCount] = true; const move = moves.pop(); this.path.push({ pos: this.knightPos, m: moves }); this.knightPos = move.pos this.success = true; this.jumps++; } requestAnimationFrame(this.mainLoop); }; this.mainLoop(); } init() { const canvas = document.createElement("canvas"); canvas.id = "cv"; canvas.width = this.width; canvas.height = this.height; this.ctx = canvas.getContext("2d"); document.getElementById("out").appendChild(canvas); this.directions = [{ x: -1, y: -2 }, { x: -2, y: -1 }, { x: 1, y: -2 }, { x: 2, y: -1 }, { x: -1, y: 2 }, { x: -2, y: 1 }, { x: 1, y: 2 }, { x: 2, y: 1 } ]; } } new KnightTour();
690Knight's tour
10javascript
6hu38
from PIL import Image if __name__ == : w, h, zoom = 800,600,1 bitmap = Image.new(, (w, h), ) pix = bitmap.load() cX, cY = -0.7, 0.27015 moveX, moveY = 0.0, 0.0 maxIter = 255 for x in range(w): for y in range(h): zx = 1.5*(x - w/2)/(0.5*zoom*w) + moveX zy = 1.0*(y - h/2)/(0.5*zoom*h) + moveY i = maxIter while zx*zx + zy*zy < 4 and i > 1: tmp = zx*zx - zy*zy + cX zy,zx = 2.0*zx*zy + cY, tmp i -= 1 pix[x][y] = (i << 21) + (i << 10) + i*8 bitmap.show()
688Julia set
3python
9p7mf
function isKaprekar( n, bs ) { if ( n < 1 ) return false if ( n == 1 ) return true bs = bs || 10 var s = (n * n).toString(bs) for (var i=1, e=s.length; i<e; i+=1) { var a = parseInt(s.substr(0, i), bs) var b = parseInt(s.substr(i), bs) if (b && a + b == n) return true } return false }
693Kaprekar numbers
10javascript
e60ao
import scala.annotation.tailrec object ContinousKnapsackForRobber extends App { val MaxWeight = 15.0 val items = Seq( Item("Beef", 3.8, 3600), Item("Pork", 5.4, 4300), Item("Ham", 3.6, 9000), Item("Greaves", 2.4, 4500), Item("Flitch", 4.0, 3000), Item("Brawn", 2.5, 5600), Item("Welt", 3.7, 6700), Item("Salami", 3.0, 9500), Item("Sausage", 5.9, 9800))
677Knapsack problem/Continuous
16scala
xmuwg
null
691JSON
11kotlin
z7lts
data class Square(val x : Int, val y : Int) val board = Array(8 * 8, { Square(it / 8 + 1, it % 8 + 1) }) val axisMoves = arrayOf(1, 2, -1, -2) fun <T> allPairs(a: Array<T>) = a.flatMap { i -> a.map { j -> Pair(i, j) } } fun knightMoves(s : Square) : List<Square> { val moves = allPairs(axisMoves).filter{ Math.abs(it.first) != Math.abs(it.second) } fun onBoard(s : Square) = board.any {it == s} return moves.map { Square(s.x + it.first, s.y + it.second) }.filter(::onBoard) } fun knightTour(moves : List<Square>) : List<Square> { fun findMoves(s: Square) = knightMoves(s).filterNot { m -> moves.any { it == m } } val newSquare = findMoves(moves.last()).minBy { findMoves(it).size } return if (newSquare == null) moves else knightTour(moves + newSquare) } fun knightTourFrom(start : Square) = knightTour(listOf(start)) fun main(args : Array<String>) { var col = 0 for ((x, y) in knightTourFrom(Square(1, 1))) { System.out.print("$x,$y") System.out.print(if (col == 7) "\n" else " ") col = (col + 1) % 8 } }
690Knight's tour
11kotlin
0lzsf
import java.lang.Long.parseLong import java.lang.Long.toString fun String.splitAt(idx: Int): Array<String> { val ans = arrayOf(substring(0, idx), substring(idx)) if (ans.first() == "") ans[0] = "0"
693Kaprekar numbers
11kotlin
g0k4d
def julia(c_real, c_imag) puts Complex(c_real, c_imag) -1.0.step(1.0, 0.04) do |v| puts -1.4.step(1.4, 0.02).map{|h| judge(c_real, c_imag, h, v)}.join end end def judge(c_real, c_imag, x, y) 50.times do z_real = (x * x - y * y) + c_real z_imag = x * y * 2 + c_imag return if z_real**2 > 10000 x, y = z_real, z_imag end end julia(-0.8, 0.156)
688Julia set
14ruby
lahcl
N = 8 moves = { {1,-2},{2,-1},{2,1},{1,2},{-1,2},{-2,1},{-2,-1},{-1,-2} } function Move_Allowed( board, x, y ) if board[x][y] >= 8 then return false end local new_x, new_y = x + moves[board[x][y]+1][1], y + moves[board[x][y]+1][2] if new_x >= 1 and new_x <= N and new_y >= 1 and new_y <= N and board[new_x][new_y] == 0 then return true end return false end board = {} for i = 1, N do board[i] = {} for j = 1, N do board[i][j] = 0 end end x, y = 1, 1 lst = {} lst[1] = { x, y } repeat if Move_Allowed( board, x, y ) then board[x][y] = board[x][y] + 1 x, y = x+moves[board[x][y]][1], y+moves[board[x][y]][2] lst[#lst+1] = { x, y } else if board[x][y] >= 8 then board[x][y] = 0 lst[#lst] = nil if #lst == 0 then print "No solution found." os.exit(1) end x, y = lst[#lst][1], lst[#lst][2] end board[x][y] = board[x][y] + 1 end until #lst == N^2 last = lst[1] for i = 2, #lst do print( string.format( "%s%d -%s%d", string.sub("ABCDEFGH",last[1],last[1]), last[2], string.sub("ABCDEFGH",lst[i][1],lst[i][1]), lst[i][2] ) ) last = lst[i] end
690Knight's tour
1lua
8230e
extern crate image; use image::{ImageBuffer, Pixel, Rgb}; fn main() {
688Julia set
15rust
2eklt
import java.awt._ import java.awt.image.BufferedImage import javax.swing._ object JuliaSet extends App { SwingUtilities.invokeLater(() => new JFrame("Julia Set") { class JuliaSet() extends JPanel { private val (maxIter, zoom) = (300, 1) override def paintComponent(gg: Graphics): Unit = { val g = gg.asInstanceOf[Graphics2D] def drawJuliaSet(g: Graphics2D): Unit = { val (w, h) = (getWidth, getHeight) val image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB) val (cX, cY) = (-0.7, 0.27015) val moveX, moveY = 0 var zx, zy = 0.0 for (x <- 0 until w; y <- 0 until h) { zx = 1.5 * (x - w / 2) / (0.5 * zoom * w) + moveX zy = (y - h / 2) / (0.5 * zoom * h) + moveY var i: Float = maxIter while (zx * zx + zy * zy < 4 && i > 0) { val tmp = zx * zx - zy * zy + cX zy = 2.0 * zx * zy + cY zx = tmp i -= 1 } val c = Color.HSBtoRGB((maxIter / i) % 1, 1, if (i > 0) 1 else 0) image.setRGB(x, y, c) } g.drawImage(image, 0, 0, null) } super.paintComponent(gg) g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) drawJuliaSet(g) } setBackground(Color.white) setPreferredSize(new Dimension(800, 600)) } add(new JuliaSet, BorderLayout.CENTER) pack() setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE) setLocationRelativeTo(null) setResizable(false) setVisible(true) } ) }
688Julia set
16scala
5q1ut
from goto import goto, label label .start for i in range(1, 4): print i if i == 2: try: output = message except NameError: print message = goto .start print output,
684Jump anywhere
3python
xmywr
package main import "fmt" type item struct { string w, v int } var wants = []item{ {"map", 9, 150}, {"compass", 13, 35}, {"water", 153, 200}, {"sandwich", 50, 160}, {"glucose", 15, 60}, {"tin", 68, 45}, {"banana", 27, 60}, {"apple", 39, 40}, {"cheese", 23, 30}, {"beer", 52, 10}, {"suntan cream", 11, 70}, {"camera", 32, 30}, {"T-shirt", 24, 15}, {"trousers", 48, 10}, {"umbrella", 73, 40}, {"waterproof trousers", 42, 70}, {"waterproof overclothes", 43, 75}, {"note-case", 22, 80}, {"sunglasses", 7, 20}, {"towel", 18, 12}, {"socks", 4, 50}, {"book", 30, 10}, } const maxWt = 400 func main() { items, w, v := m(len(wants)-1, maxWt) fmt.Println(items) fmt.Println("weight:", w) fmt.Println("value:", v) } func m(i, w int) ([]string, int, int) { if i < 0 || w == 0 { return nil, 0, 0 } else if wants[i].w > w { return m(i-1, w) } i0, w0, v0 := m(i-1, w) i1, w1, v1 := m(i-1, w-wants[i].w) v1 += wants[i].v if v1 > v0 { return append(i1, wants[i].string), w1 + wants[i].w, v1 } return i0, w0, v0 }
692Knapsack problem/0-1
0go
jia7d
null
693Kaprekar numbers
1lua
r8bga
local json = require("json") local json_data = [=[[ 42, 3.14159, [ 2, 4, 8, 16, 32, 64, "apples", "bananas", "cherries" ], { "H": 1, "He": 2, "X": null, "Li": 3 }, null, true, false ]]=] print("Original JSON: " .. json_data) local data = json.decode(json_data) json.util.printValue(data, 'Lua') print("JSON re-encoded: " .. json.encode(data)) local data = { 42, 3.14159, { 2, 4, 8, 16, 32, 64, "apples", "bananas", "cherries" }, { H = 1, He = 2, X = json.util.null(), Li = 3 }, json.util.null(), true, false } print("JSON from new Lua data: " .. json.encode(data))
691JSON
1lua
3j2zo
def totalWeight = { list -> list*.weight.sum() } def totalValue = { list -> list*.value.sum() } def knapsack01bf = { possibleItems -> possibleItems.subsequences().findAll{ ss -> def w = totalWeight(ss) 350 < w && w < 401 }.max(totalValue) }
692Knapsack problem/0-1
7groovy
5qhuv
inv = [("map",9,150), ("compass",13,35), ("water",153,200), ("sandwich",50,160), ("glucose",15,60), ("tin",68,45), ("banana",27,60), ("apple",39,40), ("cheese",23,30), ("beer",52,10), ("cream",11,70), ("camera",32,30), ("tshirt",24,15), ("trousers",48,10), ("umbrella",73,40), ("trousers",42,70), ("overclothes",43,75), ("notecase",22,80), ("sunglasses",7,20), ("towel",18,12), ("socks",4,50), ("book",30,10)] combs [] _ = [ (0, []) ] combs ((name,w,v):rest) cap = combs rest cap ++ if w > cap then [] else map (prepend (name,w,v)) (combs rest (cap - w)) where prepend (name,w,v) (v2, lst) = (v2 + v, (name,w,v):lst) main = do putStr "Total value: "; print value mapM_ print items where (value, items) = maximum $ combs inv 400
692Knapsack problem/0-1
8haskell
ovz8p
package main import ( "fmt" "math/rand" "time" ) func main() { var a [20]int for i := range a { a[i] = i } fmt.Println(a) rand.Seed(time.Now().UnixNano()) for i := len(a) - 1; i >= 1; i-- { j := rand.Intn(i + 1) a[i], a[j] = a[j], a[i] } fmt.Println(a) }
686Knuth shuffle
0go
wyzeg
def shuffle = { list -> if (list == null || list.empty) return list def r = new Random() def n = list.size() (n..1).each { i -> def j = r.nextInt(i) list[[i-1, j]] = list[[j, i-1]] } list }
686Knuth shuffle
7groovy
bfiky
import System.Random (randomRIO) mkRands :: Int -> IO [Int] mkRands = mapM (randomRIO . (,) 0) . enumFromTo 1 . pred replaceAt :: Int -> a -> [a] -> [a] replaceAt i c l = let (a, b) = splitAt i l in a ++ c: drop 1 b swapElems :: (Int, Int) -> [a] -> [a] swapElems (i, j) xs | i == j = xs | otherwise = replaceAt j (xs !! i) $ replaceAt i (xs !! j) xs knuthShuffle :: [a] -> IO [a] knuthShuffle xs = (foldr swapElems xs . zip [1 ..]) <$> mkRands (length xs)
686Knuth shuffle
8haskell
6hr3k
require 'continuation' unless defined? Continuation if a = callcc { |c| [c, 1] } c, i = a c[nil] if i > 100 case 0 when i % 3 print case 0 when i % 5 print end when i % 5 print else print i end puts c[c, i + 1] end
684Jump anywhere
14ruby
sc9qw
package hu.pj.alg.test; import hu.pj.alg.ZeroOneKnapsack; import hu.pj.obj.Item; import java.util.*; import java.text.*; public class ZeroOneKnapsackForTourists { public ZeroOneKnapsackForTourists() { ZeroOneKnapsack zok = new ZeroOneKnapsack(400);
692Knapsack problem/0-1
9java
wyoej
sub isKap { my $k = shift; return if $k*($k-1) % 9; my($k2, $p) = ($k*$k, 10); do { my $i = int($k2/$p); my $j = $k2 % $p; return 1 if $j && $i+$j == $k; $p *= 10; } while $p <= $k2; 0; } print "[", join(" ", grep { isKap($_) } 1..9999), "]\n\n"; my @kaprekar; isKap($_) && push @kaprekar,$_ for 1..1_000_000; print "Kaprekar Numbers below 1000000: ", scalar(@kaprekar), "\n";
693Kaprekar numbers
2perl
n53iw
myLabel -> ... :myLabel
684Jump anywhere
16scala
iuvox
portviz.knapsack = {}; (function() { this.combiner = function(items, weightfn, valuefn) {
692Knapsack problem/0-1
10javascript
82t0l
use strict; use warnings; my @board; my ($i, $j); if (my $sq = shift @ARGV) { die "$0: illegal start square '$sq'\n" unless ($i, $j) = from_algebraic($sq); } else { ($i, $j) = (int rand 8, int rand 8); } my @moves = (); foreach my $move (1..64) { push @moves, to_algebraic($i,$j); $board[$i][$j] = $move; my @targets = possible_moves($i,$j); my @min = (9); foreach my $target (@targets) { my ($ni, $nj) = @$target; my $next = possible_moves($ni,$nj); @min = ($next, $ni, $nj) if $next < $min[0]; } ($i, $j) = @min[1,2]; } for (my $i=0; $i<4; ++$i) { for (my $j=0; $j<16; ++$j) { my $n = $i*16+$j; print $moves[$n]; print ', ' unless $n+1 >= @moves; } print "\n"; } print "\n"; for (my $i=0; $i<8; ++$i) { for (my $j=0; $j<8; ++$j) { print "\e[7m" if ($i%2==$j%2); printf "%2d", $board[$i][$j]; print "\e[0m"; } print "\n"; } sub possible_moves { my ($i, $j) = @_; return grep { $_->[0] >= 0 && $_->[0] < 8 && $_->[1] >= 0 && $_->[1] < 8 && !$board[$_->[0]][$_->[1]] } ( [$i-2,$j-1], [$i-2,$j+1], [$i-1,$j-2], [$i-1,$j+2], [$i+1,$j-2], [$i+1,$j+2], [$i+2,$j-1], [$i+2,$j+1]); } sub to_algebraic { my ($i, $j) = @_; chr(ord('a') + $j) . (8-$i); } sub from_algebraic { my $square = shift; return unless $square =~ /^([a-h])([1-8])$/; return (8-$2, ord($1) - ord('a')); }
690Knight's tour
2perl
5qbu2
set_time_limit(300); print_r(array_filter(range(1, 10000), 'isKaprekar')); echo count(array_filter(range(1, 1000000), 'isKaprekar')); function isKaprekar($n) { $a = $n * $n; $b = bcmod(, ); for ($d = 1, $t = 0; $a > 0; $d *= 10) { $b += $t * $d; if ($b > $n) break; $a = floor($a / 10); if ($b && $a + $b == $n) return true; $t = bcmod(, ); } return false; }
693Kaprekar numbers
12php
7oprp
use JSON; my $data = decode_json('{ "foo": 1, "bar": [10, "apples"] }'); my $sample = { blue => [1,2], ocean => "water" }; my $json_string = encode_json($sample);
691JSON
2perl
bfqk4
import java.util.Random; public static final Random gen = new Random();
686Knuth shuffle
9java
n52ih
null
692Knapsack problem/0-1
11kotlin
bfxkb
<?php $data = json_decode('{ : 1, : [10, ] }'); $data2 = json_decode('{ : 1, : [10, ] }', true); $sample = array( => array(1,2), => ); $json_string = json_encode($sample); ?>
691JSON
12php
6hv3g
function knuthShuffle(arr) { var rand, temp, i; for (i = arr.length - 1; i > 0; i -= 1) { rand = Math.floor((i + 1) * Math.random());
686Knuth shuffle
10javascript
3jgz0
items = { {"map", 9, 150}, {"compass", 13, 35}, {"water", 153, 200}, {"sandwich", 50, 160}, {"glucose", 15, 60}, {"tin", 68, 45}, {"banana", 27, 60}, {"apple", 39, 40}, {"cheese", 23, 30}, {"beer", 52, 10}, {"suntan cream", 11, 70}, {"camera", 32, 30}, {"t-shirt", 24, 15}, {"trousers", 48, 10}, {"umbrella", 73, 40}, {"waterproof trousers", 42, 70}, {"waterproof overclothes", 43, 75}, {"note-case", 22, 80}, {"sunglasses", 7, 20}, {"towel", 18, 12}, {"socks", 4, 50}, {"book", 30, 10}, } local unpack = table.unpack function m(i, w) if i<1 or w==0 then return 0, {} else local _, wi, vi = unpack(items[i]) if wi > w then return mm(i - 1, w) else local vn, ln = mm(i - 1, w) local vy, ly = mm(i - 1, w - wi) if vy + vi > vn then return vy + vi, { i, ly } else return vn, ln end end end end local memo, mm_calls = {}, 0 function mm(i, w)
692Knapsack problem/0-1
1lua
ptqbw
>>> def k(n): n2 = str(n**2) for i in range(len(n2)): a, b = int(n2[:i] or 0), int(n2[i:]) if b and a + b == n: return n >>> [x for x in range(1,10000) if k(x)] [1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999] >>> len([x for x in range(1,1000000) if k(x)]) 54 >>>
693Kaprekar numbers
3python
d46n1
>>> import json >>> data = json.loads('{ : 1, : [10, ] }') >>> sample = { : [1,2], : } >>> json_string = json.dumps(sample) >>> json_string '{: [1, 2], : }' >>> sample {'blue': [1, 2], 'ocean': 'water'} >>> data {'foo': 1, 'bar': [10, 'apples']}
691JSON
3python
ptsbm
library(rjson) data <- fromJSON('{ "foo": 1, "bar": [10, "apples"] }') data
691JSON
13r
jie78
import copy boardsize=6 _kmoves = ((2,1), (1,2), (-1,2), (-2,1), (-2,-1), (-1,-2), (1,-2), (2,-1)) def chess2index(chess, boardsize=boardsize): 'Convert Algebraic chess notation to internal index format' chess = chess.strip().lower() x = ord(chess[0]) - ord('a') y = boardsize - int(chess[1:]) return (x, y) def boardstring(board, boardsize=boardsize): r = range(boardsize) lines = '' for y in r: lines += '\n' + ','.join('%2i'% board[(x,y)] if board[(x,y)] else ' ' for x in r) return lines def knightmoves(board, P, boardsize=boardsize): Px, Py = P kmoves = set((Px+x, Py+y) for x,y in _kmoves) kmoves = set( (x,y) for x,y in kmoves if 0 <= x < boardsize and 0 <= y < boardsize and not board[(x,y)] ) return kmoves def accessibility(board, P, boardsize=boardsize): access = [] brd = copy.deepcopy(board) for pos in knightmoves(board, P, boardsize=boardsize): brd[pos] = -1 access.append( (len(knightmoves(brd, pos, boardsize=boardsize)), pos) ) brd[pos] = 0 return access def knights_tour(start, boardsize=boardsize, _debug=False): board = {(x,y):0 for x in range(boardsize) for y in range(boardsize)} move = 1 P = chess2index(start, boardsize) board[P] = move move += 1 if _debug: print(boardstring(board, boardsize=boardsize)) while move <= len(board): P = min(accessibility(board, P, boardsize))[1] board[P] = move move += 1 if _debug: print(boardstring(board, boardsize=boardsize)) input('\n%2i next: '% move) return board if __name__ == '__main__': while 1: boardsize = int(input('\nboardsize: ')) if boardsize < 5: continue start = input('Start position: ') board = knights_tour(start, boardsize) print(boardstring(board, boardsize=boardsize))
690Knight's tour
3python
4sp5k
M = 8; N = 8; board = matrix(0, nrow = M, ncol = N) getboard = function (position) { board[position[1], position[2]] } setboard = function (position, x) { board[position[1], position[2]] <<- x } hops = cbind(c(-2, -1), c(-1, -2), c(+1, -2), c(+2, -1), c(+2, +1), c(+1, +2), c(-1, +2), c(-2, +1)) valid = function (move) { all(1 <= move & move <= c(M, N)) && (getboard(move) == 0) } explore = function (position) { moves = position + hops cbind(moves[, apply(moves, 2, valid)]) } candidates = function (position) { moves = explore(position) if (ncol(moves) == 0) { return(moves) } wcosts = apply(moves, 2, function (position) { ncol(explore(position)) }) cbind(moves[, order(wcosts)]) } knightTour = function (position, moveN) { if (moveN > (M * N)) { print(board) quit() } moves = candidates(position) if (ncol(moves) == 0) { return() } apply(moves, 2, function (position) { setboard(position, moveN) knightTour(position, moveN + 1) setboard(position, 0) }) } square = commandArgs(trailingOnly = TRUE) row = M + 1 - as.integer(substr(square, 2, 2)) ascii = function (ch) { as.integer(charToRaw(ch)) } col = 1 + ascii(substr(square, 1, 1)) - ascii('a') position = c(row, col) setboard(position, 1); knightTour(position, 2)
690Knight's tour
13r
2ejlg
object Knuth { internal val gen = java.util.Random() } fun <T> Array<T>.shuffle(): Array<T> { val a = clone() var n = a.size while (n > 1) { val k = Knuth.gen.nextInt(n--) val t = a[n] a[n] = a[k] a[k] = t } return a } fun main(args: Array<String>) { val str = "abcdefghijklmnopqrstuvwxyz".toCharArray() (1..10).forEach { val s = str.toTypedArray().shuffle().toCharArray() println(s) require(s.toSortedSet() == str.toSortedSet()) } val ia = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) (1..10).forEach { val s = ia.shuffle() println(s.distinct()) require(s.toSortedSet() == ia.toSet()) } }
686Knuth shuffle
11kotlin
scyq7
require 'json' ruby_obj = JSON.parse('{: [1, 2], : }') puts ruby_obj ruby_obj[] = { => [, ] } puts JSON.generate(ruby_obj) puts JSON.pretty_generate(ruby_obj)
691JSON
14ruby
a381s
[dependencies] serde = { version = "1.0", features = ["derive"] } serde_json = "1.0"
691JSON
15rust
e6oaj
scala> import scala.util.parsing.json.{JSON, JSONObject} import scala.util.parsing.json.{JSON, JSONObject} scala> JSON.parseFull("""{"foo": "bar"}""") res0: Option[Any] = Some(Map(foo -> bar)) scala> JSONObject(Map("foo" -> "bar")).toString() res1: String = {"foo" : "bar"}
691JSON
16scala
q9dxw
def kaprekar(n, base = 10) return [1, 1, 1, ] if n == 1 return if n*(n-1) % (base-1)!= 0 sqr = (n ** 2).to_s(base) (1...sqr.length).each do |i| a = sqr[0 ... i] b = sqr[i .. -1] break if b.delete().empty? sum = a.to_i(base) + b.to_i(base) return n.to_s(base), sqr, a, b if sum == n end nil end count = 0 1.upto(10_000 - 1) do |i| if result = kaprekar(i) puts % result count += 1 end end 10_000.upto(1_000_000 - 1) {|i| count += 1 if kaprekar(i)} puts puts base = 17 1.upto(1_000_000) do |decimal| if result = kaprekar(decimal, base) puts % [decimal, *result] end end
693Kaprekar numbers
14ruby
trmf2
object Kaprekar extends App { def isKaprekar(n: Int, base: Int = 10):Option[Triple[String,String,String]] = { val check: Long => Option[Triple[String,String,String]] = n => { val split: Pair[String, Int] => Pair[String, String] = p => (p._1.slice(0,p._2),p._1.slice(p._2,p._1.size).padTo[Char,String](1,'0')) val pwr = n*n val sN = java.lang.Long.toString(n, base) val sPwr = java.lang.Long.toString(pwr, base) for (i <- 1 to sPwr.size) { val (a, b) = split(sPwr,i) val la = java.lang.Long.parseLong(a, base) val lb = java.lang.Long.parseLong(b, base) if (lb==0) return None if (la+lb==n) return Some(Triple(sPwr,a,b)) } None } n match { case 1 => Some(Triple("1","0","1")) case n if (n>1) => check(n) case _ => None } } def kaprekars(n: Int,base: Int=10) = (1 to n).map(isKaprekar(_,base)).zip(1 to n).filter(_._1!=None).map(p=>Triple(base,p._2,p._1 match {case Some(t) => t; case _ => Nil})) val k1 = kaprekars(10000) k1 foreach {p=>println(p._2)} println(k1.size + " Kaprekar numbers < 10000 (b:10) for base 10"+"\n"*2) val k2 = kaprekars(1000000) k2 foreach {p => println(p._2+"\t"+java.lang.Long.toString(p._2,p._1)+"\t"+p._3.productElement(0)+"\t"+p._3.productElement(1)+" + "+p._3.productElement(2))} println(k2.size + " Kaprekar numbers < 1000000 (b:10) for base 10"+"\n"*2) val k3 = kaprekars(1000000,17) k3 foreach {p => println(p._2+"\t"+java.lang.Long.toString(p._2,p._1)+"\t"+p._3.productElement(0)+"\t"+p._3.productElement(1)+" + "+p._3.productElement(2))} println(k3.size + " Kaprekar numbers < 1000000 (b:10) for base 17"+"\n"*2) }
693Kaprekar numbers
16scala
yk263
class Board Cell = Struct.new(:value, :adj) do def self.end=(end_val) @@end = end_val end def try(seq_num) self.value = seq_num return true if seq_num==@@end a = [] adj.each_with_index do |cell, n| a << [wdof(cell.adj)*10+n, cell] if cell.value.zero? end a.sort.each {|_, cell| return true if cell.try(seq_num+1)} self.value = 0 false end def wdof(adj) adj.count {|cell| cell.value.zero?} end end def initialize(rows, cols) @rows, @cols = rows, cols unless defined? ADJACENT eval() end frame = ADJACENT.flatten.map(&:abs).max @board = Array.new(rows+frame) do |i| Array.new(cols+frame) do |j| (i<rows and j<cols)? Cell.new(0): nil end end rows.times do |i| cols.times do |j| @board[i][j].adj = ADJACENT.map{|di,dj| @board[i+di][j+dj]}.compact end end Cell.end = rows * cols @format = end def solve(sx, sy) if (@rows*@cols).odd? and (sx+sy).odd? puts else puts (@board[sx][sy].try(1)? to_s: ) end end def to_s (0...@rows).map do |x| (0...@cols).map{|y| @format % @board[x][y].value}.join end end end def knight_tour(rows=8, cols=rows, sx=rand(rows), sy=rand(cols)) puts % [rows, cols, sx, sy] Board.new(rows, cols).solve(sx, sy) end knight_tour(8,8,3,1) knight_tour(5,5,2,2) knight_tour(4,9,0,0) knight_tour(5,5,0,1) knight_tour(12,12,1,1)
690Knight's tour
14ruby
r8ags
import Foundation let jsonString = "{ \"foo\": 1, \"bar\": [10, \"apples\"] }" if let jsonData = jsonString.data(using: .utf8) { if let jsonObject: Any = try? JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) { print("Dictionary: \(jsonObject)") } } let obj = [ "foo": [1, "Orange"], "bar": 1 ] as [String: Any] if let objData = try? JSONSerialization.data(withJSONObject: obj, options: .prettyPrinted) { if let jsonString2 = String(data: objData, encoding: .utf8) { print("JSON: \(jsonString2)") } }
691JSON
17swift
1z0pt
use std::fmt; const SIZE: usize = 8; const MOVES: [(i32, i32); 8] = [ (2, 1), (1, 2), (-1, 2), (-2, 1), (-2, -1), (-1, -2), (1, -2), (2, -1), ]; #[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord)] struct Point { x: i32, y: i32, } impl Point { fn mov(&self, &(dx, dy): &(i32, i32)) -> Self { Self { x: self.x + dx, y: self.y + dy, } } } struct Board { field: [[i32; SIZE]; SIZE], } impl Board { fn new() -> Self { Self { field: [[0; SIZE]; SIZE], } } fn available(&self, p: Point) -> bool { 0 <= p.x && p.x < SIZE as i32 && 0 <= p.y && p.y < SIZE as i32 && self.field[p.x as usize][p.y as usize] == 0 }
690Knight's tour
15rust
7oerc
function table.shuffle(t) for n = #t, 1, -1 do local k = math.random(n) t[n], t[k] = t[k], t[n] end return t end math.randomseed( os.time() ) a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} table.shuffle(a) for i,v in ipairs(a) do print(i,v) end
686Knuth shuffle
1lua
0lmsd
val b=Seq.tabulate(8,8,8,8)((x,y,z,t)=>(1L<<(x*8+y),1L<<(z*8+t),f"${97+z}%c${49+t}%c",(x-z)*(x-z)+(y-t)*(y-t)==5)).flatten.flatten.flatten.filter(_._4).groupBy(_._1) def f(p:Long,s:Long,v:Any){if(-1L!=s)b(p).foreach(x=>if((s&x._2)==0)f(x._2,s|x._2,v+x._3))else println(v)} f(1,1,"a1")
690Knight's tour
16scala
kdqhk
my $raw = <<'TABLE'; map 9 150 compass 13 35 water 153 200 sandwich 50 160 glucose 15 60 tin 68 45 banana 27 60 apple 39 40 cheese 23 30 beer 52 10 suntancream 11 70 camera 32 30 T-shirt 24 15 trousers 48 10 umbrella 73 40 waterproof trousers 42 70 waterproof overclothes 43 75 note-case 22 80 sunglasses 7 20 towel 18 12 socks 4 50 book 30 10 TABLE my (@name, @weight, @value); for (split "\n", $raw) { for ([ split /\t+/ ]) { push @name, $_->[0]; push @weight, $_->[1]; push @value, $_->[2]; } } my $max_weight = 400; my @p = map [map undef, 0 .. 1+$max_weight], 0 .. $ sub optimal { my ($i, $w) = @_; return [0, []] if $i < 0; return $p[$i][$w] if $p[$i][$w]; if ($weight[$i] > $w) { $p[$i][$w] = optimal($i - 1, $w) } else { my $x = optimal($i - 1, $w); my $y = optimal($i - 1, $w - $weight[$i]); if ($x->[0] > $y->[0] + $value[$i]) { $p[$i][$w] = $x } else { $p[$i][$w] = [ $y->[0] + $value[$i], [ @{$y->[1]}, $name[$i] ]] } } return $p[$i][$w] } my $solution = optimal($ print "$solution->[0]: @{$solution->[1]}\n";
692Knapsack problem/0-1
2perl
6h236
function knapSolveFast2($w, $v, $i, $aW, &$m) { global $numcalls; $numcalls ++; if (isset($m[$i][$aW])) { return array( $m[$i][$aW], $m['picked'][$i][$aW] ); } else { if ($i == 0) { if ($w[$i] <= $aW) { $m[$i][$aW] = $v[$i]; $m['picked'][$i][$aW] = array($i); return array($v[$i],array($i)); } else { $m[$i][$aW] = 0; $m['picked'][$i][$aW] = array(); return array(0,array()); } } list ($without_i, $without_PI) = knapSolveFast2($w, $v, $i-1, $aW, $m); if ($w[$i] > $aW) { $m[$i][$aW] = $without_i; $m['picked'][$i][$aW] = $without_PI; return array($without_i, $without_PI); } else { list ($with_i,$with_PI) = knapSolveFast2($w, $v, ($i-1), ($aW - $w[$i]), $m); $with_i += $v[$i]; if ($with_i > $without_i) { $res = $with_i; $picked = $with_PI; array_push($picked,$i); } else { $res = $without_i; $picked = $without_PI; } $m[$i][$aW] = $res; $m['picked'][$i][$aW] = $picked; return array ($res,$picked); } } } $items4 = array(,,,,,,,,,,,,,,,,,,,,,); $w4 = array(9,13,153,50,15,68,27,39,23,52,11,32,24,48,73,42,43,22,7,18,4,30); $v4 = array(150,35,200,160,60,45,60,40,30,10,70,30,15,10,40,70,75,80,20,12,50,10); $numcalls = 0; $m = array(); $pickedItems = array(); list ($m4,$pickedItems) = knapSolveFast2($w4, $v4, sizeof($v4) -1, 400, $m); echo .join(,$items4).; echo ; echo .join(,$pickedItems).; echo ; echo ; echo ; $totalVal = $totalWt = 0; foreach($pickedItems as $key) { $totalVal += $v4[$key]; $totalWt += $w4[$key]; echo .$items4[$key]..$v4[$key]..$w4[$key].; } echo ; echo ;
692Knapsack problem/0-1
12php
1zspq
public struct CPoint { public var x: Int public var y: Int public init(x: Int, y: Int) { (self.x, self.y) = (x, y) } public func move(by: (dx: Int, dy: Int)) -> CPoint { return CPoint(x: self.x + by.dx, y: self.y + by.dy) } } extension CPoint: Comparable { public static func <(lhs: CPoint, rhs: CPoint) -> Bool { if lhs.x == rhs.x { return lhs.y < rhs.y } else { return lhs.x < rhs.x } } } public class KnightsTour { public var size: Int { board.count } private var board: [[Int]] public init(size: Int) { board = Array(repeating: Array(repeating: 0, count: size), count: size) } public func countMoves(forPoint point: CPoint) -> Int { return KnightsTour.knightMoves.lazy .map(point.move) .reduce(0, {count, movedTo in return squareAvailable(movedTo)? count + 1: count }) } public func printBoard() { for row in board { for x in row { print("\(x) ", terminator: "") } print() } print() } private func reset() { for i in 0..<size { for j in 0..<size { board[i][j] = 0 } } } public func squareAvailable(_ p: CPoint) -> Bool { return 0 <= p.x && p.x < size && 0 <= p.y && p.y < size && board[p.x][p.y] == 0 } public func tour(startingAt point: CPoint = CPoint(x: 0, y: 0)) -> Bool { var step = 2 var p = point reset() board[p.x][p.y] = 1 while step <= size * size { let candidates = KnightsTour.knightMoves.lazy .map(p.move) .map({moved in (moved, self.countMoves(forPoint: moved), self.squareAvailable(moved)) }) .filter({ $0.2 }) guard let bestMove = candidates.sorted(by: bestChoice).first else { return false } p = bestMove.0 board[p.x][p.y] = step step += 1 } return true } } private func bestChoice(_ choice1: (CPoint, Int, Bool), _ choice2: (CPoint, Int, Bool)) -> Bool { if choice1.1 == choice2.1 { return choice1.0 < choice2.0 } return choice1.1 < choice2.1 } extension KnightsTour { fileprivate static let knightMoves = [ (2, 1), (1, 2), (-1, 2), (-2, 1), (-2, -1), (-1, -2), (1, -2), (2, -1), ] } let b = KnightsTour(size: 8) print() let completed = b.tour(startingAt: CPoint(x: 3, y: 1)) if completed { print("Completed tour") } else { print("Did not complete tour") } b.printBoard()
690Knight's tour
17swift
g0149
from itertools import combinations def anycomb(items): ' return combinations of any length from the items ' return ( comb for r in range(1, len(items)+1) for comb in combinations(items, r) ) def totalvalue(comb): ' Totalise a particular combination of items' totwt = totval = 0 for item, wt, val in comb: totwt += wt totval += val return (totval, -totwt) if totwt <= 400 else (0, 0) items = ( (, 9, 150), (, 13, 35), (, 153, 200), (, 50, 160), (, 15, 60), (, 68, 45), (, 27, 60), (, 39, 40), (, 23, 30), (, 52, 10), (, 11, 70), (, 32, 30), (, 24, 15), (, 48, 10), (, 73, 40), (, 42, 70), (, 43, 75), (, 22, 80), (, 7, 20), (, 18, 12), (, 4, 50), (, 30, 10), ) bagged = max( anycomb(items), key=totalvalue) print( + '\n '.join(sorted(item for item,_,_ in bagged))) val, wt = totalvalue(bagged) print(% (val, -wt))
692Knapsack problem/0-1
3python
ykv6q
Full_Data<-structure(list(item = c("map", "compass", "water", "sandwich", "glucose", "tin", "banana", "apple", "cheese", "beer", "suntan_cream", "camera", "T-shirt", "trousers", "umbrella", "waterproof_trousers", "waterproof_overclothes", "note-case", "sunglasses", "towel", "socks", "book"), weigth = c(9, 13, 153, 50, 15, 68, 27, 39, 23, 52, 11, 32, 24, 48, 73, 42, 43, 22, 7, 18, 4, 30), value = c(150, 35, 200, 160, 60, 45, 60, 40, 30, 10, 70, 30, 15, 10, 40, 70, 75, 80, 20, 12, 50, 10)), .Names = c("item", "weigth", "value" ), row.names = c(NA, 22L), class = "data.frame") Bounded_knapsack<-function(Data,W) { K<-matrix(NA,nrow=W+1,ncol=dim(Data)[1]+1) 0->K[1,]->K[,1] matrix_item<-matrix('',nrow=W+1,ncol=dim(Data)[1]+1) for(j in 1:dim(Data)[1]) { for(w in 1:W) { wj<-Data$weigth[j] item<-Data$item[j] value<-Data$value[j] if( wj > w ) { K[w+1,j+1]<-K[w+1,j] matrix_item[w+1,j+1]<-matrix_item[w+1,j] } else { if( K[w+1,j] >= K[w+1-wj,j]+value ) { K[w+1,j+1]<-K[w+1,j] matrix_item[w+1,j+1]<-matrix_item[w+1,j] } else { K[w+1,j+1]<-K[w+1-wj,j]+value matrix_item[w+1,j+1]<-item } } } } return(list(K=K,Item=matrix_item)) } backtracking<-function(knapsack, Data) { W<-dim(knapsack$K)[1] itens<-c() col<-dim(knapsack$K)[2] selected_item<-knapsack$Item[W,col] while(selected_item!='') { selected_item<-knapsack$Item[W,col] if(selected_item!='') { selected_item_value<-Data[Data$item == selected_item,] if(-knapsack$K[W - selected_item_value$weigth,col-1]+knapsack$K[W,col]==selected_item_value$value) { W <- W - selected_item_value$weigth itens<-c(itens,selected_item) } col <- col - 1 } } return(itens) } print_output<-function(Data,W) { Bounded_knapsack(Data,W)->Knap backtracking(Knap, Data)->Items output<-paste('You must carry:', paste(Items, sep = ', '), sep=' ' ) return(output) } print_output(Full_Data, 400)
692Knapsack problem/0-1
13r
tr9fz
KnapsackItem = Struct.new(:name, :weight, :value) potential_items = [ KnapsackItem['map', 9, 150], KnapsackItem['compass', 13, 35], KnapsackItem['water', 153, 200], KnapsackItem['sandwich', 50, 160], KnapsackItem['glucose', 15, 60], KnapsackItem['tin', 68, 45], KnapsackItem['banana', 27, 60], KnapsackItem['apple', 39, 40], KnapsackItem['cheese', 23, 30], KnapsackItem['beer', 52, 10], KnapsackItem['suntan cream', 11, 70], KnapsackItem['camera', 32, 30], KnapsackItem['t-shirt', 24, 15], KnapsackItem['trousers', 48, 10], KnapsackItem['umbrella', 73, 40], KnapsackItem['waterproof trousers', 42, 70], KnapsackItem['waterproof overclothes', 43, 75], KnapsackItem['note-case', 22, 80], KnapsackItem['sunglasses', 7, 20], KnapsackItem['towel', 18, 12], KnapsackItem['socks', 4, 50], KnapsackItem['book', 30, 10], ] knapsack_capacity = 400 class Array def power_set yield [] if block_given? self.inject([[]]) do |ps, elem| ps.each_with_object([]) do |i,r| r << i new_subset = i + [elem] yield new_subset if block_given? r << new_subset end end end end maxval, solutions = potential_items.power_set.group_by {|subset| weight = subset.inject(0) {|w, elem| w + elem.weight} weight>knapsack_capacity? 0: subset.inject(0){|v, elem| v + elem.value} }.max puts solutions.each do |set| wt, items = 0, [] set.each {|elem| wt += elem.weight; items << elem.name} puts puts end
692Knapsack problem/0-1
14ruby
9p5mz
use std::cmp; struct Item { name: &'static str, weight: usize, value: usize } fn knapsack01_dyn(items: &[Item], max_weight: usize) -> Vec<&Item> { let mut best_value = vec![vec![0; max_weight + 1]; items.len() + 1]; for (i, it) in items.iter().enumerate() { for w in 1 .. max_weight + 1 { best_value[i + 1][w] = if it.weight > w { best_value[i][w] } else { cmp::max(best_value[i][w], best_value[i][w - it.weight] + it.value) } } } let mut result = Vec::with_capacity(items.len()); let mut left_weight = max_weight; for (i, it) in items.iter().enumerate().rev() { if best_value[i + 1][left_weight]!= best_value[i][left_weight] { result.push(it); left_weight -= it.weight; } } result } fn main () { const MAX_WEIGHT: usize = 400; const ITEMS: &[Item] = &[ Item { name: "map", weight: 9, value: 150 }, Item { name: "compass", weight: 13, value: 35 }, Item { name: "water", weight: 153, value: 200 }, Item { name: "sandwich", weight: 50, value: 160 }, Item { name: "glucose", weight: 15, value: 60 }, Item { name: "tin", weight: 68, value: 45 }, Item { name: "banana", weight: 27, value: 60 }, Item { name: "apple", weight: 39, value: 40 }, Item { name: "cheese", weight: 23, value: 30 }, Item { name: "beer", weight: 52, value: 10 }, Item { name: "suntancream", weight: 11, value: 70 }, Item { name: "camera", weight: 32, value: 30 }, Item { name: "T-shirt", weight: 24, value: 15 }, Item { name: "trousers", weight: 48, value: 10 }, Item { name: "umbrella", weight: 73, value: 40 }, Item { name: "waterproof trousers", weight: 42, value: 70 }, Item { name: "waterproof overclothes", weight: 43, value: 75 }, Item { name: "note-case", weight: 22, value: 80 }, Item { name: "sunglasses", weight: 7, value: 20 }, Item { name: "towel", weight: 18, value: 12 }, Item { name: "socks", weight: 4, value: 50 }, Item { name: "book", weight: 30, value: 10 } ]; let items = knapsack01_dyn(ITEMS, MAX_WEIGHT);
692Knapsack problem/0-1
15rust
c149z
object Knapsack extends App { case class Item(name: String, weight: Int, value: Int) val elapsed: (=> Unit) => Long = f => {val s = System.currentTimeMillis; f; (System.currentTimeMillis - s)/1000}
692Knapsack problem/0-1
16scala
vw72s