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/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
... | #ALGOL-M | ALGOL-M | BEGIN
INTEGER FUNCTION DIVBY(N, D);
INTEGER N;
INTEGER D;
BEGIN
DIVBY := 1 - (N - D * (N / D));
END;
INTEGER I;
FOR I := 1 STEP 1 UNTIL 100 DO
BEGIN
IF DIVBY(I, 15) = 1 THEN
WRITE("FizzBuzz")
ELSE IF DIVBY(I, 5) = 1 THEN
WRITE("Buzz")
ELSE IF DIVBY(I, 3) = 1 THEN
WRITE("Fizz")
ELSE
WRITE(I... |
http://rosettacode.org/wiki/Five_weekends | Five weekends | The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.
Task
Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar).
Show the number of months with this property (there should be 201).
Show at leas... | #Common_Lisp | Common Lisp | ;; Given a date, get the day of the week. Adapted from
;; http://lispcookbook.github.io/cl-cookbook/dates_and_times.html
(defun day-of-week (day month year)
(nth-value
6
(decode-universal-time
(encode-universal-time 0 0 0 day month year 0)
0)))
(defparameter *long-months* '(1 3 5 7 8 10 12))
(defun sun... |
http://rosettacode.org/wiki/First_perfect_square_in_base_n_with_n_unique_digits | First perfect square in base n with n unique digits | Find the first perfect square in a given base N that has at least N digits and
exactly N significant unique digits when expressed in base N.
E.G. In base 10, the first perfect square with at least 10 unique digits is 1026753849 (32043²).
You may use analytical methods to reduce the search space, but the code must do ... | #Perl | Perl | use strict;
use warnings;
use feature 'say';
use ntheory qw/fromdigits todigitstring/;
use utf8;
binmode('STDOUT', 'utf8');
sub first_square {
my $n = shift;
my $sr = substr('1023456789abcdef',0,$n);
my $r = int fromdigits($sr, $n) ** .5;
my @digits = reverse split '', $sr;
TRY: while (1) {
... |
http://rosettacode.org/wiki/First-class_functions | First-class functions | A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming:
Create new functions from preexisting functions at run-time
Store functions in collections
Use functions as arguments to other functions
Use functions as retu... | #E | E | def sin(x) { return x.sin() }
def cos(x) { return x.cos() }
def asin(x) { return x.asin() }
def acos(x) { return x.acos() }
def cube(x) { return x ** 3 }
def curt(x) { return x ** (1/3) }
def forward := [sin, cos, cube]
def reverse := [asin, acos, curt] |
http://rosettacode.org/wiki/Forest_fire | Forest fire |
This page uses content from Wikipedia. The original article was at Forest-fire model. 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)
Task
Implement the Drossel and Schwabl definition of the fores... | #Julia | Julia | using Printf
@enum State empty tree fire
function evolution(nepoch::Int=100, init::Matrix{State}=fill(tree, 30, 50))
# Single evolution
function evolve!(forest::Matrix{State}; f::Float64=0.12, p::Float64=0.5)
dir = [-1 -1; -1 0; -1 1; 0 -1; 0 1; 1 -1; 1 0; 1 1]
# A tree will burn if at lea... |
http://rosettacode.org/wiki/Flatten_a_list | Flatten a list | Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
| #Emacs_Lisp | Emacs Lisp | (defun flatten (mylist)
(cond
((null mylist) nil)
((atom mylist) (list mylist))
(t
(append (flatten (car mylist)) (flatten (cdr mylist)))))) |
http://rosettacode.org/wiki/Flipping_bits_game | Flipping bits game | The game
Given an N×N square array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones.
The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered
columns at once (as one move).
In an inversion. any 1 ... | #Ring | Ring |
load "guilib.ring"
load "stdlib.ring"
size = 3
flip = newlist(size,size)
board = newlist(size,size)
colflip = list(size)
rowflip = list(size)
new qapp
{
win1 = new qwidget() {
setwindowtitle("Flipping bits game")
setgeometry(465,115,800,600)
l... |
http://rosettacode.org/wiki/Flipping_bits_game | Flipping bits game | The game
Given an N×N square array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones.
The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered
columns at once (as one move).
In an inversion. any 1 ... | #Ruby | Ruby | class FlipBoard
def initialize(size)
raise ArgumentError.new("Invalid board size: #{size}") if size < 2
@size = size
@board = Array.new(size**2, 0)
randomize_board
loop do
@target = generate_target
break unless solved?
end
# these are used for validating user input
@... |
http://rosettacode.org/wiki/First_power_of_2_that_has_leading_decimal_digits_of_12 | First power of 2 that has leading decimal digits of 12 | (This task is taken from a Project Euler problem.)
(All numbers herein are expressed in base ten.)
27 = 128 and 7 is
the first power of 2 whose leading decimal digits are 12.
The next power of 2 whose leading decimal digits
are 12 is 80,
280 = 1208925819614629174706176.
Define ... | #Sidef | Sidef | func farey_approximations(r, callback) {
var (a1 = r.int, b1 = 1)
var (a2 = a1+1, b2 = 1)
loop {
var a3 = a1+a2
var b3 = b1+b2
if (a3 < r*b3) {
(a1, b1) = (a3, b3)
}
else {
(a2, b2) = (a3, b3)
}
callback(a3 / b3)
}
... |
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously | First-class functions/Use numbers analogously | In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types.
This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.
Write a program to create an ordered collection of a m... | #Ruby | Ruby | multiplier = proc {|n1, n2| proc {|m| n1 * n2 * m}}
numlist = [x=2, y=4, x+y]
invlist = [0.5, 0.25, 1.0/(x+y)]
p numlist.zip(invlist).map {|n, invn| multiplier[invn, n][0.5]}
# => [0.5, 0.5, 0.5] |
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously | First-class functions/Use numbers analogously | In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types.
This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.
Write a program to create an ordered collection of a m... | #Rust | Rust | #![feature(conservative_impl_trait)]
fn main() {
let (x, xi) = (2.0, 0.5);
let (y, yi) = (4.0, 0.25);
let z = x + y;
let zi = 1.0/z;
let numlist = [x,y,z];
let invlist = [xi,yi,zi];
let result = numlist.iter()
.zip(&invlist)
.map(|(x,y)| mu... |
http://rosettacode.org/wiki/Flow-control_structures | Flow-control structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
Document common flow-control structures.
One common example of a flow-control structure is the goto construct.
Note that Conditional Struc... | #Scala | Scala | import Goto._
import scala.util.continuations._
object Goto {
case class Label(k: Label => Unit)
private case class GotoThunk(label: Label) extends Throwable
def label: Label @suspendable =
shift((k: Label => Unit) => executeFrom(Label(k)))
def goto(l: Label): Nothing =
throw new GotoThunk(l)
... |
http://rosettacode.org/wiki/Flow-control_structures | Flow-control structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
Document common flow-control structures.
One common example of a flow-control structure is the goto construct.
Note that Conditional Struc... | #Sidef | Sidef | say "Hello"
goto :world
say "Never printed"
@:world
say "World" |
http://rosettacode.org/wiki/Floyd%27s_triangle | Floyd's triangle | Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
the first row is 1 (unity)
successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like thi... | #Groovy | Groovy | class Floyd {
static void main(String[] args) {
printTriangle(5)
printTriangle(14)
}
private static void printTriangle(int n) {
println(n + " rows:")
int printMe = 1
int numsPrinted = 0
for (int rowNum = 1; rowNum <= n; printMe++) {
int cols = (i... |
http://rosettacode.org/wiki/Floyd-Warshall_algorithm | Floyd-Warshall algorithm | The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights.
Task
Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already been checked for loops, parallel ... | #Python | Python | from math import inf
from itertools import product
def floyd_warshall(n, edge):
rn = range(n)
dist = [[inf] * n for i in rn]
nxt = [[0] * n for i in rn]
for i in rn:
dist[i][i] = 0
for u, v, w in edge:
dist[u-1][v-1] = w
nxt[u-1][v-1] = v-1
for k, i, j in product(rn,... |
http://rosettacode.org/wiki/Function_definition | Function definition | A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are ... | #UNIX_Shell | UNIX Shell | multiply() {
# There is never anything between the parentheses after the function name
# Arguments are obtained using the positional parameters $1, and $2
# The return is given as a parameter to the return command
return `expr "$1" \* "$2"` # The backslash is required to suppress interpolation
}
# Call the... |
http://rosettacode.org/wiki/Forward_difference | Forward difference | Task
Provide code that produces a list of numbers which is the nth order forward difference, given a non-negative integer (specifying the order) and a list of numbers.
The first-order forward difference of a list of numbers A is a new list B, where Bn = An+1 - An.
List B should have one fewer elem... | #Racket | Racket |
#lang racket
(define (forward-difference list)
(for/list ([x (cdr list)] [y list]) (- x y)))
(define (nth-forward-difference n list)
(for/fold ([list list]) ([n n]) (forward-difference list)))
(nth-forward-difference 9 '(90 47 58 29 22 32 55 5 55 73))
;; -> '(-2921)
|
http://rosettacode.org/wiki/Forward_difference | Forward difference | Task
Provide code that produces a list of numbers which is the nth order forward difference, given a non-negative integer (specifying the order) and a list of numbers.
The first-order forward difference of a list of numbers A is a new list B, where Bn = An+1 - An.
List B should have one fewer elem... | #Raku | Raku | sub dif(@array [$, *@tail]) { @tail Z- @array }
sub difn($array, $n) { ($array, &dif ... *)[$n] } |
http://rosettacode.org/wiki/Formatted_numeric_output | Formatted numeric output | Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
| #XPL0 | XPL0 | int C;
[Format(5, 3); \5 places before decimal point and 3 after
RlOut(8, 7.125); \output real number to internal buffer
loop [C:= ChIn(8); \read character from internal buffer
if C = ^ then C:= ^0; \change leading space characters to zeros
if C = $1A then ... |
http://rosettacode.org/wiki/Formatted_numeric_output | Formatted numeric output | Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
| #XSLT | XSLT | <xsl:value-of select="format-number(7.125, '00000000.#############')" />
|
http://rosettacode.org/wiki/Four_bit_adder | Four bit adder | Task
"Simulate" a four-bit adder.
This design can be realized using four 1-bit full adders.
Each of these 1-bit full adders can be built with two half adders and an or gate. ;
Finally a half adder can be made using an xor gate and an and gate.
The xor gate can be made using two nots, two ands ... | #Ruby | Ruby | # returns pair [sum, carry]
def four_bit_adder(a, b)
a_bits = binary_string_to_bits(a,4)
b_bits = binary_string_to_bits(b,4)
s0, c0 = full_adder(a_bits[0], b_bits[0], 0)
s1, c1 = full_adder(a_bits[1], b_bits[1], c0)
s2, c2 = full_adder(a_bits[2], b_bits[2], c1)
s3, c3 = full_adder(a_bits[3], b_bits[3], c... |
http://rosettacode.org/wiki/Fivenum | Fivenum | Many big data or scientific programs use boxplots to show distributions of data. In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM. It can be useful to save large arrays as arrays with five numbers to save memory.
For example, the R programming language i... | #PicoLisp | PicoLisp | (de median (Lst)
(let N (length Lst)
(if (bit? 1 N)
(get Lst (/ (inc N) 2))
(setq Lst (nth Lst (/ N 2)))
(/ (+ (car Lst) (cadr Lst)) 2) ) ) )
(de fivenum (Lst) # destructive
(let
(Len (length Lst)
M (/ Len 2)
S (sort Lst) )
(list
(format (c... |
http://rosettacode.org/wiki/Fivenum | Fivenum | Many big data or scientific programs use boxplots to show distributions of data. In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM. It can be useful to save large arrays as arrays with five numbers to save memory.
For example, the R programming language i... | #Python | Python | from __future__ import division
import math
import sys
def fivenum(array):
n = len(array)
if n == 0:
print("you entered an empty array.")
sys.exit()
x = sorted(array)
n4 = math.floor((n+3.0)/2.0)/2.0
d = [1, n4, (n+1)/2, n+1-n4, n]
sum_array = []
for e in range(5):
... |
http://rosettacode.org/wiki/Find_the_missing_permutation | Find the missing permutation | ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
... | #BBC_BASIC | BBC BASIC | DIM perms$(22), miss&(4)
perms$() = "ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", \
\ "CDAB", "DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", \
\ "BDCA", "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB"
FOR i% = 0 TO DIM(perms$(),1)
FOR j% = 1 TO DIM(mis... |
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month | Find the last Sunday of each month | Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc).
Example of an expected output:
./last_sundays 2013
2013-01-27
2013-02-24
2013-03-31
2013-04-28
2013-05-26
2013-06-30
2013-07-28
2... | #Clojure | Clojure | (ns last-sundays.core
(:require [clj-time.core :as time]
[clj-time.periodic :refer [periodic-seq]]
[clj-time.format :as fmt])
(:import (org.joda.time DateTime DateTimeConstants))
(:gen-class))
(defn sunday? [t]
(= (.getDayOfWeek t) (DateTimeConstants/SUNDAY)))
(defn sundays [year]
... |
http://rosettacode.org/wiki/Find_the_intersection_of_two_lines | Find the intersection of two lines | [1]
Task
Find the point of intersection of two lines in 2D.
The 1st line passes though (4,0) and (6,10) .
The 2nd line passes though (0,3) and (10,7) .
| #F.23 | F# |
(*
Find the point of intersection of 2 lines.
Nigel Galloway May 20th., 2017
*)
type Line={a:float;b:float;c:float} member N.toS=sprintf "%.2fx + %.2fy = %.2f" N.a N.b N.c
let intersect (n:Line) g = match (n.a*g.b-g.a*n.b) with
|0.0 ->printfn "%s does not intersect %s" n.toS g.toS
... |
http://rosettacode.org/wiki/Find_the_intersection_of_a_line_with_a_plane | Find the intersection of a line with a plane | Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection.
Task
Find the point of intersection for the infinite ray with direction (0, -1, -1) passing through position (0, 0, 10) with the infinite plane with a normal vector of (0, 0, 1) and which passes ... | #Factor | Factor | USING: io locals math.vectors prettyprint ;
:: intersection-point ( rdir rpt pnorm ppt -- loc )
rpt rdir pnorm rpt ppt v- v. v*n rdir pnorm v. v/n v- ;
"The ray intersects the plane at " write
{ 0 -1 -1 } { 0 0 10 } { 0 0 1 } { 0 0 5 } intersection-point . |
http://rosettacode.org/wiki/Find_the_intersection_of_a_line_with_a_plane | Find the intersection of a line with a plane | Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection.
Task
Find the point of intersection for the infinite ray with direction (0, -1, -1) passing through position (0, 0, 10) with the infinite plane with a normal vector of (0, 0, 1) and which passes ... | #FreeBASIC | FreeBASIC | ' version 11-07-2018
' compile with: fbc -s console
Type vector3d
Dim As Double x, y ,z
Declare Constructor ()
Declare Constructor (ByVal x As Double, ByVal y As Double, ByVal z As Double)
End Type
Constructor vector3d()
This.x = 0
This.y = 0
This.z = 0
End Constructor
Constructor vector3d... |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
... | #ALGOL_W | ALGOL W |
begin
i_w := 1; % set integers to print in minimum space %
for i := 1 until 100 do begin
if i rem 15 = 0 then write( "FizzBuzz" )
else if i rem 5 = 0 then write( "Buzz" )
else if i rem 3 = 0 then write( "Fizz" )
else write( i )
end for_i
end. |
http://rosettacode.org/wiki/Five_weekends | Five weekends | The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.
Task
Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar).
Show the number of months with this property (there should be 201).
Show at leas... | #D | D | import std.stdio, std.datetime, std.algorithm, std.range;
Date[] m5w(in Date start, in Date end) pure /*nothrow*/ {
typeof(return) res;
// adjust to 1st day
for (Date when = Date(start.year, start.month, 1);
when < end;
when.add!"months"(1))
// Such month must have 3+4*7 days and... |
http://rosettacode.org/wiki/First_perfect_square_in_base_n_with_n_unique_digits | First perfect square in base n with n unique digits | Find the first perfect square in a given base N that has at least N digits and
exactly N significant unique digits when expressed in base N.
E.G. In base 10, the first perfect square with at least 10 unique digits is 1026753849 (32043²).
You may use analytical methods to reduce the search space, but the code must do ... | #Phix | Phix | -- demo\rosetta\PandigitalSquares.exw
without javascript_semantics -- (mpz_set_str() currently only supports bases 2, 8, 10, and 16 under pwa/p2js)
include mpfr.e
atom t0 = time()
constant chars = "0123456789abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz|",
use_hll_code = true
function str_conv(sequ... |
http://rosettacode.org/wiki/First-class_functions | First-class functions | A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming:
Create new functions from preexisting functions at run-time
Store functions in collections
Use functions as arguments to other functions
Use functions as retu... | #EchoLisp | EchoLisp |
;; adapted from Racket
;; (compose f g h ... ) is a built-in defined as :
;; (define (compose f g) (λ (x) (f (g x))))
(define (cube x) (expt x 3))
(define (cube-root x) (expt x (// 1 3)))
(define funlist (list sin cos cube))
(define ifunlist (list asin acos cube-root))
(for ([f funlist] [i ifunlist])
(writeln (... |
http://rosettacode.org/wiki/Forest_fire | Forest fire |
This page uses content from Wikipedia. The original article was at Forest-fire model. 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)
Task
Implement the Drossel and Schwabl definition of the fores... | #Lua | Lua |
-- ForestFire automaton implementation
-- Rules: at each step:
-- 1) a burning tree disappears
-- 2) a non-burning tree starts burning if any of its neighbours is
-- 3) an empty spot may generate a tree with prob P
-- 4) a non-burning tree may ignite with prob F
local socket = require 'socket' -- needed for socket.... |
http://rosettacode.org/wiki/Flatten_a_list | Flatten a list | Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
| #Erlang | Erlang | flatten([]) -> [];
flatten([H|T]) -> flatten(H) ++ flatten(T);
flatten(H) -> [H]. |
http://rosettacode.org/wiki/Flipping_bits_game | Flipping bits game | The game
Given an N×N square array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones.
The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered
columns at once (as one move).
In an inversion. any 1 ... | #Rust | Rust |
// For random generation
extern crate rand;
// For fmt::Display
use std::fmt;
// For I/O (stdin, stdout, etc)
use std::io::prelude::*;
use rand::Rng;
/// A simple struct for a board
struct Board {
/// The cells of the board
cells: Vec<bool>,
/// The size of the board
size: usize,
}
// Function... |
http://rosettacode.org/wiki/First_power_of_2_that_has_leading_decimal_digits_of_12 | First power of 2 that has leading decimal digits of 12 | (This task is taken from a Project Euler problem.)
(All numbers herein are expressed in base ten.)
27 = 128 and 7 is
the first power of 2 whose leading decimal digits are 12.
The next power of 2 whose leading decimal digits
are 12 is 80,
280 = 1208925819614629174706176.
Define ... | #Swift | Swift | let ld10 = log(2.0) / log(10.0)
func p(L: Int, n: Int) -> Int {
var l = L
var digits = 1
while l >= 10 {
digits *= 10
l /= 10
}
var count = 0
var i = 0
while count < n {
let rhs = (Double(i) * ld10).truncatingRemainder(dividingBy: 1)
let e = exp(log(10.0) * rhs)
if Int(e * Do... |
http://rosettacode.org/wiki/First_power_of_2_that_has_leading_decimal_digits_of_12 | First power of 2 that has leading decimal digits of 12 | (This task is taken from a Project Euler problem.)
(All numbers herein are expressed in base ten.)
27 = 128 and 7 is
the first power of 2 whose leading decimal digits are 12.
The next power of 2 whose leading decimal digits
are 12 is 80,
280 = 1208925819614629174706176.
Define ... | #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Function Func(ByVal l As Integer, ByVal n As Integer) As Long
Dim res As Long = 0, f As Long = 1
Dim lf As Double = Math.Log10(2)
Dim i As Integer = l
While i > 10
f *= 10
i /= 10
End While
While n > 0
res += 1
... |
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously | First-class functions/Use numbers analogously | In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types.
This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.
Write a program to create an ordered collection of a m... | #Scala | Scala | scala> val x = 2.0
x: Double = 2.0
scala> val xi = 0.5
xi: Double = 0.5
scala> val y = 4.0
y: Double = 4.0
scala> val yi = 0.25
yi: Double = 0.25
scala> val z = x + y
z: Double = 6.0
scala> val zi = 1.0 / ( x + y )
zi: Double = 0.16666666666666666
scala> val numbers = List(x, y, z)
numbers: List[Double] = L... |
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously | First-class functions/Use numbers analogously | In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types.
This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.
Write a program to create an ordered collection of a m... | #Scheme | Scheme | (define x 2.0)
(define xi 0.5)
(define y 4.0)
(define yi 0.25)
(define z (+ x y))
(define zi (/ (+ x y)))
(define number (list x y z))
(define inverse (list xi yi zi))
(define (multiplier n1 n2) (lambda (m) (* n1 n2 m)))
(define m 0.5)
(define (go n1 n2)
(for-each (lambda (n1 n2)
(display ((mul... |
http://rosettacode.org/wiki/Flow-control_structures | Flow-control structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
Document common flow-control structures.
One common example of a flow-control structure is the goto construct.
Note that Conditional Struc... | #SSEM | SSEM | 00101000000000000000000000000000 20 to CI
...
01010000000000000000000000000000 20. 10 |
http://rosettacode.org/wiki/Flow-control_structures | Flow-control structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
Document common flow-control structures.
One common example of a flow-control structure is the goto construct.
Note that Conditional Struc... | #Stata | Stata | mata
function pythagorean_triple(n) {
for (a=1; a<=n; a++) {
for (b=a; b<=n-a; b++) {
c=n-a-b
if (c>b & c*c==a*a+b*b) {
printf("%f %f %f\n",a,b,c)
goto END
}
}
}
END:
}
pythagorean_triple(1980)
165 900 915 |
http://rosettacode.org/wiki/Floyd%27s_triangle | Floyd's triangle | Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
the first row is 1 (unity)
successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like thi... | #Haskell | Haskell | --------------------- FLOYDS TRIANGLE --------------------
floydTriangle :: [[Int]]
floydTriangle =
( zipWith
(fmap (.) enumFromTo <*> (\a b -> pred (a + b)))
<$> scanl (+) 1
<*> id
)
[1 ..]
--------------------------- TEST -------------------------
main :: IO ()
main = mapM_ (putStrLn .... |
http://rosettacode.org/wiki/Floyd-Warshall_algorithm | Floyd-Warshall algorithm | The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights.
Task
Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already been checked for loops, parallel ... | #Racket | Racket | #lang typed/racket
(require math/array)
;; in : initialized dist and next matrices
;; out : dist and next matrices
;; O(n^3)
(define-type Next-T (Option Index))
(define-type Dist-T Real)
(define-type Dists (Array Dist-T))
(define-type Nexts (Array Next-T))
(define-type Settable-Dists (Settable-Array Dist-T))
(define-... |
http://rosettacode.org/wiki/Function_definition | Function definition | A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are ... | #Ursa | Ursa | # multiply is a built-in in ursa, so the function is called mult instead
def mult (int a, int b)
return (* a b)
end |
http://rosettacode.org/wiki/Function_definition | Function definition | A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are ... | #Ursala | Ursala | multiply = math..mul |
http://rosettacode.org/wiki/Forward_difference | Forward difference | Task
Provide code that produces a list of numbers which is the nth order forward difference, given a non-negative integer (specifying the order) and a list of numbers.
The first-order forward difference of a list of numbers A is a new list B, where Bn = An+1 - An.
List B should have one fewer elem... | #REXX | REXX | /*REXX program computes the forward difference of a list of numbers. */
numeric digits 100 /*ensure enough accuracy (decimal digs)*/
parse arg e ',' N /*get a list: ε1 ε2 ε3 ε4 ··· , order */
if e=='' then e=90 47 58 29 22 32 55 5 55 73 ... |
http://rosettacode.org/wiki/Formatted_numeric_output | Formatted numeric output | Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
| #zkl | zkl | "%09.3f".fmt(7.125) //-->"00007.125"
"%09.3e".fmt(7.125) //-->"7.125e+00"
"%09.3g".fmt(7.125) //-->"000007.12"
"%09d".fmt(7.125) //-->"000000007"
"%09,d".fmt(78901.125)//-->"00078,901" |
http://rosettacode.org/wiki/Formatted_numeric_output | Formatted numeric output | Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 LET n=7.125
20 LET width=9
30 GO SUB 1000
40 PRINT AT 10,10;n$
50 STOP
1000 REM Formatted fixed-length
1010 LET n$=STR$ n
1020 FOR i=1 TO width-LEN n$
1030 LET n$="0"+n$
1040 NEXT i
1050 RETURN |
http://rosettacode.org/wiki/Four_bit_adder | Four bit adder | Task
"Simulate" a four-bit adder.
This design can be realized using four 1-bit full adders.
Each of these 1-bit full adders can be built with two half adders and an or gate. ;
Finally a half adder can be made using an xor gate and an and gate.
The xor gate can be made using two nots, two ands ... | #Rust | Rust |
// half adder with XOR and AND
// SUM = A XOR B
// CARRY = A.B
fn half_adder(a: usize, b: usize) -> (usize, usize) {
return (a ^ b, a & b);
}
// full adder as a combination of half adders
// SUM = A XOR B XOR C
// CARRY = A.B + B.C + C.A
fn full_adder(a: usize, b: usize, c_in: usize) -> (usize, usize) {
let... |
http://rosettacode.org/wiki/Fivenum | Fivenum | Many big data or scientific programs use boxplots to show distributions of data. In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM. It can be useful to save large arrays as arrays with five numbers to save memory.
For example, the R programming language i... | #R | R | x <- c(0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555,-0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578)
fivenum(x) |
http://rosettacode.org/wiki/Fivenum | Fivenum | Many big data or scientific programs use boxplots to show distributions of data. In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM. It can be useful to save large arrays as arrays with five numbers to save memory.
For example, the R programming language i... | #Racket | Racket | #lang racket/base
(require math/private/statistics/quickselect)
;; racket's quantile uses "Method 1" of https://en.wikipedia.org/wiki/Quartile
;; Tukey (fivenum) uses "Method 2", so we will need a specialist median
(define (fivenum! data-v)
(define (tukey-median start end)
(define-values (n/2 parity) (quotient/... |
http://rosettacode.org/wiki/Find_the_missing_permutation | Find the missing permutation | ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
... | #Burlesque | Burlesque |
ln"ABCD"r@\/\\
|
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month | Find the last Sunday of each month | Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc).
Example of an expected output:
./last_sundays 2013
2013-01-27
2013-02-24
2013-03-31
2013-04-28
2013-05-26
2013-06-30
2013-07-28
2... | #COBOL | COBOL |
program-id. last-sun.
data division.
working-storage section.
1 wk-date.
2 yr pic 9999.
2 mo pic 99 value 1.
2 da pic 99 value 1.
1 rd-date redefines wk-date pic 9(8).
1 binary.
2 int-date pic 9(8).
2 dow pic 9(4).
2 sunday pic ... |
http://rosettacode.org/wiki/Find_the_intersection_of_two_lines | Find the intersection of two lines | [1]
Task
Find the point of intersection of two lines in 2D.
The 1st line passes though (4,0) and (6,10) .
The 2nd line passes though (0,3) and (10,7) .
| #Factor | Factor | USING: arrays combinators.extras kernel math
math.matrices.laplace math.vectors prettyprint sequences ;
: det ( pt pt -- x ) 2array determinant ;
: numerator ( x y pt pt quot -- z )
bi@ swapd [ 2array ] 2bi@ det ; inline
: intersection ( pt pt pt pt -- pt )
[ [ det ] 2bi@ ]
[ [ v- ] 2bi@ ] 4bi
[ [... |
http://rosettacode.org/wiki/Find_the_intersection_of_two_lines | Find the intersection of two lines | [1]
Task
Find the point of intersection of two lines in 2D.
The 1st line passes though (4,0) and (6,10) .
The 2nd line passes though (0,3) and (10,7) .
| #Fortran | Fortran | program intersect_two_lines
implicit none
type point
real::x,y
end type point
integer, parameter :: n = 4
type(point) :: p(n)
p(1)%x = 4; p(1)%y = 0; p(2)%x = 6; p(2)%y = 10 ! fist line
p(3)%x = 0; p(3)%y = 3; p(4)%x = 10; p(4)%y = 7 ! second line
call intersect(p, n)
contains
... |
http://rosettacode.org/wiki/Find_the_intersection_of_a_line_with_a_plane | Find the intersection of a line with a plane | Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection.
Task
Find the point of intersection for the infinite ray with direction (0, -1, -1) passing through position (0, 0, 10) with the infinite plane with a normal vector of (0, 0, 1) and which passes ... | #Go | Go | package main
import "fmt"
type Vector3D struct{ x, y, z float64 }
func (v *Vector3D) Add(w *Vector3D) *Vector3D {
return &Vector3D{v.x + w.x, v.y + w.y, v.z + w.z}
}
func (v *Vector3D) Sub(w *Vector3D) *Vector3D {
return &Vector3D{v.x - w.x, v.y - w.y, v.z - w.z}
}
func (v *Vector3D) Mul(s float64) *V... |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
... | #AntLang | AntLang | n:{1+ x}map range[100]
s:{a:0eq x mod 3;b:0eq x mod 5;concat apply{1elem x}map{0elem x}hfilter seq[1- max[a;b];a;b]merge seq[str[x];"Fizz";"Buzz"]}map n
echo map s |
http://rosettacode.org/wiki/Five_weekends | Five weekends | The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.
Task
Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar).
Show the number of months with this property (there should be 201).
Show at leas... | #Dart | Dart |
main() {
var total = 0;
var empty = <int>[];
for (var year = 1900; year < 2101; year++) {
var months =
[1, 3, 5, 7, 8, 10, 12].where((m) => DateTime(year, m, 1).weekday == 5);
print('$year\t$months');
total += months.length;
if (months.isEmpty) empty.add(year);
}
print('Total: $total... |
http://rosettacode.org/wiki/Five_weekends | Five weekends | The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.
Task
Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar).
Show the number of months with this property (there should be 201).
Show at leas... | #Delphi | Delphi | program FiveWeekends;
{$APPTYPE CONSOLE}
uses SysUtils, DateUtils;
var
lMonth, lYear: Integer;
lDate: TDateTime;
lFiveWeekendCount: Integer;
lYearsWithout: Integer;
lFiveWeekendFound: Boolean;
begin
for lYear := 1900 to 2100 do
begin
lFiveWeekendFound := False;
for lMonth := 1 to 12 do
b... |
http://rosettacode.org/wiki/First_perfect_square_in_base_n_with_n_unique_digits | First perfect square in base n with n unique digits | Find the first perfect square in a given base N that has at least N digits and
exactly N significant unique digits when expressed in base N.
E.G. In base 10, the first perfect square with at least 10 unique digits is 1026753849 (32043²).
You may use analytical methods to reduce the search space, but the code must do ... | #Python | Python | '''Perfect squares using every digit in a given base.'''
from itertools import count, dropwhile, repeat
from math import ceil, sqrt
from time import time
# allDigitSquare :: Int -> Int -> Int
def allDigitSquare(base, above):
'''The lowest perfect square which
requires all digits in the given base.
... |
http://rosettacode.org/wiki/First-class_functions | First-class functions | A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming:
Create new functions from preexisting functions at run-time
Store functions in collections
Use functions as arguments to other functions
Use functions as retu... | #Ela | Ela | open number //sin,cos,asin,acos
open list //zipWith
cube x = x ** 3
croot x = x ** (1/3)
funclist = [sin, cos, cube]
funclisti = [asin, acos, croot]
zipWith (\f inversef -> (inversef << f) 0.5) funclist funclisti |
http://rosettacode.org/wiki/First-class_functions | First-class functions | A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming:
Create new functions from preexisting functions at run-time
Store functions in collections
Use functions as arguments to other functions
Use functions as retu... | #Elena | Elena | import system'routines;
import system'math;
import extensions'routines;
import extensions'math;
extension op
{
compose(f,g)
= f(g(self));
}
public program()
{
var fs := new object[]{ mssgconst sin<mathOp>[1], mssgconst cos<mathOp>[1], (x => power(x, 3.0r)) };
var gs := new object[]{ mssgconst arcs... |
http://rosettacode.org/wiki/Forest_fire | Forest fire |
This page uses content from Wikipedia. The original article was at Forest-fire model. 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)
Task
Implement the Drossel and Schwabl definition of the fores... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | evolve[nbhd_List, k_] := 0 /; nbhd[[2, 2]] == 2 (*burning->empty*)
evolve[nbhd_List, k_] := 2 /; nbhd[[2, 2]] == 1 && Max@nbhd == 2 (*near_burning&nonempty->burning*)
evolve[nbhd_List, k_] := RandomChoice[{f, 1 - f} -> {2, nbhd[[2, 2]]}] /; nbhd[[2, 2]] == 1 && Max@nbhd < 2 (*spontaneously combusting tree*)
ev... |
http://rosettacode.org/wiki/Flatten_a_list | Flatten a list | Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
| #Euphoria | Euphoria | sequence a = {{1}, 2, {{3, 4}, 5}, {{{}}}, {{{6}}}, 7, 8, {}}
function flatten( object s )
sequence res = {}
if sequence( s ) then
for i = 1 to length( s ) do
sequence c = flatten( s[ i ] )
if length( c ) > 0 then
res &= c
end if
end for
else
if length( s ) > 0 then
res = { s }
end if
... |
http://rosettacode.org/wiki/Flipping_bits_game | Flipping bits game | The game
Given an N×N square array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones.
The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered
columns at once (as one move).
In an inversion. any 1 ... | #Scala | Scala | import java.awt.{BorderLayout, Color, Dimension, Font, Graphics, Graphics2D, Rectangle, RenderingHints}
import java.awt.event.{MouseAdapter, MouseEvent}
import javax.swing.{JFrame, JPanel}
object FlippingBitsGame extends App {
class FlippingBitsGame extends JPanel {
private val maxLevel: Int = 7
private... |
http://rosettacode.org/wiki/First_power_of_2_that_has_leading_decimal_digits_of_12 | First power of 2 that has leading decimal digits of 12 | (This task is taken from a Project Euler problem.)
(All numbers herein are expressed in base ten.)
27 = 128 and 7 is
the first power of 2 whose leading decimal digits are 12.
The next power of 2 whose leading decimal digits
are 12 is 80,
280 = 1208925819614629174706176.
Define ... | #Wren | Wren | import "/fmt" for Fmt
import "/math" for Math
var ld10 = Math.ln2 / Math.ln10
var p = Fn.new { |L, n|
var i = L
var digits = 1
while (i >= 10) {
digits = digits * 10
i = (i/10).floor
}
var count = 0
i = 0
while (count < n) {
var e = (Math.ln10 * (i * ld10).fractio... |
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously | First-class functions/Use numbers analogously | In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types.
This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.
Write a program to create an ordered collection of a m... | #Sidef | Sidef | func multiplier(n1, n2) {
func (n3) {
n1 * n2 * n3
}
}
var x = 2.0
var xi = 0.5
var y = 4.0
var yi = 0.25
var z = (x + y)
var zi = (1 / (x + y))
var numbers = [x, y, z]
var inverses = [xi, yi, zi]
for f,g (numbers ~Z inverses) {
say multiplier(f, g)(0.5)
} |
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously | First-class functions/Use numbers analogously | In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types.
This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.
Write a program to create an ordered collection of a m... | #Slate | Slate | define: #multiplier -> [| :n1 :n2 | [| :m | n1 * n2 * m]].
define: #x -> 2.
define: #y -> 4.
define: #numlist -> {x. y. x + y}.
define: #numlisti -> (numlist collect: [| :x | 1.0 / x]).
numlist with: numlisti collect: [| :n1 :n2 | (multiplier applyTo: {n1. n2}) applyWith: 0.5]. |
http://rosettacode.org/wiki/Flow-control_structures | Flow-control structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
Document common flow-control structures.
One common example of a flow-control structure is the goto construct.
Note that Conditional Struc... | #Tcl | Tcl | after 1000 {myroutine x} |
http://rosettacode.org/wiki/Flow-control_structures | Flow-control structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
Document common flow-control structures.
One common example of a flow-control structure is the goto construct.
Note that Conditional Struc... | #Tiny_BASIC | Tiny BASIC | REM TinyBASIC has only two control flow structures: goto and gosub
LET N = 0
10 LET N = N + 1
PRINT N
IF N < 10 THEN GOTO 10
LET R = 10
15 IF N < 10000 THEN GOSUB 20
IF N > 10000 THEN GOTO 30
GOTO R + 5 REM goto can be computed
20 LET N = N * 2
PRINT N
RETURN REM gosub... |
http://rosettacode.org/wiki/Floyd%27s_triangle | Floyd's triangle | Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
the first row is 1 (unity)
successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like thi... | #Icon_and_Unicon | Icon and Unicon | procedure main(a)
n := integer(a[1]) | 5
w := ((n*(n-1))/2)-n
c := create seq()
every row := 1 to n do {
every col := 1 to row do {
width := *(w+col)+1
every writes(right(@c,width))
}
write()
}
end |
http://rosettacode.org/wiki/Floyd-Warshall_algorithm | Floyd-Warshall algorithm | The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights.
Task
Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already been checked for loops, parallel ... | #Raku | Raku | sub Floyd-Warshall (Int $n, @edge) {
my @dist = [0, |(Inf xx $n-1)], *.Array.rotate(-1) … !*[*-1];
my @next = [0 xx $n] xx $n;
for @edge -> ($u, $v, $w) {
@dist[$u-1;$v-1] = $w;
@next[$u-1;$v-1] = $v-1;
}
for [X] ^$n xx 3 -> ($k, $i, $j) {
if @dist[$i;$j] > my $sum = @dis... |
http://rosettacode.org/wiki/Function_definition | Function definition | A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are ... | #V | V | [multiply *]. |
http://rosettacode.org/wiki/Function_definition | Function definition | A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are ... | #VBA | VBA | Function Multiply(lngMcand As Long, lngMplier As Long) As Long
Multiply = lngMcand * lngMplier
End Function |
http://rosettacode.org/wiki/Forward_difference | Forward difference | Task
Provide code that produces a list of numbers which is the nth order forward difference, given a non-negative integer (specifying the order) and a list of numbers.
The first-order forward difference of a list of numbers A is a new list B, where Bn = An+1 - An.
List B should have one fewer elem... | #Ring | Ring |
# Project : Forward difference
s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73]
for p = 1 to 9
s = fwddiff(s)
showarray(s)
next
func fwddiff(s)
for j=1 to len(s)-1
s[j] = s[j+1]-s[j]
next
n = len(s)
del(s, n)
return s
func showarray(vect)
see... |
http://rosettacode.org/wiki/Forward_difference | Forward difference | Task
Provide code that produces a list of numbers which is the nth order forward difference, given a non-negative integer (specifying the order) and a list of numbers.
The first-order forward difference of a list of numbers A is a new list B, where Bn = An+1 - An.
List B should have one fewer elem... | #Ruby | Ruby | def dif(s)
s.each_cons(2).collect { |x, y| y - x }
end
def difn(s, n)
n.times.inject(s) { |s, | dif(s) }
end |
http://rosettacode.org/wiki/Four_bit_adder | Four bit adder | Task
"Simulate" a four-bit adder.
This design can be realized using four 1-bit full adders.
Each of these 1-bit full adders can be built with two half adders and an or gate. ;
Finally a half adder can be made using an xor gate and an and gate.
The xor gate can be made using two nots, two ands ... | #Sather | Sather | -- a "pin" can be connected only to one component
-- that "sets" it to 0 or 1, while it can be "read"
-- ad libitum. (Tristate logic is not taken into account)
-- This class does the proper checking, assuring the "circuit"
-- and the connections are described correctly. Currently can make
-- hard the implementation of ... |
http://rosettacode.org/wiki/Fivenum | Fivenum | Many big data or scientific programs use boxplots to show distributions of data. In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM. It can be useful to save large arrays as arrays with five numbers to save memory.
For example, the R programming language i... | #Raku | Raku | sub fourths ( Int $end ) {
my $end_22 = $end div 2 / 2;
return 0, $end_22, $end/2, $end - $end_22, $end;
}
sub fivenum ( @nums ) {
my @x = @nums.sort(+*)
or die 'Input must have at least one element';
my @d = fourths(@x.end);
return ( @x[@d».floor] Z+ @x[@d».ceiling] ) »/» 2;
}
say .... |
http://rosettacode.org/wiki/Find_the_missing_permutation | Find the missing permutation | ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
... | #C | C | #include <stdio.h>
#define N 4
const char *perms[] = {
"ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB",
"DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA",
"DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB",
};
int main()
{
int i, j, n, cnt[N];
char miss[N];
for (n = i = 1; i ... |
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month | Find the last Sunday of each month | Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc).
Example of an expected output:
./last_sundays 2013
2013-01-27
2013-02-24
2013-03-31
2013-04-28
2013-05-26
2013-06-30
2013-07-28
2... | #Common_Lisp | Common Lisp | (defun last-sundays (year)
(loop for month from 1 to 12
for last-month-p = (= month 12)
for next-month = (if last-month-p 1 (1+ month))
for year-of-next-month = (if last-month-p (1+ year) year)
for 1st-day-next-month = (encode-universal-time 0 0 0 1 next-month year-of-next-month 0)
... |
http://rosettacode.org/wiki/Find_the_intersection_of_two_lines | Find the intersection of two lines | [1]
Task
Find the point of intersection of two lines in 2D.
The 1st line passes though (4,0) and (6,10) .
The 2nd line passes though (0,3) and (10,7) .
| #FreeBASIC | FreeBASIC | ' version 16-08-2017
' compile with: fbc -s console
#Define NaN 0 / 0 ' FreeBASIC returns -1.#IND
Type _point_
As Double x, y
End Type
Function l_l_intersect(s1 As _point_, e1 As _point_, s2 As _point_, e2 As _point_) As _point_
Dim As Double a1 = e1.y - s1.y
Dim As Double b1 = s1.x - e1.x
Dim A... |
http://rosettacode.org/wiki/Find_the_intersection_of_a_line_with_a_plane | Find the intersection of a line with a plane | Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection.
Task
Find the point of intersection for the infinite ray with direction (0, -1, -1) passing through position (0, 0, 10) with the infinite plane with a normal vector of (0, 0, 1) and which passes ... | #Groovy | Groovy | class LinePlaneIntersection {
private static class Vector3D {
private double x, y, z
Vector3D(double x, double y, double z) {
this.x = x
this.y = y
this.z = z
}
Vector3D plus(Vector3D v) {
return new Vector3D(x + v.x, y + v.y, z + v... |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
... | #APEX | APEX |
for(integer i=1; i <= 100; i++){
String output = '';
if(math.mod(i, 3) == 0) output += 'Fizz';
if(math.mod(i, 5) == 0) output += 'Buzz';
if(output != ''){
System.debug(output);
} else {
System.debug(i);
}
}
|
http://rosettacode.org/wiki/Five_weekends | Five weekends | The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.
Task
Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar).
Show the number of months with this property (there should be 201).
Show at leas... | #Elixir | Elixir | defmodule Date do
@months { "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December" }
def five_weekends(year) do
for m <-[1,3,5,7,8,10,12], :calendar.day_of_the_week(year, m, 31) == 7, do: elem(@months, m-1)
end
end... |
http://rosettacode.org/wiki/Five_weekends | Five weekends | The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.
Task
Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar).
Show the number of months with this property (there should be 201).
Show at leas... | #Erlang | Erlang |
#!/usr/bin/env escript
%%
%% Calculate number of months with five weekends between years 1900-2100
%%
main(_) ->
Years = [ [{Y,M} || M <- lists:seq(1,12)] || Y <- lists:seq(1900,2100) ],
{CountedYears, {Has5W, TotM5W}} = lists:mapfoldl(
fun(Months, {Has5W, Tot}) ->
WithFive = [M || M <- Months, has_five... |
http://rosettacode.org/wiki/First_perfect_square_in_base_n_with_n_unique_digits | First perfect square in base n with n unique digits | Find the first perfect square in a given base N that has at least N digits and
exactly N significant unique digits when expressed in base N.
E.G. In base 10, the first perfect square with at least 10 unique digits is 1026753849 (32043²).
You may use analytical methods to reduce the search space, but the code must do ... | #Raku | Raku | #`[
Only search square numbers that have at least N digits;
smaller could not possibly match.
Only bother to use analytics for large N. Finesse takes longer than brute force for small N.
]
unit sub MAIN ($timer = False);
sub first-square (Int $n) {
my @start = flat '1', '0', (2 ..^ $n)».base: $n;
if... |
http://rosettacode.org/wiki/First-class_functions | First-class functions | A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming:
Create new functions from preexisting functions at run-time
Store functions in collections
Use functions as arguments to other functions
Use functions as retu... | #Elixir | Elixir | defmodule First_class_functions do
def task(val) do
as = [&:math.sin/1, &:math.cos/1, fn x -> x * x * x end]
bs = [&:math.asin/1, &:math.acos/1, fn x -> :math.pow(x, 1/3) end]
Enum.zip(as, bs)
|> Enum.each(fn {a,b} -> IO.puts compose([a,b], val) end)
end
defp compose(funs, x) do
Enum.reduce(... |
http://rosettacode.org/wiki/First-class_functions | First-class functions | A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming:
Create new functions from preexisting functions at run-time
Store functions in collections
Use functions as arguments to other functions
Use functions as retu... | #Erlang | Erlang |
-module( first_class_functions ).
-export( [task/0] ).
task() ->
As = [fun math:sin/1, fun math:cos/1, fun cube/1],
Bs = [fun math:asin/1, fun math:acos/1, fun square_inverse/1],
[io:fwrite( "Value: 1.5 Result: ~p~n", [functional_composition([A, B], 1.5)]) || {A, B} <- lists:zip(As, Bs)].
functional_comp... |
http://rosettacode.org/wiki/Forest_fire | Forest fire |
This page uses content from Wikipedia. The original article was at Forest-fire model. 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)
Task
Implement the Drossel and Schwabl definition of the fores... | #MATLAB_.2F_Octave | MATLAB / Octave | function forest_fire(f,p,N,M)
% Forest fire
if nargin<4;
M=200;
end
if nargin<3;
N=200;
end
if nargin<2;
p=.03;
end
if nargin<1;
f=p*.0001;
end
% initialize;
F = (rand(M,N) < p)+1; % tree with probability p
S = ones(3); S(2,2)=0; % surrounding
textmap = ' T#';
colormap([.5,.5,.5;0,1,0;1,0,0]);
while(1)
... |
http://rosettacode.org/wiki/Flatten_a_list | Flatten a list | Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
| #F.23 | F# | type 'a ll =
| I of 'a // leaf Item
| L of 'a ll list // ' <- confine the syntax colouring confusion
let rec flatten = function
| [] -> []
| (I x)::y -> x :: (flatten y)
| (L x)::y -> List.append (flatten x) (flatten y)
printfn "%A" (flatten [L([I(1)]); I(2); L([L([I(3);I(4)]); I... |
http://rosettacode.org/wiki/Flipping_bits_game | Flipping bits game | The game
Given an N×N square array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones.
The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered
columns at once (as one move).
In an inversion. any 1 ... | #Swift | Swift | import Foundation
struct Board: Equatable, CustomStringConvertible {
let size: Int
private var tiles: [Bool]
init(size: Int) {
self.size = size
tiles = Array(count: size * size, repeatedValue: false)
}
subscript(x: Int, y: Int) -> Bool {
get {
return tiles[y... |
http://rosettacode.org/wiki/Flipping_bits_game | Flipping bits game | The game
Given an N×N square array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones.
The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered
columns at once (as one move).
In an inversion. any 1 ... | #Tcl | Tcl | package require Tcl 8.6
oo::class create Flip {
variable board target s
constructor {size} {
set s $size
set target [my RandomConfiguration]
set board $target
while {$board eq $target} {
for {set i 0} {$i < $s} {incr i} {
if {rand()<.5} {
my SwapRow $i
}
if {rand()<.5} {
my SwapColu... |
http://rosettacode.org/wiki/First_power_of_2_that_has_leading_decimal_digits_of_12 | First power of 2 that has leading decimal digits of 12 | (This task is taken from a Project Euler problem.)
(All numbers herein are expressed in base ten.)
27 = 128 and 7 is
the first power of 2 whose leading decimal digits are 12.
The next power of 2 whose leading decimal digits
are 12 is 80,
280 = 1208925819614629174706176.
Define ... | #Yabasic | Yabasic | FAC = 0.30102999566398119521373889472449302677
print p(12, 1)
print p(12, 2)
print p(123, 45)
print p(123, 12345)
print p(123, 678910)
end
sub p(L, n)
cont = 0 : j = 0
LS$ = str$(L)
while cont < n
j = j + 1
x = FAC * j
//if x < len(LS$) continue while 'sino da error
... |
http://rosettacode.org/wiki/First_power_of_2_that_has_leading_decimal_digits_of_12 | First power of 2 that has leading decimal digits of 12 | (This task is taken from a Project Euler problem.)
(All numbers herein are expressed in base ten.)
27 = 128 and 7 is
the first power of 2 whose leading decimal digits are 12.
The next power of 2 whose leading decimal digits
are 12 is 80,
280 = 1208925819614629174706176.
Define ... | #zkl | zkl | // float*int --> float and int*float --> int
fcn p(L,nth){ // 2^j = <L><digits>
var [const] ln10=(10.0).log(), ld10=(2.0).log() / ln10;
digits := (10).pow(L.numDigits - 1);
foreach i in ([1..]){
z:=ld10*i;
if(L == ( ln10 * (z - z.toInt()) ).exp()*digits and (nth-=1) <= 0)
return(i);
}
} |
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously | First-class functions/Use numbers analogously | In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types.
This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.
Write a program to create an ordered collection of a m... | #Tcl | Tcl | package require Tcl 8.5
proc multiplier {a b} {
list apply {{ab m} {expr {$ab*$m}}} [expr {$a*$b}]
} |
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously | First-class functions/Use numbers analogously | In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types.
This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.
Write a program to create an ordered collection of a m... | #Ursala | Ursala | #import std
#import flo
numbers = <2.,4.,plus(2.,4.)>
inverses = <0.5,0.25,div(1.,plus(2.,4.))>
multiplier = //times+ times
#cast %eL
main = (gang multiplier*p\numbers inverses) 0.5 |
http://rosettacode.org/wiki/Flow-control_structures | Flow-control structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
Document common flow-control structures.
One common example of a flow-control structure is the goto construct.
Note that Conditional Struc... | #Visual_Basic_.NET | Visual Basic .NET | Sub bar2()
Dim x = 0
GoTo label
x = 5
label:
Console.WriteLine(x)
End Sub |
http://rosettacode.org/wiki/Flow-control_structures | Flow-control structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
Document common flow-control structures.
One common example of a flow-control structure is the goto construct.
Note that Conditional Struc... | #Wren | Wren | var func = Fn.new { |n|
var i = 1
while (true) {
if (i == 1) {
i = i + 1
continue // jumps to next iteration
}
System.print(i)
if (i == n) break // exits while loop
i = i + 1
}
if (n < 3) return // exits function
System.print(n + 1)
}
... |
http://rosettacode.org/wiki/Floyd%27s_triangle | Floyd's triangle | Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
the first row is 1 (unity)
successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like thi... | #J | J | require 'strings'
floyd=: [: rplc&(' 0';' ')"1@":@(* ($ $ +/\@,)) >:/~@:i. |
http://rosettacode.org/wiki/Floyd%27s_triangle | Floyd's triangle | Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
the first row is 1 (unity)
successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like thi... | #Java | Java |
public class Floyd {
public static void main(String[] args){
printTriangle(5);
printTriangle(14);
}
private static void printTriangle(int n){
System.out.println(n + " rows:");
for(int rowNum = 1, printMe = 1, numsPrinted = 0;
rowNum <= n; printMe++){
int cols = (int)Math.ceil(Math.log10(n*(n-1)/2 ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.