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/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#Crystal
Crystal
require "complex"   def julia(c_real, c_imag) puts Complex.new(c_real, c_imag) -1.0.step(to: 1.0, by: 0.04) do |v| puts -1.4.step(to: 1.4, by: 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 + ...
http://rosettacode.org/wiki/Knapsack_problem/Unbounded
Knapsack problem/Unbounded
A traveler gets diverted and has to make an unscheduled stop in what turns out to be Shangri La.   Opting to leave, he is allowed to take as much as he likes of the following items, so long as it will fit in his knapsack, and he can carry it. He knows that he can carry no more than   25   'weights' in total;   and tha...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
{pva,pwe,pvo}={3000,3/10,1/40}; {iva,iwe,ivo}={1800,2/10,3/200}; {gva,gwe,gvo}={2500,2,2/1000}; wemax=25; vomax=1/4; {pmax,imax,gmax}=Floor/@{Min[vomax/pvo,wemax/pwe],Min[vomax/ivo,wemax/iwe],Min[vomax/gvo,wemax/gwe]};   data=Flatten[Table[{{p,i,g}.{pva,iva,gva},{p,i,g}.{pwe,iwe,gwe},{p,i,g}.{pvo,ivo,gvo},{p,i,g}},{p,0...
http://rosettacode.org/wiki/Knapsack_problem/Unbounded
Knapsack problem/Unbounded
A traveler gets diverted and has to make an unscheduled stop in what turns out to be Shangri La.   Opting to leave, he is allowed to take as much as he likes of the following items, so long as it will fit in his knapsack, and he can carry it. He knows that he can carry no more than   25   'weights' in total;   and tha...
#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}; param volume{t in Items};   var take{t in Items}, integer, >=0;   knap_weight : sum{t in Items} take[t] * weight[t] <= 25; knap_vol  : su...
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#Python
Python
#!/usr/bin/env python   try: from msvcrt import getch except ImportError: def getch(): import sys, tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: ...
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#QB64
QB64
WHILE INKEY$ <> "": WEND ' Flushes keyboard buffer. PRINT "Do you want to continue? (Y/N)" DO k$ = UCASE$(INKEY$) ' Forces key response to upper case. LOOP UNTIL k$ = "Y" OR k$ = "N" PRINT "You pressed " + CHR$(34) + k$ + CHR$(34) + "." ' CHR$(3...
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...
#OCaml
OCaml
let 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; ]   let () = let items = List.map (fun (name, w, p) -> (name, w, p, floa...
http://rosettacode.org/wiki/Knapsack_problem/Bounded
Knapsack problem/Bounded
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 some items during the trip.   Food, clothing, etc.   He has a good knapsack for carrying the things, but he knows that he can carry only 4 kg weight in his knapsack, because th...
#Prolog
Prolog
:- use_module(library(clpfd)).   % tuples (name, weights, value, nb pieces). knapsack :- L = [( map, 9, 150, 1), ( compass, 13, 35, 1), ( water, 153, 200, 2), ( sandwich, 50, 60, 2), ( glucose, 15, 60, 2), ( tin, 68, 45, 3), ( banana, 27, 60...
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...
#ERRE
ERRE
  PROGRAM GOTO_ERR   LABEL 99,100   PROCEDURE P1 INPUT(I) IF I=0 THEN GOTO 99 END IF END PROCEDURE   PROCEDURE P2 99: PRINT("I'm in procdedure P2") END PROCEDURE   BEGIN 100: INPUT(J) IF J=1 THEN GOTO 99 END IF IF J<>0 THEN GOTO 100 END IF END PROGRAM  
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...
#Factor
Factor
USING: continuations prettyprint ;   current-continuation short.
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...
#Bracmat
Bracmat
(knapsack= ( things = (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....
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. ...
#BASIC256
BASIC256
n = 0 for i = 1 to 1999999 if Kaprekar(i) then n = n + 1 if i < 100001 then print n; ": "; i endif next i print print "Total de números de Kaprekar por debajo de 1.000.000 = "; n end   function Kaprekar(n) s = n ^ 2 t = 10 ^ (int(log(s)) + 1) do t = t / 10 if t <= n then exit do #break if s-n = int(s/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. ...
#BBC_BASIC
BBC BASIC
*FLOAT 64 n% = 0 FOR i% = 1 TO 999999 IF FNkaprekar(i%) THEN n% += 1 IF i% < 100001PRINT ; n% ":", i% ENDIF NEXT PRINT "Total Kaprekar numbers under 1,000,000 = "; n% END   DEF FNkaprekar(n) LOCAL s, t s = n^2 t = 10^(INT(LO...
http://rosettacode.org/wiki/Juggler_sequence
Juggler sequence
Background of the   juggler sequence: Juggler sequences were publicized by an American mathematician and author   Clifford A. Pickover.   The name of the sequence gets it's name from the similarity of the rising and falling nature of the numbers in the sequences,   much like balls in the hands of a juggler. Descrip...
#REXX
REXX
/*REXX program calculates and displays the juggler sequence for any positive integer*/ numeric digits 20 /*define the number of decimal digits. */ parse arg LO HI list /*obtain optional arguments from the CL*/ if LO='' | LO="," then do; LO= 20; HI= 39; end...
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).
#C.23
C#
using System; using System.Collections.Generic; using System.Web.Script.Serialization;   class Program { static void Main() { var people = new Dictionary<string, object> {{"1", "John"}, {"2", "Susan"}}; var serializer = new JavaScriptSerializer();   var json = serializer.Serialize(people...
http://rosettacode.org/wiki/Joystick_position
Joystick position
The task is to determine the joystick position and represent this on the display via a crosshair. For a centred joystick, the crosshair should appear in the centre of the screen. If the joystick is pushed left or right, then the cross hair should move left or right according to the extent that the joystick is pushed. ...
#GUISS
GUISS
Start,Control Panel, Game Controllers, List:installed controllers,Click:Joystick, Button:Properties,Button:Test
http://rosettacode.org/wiki/Joystick_position
Joystick position
The task is to determine the joystick position and represent this on the display via a crosshair. For a centred joystick, the crosshair should appear in the centre of the screen. If the joystick is pushed left or right, then the cross hair should move left or right according to the extent that the joystick is pushed. ...
#Haskell
Haskell
import qualified Graphics.UI.GLFW as GLFW -- cabal install GLFW-b import Graphics.Win32.Key import Control.Monad.RWS.Strict (liftIO)   main = do liftIO $ do _ <- GLFW.init GLFW.pollEvents (jxrot, jyrot) <- liftIO $ getJoystickDirections GLFW.Joystick'1 putStrLn $ (show jxrot...
http://rosettacode.org/wiki/Joystick_position
Joystick position
The task is to determine the joystick position and represent this on the display via a crosshair. For a centred joystick, the crosshair should appear in the centre of the screen. If the joystick is pushed left or right, then the cross hair should move left or right according to the extent that the joystick is pushed. ...
#IS-BASIC
IS-BASIC
100 CLEAR SCREEN 110 DO 120 LET J=JOY(0) OR JOY(1) OR JOY(2) 130 PRINT AT 1,1:" ";:PRINT AT 1,1:""; 140 IF J BAND 1 THEN PRINT "right "; 150 IF J BAND 2 THEN PRINT "left "; 160 IF J BAND 4 THEN PRINT "down "; 170 IF J BAND 8 THEN PRINT "up "; 180 IF J BAND 16 THEN PRINT "fire "; ...
http://rosettacode.org/wiki/K-d_tree
K-d tree
This page uses content from Wikipedia. The original article was at K-d tree. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) A k-d tree (short for k-dimensional tree) is a space-partitioning data str...
#Python
Python
from random import seed, random from time import time from operator import itemgetter from collections import namedtuple from math import sqrt from copy import deepcopy     def sqd(p1, p2): return sum((c1 - c2) ** 2 for c1, c2 in zip(p1, p2))     class KdNode(object): __slots__ = ("dom_elt", "split", "left", "r...
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...
#C.2B.2B
C++
#include <iostream> #include <iomanip> #include <array> #include <string> #include <tuple> #include <algorithm> using namespace std;   template<int N = 8> class Board { public: array<pair<int, int>, 8> moves; array<array<int, N>, N> data;   Board() { moves[0] = make_pair(2, 1); moves[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...
#Common_Lisp
Common Lisp
(defun nshuffle (sequence) (loop for i from (length sequence) downto 2 do (rotatef (elt sequence (random i)) (elt sequence (1- i)))) sequence)
http://rosettacode.org/wiki/K-means%2B%2B_clustering
K-means++ clustering
K-means++ clustering K-means This data was partitioned into 7 clusters using the K-means algorithm. The task is to implement the K-means++ algorithm. Produce a function which takes two arguments: the number of clusters K, and the dataset to classify. K is a positive integer and the dataset is a list of points in the C...
#JavaScript
JavaScript
  /** * kmeans module * * cluster(model, k, converged = assignmentsConverged) * distance(p, q), * distanceSquared(p, q), * centroidsConverged(delta) * assignmentsConverged(model, newModel) * assignmentsToClusters(model) */ define(function () { "use strict";   /** * @public * Calc...
http://rosettacode.org/wiki/Kernighans_large_earthquake_problem
Kernighans large earthquake problem
Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines from the file would be lines li...
#Phix
Phix
with javascript_semantics constant filename = "data.txt" string text = iff(platform()=JS or not file_exists(filename)?""" 8/27/1883 Krakatoa 8.8 5/18/1980 MountStHelens 7.6 3/13/2009 CostaRica 5.1""" : get_text(filename)) sequence lines = split_any(text,"\r\n") for i=1 to length(line...
http://rosettacode.org/wiki/Kernighans_large_earthquake_problem
Kernighans large earthquake problem
Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines from the file would be lines li...
#Phixmonti
Phixmonti
argument tail nip len dup if get nip else drop drop "data.txt" endif   dup "r" fopen dup 0 < if drop "Could not open '" print print "' for reading" print -1 quit endif nip   true while dup fgets dup 0 < if drop false else dup split 3 get tonum 6 > if drop print else drop drop endif ...
http://rosettacode.org/wiki/Kernighans_large_earthquake_problem
Kernighans large earthquake problem
Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines from the file would be lines li...
#PHP
PHP
<?php   // make sure filename was specified on command line if ( ! isset( $argv[1] ) ) die( 'Data file name required' );   // open file and check for success if ( ! $fh = fopen( $argv[1], 'r' ) ) die ( 'Cannot open file: ' . $argv[1] );   while ( list( $date, $loc, $mag ) = fscanf( $fh, "%s %s %f" ) ) { if ...
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#Delphi
Delphi
  program Julia_set;   {$APPTYPE CONSOLE}   uses System.SysUtils, Winapi.Windows, Vcl.Graphics;   var Colors: array[0..255] of TColor; w, h, zoom, maxiter, moveX, moveY: Integer; cX, cY, zx, zy, tmp: Double; i: Integer; bitmap: TBitmap; x, y: Integer;   begin w := 800; h := 600; zoom := 1; max...
http://rosettacode.org/wiki/Knapsack_problem/Unbounded
Knapsack problem/Unbounded
A traveler gets diverted and has to make an unscheduled stop in what turns out to be Shangri La.   Opting to leave, he is allowed to take as much as he likes of the following items, so long as it will fit in his knapsack, and he can carry it. He knows that he can carry no more than   25   'weights' in total;   and tha...
#Modula-3
Modula-3
MODULE Knapsack EXPORTS Main;   FROM IO IMPORT Put; FROM Fmt IMPORT Int, Real;   TYPE Bounty = RECORD value: INTEGER; weight, volume: REAL; END;   VAR totalWeight, totalVolume: REAL; maxPanacea, maxIchor, maxGold, maxValue: INTEGER := 0; n: ARRAY [1..3] OF INTEGER; panacea, ichor, gold, sack, current: B...
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#QUACKASM
QUACKASM
  ; Stores result in cell 2; 1 if yes, 0 if no. :YORN PRINT YORNMSG :YORN1 INPUT >2 AND *2,$5F,'Y >2 /YORN2 AND *2,,'N \YORN1 :YORN2 PRINTC *2 PRINTC 13 AND *2,1 >2 RETURN :YORNMSG " (Y/N)? \  
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#Racket
Racket
  #lang racket   ;; GUI version (require racket/gui) (message-box "Yes/No example" "Yes or no?" #f '(yes-no))   ;; Text version, via stty (define stty (let ([exe (find-executable-path "stty")]) (λ args (void (apply system* exe args))))) (define tty-settings (string-trim (with-output-to-string (λ() (stty "-g")))))...
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...
#Oforth
Oforth
[ [ "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 ] ] const: Items   : rob | item value | 0.0 ->value 15.0 #[ dup second swap third / ] Items s...
http://rosettacode.org/wiki/Knapsack_problem/Bounded
Knapsack problem/Bounded
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 some items during the trip.   Food, clothing, etc.   He has a good knapsack for carrying the things, but he knows that he can carry only 4 kg weight in his knapsack, because th...
#Python
Python
from itertools import groupby from collections import namedtuple   def anyvalidcomb(items, maxwt, val=0, wt=0): ' All combinations below the maxwt ' if not items: yield [], val, wt else: this, *items = items # car, cdr for n in range(this.number + 1): w = wt +...
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...
#FBSL
FBSL
\ this prints five lines containing elements from the two \ words 'proc1' and 'proc2'. gotos are used here to jump \ into and out of the two words at various points, as well \ as to create a loop. this functions with ficl, pfe, \ gforth, bigforth, swiftforth, iforth, and vfxforth; it \ may work with other forths as wel...
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...
#Forth
Forth
\ this prints five lines containing elements from the two \ words 'proc1' and 'proc2'. gotos are used here to jump \ into and out of the two words at various points, as well \ as to create a loop. this functions with ficl, pfe, \ gforth, bigforth, swiftforth, iforth, and vfxforth; it \ may work with other forths as wel...
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...
#C
C
#include <stdio.h> #include <stdlib.h>   typedef struct { char *name; int weight; int value; } item_t;   item_t items[] = { {"map", 9, 150}, {"compass", 13, 35}, {"water", 153, 200}, {"sandwich", 50, 160}, {"gl...
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. ...
#Bracmat
Bracmat
( 0:?n & 1:?count & out$(!count 1) & whl ' ( 1+!n:<1000000:?n & ( @( !n^2  : #?a ( ? (#>0:?b) & !a+!b:!n & 1+!count:?count & (!n:<10000&out$!n|) ) ) | ) ) & out$(str$("There are " !count " kaprekar numbers less 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. ...
#Brat
Brat
kaprekar = { limit | results = []   1.to limit, { num | true? num == 1 { results << 1 } { sqr = (num ^ 2).to_s   0.to (sqr.length - 1) { i | lhs = sqr[0,i].to_i rhs = sqr[i + 1,-1].to_i   true? (rhs > 0) && { lhs + rhs == num } { results << num } } }...
http://rosettacode.org/wiki/Juggler_sequence
Juggler sequence
Background of the   juggler sequence: Juggler sequences were publicized by an American mathematician and author   Clifford A. Pickover.   The name of the sequence gets it's name from the similarity of the rising and falling nature of the numbers in the sequences,   much like balls in the hands of a juggler. Descrip...
#Ruby
Ruby
def juggler(k) = k.even? ? Integer.sqrt(k) : Integer.sqrt(k*k*k)   (20..39).chain([113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909, 2264915]).each do |k| k1 = k l = h = i = 0 until k == 1 do h, i = k, l if k > h l += 1 k = juggler(k) end if k1 < 40 then puts "#{k1}: l[...
http://rosettacode.org/wiki/Juggler_sequence
Juggler sequence
Background of the   juggler sequence: Juggler sequences were publicized by an American mathematician and author   Clifford A. Pickover.   The name of the sequence gets it's name from the similarity of the rising and falling nature of the numbers in the sequences,   much like balls in the hands of a juggler. Descrip...
#Wren
Wren
import "/fmt" for Fmt import "/big" for BigInt   var one = BigInt.one   var juggler = Fn.new { |n| if (n < 1) Fiber.abort("Starting value must be a positive integer.") var a = BigInt.new(n) var count = 0 var maxCount = 0 var max = a.copy() while (a != one) { if (a.isEven) { ...
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).
#C.2B.2B
C++
#include "Core/Core.h"   using namespace Upp;   CONSOLE_APP_MAIN { JsonArray a; a << Json("name", "John")("phone", "1234567") << Json("name", "Susan")("phone", "654321"); String txt = ~a; Cout() << txt << '\n'; Value v = ParseJSON(txt); for(int i = 0; i < v.GetCount(); i++) Cout() << v[i]["name"] << ' ' << v[i]...
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).
#Cach.C3.A9_ObjectScript
Caché ObjectScript
  Class Sample.JSON [ Abstract ] {   ClassMethod GetPerson(ByRef pParms, Output pObject As %RegisteredObject) As %Status { Set pObject=##class(Sample.Person).%OpenId(pParms("oid")) Quit $$$OK }   }  
http://rosettacode.org/wiki/Joystick_position
Joystick position
The task is to determine the joystick position and represent this on the display via a crosshair. For a centred joystick, the crosshair should appear in the centre of the screen. If the joystick is pushed left or right, then the cross hair should move left or right according to the extent that the joystick is pushed. ...
#Julia
Julia
using CSFML.LibCSFML, Gtk.ShortNames, Colors, Graphics, Cairo   #------------ input code ----------------------#   mutable struct Joystick devnum::Int isconnected::Bool hasXaxis::Bool nbuttons::Int pressed::Vector{Bool} ypos::Int xpos::Int name::String Joystick(n, b=2, c=false, x=tru...
http://rosettacode.org/wiki/Joystick_position
Joystick position
The task is to determine the joystick position and represent this on the display via a crosshair. For a centred joystick, the crosshair should appear in the centre of the screen. If the joystick is pushed left or right, then the cross hair should move left or right according to the extent that the joystick is pushed. ...
#Liberty_BASIC
Liberty BASIC
'disable text window nomainwin   'set window size WindowWidth = 308 WindowHeight = 331   'center window on screen UpperLeftX = int((DisplayWidth-WindowWidth)/2) UpperLeftY = int((DisplayHeight-WindowHeight)/2)   'open graphics window open "Joystick Position" for graphics_nf_nsb ...
http://rosettacode.org/wiki/K-d_tree
K-d tree
This page uses content from Wikipedia. The original article was at K-d tree. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) A k-d tree (short for k-dimensional tree) is a space-partitioning data str...
#Racket
Racket
  #lang racket   ; A tree consists of a point, a left and a right subtree. (struct tree (p l r) #:transparent) ; If the node is in depth d, then the points in l has ; the (d mod k)'th coordinate less than the same coordinate in p.   (define (kdtree d k ps) (cond [(empty? ps) #f] ; #f represents an empty subtree ...
http://rosettacode.org/wiki/K-d_tree
K-d tree
This page uses content from Wikipedia. The original article was at K-d tree. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) A k-d tree (short for k-dimensional tree) is a space-partitioning data str...
#Raku
Raku
class Kd_node { has $.d; has $.split; has $.left; has $.right; }   class Orthotope { has $.min; has $.max; }   class Kd_tree { has $.n; has $.bounds; method new($pts, $bounds) { self.bless(n => nk2(0,$pts), bounds => $bounds) }   sub nk2($split, @e) { return () unless @e;...
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...
#Common_Lisp
Common Lisp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Solving the knight's tour.  ;;; ;;; Warnsdorff's rule with random tie break.  ;;; ;;; Optionally outputs a closed tour.  ;;; ;;; Options from interactive prompt.  ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;...
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...
#Crystal
Crystal
def knuthShuffle(items : Array) i = items.size-1 while i > 1 j = Random.rand(0..i) items.swap(i, j)   i -= 1 end end
http://rosettacode.org/wiki/K-means%2B%2B_clustering
K-means++ clustering
K-means++ clustering K-means This data was partitioned into 7 clusters using the K-means algorithm. The task is to implement the K-means++ algorithm. Produce a function which takes two arguments: the number of clusters K, and the dataset to classify. K is a positive integer and the dataset is a list of points in the C...
#jq
jq
#!/bin/bash export LC_ALL=C # Generate $1 pseudo-random integers of width $2. # The integers may have leading 0s function prng { cat /dev/urandom | tr -cd '0-9' | fold -w "$2" | head -n "$1" }   PTS=30000 prng $((4 * PTS)) 3 | jq -nr --argjson PTS $PTS -f k-means++-clustering.jq  
http://rosettacode.org/wiki/Kernighans_large_earthquake_problem
Kernighans large earthquake problem
Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines from the file would be lines li...
#PicoLisp
PicoLisp
  (load "@lib/misc.l")   (in "kernighan.txt" (until (eof) (let (Date (read) Quake (read) Mag (read)) (when (> Mag 6) (prinl (align -10 Date) " " (align -15 Quake) " " Mag))))) (bye)  
http://rosettacode.org/wiki/Kernighans_large_earthquake_problem
Kernighans large earthquake problem
Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines from the file would be lines li...
#Prolog
Prolog
:- initialization(main, main).   process_line(Line):- split_string(Line, "\s\t", "\s\t", [_, _, Magnitude_string]), read_term_from_atom(Magnitude_string, Magnitude, []), Magnitude > 6, !, writef('%w\n', [Line]). process_line(_).   process_stream(Stream):- read_line_to_string(Stream, String), ...
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#EasyLang
EasyLang
cx = -0.7 cy = 0.27015 for y range 300 for x range 300 zx = (x - 150) / 100 zy = (y - 150) / 150 color3 0 0 0 for iter range 128 if zx * zx + zy * zy > 4 color3 iter / 16 0 0 break 1 . h = zx * zx - zy * zy + cx zy = 2 * zx * zy + cy zx = h . move ...
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#Elixir
Elixir
defmodule Julia do def set(c_real, c_imag) do IO.puts "#{c_real}, #{c_imag}" vlist = Enum.take_every(-100..100, 4) hlist = Enum.take_every(-280..280, 4) Enum.each(vlist, fn v -> Enum.map(hlist, fn h -> loop(c_real, c_imag, h/200, v/100, "#", 0) end) |> IO.puts end) end   de...
http://rosettacode.org/wiki/Knapsack_problem/Unbounded
Knapsack problem/Unbounded
A traveler gets diverted and has to make an unscheduled stop in what turns out to be Shangri La.   Opting to leave, he is allowed to take as much as he likes of the following items, so long as it will fit in his knapsack, and he can carry it. He knows that he can carry no more than   25   'weights' in total;   and tha...
#Nim
Nim
# Knapsack unbounded. Brute force solution.   import lenientops # Mixed float/int operators. import strformat   type Bounty = tuple[value: int; weight, volume: float]   const Panacea: Bounty = (value: 3000, weight: 0.3, volume: 0.025) Ichor: Bounty = (value: 1800, weight: 0.2, volume: 0.015) Gold: Bounty = (val...
http://rosettacode.org/wiki/Knapsack_problem/Unbounded
Knapsack problem/Unbounded
A traveler gets diverted and has to make an unscheduled stop in what turns out to be Shangri La.   Opting to leave, he is allowed to take as much as he likes of the following items, so long as it will fit in his knapsack, and he can carry it. He knows that he can carry no more than   25   'weights' in total;   and tha...
#OCaml
OCaml
type bounty = { name:string; value:int; weight:float; volume:float }   let bounty n d w v = { name = n; value = d; weight = w; volume = v }   let items = [ bounty "panacea" 3000 0.3 0.025; bounty "ichor" 1800 0.2 0.015; bounty "gold" 2500 2.0 0.002; ]   let max_wgt = 25.0 and max_vol = 0.25   le...
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#Raku
Raku
my $TTY = open("/dev/tty");   sub prompt-char($prompt) { ENTER shell "stty raw -echo min 1 time 1"; LEAVE shell "stty sane";   print $prompt; $TTY.read(1).decode('latin1'); }   say so prompt-char("Y or N? ") ~~ /:i y/;
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#REXX
REXX
/*REXX program tests for a Y or N key when entered from keyboard after a prompt.*/   do queued(); pull; end /*flush the stack if anything is queued*/   prompt = 'Please enter Y or N for verification:' /*this is the PROMPT message.*/   do until pos(ans,'NY')\==0 & length(a...
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...
#ooRexx
ooRexx
/*-------------------------------------------------------------------- * 20.09.2014 Walter Pachl translated from REXX version 2 * utilizing ooRexx features like objects, array(s) and sort *-------------------------------------------------------------------*/ maxweight = 15.0 items=.array~new items~appe...
http://rosettacode.org/wiki/Knapsack_problem/Bounded
Knapsack problem/Bounded
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 some items during the trip.   Food, clothing, etc.   He has a good knapsack for carrying the things, but he knows that he can carry only 4 kg weight in his knapsack, because th...
#R
R
library(tidyverse) library(rvest)   task_html= read_html("http://rosettacode.org/wiki/Knapsack_problem/Bounded") task_table= html_nodes(html, "table")[[1]] %>% html_table(table, header= T, trim= T) %>% set_names(c("items", "weight", "value", "pieces")) %>% filter(items != "knapsack") %>% mutate(weight= as.numer...
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...
#Fortran
Fortran
' FB 1.05.0 Win64   ' compiled with -lang fb (the default) and -e switches   Sub MySub() Goto localLabel Dim a As Integer = 10 '' compiler warning that this variable definition is being skipped localLabel: Print "localLabel reached" Print "a = "; a '' prints garbage as 'a' is uninitialized End Sub   Sub MyS...
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...
#C.23
C#
using System; using System.Collections.Generic;   namespace Tests_With_Framework_4 {   class Bag : IEnumerable<Bag.Item> { List<Item> items; const int MaxWeightAllowed = 400;   public Bag() { items = new List<Item>(); }   vo...
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. ...
#C
C
#include <stdio.h> #include <stdint.h> typedef uint64_t ulong;   int kaprekar(ulong n, int base) { ulong nn = n * n, r, tens = 1;   if ((nn - n) % (base - 1)) return 0;   while (tens < n) tens *= base; if (n == tens) return 1 == n;   while ((r = nn % tens) < n) { if (nn / tens + r == n) return tens; tens *= ba...
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).
#Clojure
Clojure
(use 'clojure.data.json)   ; Load as Clojure data structures and bind the resulting structure to 'json-map'. (def json-map (read-json "{ \"foo\": 1, \"bar\": [10, \"apples\"] }"))   ; Use pr-str to print out the Clojure representation of the JSON created by read-json. (pr-str json-map)   ; Pretty-print the Clojure rep...
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).
#CoffeeScript
CoffeeScript
  sample = blue: [1, 2] ocean: 'water'   json_string = JSON.stringify sample json_obj = JSON.parse json_string   console.log json_string console.log json_obj  
http://rosettacode.org/wiki/Joystick_position
Joystick position
The task is to determine the joystick position and represent this on the display via a crosshair. For a centred joystick, the crosshair should appear in the centre of the screen. If the joystick is pushed left or right, then the cross hair should move left or right according to the extent that the joystick is pushed. ...
#Locomotive_Basic
Locomotive Basic
10 MODE 1:BORDER 14:x=320:y=200:d=1 20 a=JOY(0) ' read state of first joystick 30 IF d THEN q$="*" ELSE q$=" " 40 IF a THEN MOVE x-8,y+8:TAG:PRINT q$;:TAGOFF 50 IF (a AND 1) AND y<380 THEN y=y+10 60 IF (a AND 2) AND y>20 THEN y=y-10 70 IF (a AND 4) AND x>20 THEN x=x-10 80 IF (a AND 8) AND x<620 THEN x=x+10 90 IF a A...
http://rosettacode.org/wiki/Joystick_position
Joystick position
The task is to determine the joystick position and represent this on the display via a crosshair. For a centred joystick, the crosshair should appear in the centre of the screen. If the joystick is pushed left or right, then the cross hair should move left or right according to the extent that the joystick is pushed. ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Slider2D[Dynamic[ControllerState[{"X", "Y"}]], ImageSize -> {500, 500}]
http://rosettacode.org/wiki/K-d_tree
K-d tree
This page uses content from Wikipedia. The original article was at K-d tree. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) A k-d tree (short for k-dimensional tree) is a space-partitioning data str...
#Rust
Rust
  use std::cmp::Ordering; use std::cmp::Ordering::Less; use std::ops::Sub; use std::time::Instant;   use rand::prelude::*;   #[derive(Clone, PartialEq, Debug)] struct Point { pub coords: Vec<f32>, }   impl<'a, 'b> Sub<&'b Point> for &'a Point { type Output = Point;   fn sub(self, rhs: &Point) -> Point { ...
http://rosettacode.org/wiki/K-d_tree
K-d tree
This page uses content from Wikipedia. The original article was at K-d tree. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) A k-d tree (short for k-dimensional tree) is a space-partitioning data str...
#Scala
Scala
object KDTree { import Numeric._   // Task 1A. Build tree of KDNodes. Translated from Wikipedia. def apply[T](points: Seq[Seq[T]], depth: Int = 0)(implicit num: Numeric[T]): Option[KDNode[T]] = { val dim = points.headOption.map(_.size) getOrElse 0 if (points.isEmpty || dim < 1) None else { val a...
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...
#Clojure
Clojure
  (defn isin? [x li] (not= [] (filter #(= x %) li)))   (defn options [movements pmoves n] (let [x (first (last movements)) y (second (last movements)) op (vec (map #(vector (+ x (first %)) (+ y (second %))) pmoves)) vop (filter #(and (>= (first %) 0) (>= (last %) 0)) op) vop1 (filter #(and (...
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...
#D
D
void main() { import std.stdio, std.random;   auto a = [1, 2, 3, 4, 5, 6, 7, 8, 9]; a.randomShuffle; a.writeln; }
http://rosettacode.org/wiki/K-means%2B%2B_clustering
K-means++ clustering
K-means++ clustering K-means This data was partitioned into 7 clusters using the K-means algorithm. The task is to implement the K-means++ algorithm. Produce a function which takes two arguments: the number of clusters K, and the dataset to classify. K is a positive integer and the dataset is a list of points in the C...
#Julia
Julia
# run via Julia REPL using Clustering, Plots, DataFrames, RDatasets   const iris = dataset("datasets", "iris") plt1 = plot(title= "Species Classification", xlabel = "Sepal Width", ylabel = "Sepal length") plt2 = plot(title= "Kmeans++ Classification", xlabel = "Sepal Width", ylabel = "Sepal length")   for (i, sp) in e...
http://rosettacode.org/wiki/Kernighans_large_earthquake_problem
Kernighans large earthquake problem
Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines from the file would be lines li...
#PureBasic
PureBasic
If OpenConsole() And ReadFile(0,"data.txt") PrintN("Those earthquakes with a magnitude > 6.0 are:") While Not Eof(0) buf$=Trim(ReadString(0)) If ValF((StringField(buf$,CountString(buf$," ")+1," ")))>6.0 PrintN(buf$) EndIf Wend CloseFile(0) Input() EndIf
http://rosettacode.org/wiki/Kernighans_large_earthquake_problem
Kernighans large earthquake problem
Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines from the file would be lines li...
#Python
Python
python -c ' with open("data.txt") as f: for ln in f: if float(ln.strip().split()[2]) > 6: print(ln.strip())'
http://rosettacode.org/wiki/Kernighans_large_earthquake_problem
Kernighans large earthquake problem
Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines from the file would be lines li...
#Racket
Racket
#lang racket   (with-input-from-file "data/large-earthquake.txt" (λ () (for ((s (in-port read-line)) #:when (> (string->number (third (string-split s))) 6)) (displayln s))))
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#Emacs_Lisp
Emacs Lisp
; === Graphical Julia set display in Emacs =====================   (setq julia-size (cons 300 200)) (setq xmin -1.5) (setq xmax 1.5) (setq ymin -1) (setq ymax 1) (setq julia0 (cons -0.512511498387847167 0.521295573094847167)) (setq max-iter 100)   (defun julia-iter-point (x y) "Run the actual iteration for each point...
http://rosettacode.org/wiki/Knapsack_problem/Unbounded
Knapsack problem/Unbounded
A traveler gets diverted and has to make an unscheduled stop in what turns out to be Shangri La.   Opting to leave, he is allowed to take as much as he likes of the following items, so long as it will fit in his knapsack, and he can carry it. He knows that he can carry no more than   25   'weights' in total;   and tha...
#OOCalc
OOCalc
declare proc {Knapsack Sol} solution(panacea:P = {FD.decl} ichor: I = {FD.decl} gold: G = {FD.decl} ) = Sol in {Show 0#Sol} 3 * P + 2 * I + 20 * G =<: 250 {Show 1#Sol} 25 * P + 15 * I + 2 * G =<: 250 {Show 2#Sol} ...
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#Ring
Ring
  while true give c if c = "Y" see "You said yes!" + nl but c = "N" see "You said no!" + nl else see "Try again!" + nl ok end  
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#Ruby
Ruby
  def yesno begin system("stty raw -echo") str = STDIN.getc ensure system("stty -raw echo") end if str == "Y" return true elsif str == "N" return false else raise "Invalid character." end end  
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...
#Perl
Perl
my @items = sort { $b->[2]/$b->[1] <=> $a->[2]/$a->[1] } ( [qw'beef 3.8 36'], [qw'pork 5.4 43'], [qw'ham 3.6 90'], [qw'greaves 2.4 45'], [qw'flitch 4.0 30'], [qw'brawn 2.5 56'], [qw'welt 3.7 67'], [qw'salami 3.0 95'], [qw'sausage 5...
http://rosettacode.org/wiki/Knapsack_problem/Bounded
Knapsack problem/Bounded
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 some items during the trip.   Food, clothing, etc.   He has a good knapsack for carrying the things, but he knows that he can carry only 4 kg weight in his knapsack, because th...
#Racket
Racket
  #lang racket (require net/url html xml xml/path)   (struct item (name mass value count) #:transparent)   ;this section is to convert the web page on the problem into the data for the problem ;i don't got time to manually type tables, nevermind that this took longer (define (group-n n l) (let group-n ([l l] [acc '()...
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...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   ' compiled with -lang fb (the default) and -e switches   Sub MySub() Goto localLabel Dim a As Integer = 10 '' compiler warning that this variable definition is being skipped localLabel: Print "localLabel reached" Print "a = "; a '' prints garbage as 'a' is uninitialized End Sub   Sub MyS...
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...
#C.2B.2B
C++
#include <vector> #include <string> #include <iostream> #include <boost/tuple/tuple.hpp> #include <set>   int findBestPack( const std::vector<boost::tuple<std::string , int , int> > & , std::set<int> & , const int ) ;   int main( ) { std::vector<boost::tuple<std::string , int , int> > items ; //==========...
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. ...
#C.23
C#
using System; using System.Collections.Generic;   public class KaprekarNumbers {   /// <summary> /// The entry point of the program, where the program control starts and ends. /// </summary> public static void Main() { int count = 0;   foreach ( ulong i in _kaprekarGenerator(999999) ) { ...
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).
#ColdFusion
ColdFusion
  <!--- Create sample JSON structure ---> <cfset json = { string: "Hello", number: 42, arrayOfNumbers: [1, 2, 3, 4], arrayOfStrings: ["One", "Two", "Three", "Four"], arrayOfAnything: [1, "One", [1, "One"], { one: 1 }], object: { key: "value" } } />   <!--- Convert to JSON string ---> <cfset jsonSerial...
http://rosettacode.org/wiki/Joystick_position
Joystick position
The task is to determine the joystick position and represent this on the display via a crosshair. For a centred joystick, the crosshair should appear in the centre of the screen. If the joystick is pushed left or right, then the cross hair should move left or right according to the extent that the joystick is pushed. ...
#OCaml
OCaml
let remove x = List.filter (fun y -> y <> x) let buttons_string b = String.concat " " (List.map string_of_int b)   let position app x y = let view = SFRenderWindow.getView app in let width, height = SFView.getSize view in let hw = width /. 2.0 in let hh = height /. 2.0 in (hw +. ((x /. 100.0) *. hw), hh ...
http://rosettacode.org/wiki/K-d_tree
K-d tree
This page uses content from Wikipedia. The original article was at K-d tree. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) A k-d tree (short for k-dimensional tree) is a space-partitioning data str...
#Sidef
Sidef
struct Kd_node { d, split, left, right, }   struct Orthotope { min, max, }   class Kd_tree(n, bounds) {   method init { n = self.nk2(0, n); }   method nk2(split, e) { return(nil) if (e.len <= 0); var exset = e.sort_by { _[split] } var m = (exset.len //...
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...
#CoffeeScript
CoffeeScript
  graph_tours = (graph, max_num_solutions) -> # graph is an array of arrays # graph[3] = [4, 5] means nodes 4 and 5 are reachable from node 3 # # Returns an array of tours (up to max_num_solutions in size), where # each tour is an array of nodes visited in order, and where each # tour visits every node in t...
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...
#Delphi
Delphi
procedure KnuthShuffle(a : array of Integer); var i, j, tmp : Integer; begin for i:=a.High downto 1 do begin j:=RandomInt(a.Length); tmp:=a[i]; a[i]:=a[j]; a[j]:=tmp; end; end;
http://rosettacode.org/wiki/K-means%2B%2B_clustering
K-means++ clustering
K-means++ clustering K-means This data was partitioned into 7 clusters using the K-means algorithm. The task is to implement the K-means++ algorithm. Produce a function which takes two arguments: the number of clusters K, and the dataset to classify. K is a positive integer and the dataset is a list of points in the C...
#Kotlin
Kotlin
// version 1.2.21   import java.util.Random import kotlin.math.*   data class Point(var x: Double, var y: Double, var group: Int)   typealias LPoint = List<Point> typealias MLPoint = MutableList<Point>   val origin get() = Point(0.0, 0.0, 0) val r = Random() val hugeVal = Double.POSITIVE_INFINITY   const val RAND_MAX =...
http://rosettacode.org/wiki/Kernighans_large_earthquake_problem
Kernighans large earthquake problem
Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines from the file would be lines li...
#Raku
Raku
$_ = @*ARGS[0] ?? @*ARGS[0].IO !! q:to/END/; 8/27/1883 Krakatoa 8.8 5/18/1980 MountStHelens 7.6 3/13/2009 CostaRica 5.1 END   map { .say if .words[2] > 6 }, .lines;
http://rosettacode.org/wiki/Kernighans_large_earthquake_problem
Kernighans large earthquake problem
Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines from the file would be lines li...
#REXX
REXX
/*REXX program to read a file containing a list of earthquakes: date, site, magnitude.*/ parse arg iFID mMag . /*obtain optional arguments from the CL*/ if iFID=='' | iFID=="," then iFID= 'earthquakes.dat' /*Not specified? Then use default*/ if mMag=='' | mMag=="," then mMag= 6 ...
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#F.23
F#
  let getJuliaValues width height centerX centerY zoom maxIter = let initzx x = 1.5 * float(x - width/2) / (0.5 * zoom * float(width)) let initzy y = 1.0 * float(y - height/2) / (0.5 * zoom * float(height)) let calc y x = let rec loop i zx zy = if i=maxIter then 0 elif zx*zx + zy*zy >= 4.0 then i ...
http://rosettacode.org/wiki/Knapsack_problem/Unbounded
Knapsack problem/Unbounded
A traveler gets diverted and has to make an unscheduled stop in what turns out to be Shangri La.   Opting to leave, he is allowed to take as much as he likes of the following items, so long as it will fit in his knapsack, and he can carry it. He knows that he can carry no more than   25   'weights' in total;   and tha...
#Oz
Oz
declare proc {Knapsack Sol} solution(panacea:P = {FD.decl} ichor: I = {FD.decl} gold: G = {FD.decl} ) = Sol in {Show 0#Sol} 3 * P + 2 * I + 20 * G =<: 250 {Show 1#Sol} 25 * P + 15 * I + 2 * G =<: 250 {Show 2#Sol} ...
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#Run_BASIC
Run BASIC
[loop] cls ' Clear screen html "Click Y or N" ' no other options button #y, "Y", [Y] ' they either click [Y] button #n, "N", [N] ' or they click [N] html "<br>";msg$ ' print message showing what they entered wait [...
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#Rust
Rust
//cargo-deps: ncurses   extern crate ncurses; use ncurses::*;   fn main() { initscr(); loop { printw("Yes or no? "); refresh();   match getch() as u8 as char { 'Y'|'y' => {printw("You said yes!");}, 'N'|'n' => {printw("You said no!");}, _ => {printw("T...
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...
#Phix
Phix
with javascript_semantics constant meats = { --Item Weight (kg) Price (Value) {"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}} function b...
http://rosettacode.org/wiki/Knapsack_problem/Bounded
Knapsack problem/Bounded
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 some items during the trip.   Food, clothing, etc.   He has a good knapsack for carrying the things, but he knows that he can carry only 4 kg weight in his knapsack, because th...
#Raku
Raku
my class KnapsackItem { has $.name; has $.weight; has $.unit; }   multi sub pokem ([], $, $v = 0) { $v } multi sub pokem ([$, *@], 0, $v = 0) { $v } multi sub pokem ([$i, *@rest], $w, $v = 0) { my $key = "{+@rest} $w $v"; (state %cache){$key} or do { my @skip = pokem @rest, $w, $v; if $w >=...
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...
#FutureBasic
FutureBasic
  include "ConsoleWindow"   print "First line." gosub "sub1" print "Fifth line." goto "Almost over" "sub1" print "Second line." gosub "sub2" print "Fourth line." return "Almost over" print "We're just about done..." goto "Outa here" "sub2" print "Third line." return "Outa here" print "... with goto and gosub, thankfull...
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...
#Go
Go
package main   import "fmt"   func main() { outer: for i := 0; i < 4; i++ { for j := 0; j < 4; j++ { if i + j == 4 { continue outer } if i + j == 5 { break outer } fmt.Println(i + j) } }   k := 3 if k == 3 { goto later } fmt.Println(k) // neve...
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...
#C_sharp
C_sharp
using System; // 4790@3.6 using System.Threading.Tasks; class Program { static void Main() { var sw = System.Diagnostics.Stopwatch.StartNew(); Console.Write(knapSack(400) + "\n" + sw.Elapsed); // 60 ms Console.Read(); }   static string knapSack(uint w1) { uint sol =...
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. ...
#C.2B.2B
C++
#include <vector> #include <string> #include <iostream> #include <sstream> #include <algorithm> #include <iterator> #include <utility>   long string2long( const std::string & s ) { long result ; std::istringstream( s ) >> result ; return result ; }   bool isKaprekar( long number ) { long long squarenumber =...
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).
#Common_Lisp
Common Lisp
  (ql:quickload '("cl-json"))   (json:encode-json '#( ((foo . (1 2 3)) (bar . t) (baz . #\!)) "quux" 4/17 4.25))   (print (with-input-from-string (s "{\"foo\": [1, 2, 3], \"bar\": true, \"baz\": \"!\"}") (json:decode-json s)))    
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).
#Crystal
Crystal
  require "json_mapping"   class Foo JSON.mapping( num: Int64, array: Array(String), ) end   def json foo = Foo.from_json(%({"num": 1, "array": ["a", "b"]})) puts("#{foo.num} #{foo.array}") puts(foo.to_json) end