task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Kaprekar_numbers
Kaprekar numbers
A positive integer is a Kaprekar number if: It is   1     (unity) The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. Note that a split resulting in a part consisting purely of 0s is not valid, as 0 is not considered positive. ...
#Modula-2
Modula-2
MODULE Kaprekar; FROM FormatString IMPORT FormatString; FROM Terminal IMPORT Write,WriteString,WriteLn,ReadChar;   PROCEDURE kaprekar(n,base : LONGCARD) : BOOLEAN; VAR nn,r,tens : LONGCARD; BEGIN nn := n*n; tens := 1; IF ((nn - n) MOD (base - 1)) # 0 THEN RETURN FALSE END;   WHILE tens < n DO tens :...
http://rosettacode.org/wiki/JSON
JSON
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   import java.util.List import org.json.JSONObject import org.json.JSONArray import org.json.JSONTokener import org.json.JSONException   /** * Using library from json.org * * @see http://www.json.org/java/index.html */ class RJson01 publi...
http://rosettacode.org/wiki/Knight%27s_tour
Knight's tour
Task Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is not a requirement that the tour be "closed"; that is, the knight need not e...
#Mathprog
Mathprog
  /*Knights.mathprog   Find a Knights Tour   Nigel_Galloway January 11th., 2012 */   param ZBLS; param ROWS; param COLS; param D := 2; set ROWSR := 1..ROWS; set COLSR := 1..COLS; set ROWSV := (1-D)..(ROWS+D); set COLSV := (1-D)..(COLS+D); param Iz{ROWSR,COLSR}, integer, default 0; set ZBLSV := 1..(ZBLS+1); set ZB...
