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;
... | 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::It... | 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"... | 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)... | 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)
... | 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
parse... | 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;
... | 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, s... | 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 f... | 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] ... | 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 *... | 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)
... | 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::{R... | 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... | 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 <- fun... | 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 <- fun... | 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] <=... | 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(c... | 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": []interf... | 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 /... | 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":"peo... | 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 $ new... | 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 * ($... | 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/ite... | 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 [
... | 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 / w... | 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 $
takeWhil... | 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];
... | 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: Se... | 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.getB... | 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 =... | 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 ... | 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 h... | 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;
th... | 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 = max... | 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),
I... | 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... | 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
... | 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[n... | 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 = {... | 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"... | 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, 'L... | 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,7... | 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... | 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 = replace... | 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,... | 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] = $mo... | 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 /... | 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... | 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:])
re... | 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))
va... | 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... | 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
en... | 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')... | 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
... | 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": ... | 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): &(... | 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... | 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],arra... | 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:... | 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'
totw... | 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, ... | 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['banan... | 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 {
... | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.