http://rosettacode.org/wiki/Knuth_shuffle
Knuth shuffle
The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 to last, the algorithm can be d...
#Groovy
Groovy
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 }
http://rosettacode.org/wiki/Knapsack_problem/Continuous
Knapsack problem/Continuous
A thief burgles a butcher's shop, where he can select from some items. The thief knows the weights and prices of each items.   Because he has a knapsack with 15 kg maximal capacity, he wants to select the items such that he would have his profit maximized.   He may cut the items;   the item has a reduced price after...
#zkl
zkl
items:=List( T(3.8, 36.0, "beef"), T(5.4, 43.0, "pork"), // weight, value, name T(3.6, 90.0, "ham"), T(2.4, 45.0, "greaves"), T(4.0, 30.0, "flitch"),T(2.5, 56.0, "brawn"), T(3.7, 67.0, "welt"), T(3.0, 95.0, "salami"), T(5.9, 98.0, "sausage"), ); fcn item_cmp(a,b){ a[1]/a[0] > b[1]/b[0] }   ...
http://rosettacode.org/wiki/Jump_anywhere
Jump anywhere
Imperative programs conditional structures loops local jumps This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different...
#REXX
REXX
/*REXX pgm demonstrates various jumps (GOTOs). In REXX, it's a SIGNAL. */ say 'starting...' signal aJump say 'this statement is never executed.'   aJump: say 'and here we are at aJump.' do j=1 to 10 say 'j=' j ...
http://rosettacode.org/wiki/Jump_anywhere
Jump anywhere
Imperative programs conditional structures loops local jumps This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different...
#Ring
Ring
  . "The label 'touch' is used to let the player touch the robot" . "to execute the following" end : "touch" goto "label_b"   : "label_a" * "Label A was reached" end   : "label_b" * "Label B was reached" end  
http://rosettacode.org/wiki/Knapsack_problem/0-1
Knapsack problem/0-1
A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it,   and it will have to last the whole day. He cre...
#J
J
'names values'=:|:".;._2]0 :0 'map'; 9 150 'compass'; 13 35 'water'; 153 200 'sandwich'; 50 160 'glucose'; 15 60 'tin'; 68 45 'banana'; ...
http://rosettacode.org/wiki/Kaprekar_numbers
Kaprekar numbers
A positive integer is a Kaprekar number if: It is   1     (unity) The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. Note that a split resulting in a part consisting purely of 0s is not valid, as 0 is not considered positive. ...
#Nim
Nim
import strutils, sequtils   proc k(n: int): bool = let n2 = $(n.int64 * n) for i in 0 .. n2.high: let a = if i > 0: parseBiggestInt n2[0 ..< i] else: 0 let b = parseBiggestInt n2[i .. n2.high] if b > 0 and a + b == n: return true   echo toSeq(1..10_000).filter(k) echo len toSeq(1..1_000_000).filte...
http://rosettacode.org/wiki/Kaprekar_numbers
Kaprekar numbers
A positive integer is a Kaprekar number if: It is   1     (unity) The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. Note that a split resulting in a part consisting purely of 0s is not valid, as 0 is not considered positive. ...
#PARI.2FGP
PARI/GP
K(d)={ my(D=10^d,DD,t,v=List()); for(n=D/10+1,D-1, t=divrem(n^2,D); if(t[2]&t[1]+t[2]==n,listput(v,n);next); DD=D; while(t[2]<n, t=divrem(n^2,DD*=10); if(t[2]&t[1]+t[2]==n,listput(v,n);next(2)) ); DD=D; while(t[1]<n, t=divrem(n^2,DD/=10); if(t[2]&t[1]+t[2]==n,list...
http://rosettacode.org/wiki/JSON
JSON
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
#Nim
Nim
import json   var data = parseJson("""{ "foo": 1, "bar": [10, "apples"] }""") echo data["foo"] echo data["bar"]   var js = %* [{"name": "John", "age": 30}, {"name": "Susan", "age": 31}] echo js
http://rosettacode.org/wiki/JSON
JSON
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
#Objeck
Objeck
  use Struct; use JSON;   bundle Default { class Json { function : Main(args : String[]) ~ Nil { parser := JSONParser->New("{ \"foo\": 1, \"bar\": [10, \"apples\"] }"); root := parser->Parse(); if(root <> Nil) { root->ToString()->PrintLine(); }; } } }
http://rosettacode.org/wiki/Knight%27s_tour
Knight's tour
Task Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is not a requirement that the tour be "closed"; that is, the knight need not e...
#Nim
Nim
import algorithm, options, random, parseutils, strutils, strformat   type Board[N: static Positive] = array[N, array[N, int]] Move = tuple[x, y: int] MoveList = array[8, Move] MoveIndexes = array[8, int]   const Moves: MoveList = [(2, 1), (1, 2), (-1, 2), (-2, 1), (-2, -1), (-1, -2), (1, -2), (2, -1)]   proc `$...
http://rosettacode.org/wiki/Knuth_shuffle
Knuth shuffle
The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 to last, the algorithm can be d...
#Haskell
Haskell
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 = rep...
http://rosettacode.org/wiki/Jump_anywhere
Jump anywhere
Imperative programs conditional structures loops local jumps This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different...
#Robotic
Robotic
  . "The label 'touch' is used to let the player touch the robot" . "to execute the following" end : "touch" goto "label_b"   : "label_a" * "Label A was reached" end   : "label_b" * "Label B was reached" end  
http://rosettacode.org/wiki/Jump_anywhere
Jump anywhere
Imperative programs conditional structures loops local jumps This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different...
#Ruby
Ruby
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 "Fizz" case 0 when i % 5 print "Buzz" end when i % 5 print "Buzz" else print i end   puts c[c, i + 1] end
http://rosettacode.org/wiki/Knapsack_problem/0-1
Knapsack problem/0-1
A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it,   and it will have to last the whole day. He cre...
#Java
Java
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); // 400 dkg = 400 dag = 4 kg   // making the l...
http://rosettacode.org/wiki/Kaprekar_numbers
Kaprekar numbers
A positive integer is a Kaprekar number if: It is   1     (unity) The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. Note that a split resulting in a part consisting purely of 0s is not valid, as 0 is not considered positive. ...
#Perl
Perl
sub isKap { my $k = shift; return if $k*($k-1) % 9; # Fast return "casting out nines" 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 @kapr...
http://rosettacode.org/wiki/JSON
JSON
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
#Objective-C
Objective-C
NSString *jsonString = @"{ \"foo\": 1, \"bar\": [10, \"apples\"] }"; id obj = [NSJSONSerialization JSONObjectWithData: [jsonString dataUsingEncoding: NSUTF8StringEncoding] options: 0 error: NULL]; NSLog(@"%@", obj);   NSDictionary *dict = @{ @"blue": @[@1, @2], @"ocean": @"water"}; ...
http://rosettacode.org/wiki/JSON
JSON
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
#OCaml
OCaml
type json item = < name "Name": string; kingdom "Kingdom": string; phylum "Phylum": string; class_ "Class": string; order "Order": string; family "Family": string; tribe "Tribe": string >   let str = " { \"Name\": \"camel\", \"Kingdom\": \"Animalia\", \"Phylum\": ...
http://rosettacode.org/wiki/Knight%27s_tour
Knight's tour
Task Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is not a requirement that the tour be "closed"; that is, the knight need not e...
#ObjectIcon
ObjectIcon
# # Find Knight’s Tours. # # Using Warnsdorff’s heuristic, find multiple solutions. # # Based on my ATS/Postiats program. # # The main difference from the ATS is this program uses a # co-expression pair to make a generator of solutions, whereas the ATS # simply prints solutions where they are found. # # Usage: ./knigh...
http://rosettacode.org/wiki/Knuth_shuffle
Knuth shuffle
The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 to last, the algorithm can be d...
#Icon_and_Unicon
Icon and Unicon
procedure main() show(shuffle([3,1,4,1,5,9,2,6,3])) show(shuffle("this is a string")) end   procedure shuffle(A) every A[i := *A to 1 by -1] :=: A[?i] return A end   procedure show(A) every writes(!A," ") write() end
http://rosettacode.org/wiki/Jump_anywhere
Jump anywhere
Imperative programs conditional structures loops local jumps This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different...
#Scala
Scala
myLabel -> ... :myLabel
http://rosettacode.org/wiki/Jump_anywhere
Jump anywhere
Imperative programs conditional structures loops local jumps This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different...
#SPL
SPL
myLabel -> ... :myLabel
http://rosettacode.org/wiki/Knapsack_problem/0-1
Knapsack problem/0-1
A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it,   and it will have to last the whole day. He cre...
#JavaScript
JavaScript
/*global portviz:false, _:false */ /* * 0-1 knapsack solution, recursive, memoized, approximate. * * credits: * * the Go implementation here: * http://rosettacode.org/mw/index.php?title=Knapsack_problem/0-1 * * approximation details here: * http://math.mit.edu/~goemans/18434S06/knapsack-katherine.pdf */ p...
http://rosettacode.org/wiki/Kaprekar_numbers
Kaprekar numbers
A positive integer is a Kaprekar number if: It is   1     (unity) The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. Note that a split resulting in a part consisting purely of 0s is not valid, as 0 is not considered positive. ...
#Phix
Phix
with javascript_semantics atom r, l function Kaprekar(integer n, base=10) if n=1 then return true end if atom sq=n*n, basen = base r=0 while r<n do r = mod(sq,basen) l = floor(sq/basen) if r and l and l+r=n then return true end if basen *= base end while return fa...
http://rosettacode.org/wiki/JSON
JSON
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
#Oforth
Oforth
>{"parents":["Otmar Gutmann", "Silvio Mazzola"], "name":"Pingu", "born":1986} .s [1] (Json) {"parents" : ["Otmar Gutmann", "Silvio Mazzola"], "name" : "Pingu", "born" : 1986 } ok >asString .s [1] (String) {"parents" : ["Otmar Gutmann", "Silvio Mazzola"], "name" : "Pingu", "born" :1986 } ok >perform .s [1] (Json) {"pare...
http://rosettacode.org/wiki/JSON
JSON
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
#Ol
Ol
  (import (file json))   (define o (read-json-string " { 'name': 'John', 'full name': 'John Smith', 'age': 42, 'weight': 156.18, 'married': false, 'address': { 'street': '21 2nd Street', 'city': 'New York', }, 'additional staff': [ { 'type': 'numbers', ...
http://rosettacode.org/wiki/Knight%27s_tour
Knight's tour
Task Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is not a requirement that the tour be "closed"; that is, the knight need not e...
#Perl
Perl
use strict; use warnings; # Find a knight's tour   my @board;   # Choose starting position - may be passed in on command line; if # not, choose random square. 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 ...
http://rosettacode.org/wiki/Knuth_shuffle
Knuth shuffle
The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 to last, the algorithm can be d...
#Inform_6
Inform 6
[ shuffle a n i j tmp; for(i = n - 1: i > 0: i--) { j = random(i + 1) - 1;   tmp = a->j; a->j = a->i; a->i = tmp; } ];
http://rosettacode.org/wiki/Jump_anywhere
Jump anywhere
Imperative programs conditional structures loops local jumps This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different...
#SSEM
SSEM
10000000000000000000000000000000 0. 1 to CI 11001000000000000000000000000000 1. 19
http://rosettacode.org/wiki/Jump_anywhere
Jump anywhere
Imperative programs conditional structures loops local jumps This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different...
#Tcl
Tcl
Public Sub jump() Debug.Print "VBA only allows" GoTo 1 Debug.Print "no global jumps" 1: Debug.Print "jumps in procedures with GoTo" Debug.Print "However," On 2 GoSub one, two Debug.Print "named in the list after 'GoSub'" Debug.Print "and execution will continue on the next line" On 1...
http://rosettacode.org/wiki/Knapsack_problem/0-1
Knapsack problem/0-1
A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it,   and it will have to last the whole day. He cre...
#jq
jq
# Input should be the array of objects giving name, weight and value. # Because of the way addition is defined on null and because of the # way setpath works, there is no need to initialize the matrix m in # detail. def dynamic_knapsack(W): . as $objects | length as $n | reduce range(1; $n+1) as $i ...
http://rosettacode.org/wiki/Kaprekar_numbers
Kaprekar numbers
A positive integer is a Kaprekar number if: It is   1     (unity) The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. Note that a split resulting in a part consisting purely of 0s is not valid, as 0 is not considered positive. ...
#Phixmonti
Phixmonti
def FNkaprekar var n dup 2 power var s s log int 1 + 10 swap power var t true while t 10 / var t t n <= IF false else s n - s t / int t 1 - * == IF false 1 var n else TRUE endif endif endwhile n 1 == enddef   0 10000 FOR dup FNkaprekar IF print " " print ...
http://rosettacode.org/wiki/Kaprekar_numbers
Kaprekar numbers
A positive integer is a Kaprekar number if: It is   1     (unity) The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. Note that a split resulting in a part consisting purely of 0s is not valid, as 0 is not considered positive. ...
#PHP
PHP
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("$a", "10"); for ($d = 1, $t = 0; $a > 0; $d *= 10) { $b += $t * $d; if ($b > $n) break; $a = ...
http://rosettacode.org/wiki/JSON
JSON
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
#OpenEdge.2FProgress
OpenEdge/Progress
/* using a longchar to read and write to, can also be file, memptr, stream */ DEFINE VARIABLE lcjson AS LONGCHAR NO-UNDO.   /* temp-table defines object, can also be dataset */ DEFINE TEMP-TABLE example FIELD blue AS INTEGER EXTENT 2 FIELD ocean AS CHARACTER . CREATE example. ASSIGN example.blue [1] = ...
http://rosettacode.org/wiki/JSON
JSON
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
#Oz
Oz
declare [JSON] = {Module.link ['JSON.ozf']}   {System.show {JSON.decode "{ \"foo\": 1, \"bar\": [10, \"apples\"] }"}}   Sample = object(blue:array(1 2) ocean:"water") {System.showInfo {JSON.encode Sample}}
http://rosettacode.org/wiki/Knight%27s_tour
Knight's tour
Task Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is not a requirement that the tour be "closed"; that is, the knight need not e...
#Phix
Phix
with javascript_semantics constant size = 8, nchars = length(sprintf(" %d",size*size)), fmt = sprintf(" %%%dd",nchars-1), blank = repeat(' ',nchars) -- to simplify output, each square is nchars sequence board = repeat(repeat(' ',size*nchars),size) -- keep current counts, immediately backtra...
http://rosettacode.org/wiki/Knuth_shuffle
Knuth shuffle
The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 to last, the algorithm can be d...
#J
J
KS=:{~ (2&{.@[ {`(|.@[)`]} ])/@(,~(,.?@>:))@i.@#
http://rosettacode.org/wiki/Jump_anywhere
Jump anywhere
Imperative programs conditional structures loops local jumps This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different...
#VBA
VBA
Public Sub jump() Debug.Print "VBA only allows" GoTo 1 Debug.Print "no global jumps" 1: Debug.Print "jumps in procedures with GoTo" Debug.Print "However," On 2 GoSub one, two Debug.Print "named in the list after 'GoSub'" Debug.Print "and execution will continue on the next line" On 1...
http://rosettacode.org/wiki/Jump_anywhere
Jump anywhere
Imperative programs conditional structures loops local jumps This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different...
#VBScript
VBScript
1010 ?="@1010: Where to goto? "; 1020 #=? 1030 ?="@1030" 1040 #=1010 1050 ?="@1050" 1060 #=1010 2000 ?="@2000" 2010 ?="Exiting..."
http://rosettacode.org/wiki/Knapsack_problem/0-1
Knapsack problem/0-1
A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it,   and it will have to last the whole day. He cre...
#Julia
Julia
struct KPDSupply{T<:Integer} item::String weight::T value::T quant::T end   KPDSupply{T<:Integer}(itm::AbstractString, w::T, v::T, q::T=one(T)) = KPDSupply(itm, w, v, q) Base.show(io::IO, kdps::KPDSupply) = print(io, kdps.quant, " ", kdps.item, " ($(kdps.weight) kg, $(kdps.value) €)")   using MathProgBa...
http://rosettacode.org/wiki/Kaprekar_numbers
Kaprekar numbers
A positive integer is a Kaprekar number if: It is   1     (unity) The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. Note that a split resulting in a part consisting purely of 0s is not valid, as 0 is not considered positive. ...
#Picat
Picat
go => println(base=10), println(kaprekar_number(10,10000)), nl, println("Testing 1000000:"),   K10 = kaprekar_number(10,1000000),  % println(K10), nl, println(base=16), K16 = [I.to_hex_string() : I in kaprekar_number(16,1000000)],  % println(K16), nl,   println(base=17), K17 = [to_radix_string(I...
http://rosettacode.org/wiki/Kaprekar_numbers
Kaprekar numbers
A positive integer is a Kaprekar number if: It is   1     (unity) The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. Note that a split resulting in a part consisting purely of 0s is not valid, as 0 is not considered positive. ...
#PicoLisp
PicoLisp
(de kaprekar (N) (let L (cons 0 (chop (* N N))) (for ((I . R) (cdr L) R (cdr R)) (NIL (gt0 (format R))) (T (= N (+ @ (format (head I L)))) N) ) ) )
http://rosettacode.org/wiki/JSON
JSON
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
#Perl
Perl
use JSON;   my $data = decode_json('{ "foo": 1, "bar": [10, "apples"] }');   my $sample = { blue => [1,2], ocean => "water" }; my $json_string = encode_json($sample);
http://rosettacode.org/wiki/JSON
JSON
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
#Phix
Phix
-- demo\rosetta\JSON.exw with javascript_semantics include builtins/json.e puts(1,"roundtrip (10 examples):\n") sequence json_strings = {`{"this":"that","age":{"this":"that","age":29}}`, `1`, `"hello"`, `null`, `[12]`,...
http://rosettacode.org/wiki/Knight%27s_tour
Knight's tour
Task Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is not a requirement that the tour be "closed"; that is, the knight need not e...
#Picat
Picat
import cp.   main => N = 8, A = new_array(N,N), foreach (R in 1..N, C in 1..N) Connected = [(R+1, C+2), (R+1, C-2), (R-1, C+2), (R-1, C-2), (R+2, C+1), (R+2, C-1), (R-2, C+1)...
http://rosettacode.org/wiki/Knuth_shuffle
Knuth shuffle
The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 to last, the algorithm can be d...
#Java
Java
import java.util.Random;   public static final Random gen = new Random();   // version for array of ints public static void shuffle (int[] array) { int n = array.length; while (n > 1) { int k = gen.nextInt(n--); //decrements after using the value int temp = array[n]; array[n] = array[k];...
http://rosettacode.org/wiki/Jump_anywhere
Jump anywhere
Imperative programs conditional structures loops local jumps This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different...
#VTL-2
VTL-2
1010 ?="@1010: Where to goto? "; 1020 #=? 1030 ?="@1030" 1040 #=1010 1050 ?="@1050" 1060 #=1010 2000 ?="@2000" 2010 ?="Exiting..."
http://rosettacode.org/wiki/Jump_anywhere
Jump anywhere
Imperative programs conditional structures loops local jumps This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different...
#Wren
Wren
var func = Fn.new { for (i in 1..10) { if (i == 1) continue // jumps to next iteration when 'i' equals 1 System.print("i = %(i)") if (i > 4) break // exits the loop when 'i' exceeds 4 } for (j in 1..10) { System.print("j = %(j)") if (j == 3) return // returns fr...
http://rosettacode.org/wiki/Knapsack_problem/0-1
Knapsack problem/0-1
A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it,   and it will have to last the whole day. He cre...
#Kotlin
Kotlin
// version 1.1.2   data class Item(val name: String, val weight: Int, val value: Int)   val wants = listOf( Item("map", 9, 150), Item("compass", 13, 35), Item("water", 153, 200), Item("sandwich", 50, 160), Item("glucose", 15, 60), Item("tin", 68, 45), Item("banana", 27, 60), Item("apple"...
http://rosettacode.org/wiki/Kaprekar_numbers
Kaprekar numbers
A positive integer is a Kaprekar number if: It is   1     (unity) The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. Note that a split resulting in a part consisting purely of 0s is not valid, as 0 is not considered positive. ...
#PL.2FI
PL/I
  kaprekar: procedure options (main); /* 22 January 2012 */ declare i fixed decimal (9), j fixed binary; declare s character (20) character varying; declare m fixed decimal (9); declare (z, zeros) character (20) varying;   zeros = '00000000000000000000';   put skip list (1); do i = 2 to 100000; ...
http://rosettacode.org/wiki/Kaprekar_numbers
Kaprekar numbers
A positive integer is a Kaprekar number if: It is   1     (unity) The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. Note that a split resulting in a part consisting purely of 0s is not valid, as 0 is not considered positive. ...
#PowerShell
PowerShell
  function Test-Kaprekar ([int]$Number) { if ($Number -eq 1) { return $true }   [int64]$a = $Number * $Number [int64]$b = 10   while ($b -lt $a) { [int64]$remainder = $a % $b [int64]$quotient = ($a - $remainder) / $b   if ($remainder -gt 0 -and $remainder + $...
http://rosettacode.org/wiki/JSON
JSON
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
#PHP
PHP
<?php $data = json_decode('{ "foo": 1, "bar": [10, "apples"] }'); // dictionaries will be returned as objects $data2 = json_decode('{ "foo": 1, "bar": [10, "apples"] }', true); // dictionaries will be returned as arrays   $sample = array( "blue" => array(1,2), "ocean" => "water" ); $json_string = json_encode($sample); ...
http://rosettacode.org/wiki/JSON
JSON
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
#PicoLisp
PicoLisp
(de checkJson (X Item) (unless (= X Item) (quit "Bad JSON" Item) ) )   (de readJson () (case (read "_") ("{" (make (for (X (readJson) (not (= "}" X)) (readJson)) (checkJson ":" (readJson)) (link (cons X (readJson))) (T (= "}" (setq X ...
http://rosettacode.org/wiki/Knight%27s_tour
Knight's tour
Task Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is not a requirement that the tour be "closed"; that is, the knight need not e...
#PicoLisp
PicoLisp
(load "@lib/simul.l")   # Build board (grid 8 8)   # Generate legal moves for a given position (de moves (Tour) (extract '((Jump) (let? Pos (Jump (car Tour)) (unless (memq Pos Tour) Pos ) ) ) (quote # (taken from "games/chess.l") ((This) (: 0 1 1 0 -1 1 0...
http://rosettacode.org/wiki/Knuth_shuffle
Knuth shuffle
The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 to last, the algorithm can be d...
#JavaScript
JavaScript
function knuthShuffle(arr) { var rand, temp, i;   for (i = arr.length - 1; i > 0; i -= 1) { rand = Math.floor((i + 1) * Math.random());//get random between zero and i (inclusive) temp = arr[rand];//swap i and the zero-indexed number arr[rand] = arr[i]; arr[i] = temp; } re...
http://rosettacode.org/wiki/Jump_anywhere
Jump anywhere
Imperative programs conditional structures loops local jumps This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different...
#XPL0
XPL0
print "First line." gosub sub1 print "Fifth line." goto Ending   sub1: print "Second line." gosub sub2 print "Fourth line." return   Ending: print "We're just about done..." goto Finished   sub2: print "Third line." return   Finished: print "... with goto and gosub, thankfully." end
http://rosettacode.org/wiki/Jump_anywhere
Jump anywhere
Imperative programs conditional structures loops local jumps This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different...
#Yabasic
Yabasic
print "First line." gosub sub1 print "Fifth line." goto Ending   sub1: print "Second line." gosub sub2 print "Fourth line." return   Ending: print "We're just about done..." goto Finished   sub2: print "Third line." return   Finished: print "... with goto and gosub, thankfully." end
http://rosettacode.org/wiki/Knapsack_problem/0-1
Knapsack problem/0-1
A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it,   and it will have to last the whole day. He cre...
#LSL
LSL
string sNOTECARD = "Knapsack_Problem_0_1_Data.txt"; integer iMAX_WEIGHT = 400; integer iSTRIDE = 4; list lList = []; default { integer iNotecardLine = 0; state_entry() { llOwnerSay("Reading '"+sNOTECARD+"'"); llGetNotecardLine(sNOTECARD, iNotecardLine); } dataserver(key kRequestId, string sData) { if(sData==E...
http://rosettacode.org/wiki/Kaprekar_numbers
Kaprekar numbers
A positive integer is a Kaprekar number if: It is   1     (unity) The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. Note that a split resulting in a part consisting purely of 0s is not valid, as 0 is not considered positive. ...
#Prolog
Prolog
kaprekar_(Z, X) :- split_number(Z, 10, X).     split_number(Z, N, X) :- N < Z, A is Z // N, B is Z mod N, ( (X is A+B, B\= 0)-> true; N1 is N*10, split_number(Z, N1, X)).   kaprekar(N, V) :- V <- {X & X <- 1 .. N & ((Z is X * X, kaprekar_(Z, X)); X = 1) }.  
http://rosettacode.org/wiki/JSON
JSON
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
#Pike
Pike
int main() { // Decoding string json = "{\"cake\":[\"desu\",1,2.3],\"foo\":1}"; write("%O\n", Standards.JSON.decode(json));   // Encoding mapping m = ([ "foo": ({ 1, 2, 3 }), "bar": "hello" ]);   write("%s\n", Standards.JSON.encode(m)); }
http://rosettacode.org/wiki/JSON
JSON
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
#PowerShell
PowerShell
  # JSON input is being stored in ordered hashtable. # Ordered hashtable is available in PowerShell v3 and higher. [ordered]@{ "foo"= 1; "bar"= 10, "apples" } | ConvertTo-Json   # ConvertFrom-Json converts a JSON-formatted string to a custom object. # If you use the Invoke-RestMethod cmdlet there is not need for the Co...
http://rosettacode.org/wiki/Knight%27s_tour
Knight's tour
Task Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is not a requirement that the tour be "closed"; that is, the knight need not e...
#PostScript
PostScript
%!PS-Adobe-3.0 %%BoundingBox: 0 0 300 300   /s { 300 n div } def /l { rlineto } def   % draws a square /bx { s mul exch s mul moveto s 0 l 0 s l s neg 0 l 0 s neg l } def   % draws checker board /xbd { 1 setgray 0 0 moveto 300 0 l 0 300 l -300 0 l fill .7 1 .6 setrgbcolor 0 1 n1 { dup 2 mod 2 n...
http://rosettacode.org/wiki/Knuth_shuffle
Knuth shuffle
The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 to last, the algorithm can be d...
#Joy
Joy
DEFINE knuth-shuffle ==   (* Take the size of the array (without destroying it) *) dup dup size   (* Generate a list of as many random numbers *) [rand] [rem] enconcat map   (* Zip the two lists *) swap zip   (* Sort according to the new index number *) [small] [] [uncons unswonsd [first >] split [swons] dip2] [enconca...
http://rosettacode.org/wiki/Jump_anywhere
Jump anywhere
Imperative programs conditional structures loops local jumps This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different...
#Z80_Assembly
Z80 Assembly
and &01 ;returns 0 if the accumulator is even and 1 if odd. Also sets the zero flag accordingly. jr z,SkipOddCode ;whatever you want to do when the accumulator is odd goes here, but it must be 127 bytes or fewer. SkipOddCode: ;rest of program
http://rosettacode.org/wiki/Knapsack_problem/0-1
Knapsack problem/0-1
A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it,   and it will have to last the whole day. He cre...
#Lua
Lua
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...
http://rosettacode.org/wiki/Kaprekar_numbers
Kaprekar numbers
A positive integer is a Kaprekar number if: It is   1     (unity) The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. Note that a split resulting in a part consisting purely of 0s is not valid, as 0 is not considered positive. ...
#PureBasic
PureBasic
Procedure Kaprekar(n.i) nn.q = n*n tens.q= 1 While tens<nn: tens*10: Wend Repeat tens/10 If tens<=n: Break: EndIf If nn-n = (nn/tens) * (tens-1) ProcedureReturn #True EndIf ForEver If n=1 ProcedureReturn #True EndIf EndProcedure   If OpenConsole() For i=1 To 1000000 If K...
http://rosettacode.org/wiki/JSON
JSON
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
#Prolog
Prolog
:- use_module([ library(http/json), library(func) ]).   test_json('{"widget": { "debug": "on", "window": { "title": "Sample Konfabulator Widget", "name": "main_window", "width": 500, "height": 500 }, "image": { "src": "Images/Sun.png", "name": "sun1", "hOffset": 250, "vOffset": 250, "alignment": "center...
http://rosettacode.org/wiki/JSON
JSON
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
#PureBasic
PureBasic
OpenConsole() If CreateJSON(1) PB_Team_Members=SetJSONObject(JSONValue(1)) SetJSONString(AddJSONMember(PB_Team_Members,"PB_Team_Member_1"),"Frederic Laboureur") SetJSONString(AddJSONMember(PB_Team_Members,"PB_Team_Member_2"),"Andre Beer") SetJSONString(AddJSONMember(PB_Team_Members,"PB_Team_Member_3"),"Timo Har...
http://rosettacode.org/wiki/Knight%27s_tour
Knight's tour
Task Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is not a requirement that the tour be "closed"; that is, the knight need not e...
#Prolog
Prolog
% N is the number of lines of the chessboard knight(N) :- Max is N * N, length(L, Max), knight(N, 0, Max, 0, 0, L), display(N, 0, L).   % knight(NbCol, Coup, Max, Lig, Col, L), % NbCol : number of columns per line % Coup  : number of the current move % Max  : maximum number of moves % Lig/ Col : current position o...
http://rosettacode.org/wiki/Knuth_shuffle
Knuth shuffle
The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 to last, the algorithm can be d...
#jq
jq
  # 52-card deck: def deck: [range(127137; 127148), range(127149; 127151), # Spades range(127153; 127164), range(127165; 127167), # Hearts range(127169; 127180), range(127181; 127183), # Diamonds range(127185; 127196), range(127197; 127199)] # Clubs  ;   # For splitting a deck into hands :-) def nwise($...
http://rosettacode.org/wiki/Knapsack_problem/0-1
Knapsack problem/0-1
A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it,   and it will have to last the whole day. He cre...
#Maple
Maple
weights := [9,13,153,50,15,68,27,39,23,52,11,32,24,48,73,42,43,22,7,18,4,30]: vals := [150,35,200,160,60,45,60,40,30,10,70,30,15,10,40,70,75,80,20,12,50,10]: items := ["map","compass","water","sandwich","glucose","tin","banana","apple","cheese","beer","suntan cream","camera","T-shirt","trousers","umbrella","waterproof ...
http://rosettacode.org/wiki/Kaprekar_numbers
Kaprekar numbers
A positive integer is a Kaprekar number if: It is   1     (unity) The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. Note that a split resulting in a part consisting purely of 0s is not valid, as 0 is not considered positive. ...
#Python
Python
>>> 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 #return (n, (n2[:i], n2[i:]))     >>> [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...
http://rosettacode.org/wiki/JSON
JSON
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
#Python
Python
>>> import json >>> data = json.loads('{ "foo": 1, "bar": [10, "apples"] }') >>> sample = { "blue": [1,2], "ocean": "water" } >>> json_string = json.dumps(sample) >>> json_string '{"blue": [1, 2], "ocean": "water"}' >>> sample {'blue': [1, 2], 'ocean': 'water'} >>> data {'foo': 1, 'bar': [10, 'apples']}
http://rosettacode.org/wiki/JSON
JSON
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
#R
R
library(rjson) data <- fromJSON('{ "foo": 1, "bar": [10, "apples"] }') data
http://rosettacode.org/wiki/Knight%27s_tour
Knight's tour
Task Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is not a requirement that the tour be "closed"; that is, the knight need not e...
#Python
Python
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:]) ...
http://rosettacode.org/wiki/Knuth_shuffle
Knuth shuffle
The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 to last, the algorithm can be d...
#Julia
Julia
function knuthshuffle!(r::AbstractRNG, v::AbstractVector) for i in length(v):-1:2 j = rand(r, 1:i) v[i], v[j] = v[j], v[i] end return v end knuthshuffle!(v::AbstractVector) = knuthshuffle!(Base.Random.GLOBAL_RNG, v)   v = collect(1:20) println("# v = $v\n -> ", knuthshuffle!(v))
http://rosettacode.org/wiki/Knapsack_problem/0-1
Knapsack problem/0-1
A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it,   and it will have to last the whole day. He cre...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
#[[Flatten@ Position[LinearProgramming[-#[[;; , 3]], -{#[[;; , 2]]}, -{400}, {0, 1} & /@ #, Integers], 1], 1]] &@ {{"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...
http://rosettacode.org/wiki/Kaprekar_numbers
Kaprekar numbers
A positive integer is a Kaprekar number if: It is   1     (unity) The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. Note that a split resulting in a part consisting purely of 0s is not valid, as 0 is not considered positive. ...
#Quackery
Quackery
[ dup 1 = if done dup temp put dup * false swap 1 [ base share * 2dup /mod over 0 = iff 2drop done dup 0 = iff 2drop again + temp share = iff [ rot not unrot ] done again ] 2drop temp release ] is kaprekar ( n --> b )   say...
http://rosettacode.org/wiki/Kaprekar_numbers
Kaprekar numbers
A positive integer is a Kaprekar number if: It is   1     (unity) The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. Note that a split resulting in a part consisting purely of 0s is not valid, as 0 is not considered positive. ...
#Racket
Racket
  #lang racket (define (kaprekar? n) (or (= n 1) (let ([q (sqr n)]) (let loop ((p 10)) (and (<= p q) (or (let-values ([(b a) (quotient/remainder q p)]) (and (> a 0) (= n (+ a b)))) (loop (* p 10))))))))   (filter kaprekar? (range 1 10000)...
http://rosettacode.org/wiki/JSON
JSON
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
#Racket
Racket
  #lang racket   (require json)   (string->jsexpr "{\"foo\":[1,2,3],\"bar\":null,\"baz\":\"blah\"}")   (write-json '(1 2 "three" #hash((x . 1) (y . 2) (z . 3))))  
http://rosettacode.org/wiki/JSON
JSON
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
#Raku
Raku
use JSON::Tiny;   my $data = from-json('{ "foo": 1, "bar": [10, "apples"] }');   my $sample = { blue => [1,2], ocean => "water" }; my $json_string = to-json($sample);
http://rosettacode.org/wiki/Knight%27s_tour
Knight's tour
Task Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is not a requirement that the tour be "closed"; that is, the knight need not e...
#R
R
#!/usr/bin/Rscript   # M x N Chess Board. M = 8; N = 8; board = matrix(0, nrow = M, ncol = N)   # Get/Set value on a board position. getboard = function (position) { board[position[1], position[2]] } setboard = function (position, x) { board[position[1], position[2]] <<- x }   # (Relative) Hops of a Knight. hops = c...
http://rosettacode.org/wiki/Knuth_shuffle
Knuth shuffle
The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 to last, the algorithm can be d...
#Kotlin
Kotlin
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 s...
http://rosettacode.org/wiki/Knapsack_problem/0-1
Knapsack problem/0-1
A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it,   and it will have to last the whole day. He cre...
#Mathprog
Mathprog
/*Knapsack   This model finds the integer optimal packing of a knapsack   Nigel_Galloway January 9th., 2012 */   set Items; param weight{t in Items}; param value{t in Items};   var take{t in Items}, binary;   knap_weight : sum{t in Items} take[t] * weight[t] <= 400;   maximize knap_value: sum{t in Items} take[t] ...
http://rosettacode.org/wiki/Kaprekar_numbers
Kaprekar numbers
A positive integer is a Kaprekar number if: It is   1     (unity) The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. Note that a split resulting in a part consisting purely of 0s is not valid, as 0 is not considered positive. ...
#Raku
Raku
sub kaprekar( Int $n ) { my $sq = $n ** 2; for 0 ^..^ $sq.chars -> $i { my $x = +$sq.substr(0, $i); my $y = +$sq.substr($i) || return; return True if $x + $y == $n; } False; }   print 1; print " $_" if .&kaprekar for ^10000; print "\n";
http://rosettacode.org/wiki/JSON
JSON
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
#REBOL
REBOL
json-str: {{"menu": { "id": "file", "string": "File:", "number": -3, "boolean": true, "boolean2": false, "null": null, "array": [1, 0.13, null, true, false, "\t\r\n"], "empty-string": "" } }}   res: json-to-rebol json-str js: rebol-to-json res  
http://rosettacode.org/wiki/JSON
JSON
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
#Ruby
Ruby
require 'json'   ruby_obj = JSON.parse('{"blue": [1, 2], "ocean": "water"}') puts ruby_obj   ruby_obj["ocean"] = { "water" => ["fishy", "salty"] } puts JSON.generate(ruby_obj) puts JSON.pretty_generate(ruby_obj)
http://rosettacode.org/wiki/Knight%27s_tour
Knight's tour
Task Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is not a requirement that the tour be "closed"; that is, the knight need not e...
#Racket
Racket
  #lang racket (define N 8) (define nexts ; construct the graph (let ([ds (for*/list ([x 2] [x* '(+1 -1)] [y* '(+1 -1)]) (cons (* x* (+ 1 x)) (* y* (- 2 x))))]) (for*/vector ([i N] [j N]) (filter values (for/list ([d ds]) (let ([i (+ i (car d))] [j (+ j (cdr d))]) ...
http://rosettacode.org/wiki/Knuth_shuffle
Knuth shuffle
The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 to last, the algorithm can be d...
#LabVIEW
LabVIEW
  {def shuffle   {def shuffle.in {lambda {:a} {S.map {{lambda {:a :i} {A.swap :i {floor {* {random} {+ :i 1}}} // j = random integer from 0 to i+1  :a}} :a} {S.serie {- {A.length :a} 1} 0 -1}}}} // from length-1 to 0   {...
http://rosettacode.org/wiki/Knapsack_problem/0-1
Knapsack problem/0-1
A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it,   and it will have to last the whole day. He cre...
#MAXScript
MAXScript
  global globalItems = #() global usedMass = 0 global neededItems = #() global totalValue = 0 struct kn_item ( item, weight, value )   itemStrings = #("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","sunt...
http://rosettacode.org/wiki/Kaprekar_numbers
Kaprekar numbers
A positive integer is a Kaprekar number if: It is   1     (unity) The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. Note that a split resulting in a part consisting purely of 0s is not valid, as 0 is not considered positive. ...
#REXX
REXX
╔═══════════════════════════════════════════════════════════════════╗ ║ Kaprekar numbers were thought of by the mathematician from India, ║ ║ Shri Dattathreya Ramachardra Kaprekar (1905 ───► 1986). ║ ╚═════════════════════════════════════════════════════════════════...
http://rosettacode.org/wiki/Kaprekar_numbers
Kaprekar numbers
A positive integer is a Kaprekar number if: It is   1     (unity) The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. Note that a split resulting in a part consisting purely of 0s is not valid, as 0 is not considered positive. ...
#Ring
Ring
  nr = 0 for i = 1 to 200 if kaprekar(i) nr += 1 if i < 201 see "" + nr + " : " + i + nl ok ok next see "total kaprekar numbers under 200 = " + nr + nl   func kaprekar n s = pow(n,2) x = floor(log(s)) + 1 t = pow(10,x) while true t /= 10 if t<=n exit ok ...
http://rosettacode.org/wiki/JSON
JSON
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
#Rust
Rust
[dependencies] serde = { version = "1.0", features = ["derive"] } serde_json = "1.0"
http://rosettacode.org/wiki/JSON
JSON
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
#Scala
Scala
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"}  
http://rosettacode.org/wiki/Knight%27s_tour
Knight's tour
Task Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is not a requirement that the tour be "closed"; that is, the knight need not e...
#Raku
Raku
my @board;   my $I = 8; my $J = 8; my $F = $I*$J > 99 ?? "%3d" !! "%2d";   # Choose starting position - may be passed in on command line; if # not, choose random square. my ($i, $j);   if my $sq = shift @*ARGS { die "$*PROGRAM_NAME: illegal start square '$sq'\n" unless ($i, $j) = from_algebraic($sq); } else { ($i, ...
http://rosettacode.org/wiki/Knuth_shuffle
Knuth shuffle
The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 to last, the algorithm can be d...
#Lambdatalk
Lambdatalk
  {def shuffle   {def shuffle.in {lambda {:a} {S.map {{lambda {:a :i} {A.swap :i {floor {* {random} {+ :i 1}}} // j = random integer from 0 to i+1  :a}} :a} {S.serie {- {A.length :a} 1} 0 -1}}}} // from length-1 to 0   {...
http://rosettacode.org/wiki/Knapsack_problem/0-1
Knapsack problem/0-1
A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it,   and it will have to last the whole day. He cre...
#MiniZinc
MiniZinc
  %Knapsack 0/1. Nigel Galloway: October 5th., 2020. enum Items={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}; array[Items] of int: weight=[9,13,153,50,15,68,27,39,23,52,11...
http://rosettacode.org/wiki/Kaprekar_numbers
Kaprekar numbers
A positive integer is a Kaprekar number if: It is   1     (unity) The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. Note that a split resulting in a part consisting purely of 0s is not valid, as 0 is not considered positive. ...
#Ruby
Ruby
def kaprekar(n, base = 10) return [1, 1, 1, ""] if n == 1 return if n*(n-1) % (base-1) != 0 # casting out nine sqr = (n ** 2).to_s(base) (1...sqr.length).each do |i| a = sqr[0 ... i] b = sqr[i .. -1] break if b.delete("0").empty? sum = a.to_i(base) + b.to_i(base) return n.to_s(base), sq...