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/Input_loop | Input loop | Input loop is part of Short Circuit's Console Program Basics selection.
Task
Read from a text stream either word-by-word or line-by-line until the stream runs out of data.
The stream will have an unknown amount of data on it.
| #Elixir | Elixir | defmodule RC do
def input_loop(stream) do
case IO.read(stream, :line) do
:eof -> :ok
data -> IO.write data
input_loop(stream)
end
end
end
path = hd(System.argv)
File.open!(path, [:read], fn stream -> RC.input_loop(stream) end) |
http://rosettacode.org/wiki/Isqrt_(integer_square_root)_of_X | Isqrt (integer square root) of X | Sometimes a function is needed to find the integer square root of X, where X can be a
real non─negative number.
Often X is actually a non─negative integer.
For the purposes of this task, X can be an integer or a real number, but if it
simplifies things in your computer programming language, assume... | #Python | Python | def isqrt ( x ):
q = 1
while q <= x :
q *= 4
z,r = x,0
while q > 1 :
q /= 4
t,r = z-r-q,r/2
if t >= 0 :
z,r = t,r+q
return r
print ' '.join( '%d'%isqrt( n ) for n in xrange( 66 ))
print '\n'.join( '{0:114,} = isqrt( 7^{1:3} )'.format( isqrt( 7**n ),n ... |
http://rosettacode.org/wiki/Inverted_index | Inverted index | An Inverted Index is a data structure used to create full text search.
Task
Given a set of text files, implement a program to create an inverted index.
Also create a user interface to do a search using that inverted index which returns a list of files that contain the query term / terms.
The search index can be i... | #jq | jq | # Given an array of [ doc, array_of_distinct_words ]
# construct a lookup table: { word: array_of_docs }
def inverted_index:
reduce .[] as $pair
({};
$pair[0] as $doc
| reduce $pair[1][] as $word
(.; .[$word] += [$doc]));
def search(words):
def overlap(that): . as $this
| reduce that[] as $... |
http://rosettacode.org/wiki/Introspection | Introspection | Task
verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old.
check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs(bloop).
Extra credit
Repor... | #Logtalk | Logtalk |
:- object(my_application).
:- initialization((
check_logtalk_version,
compute_predicate_if_available
)).
check_logtalk_version :-
% version data is available by consulting the "version_data" flag
current_logtalk_flag(version_data, logtalk(Major,Minor,Patch,_)),
... |
http://rosettacode.org/wiki/Josephus_problem | Josephus problem | Josephus problem is a math puzzle with a grim description:
n
{\displaystyle n}
prisoners are standing on a circle, sequentially numbered from
0
{\displaystyle 0}
to
n
−
1
{\displaystyle n-1}
.
An executioner walks along the circle, starting from prisoner
0
{\displaystyle 0}
,
removing eve... | #MATLAB | MATLAB | function [indAlive] = josephus(numPeople,count)
% Josephus: Given a circle of numPeople individuals, with a count of count,
% find the index (starting at 1) of the survivor [see Josephus Problem]
%% Definitions:
% 0 = dead position
% 1 = alive position
% index = # of person
%% Setting up
arrPeople = ones(1, n... |
http://rosettacode.org/wiki/Interactive_programming_(repl) | Interactive programming (repl) | Many language implementations come with an interactive mode.
This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions.
An interactive mode may also be known as a command mode, a read-eval-print loop (REPL), or a shell.
Task
Show how to start this... | #Oforth | Oforth | oforth --i |
http://rosettacode.org/wiki/Interactive_programming_(repl) | Interactive programming (repl) | Many language implementations come with an interactive mode.
This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions.
An interactive mode may also be known as a command mode, a read-eval-print loop (REPL), or a shell.
Task
Show how to start this... | #Ol | Ol |
$ ol
Welcome to Otus Lisp 2.1-2282-27a9b6c
type ',help' to help, ',quit' to end session.
> (define (f head tail mid)
(string-append head mid mid tail))
;; Defined f
> (f "Rosetta" "Code" ":")
"Rosetta::Code"
> ,quit
bye-bye :/
|
http://rosettacode.org/wiki/Interactive_programming_(repl) | Interactive programming (repl) | Many language implementations come with an interactive mode.
This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions.
An interactive mode may also be known as a command mode, a read-eval-print loop (REPL), or a shell.
Task
Show how to start this... | #ooRexx | ooRexx | D:\>rexx rexxtry ?
This procedure lets you interactively try REXX statements.
If you run it with no parameter, or with a question mark
as a parameter, it will briefly describe itself.
You may also enter a REXX statement directly on the command line
for immediate execution and exit. Example: rexxtry call show
E... |
http://rosettacode.org/wiki/ISBN13_check_digit | ISBN13 check digit | Task
Validate the check digit of an ISBN-13 code:
Multiply every other digit by 3.
Add these numbers and the other digits.
Take the remainder of this number after division by 10.
If it is 0, the ISBN-13 check digit is correct.
Use the following codes for testing:
978-1734314502 (good)
... | #Raku | Raku | sub check-digit ($isbn) {
(10 - (sum (|$isbn.comb(/<[0..9]>/)) »*» (1,3)) % 10).substr: *-1
}
{
my $check = .substr(*-1);
my $check-digit = check-digit .chop;
say "$_ : ", $check == $check-digit ??
'Good' !!
"Bad check-digit $check; should be $check-digit"
} for words <
978-173431... |
http://rosettacode.org/wiki/Jaro_similarity | Jaro similarity | The Jaro distance is a measure of edit distance between two strings; its inverse, called the Jaro similarity, is a measure of two strings' similarity: the higher the value, the more similar the strings are. The score is normalized such that 0 equates to no similarities and 1 is an exact match.
Definition
The... | #VBA | VBA |
Option Explicit
Function JaroWinkler(text1 As String, text2 As String, Optional p As Double = 0.1) As Double
Dim dummyChar, match1, match2 As String
Dim i, f, t, j, m, l, s1, s2, limit As Integer
i = 1
Do
dummyChar = Chr(i)
i = i + 1
Loop Until InStr(1, text1 & text2, dummyChar, vbTextCompare) = 0
s1 = ... |
http://rosettacode.org/wiki/Increment_a_numerical_string | Increment a numerical string | Task
Increment a numerical string.
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program incstring64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesAR... |
http://rosettacode.org/wiki/Increment_a_numerical_string | Increment a numerical string | Task
Increment a numerical string.
| #ABAP | ABAP | report zz_incstring
perform test using: '0', '1', '-1', '10000000', '-10000000'.
form test using iv_string type string.
data: lv_int type i,
lv_string type string.
lv_int = iv_string + 1.
lv_string = lv_int.
concatenate '"' iv_string '" + 1 = "' lv_string '"' into lv_string.
write / lv_string.
endf... |
http://rosettacode.org/wiki/Integer_comparison | Integer comparison |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #AppleScript | AppleScript | set n1 to text returned of (display dialog "Enter the first number:" default answer "") as integer
set n2 to text returned of (display dialog "Enter the second number:" default answer "") as integer
set msg to {n1}
if n1 < n2 then
set end of msg to " is less than "
else if n1 = n2 then
set end of msg to " is equal to... |
http://rosettacode.org/wiki/Include_a_file | Include a file | Task
Demonstrate the language's ability to include source code from other files.
See Also
Compiler/Simple file inclusion pre processor
| #Action.21 | Action! | INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
PROC Main()
RETURN |
http://rosettacode.org/wiki/Include_a_file | Include a file | Task
Demonstrate the language's ability to include source code from other files.
See Also
Compiler/Simple file inclusion pre processor
| #Ada | Ada | with Ada.Text_IO, Another_Package; use Ada.Text_IO;
-- the with-clause tells the compiler to include the Text_IO package from the Ada standard
-- and Another_Package. Subprograms from these packages may be called as follows:
-- Ada.Text_IO.Put_Line("some text");
-- Another_Pack... |
http://rosettacode.org/wiki/Inheritance/Single | Inheritance/Single | This task is about derived types; for implementation inheritance, see Polymorphism.
Inheritance is an operation of type algebra that creates a new type from one or several parent types.
The obtained type is called derived type.
It inherits some of the properties of its parent types.
Usually inherited properties... | #Fancy | Fancy | class Animal {
# ...
}
class Dog : Animal {
# ...
}
class Cat : Animal {
# ...
}
class Lab : Dog {
# ...
}
class Collie : Dog {
# ...
} |
http://rosettacode.org/wiki/Inheritance/Single | Inheritance/Single | This task is about derived types; for implementation inheritance, see Polymorphism.
Inheritance is an operation of type algebra that creates a new type from one or several parent types.
The obtained type is called derived type.
It inherits some of the properties of its parent types.
Usually inherited properties... | #Fantom | Fantom | class Animal
{
}
class Dog : Animal
{
}
class Cat : Animal
{
}
class Lab : Dog
{
}
class Collie : Dog
{
} |
http://rosettacode.org/wiki/Inheritance/Single | Inheritance/Single | This task is about derived types; for implementation inheritance, see Polymorphism.
Inheritance is an operation of type algebra that creates a new type from one or several parent types.
The obtained type is called derived type.
It inherits some of the properties of its parent types.
Usually inherited properties... | #Forth | Forth | include 4pp/lib/foos.4pp
:: Animal class end-class {} ;
:: Dog extends Animal end-extends {} ;
:: Cat extends Animal end-extends {} ;
:: Lab extends Dog end-extends {} ;
:: Collie extends Dog end-extends {} ; |
http://rosettacode.org/wiki/Idiomatically_determine_all_the_lowercase_and_uppercase_letters | Idiomatically determine all the lowercase and uppercase letters |
Idiomatically determine all the lowercase and uppercase letters (of the Latin [English] alphabet) being used currently by a computer programming language.
The method should find the letters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other).
Task requirements
Display the set of... | #11l | 11l | print(‘Lower case: ’, end' ‘’)
L(ch) ‘a’..‘z’
print(ch, end' ‘’)
print()
print(‘Upper case: ’, end' ‘’)
L(ch) ‘A’..‘Z’
print(ch, end' ‘’)
print() |
http://rosettacode.org/wiki/Idiomatically_determine_all_the_characters_that_can_be_used_for_symbols | Idiomatically determine all the characters that can be used for symbols | Idiomatically determine all the characters that can be used for symbols.
The word symbols is meant things like names of variables, procedures (i.e., named fragments of programs, functions, subroutines, routines), statement labels, events or conditions, and in general, anything a computer programmer can choose to name, ... | #Haskell | Haskell | varid → (small {small | large | digit | ' }) / reservedid
conid → large {small | large | digit | ' }
reservedid → case | class | data | default | deriving | do | else
| foreign | if | import | in | infix | infixl
| infixr | instance | let | module | newtype | of
| then | type ... |
http://rosettacode.org/wiki/Idiomatically_determine_all_the_characters_that_can_be_used_for_symbols | Idiomatically determine all the characters that can be used for symbols | Idiomatically determine all the characters that can be used for symbols.
The word symbols is meant things like names of variables, procedures (i.e., named fragments of programs, functions, subroutines, routines), statement labels, events or conditions, and in general, anything a computer programmer can choose to name, ... | #J | J | a.#~1=#@;: ::0:"1 'b',.a.,.'c'
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz |
http://rosettacode.org/wiki/Idiomatically_determine_all_the_characters_that_can_be_used_for_symbols | Idiomatically determine all the characters that can be used for symbols | Idiomatically determine all the characters that can be used for symbols.
The word symbols is meant things like names of variables, procedures (i.e., named fragments of programs, functions, subroutines, routines), statement labels, events or conditions, and in general, anything a computer programmer can choose to name, ... | #Java | Java | import java.util.function.IntPredicate;
import java.util.stream.IntStream;
public class Test {
public static void main(String[] args) throws Exception {
print("Java Identifier start: ", 0, 0x10FFFF, 72,
Character::isJavaIdentifierStart, "%c");
print("Java Identifier part: ... |
http://rosettacode.org/wiki/Iterated_digits_squaring | Iterated digits squaring | If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89:
15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89
7 -> 49 -> 97 -> 130 -> 10 -> 1
An example in Python:
>>> step = lambda x: sum(int(d) ** 2 for d in str(x))
>>> iterate = lambda x: x if x in [1, 89] else i... | #Sidef | Sidef | func digit_square_sum_iter(n) is cached {
if ((n == 1) || (n == 89)) {
return n
}
__FUNC__(n.digits.sum { .sqr })
}
say (1..1e6 -> count_by { digit_square_sum_iter(_) == 89 }) |
http://rosettacode.org/wiki/Index_finite_lists_of_positive_integers | Index finite lists of positive integers | It is known that the set of finite lists of positive integers is countable.
This means that there exists a subset of natural integers which can be mapped to the set of finite lists of positive integers.
Task
Implement such a mapping:
write a function rank which assigns an integer to any finite, arbi... | #Haskell | Haskell | import Data.List
toBase :: Int -> Integer -> [Int]
toBase b = unfoldr f
where
f 0 = Nothing
f n = let (q, r) = n `divMod` fromIntegral b in Just (fromIntegral r, q)
fromBase :: Int -> [Int] -> Integer
fromBase n lst = foldr (\x r -> fromIntegral n*r + fromIntegral x) 0 lst
------------------------------... |
http://rosettacode.org/wiki/Integer_sequence | Integer sequence | Task
Create a program that, when run, would display all integers from 1 to ∞ (or any relevant implementation limit), in sequence (i.e. 1, 2, 3, 4, etc) if given enough time.
An example may not be able to reach arbitrarily-large numbers based on implementations limits. For example, if integer... | #Common_Lisp | Common Lisp | (loop for i from 1 do (print i)) |
http://rosettacode.org/wiki/Infinity | Infinity | Task
Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity. Otherwise, return the largest possible po... | #D | D | auto inf() {
return typeof(1.5).infinity;
}
void main() {} |
http://rosettacode.org/wiki/Infinity | Infinity | Task
Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity. Otherwise, return the largest possible po... | #Delphi | Delphi | Infinity = 1.0 / 0.0;
NegInfinity = -1.0 / 0.0; |
http://rosettacode.org/wiki/Infinity | Infinity | Task
Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity. Otherwise, return the largest possible po... | #Dyalect | Dyalect | func infinityTask() => Float.Infinity |
http://rosettacode.org/wiki/Inheritance/Multiple | Inheritance/Multiple | Multiple inheritance allows to specify that one class is a subclass of several other classes.
Some languages allow multiple inheritance for arbitrary classes, others restrict it to interfaces, some don't allow it at all.
Task
Write two classes (or interfaces) Camera and MobilePhone, then write a class Camer... | #Nim | Nim | type
Camera = ref object of RootObj
MobilePhone = ref object of RootObj
CameraPhone = object
camera: Camera
phone: MobilePhone
proc `is`(cp: CameraPhone, t: typedesc): bool =
for field in cp.fields():
if field of t:
return true
var cp: CameraPhone
echo(cp is Camera)
echo(cp is MobilePhone) |
http://rosettacode.org/wiki/Inheritance/Multiple | Inheritance/Multiple | Multiple inheritance allows to specify that one class is a subclass of several other classes.
Some languages allow multiple inheritance for arbitrary classes, others restrict it to interfaces, some don't allow it at all.
Task
Write two classes (or interfaces) Camera and MobilePhone, then write a class Camer... | #Objective-C | Objective-C | @interface Camera : NSObject {
}
@end
@implementation Camera
@end
@interface MobilePhone : NSObject {
}
@end
@implementation MobilePhone
@end
@interface CameraPhone : NSObject {
Camera *camera;
MobilePhone *phone;
}
@end
@implementation CameraPhone
-(instancetype)init {
if ((self = [super init])) {
... |
http://rosettacode.org/wiki/Increasing_gaps_between_consecutive_Niven_numbers | Increasing gaps between consecutive Niven numbers | Note: Niven numbers are also called Harshad numbers.
They are also called multidigital numbers.
Niven numbers are positive integers which are evenly divisible by the sum of its
digits (expressed in base ten).
Evenly divisible means divisible with no remainder.
Task
find the gap (differen... | #jq | jq | infinite | nivens
|
http://rosettacode.org/wiki/Increasing_gaps_between_consecutive_Niven_numbers | Increasing gaps between consecutive Niven numbers | Note: Niven numbers are also called Harshad numbers.
They are also called multidigital numbers.
Niven numbers are positive integers which are evenly divisible by the sum of its
digits (expressed in base ten).
Evenly divisible means divisible with no remainder.
Task
find the gap (differen... | #Julia | Julia | using Formatting
function findharshadgaps(N)
isharshad(i) = i % sum(digits(i)) == 0
println("Gap Index Number Index Niven Number")
lastnum, lastnumidx, biggestgap = 1, 1, 0
for i in 2:N
if isharshad(i)
if (gap = i - lastnum) > biggestgap
println(lpad(gap, 5), lpad... |
http://rosettacode.org/wiki/Increasing_gaps_between_consecutive_Niven_numbers | Increasing gaps between consecutive Niven numbers | Note: Niven numbers are also called Harshad numbers.
They are also called multidigital numbers.
Niven numbers are positive integers which are evenly divisible by the sum of its
digits (expressed in base ten).
Evenly divisible means divisible with no remainder.
Task
find the gap (differen... | #MAD | MAD | NORMAL MODE IS INTEGER
INTERNAL FUNCTION REM.(A,B) = A-A/B*B
PRINT COMMENT $ GAP NO GAP NIVEN INDEX NIVEN NUMBER$
PRINT COMMENT $ ****** *** *********** ************$
VECTOR VALUES FMT = $I6,S2,I3,S2,I11,S2,I12*$
PREV = 1
G... |
http://rosettacode.org/wiki/Integer_overflow | Integer overflow | Some languages support one or more integer types of the underlying processor.
This integer types have fixed size; usually 8-bit, 16-bit, 32-bit, or 64-bit.
The integers supported by such a type can be signed or unsigned.
Arithmetic for machine level integers can often be done by single CPU instruct... | #Lua | Lua | assert(math.type~=nil, "Lua 5.3+ required for this test.")
minint, maxint = math.mininteger, math.maxinteger
print("min, max int64 = " .. minint .. ", " .. maxint)
print("min-1 underflow = " .. (minint-1) .. " equals max? " .. tostring(minint-1==maxint))
print("max+1 overflow = " .. (maxint+1) .. " equals min? " .... |
http://rosettacode.org/wiki/Integer_overflow | Integer overflow | Some languages support one or more integer types of the underlying processor.
This integer types have fixed size; usually 8-bit, 16-bit, 32-bit, or 64-bit.
The integers supported by such a type can be signed or unsigned.
Arithmetic for machine level integers can often be done by single CPU instruct... | #M2000_Interpreter | M2000 Interpreter |
Long A
Try ok {
A=12121221212121
}
If not ok then Print Error$ 'Overflow Long
Def Integer B
Try ok {
B=1212121212
}
If not ok then Print Error$ ' Overflow Integer
Def Currency C
Try ok {
C=121212121232934392898274327927948
}
If not ok then Print Error$ ' return Overflow Long, but is overflow Curr... |
http://rosettacode.org/wiki/Input_loop | Input loop | Input loop is part of Short Circuit's Console Program Basics selection.
Task
Read from a text stream either word-by-word or line-by-line until the stream runs out of data.
The stream will have an unknown amount of data on it.
| #Erlang | Erlang | % Implemented by Arjun Sunel
-module(read_files).
-export([main/0]).
main() ->
Read = fun (Filename) -> {ok, Data} = file:read_file(Filename), Data end,
Lines = string:tokens(binary_to_list(Read("read_files.erl")), "\n"),
lists:foreach(fun (Y) -> io:format("~s~n", [Y]) end, lists:zipwith(fun(X,_)->X end, Lines, li... |
http://rosettacode.org/wiki/Input_loop | Input loop | Input loop is part of Short Circuit's Console Program Basics selection.
Task
Read from a text stream either word-by-word or line-by-line until the stream runs out of data.
The stream will have an unknown amount of data on it.
| #ERRE | ERRE | LOOP
INPUT(LINE,A$)
PRINT(A$)
EXIT IF <condition> ! condition to be implemented to
! to avoid and endless loop
END LOOP
|
http://rosettacode.org/wiki/Isqrt_(integer_square_root)_of_X | Isqrt (integer square root) of X | Sometimes a function is needed to find the integer square root of X, where X can be a
real non─negative number.
Often X is actually a non─negative integer.
For the purposes of this task, X can be an integer or a real number, but if it
simplifies things in your computer programming language, assume... | #Quackery | Quackery | [ dup size 3 / times
[ char , swap
i 1+ -3 * stuff ]
dup 0 peek char , =
if [ behead drop ] ] is +commas ( $ --> $ )
[ over size -
space swap of
swap join ] is justify ( $ n --> $ )
[ 1
[ 2dup < not while
2 << again ]
0
[ over 1 > while
... |
http://rosettacode.org/wiki/Isqrt_(integer_square_root)_of_X | Isqrt (integer square root) of X | Sometimes a function is needed to find the integer square root of X, where X can be a
real non─negative number.
Often X is actually a non─negative integer.
For the purposes of this task, X can be an integer or a real number, but if it
simplifies things in your computer programming language, assume... | #Racket | Racket |
#lang racket
;; Integer Square Root (using Quadratic Residue)
(define (isqrt x)
(define q-init ; power of 4 greater than x
(let loop ([acc 1])
(if (<= acc x) (loop (* acc 4)) acc)))
(define-values (z r q)
(let loop ([z x] [r 0] [q q-init])
(if (<= q 1)
(values z r q)
... |
http://rosettacode.org/wiki/Inverted_index | Inverted index | An Inverted Index is a data structure used to create full text search.
Task
Given a set of text files, implement a program to create an inverted index.
Also create a user interface to do a search using that inverted index which returns a list of files that contain the query term / terms.
The search index can be i... | #Julia | Julia | function makedoubleindex(files)
idx = Dict{String, Dict}()
for file in files
str = lowercase(read(file, String))
words = split(str, r"\s+")
for word in words
if !haskey(idx, word)
idx[word] = Dict{String, Int}()
elseif !haskey(idx[word], file)
... |
http://rosettacode.org/wiki/Introspection | Introspection | Task
verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old.
check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs(bloop).
Extra credit
Repor... | #Lua | Lua | if _VERSION:sub(5) + 0 < 5.1 then print"too old" end --_VERSION is "Lua <version>".
if bloop and math.abs then print(math.abs(bloop)) end |
http://rosettacode.org/wiki/Introspection | Introspection | Task
verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old.
check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs(bloop).
Extra credit
Repor... | #Maple | Maple | > kernelopts( 'version' );
Maple 16.00, SUN SPARC SOLARIS, Mar 3 2012, Build ID 732982 |
http://rosettacode.org/wiki/Josephus_problem | Josephus problem | Josephus problem is a math puzzle with a grim description:
n
{\displaystyle n}
prisoners are standing on a circle, sequentially numbered from
0
{\displaystyle 0}
to
n
−
1
{\displaystyle n-1}
.
An executioner walks along the circle, starting from prisoner
0
{\displaystyle 0}
,
removing eve... | #Modula-2 | Modula-2 | MODULE Josephus;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
PROCEDURE Josephus(n,k : INTEGER) : INTEGER;
VAR a,m : INTEGER;
BEGIN
m := 0;
FOR a:=1 TO n DO
m := (m + k) MOD a;
END;
RETURN m
END Josephus;
VAR
buf : ARRAY[0..63] OF CHAR;
n,... |
http://rosettacode.org/wiki/Interactive_programming_(repl) | Interactive programming (repl) | Many language implementations come with an interactive mode.
This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions.
An interactive mode may also be known as a command mode, a read-eval-print loop (REPL), or a shell.
Task
Show how to start this... | #Oz | Oz | declare fun {F As Bs Sep} {Append As Sep|Sep|Bs} end |
http://rosettacode.org/wiki/Interactive_programming_(repl) | Interactive programming (repl) | Many language implementations come with an interactive mode.
This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions.
An interactive mode may also be known as a command mode, a read-eval-print loop (REPL), or a shell.
Task
Show how to start this... | #PARI.2FGP | PARI/GP | f(s1,s2,sep)=Str(s1, sep, sep, s2); |
http://rosettacode.org/wiki/Interactive_programming_(repl) | Interactive programming (repl) | Many language implementations come with an interactive mode.
This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions.
An interactive mode may also be known as a command mode, a read-eval-print loop (REPL), or a shell.
Task
Show how to start this... | #Perl | Perl | $ perl -de1
Loading DB routines from perl5db.pl version 1.3
Editor support available.
Enter h or `h h' for help, or `man perldebug' for more help.
main::(-e:1): 1
DB<1> sub f {my ($s1, $s2, $sep) = @_; $s1 . $sep . $sep . $s2}
DB<2> p f('Rosetta', 'Code', ':')
Rosetta::Code
DB<3> q |
http://rosettacode.org/wiki/ISBN13_check_digit | ISBN13 check digit | Task
Validate the check digit of an ISBN-13 code:
Multiply every other digit by 3.
Add these numbers and the other digits.
Take the remainder of this number after division by 10.
If it is 0, the ISBN-13 check digit is correct.
Use the following codes for testing:
978-1734314502 (good)
... | #Red | Red | check_valid_isbn13: function [str] [
is_digit: charset [#"0" - #"9"]
remove-each i str [not pick is_digit i] ; remove non-digits
either 13 = length? str [ ; reject strings of incorrect length
sum: 0
repeat i 13 [
mul: either even? i [3] [1] ; multiplier for odd/even digits
... |
http://rosettacode.org/wiki/Jaro_similarity | Jaro similarity | The Jaro distance is a measure of edit distance between two strings; its inverse, called the Jaro similarity, is a measure of two strings' similarity: the higher the value, the more similar the strings are. The score is normalized such that 0 equates to no similarities and 1 is an exact match.
Definition
The... | #Vlang | Vlang | import math
fn jaro(str1 string, str2 string) f64 {
s1_len := str1.len
s2_len := str2.len
if s1_len == 0 && s2_len == 0 {
return 1
}
if s1_len == 0 || s2_len == 0 {
return 0
}
match_distance := math.max<int>(s1_len,s2_len)/2 - 1
mut str1_matches := []bool{len: s1_len}... |
http://rosettacode.org/wiki/Jaro_similarity | Jaro similarity | The Jaro distance is a measure of edit distance between two strings; its inverse, called the Jaro similarity, is a measure of two strings' similarity: the higher the value, the more similar the strings are. The score is normalized such that 0 equates to no similarities and 1 is an exact match.
Definition
The... | #Wren | Wren | import "/fmt" for Fmt
var jaro = Fn.new { |s1, s2|
var le1 = s1.count
var le2 = s2.count
if (le1 == 0 && le2 == 0) return 1
if (le1 == 0 || le2 == 0) return 0
var dist = (le2 > le1) ? le2 : le1
dist = (dist/2).floor - 1
var matches1 = List.filled(le1, false)
var matches2 = List.filled(... |
http://rosettacode.org/wiki/Increment_a_numerical_string | Increment a numerical string | Task
Increment a numerical string.
| #Action.21 | Action! | PROC Increment(CHAR ARRAY src,dst)
INT val
val=ValI(src)
val==+1
StrI(val,dst)
RETURN
PROC Test(CHAR ARRAY src)
CHAR ARRAY dst(10)
Increment(src,dst)
PrintF("%S+1=%S%E",src,dst)
RETURN
PROC Main()
Test("0")
Test("1")
Test("9999")
Test("-1")
Test("-2")
Test("-10000")
RETURN |
http://rosettacode.org/wiki/Increment_a_numerical_string | Increment a numerical string | Task
Increment a numerical string.
| #ActionScript | ActionScript | function incrementString(str:String):String
{
return String(Number(str)+1);
} |
http://rosettacode.org/wiki/Integer_comparison | Integer comparison |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program comparNumber.s */
/* Constantes */
.equ BUFFERSIZE, 100
.equ STDIN, 0 @ Linux input console
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ READ, 3 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/* Initialized dat... |
http://rosettacode.org/wiki/Include_a_file | Include a file | Task
Demonstrate the language's ability to include source code from other files.
See Also
Compiler/Simple file inclusion pre processor
| #ALGOL_68 | ALGOL 68 | PR read "file.a68" PR |
http://rosettacode.org/wiki/Include_a_file | Include a file | Task
Demonstrate the language's ability to include source code from other files.
See Also
Compiler/Simple file inclusion pre processor
| #AntLang | AntLang | load["script.ant"] |
http://rosettacode.org/wiki/Inheritance/Single | Inheritance/Single | This task is about derived types; for implementation inheritance, see Polymorphism.
Inheritance is an operation of type algebra that creates a new type from one or several parent types.
The obtained type is called derived type.
It inherits some of the properties of its parent types.
Usually inherited properties... | #Fortran | Fortran | module anim
type animal
end type animal
type, extends(animal) :: dog
end type dog
type, extends(animal) :: cat
end type cat
type, extends(dog) :: lab
end type lab
type, extends(dog) :: collie
end type collie
end module anim |
http://rosettacode.org/wiki/Inheritance/Single | Inheritance/Single | This task is about derived types; for implementation inheritance, see Polymorphism.
Inheritance is an operation of type algebra that creates a new type from one or several parent types.
The obtained type is called derived type.
It inherits some of the properties of its parent types.
Usually inherited properties... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Type Animal Extends Object ' to enable virtual methods etc. if needed
' ...
End Type
Type Dog Extends Animal
' ...
End Type
Type Cat Extends Animal
' ...
End Type
Type Lab Extends Dog
' ...
End Type
Type Collie Extends Dog
' ...
End Type |
http://rosettacode.org/wiki/Idiomatically_determine_all_the_lowercase_and_uppercase_letters | Idiomatically determine all the lowercase and uppercase letters |
Idiomatically determine all the lowercase and uppercase letters (of the Latin [English] alphabet) being used currently by a computer programming language.
The method should find the letters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other).
Task requirements
Display the set of... | #Action.21 | Action! | INCLUDE "D2:CHARTEST.ACT" ;from the Action! Tool Kit
PROC Main()
CHAR ARRAY lower(128),upper(128)
CHAR c
BYTE lowerLen,upperLen
Put(125) PutE() ;clear screen
lowerLen=0
upperLen=0
FOR c=0 TO 127
DO
IF IsLower(c) THEN
lowerLen==+1
lower(lowerLen)=c
ELSEIF IsUpper(c) THEN
u... |
http://rosettacode.org/wiki/Idiomatically_determine_all_the_lowercase_and_uppercase_letters | Idiomatically determine all the lowercase and uppercase letters |
Idiomatically determine all the lowercase and uppercase letters (of the Latin [English] alphabet) being used currently by a computer programming language.
The method should find the letters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other).
Task requirements
Display the set of... | #Ada | Ada |
with Ada.Text_IO; use Ada.Text_IO;
procedure Main is
subtype Lower is Character range 'a' .. 'z';
subtype Upper is Character range 'A' .. 'Z';
begin
Put ("Lower: ");
for c in Lower'range loop
Put (c);
end loop;
New_Line;
Put ("Upper: ");
for c in Upper'range loop
Put (c);
end ... |
http://rosettacode.org/wiki/Idiomatically_determine_all_the_lowercase_and_uppercase_letters | Idiomatically determine all the lowercase and uppercase letters |
Idiomatically determine all the lowercase and uppercase letters (of the Latin [English] alphabet) being used currently by a computer programming language.
The method should find the letters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other).
Task requirements
Display the set of... | #ALGOL_68 | ALGOL 68 | STRING lc := "";
STRING uc := "";
FOR c FROM 0 TO max abs char DO
CHAR ch := REPR c;
IF is lower( ch ) THEN lc +:= ch FI;
IF is upper( ch ) THEN uc +:= ch FI
OD;
print( ( "lower: """ + lc + """", newline ) );
print( ( "upper: """ + uc + """", newline ) ) |
http://rosettacode.org/wiki/Imaginary_base_numbers | Imaginary base numbers | Imaginary base numbers are a non-standard positional numeral system which uses an imaginary number as its radix. The most common is quater-imaginary with radix 2i.
The quater-imaginary numeral system was first proposed by Donald Knuth in 1955 as a submission for a high school science talent search. [Ref.]
Other imagi... | #11l | 11l | F inv(c)
V denom = c.real * c.real + c.imag * c.imag
R Complex(c.real / denom, -c.imag / denom)
V QuaterImaginary_twoI = Complex(0, 2)
V QuaterImaginary_invTwoI = inv(QuaterImaginary_twoI)
T QuaterImaginary
String b2i
F (str)
I !re:‘[0123.]+’.match(str) | str.count(‘.’) > 1
assert(0B, ‘... |
http://rosettacode.org/wiki/Idiomatically_determine_all_the_characters_that_can_be_used_for_symbols | Idiomatically determine all the characters that can be used for symbols | Idiomatically determine all the characters that can be used for symbols.
The word symbols is meant things like names of variables, procedures (i.e., named fragments of programs, functions, subroutines, routines), statement labels, events or conditions, and in general, anything a computer programmer can choose to name, ... | #jq | jq | [range(0;128) | [.] | implode | select(test("[A-Za-z0-9$_]"))] | add |
http://rosettacode.org/wiki/Idiomatically_determine_all_the_characters_that_can_be_used_for_symbols | Idiomatically determine all the characters that can be used for symbols | Idiomatically determine all the characters that can be used for symbols.
The word symbols is meant things like names of variables, procedures (i.e., named fragments of programs, functions, subroutines, routines), statement labels, events or conditions, and in general, anything a computer programmer can choose to name, ... | #Julia | Julia |
for i in 1:0x200000 - 1
Symbol("x" * Char(i))
end
|
http://rosettacode.org/wiki/Idiomatically_determine_all_the_characters_that_can_be_used_for_symbols | Idiomatically determine all the characters that can be used for symbols | Idiomatically determine all the characters that can be used for symbols.
The word symbols is meant things like names of variables, procedures (i.e., named fragments of programs, functions, subroutines, routines), statement labels, events or conditions, and in general, anything a computer programmer can choose to name, ... | #Kotlin | Kotlin | // version 1.1.4-3
typealias CharPredicate = (Char) -> Boolean
fun printChars(msg: String, start: Int, end: Int, limit: Int, p: CharPredicate, asInt: Boolean) {
print(msg)
(start until end).map { it.toChar() }
.filter { p(it) }
.take(limit)
.for... |
http://rosettacode.org/wiki/Image_noise | Image noise | Generate a random black and white 320x240 image continuously,
showing FPS (frames per second).
A sample image
| #6502_Assembly | 6502 Assembly | define sysRandom $fe
Snow:
lda sysRandom ;get a random number
and #$01 ;remove all but bit 0
sta $0200,x ;store in first section of VRAM
lda sysRandom ;get a random number
and #$01 ;remove all but bit 0
sta $0300,x ;store in second section of VRAM
lda sysRandom ;get a random number
and #$01 ... |
http://rosettacode.org/wiki/Image_convolution | Image convolution | One class of image digital filters is described by a rectangular matrix of real coefficients called kernel convoluted in a sliding window of image pixels. Usually the kernel is square
K
k
l
{\displaystyle K_{kl}}
, where k, l are in the range -R,-R+1,..,R-1,R. W=2R+1 is the kernel width. The filter determine... | #Action.21 | Action! | INCLUDE "H6:LOADPPM5.ACT"
DEFINE HISTSIZE="256"
PROC PutBigPixel(INT x,y BYTE col)
IF x>=0 AND x<=79 AND y>=0 AND y<=47 THEN
y==LSH 2
col==RSH 4
IF col<0 THEN col=0
ELSEIF col>15 THEN col=15 FI
Color=col
Plot(x,y)
DrawTo(x,y+3)
FI
RETURN
PROC DrawImage(GrayImage POINTER image INT x... |
http://rosettacode.org/wiki/Iterated_digits_squaring | Iterated digits squaring | If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89:
15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89
7 -> 49 -> 97 -> 130 -> 10 -> 1
An example in Python:
>>> step = lambda x: sum(int(d) ** 2 for d in str(x))
>>> iterate = lambda x: x if x in [1, 89] else i... | #Swift | Swift | import BigInt
func is89(_ n: Int) -> Bool {
var n = n
while true {
var s = 0
repeat {
s += (n%10) * (n%10)
n /= 10
} while n > 0
if s == 89 {
return true
} else if s == 1 {
return false
}
n = s
}
}
func iterSquare(upToPower pow: Int) {
var sums = [... |
http://rosettacode.org/wiki/Index_finite_lists_of_positive_integers | Index finite lists of positive integers | It is known that the set of finite lists of positive integers is countable.
This means that there exists a subset of natural integers which can be mapped to the set of finite lists of positive integers.
Task
Implement such a mapping:
write a function rank which assigns an integer to any finite, arbi... | #J | J | scrunch=:3 :0
n=.1x+>./y
#.(1#~##:n),0,n,&#:n#.y
)
hcnurcs=:3 :0
b=.#:y
m=.b i.0
n=.#.m{.(m+1)}.b
n #.inv#.(1+2*m)}.b
) |
http://rosettacode.org/wiki/Index_finite_lists_of_positive_integers | Index finite lists of positive integers | It is known that the set of finite lists of positive integers is countable.
This means that there exists a subset of natural integers which can be mapped to the set of finite lists of positive integers.
Task
Implement such a mapping:
write a function rank which assigns an integer to any finite, arbi... | #Java | Java | import java.math.BigInteger;
import static java.util.Arrays.stream;
import java.util.*;
import static java.util.stream.Collectors.*;
public class Test3 {
static BigInteger rank(int[] x) {
String s = stream(x).mapToObj(String::valueOf).collect(joining("F"));
return new BigInteger(s, 16);
}
... |
http://rosettacode.org/wiki/Integer_sequence | Integer sequence | Task
Create a program that, when run, would display all integers from 1 to ∞ (or any relevant implementation limit), in sequence (i.e. 1, 2, 3, 4, etc) if given enough time.
An example may not be able to reach arbitrarily-large numbers based on implementations limits. For example, if integer... | #Component_Pascal | Component Pascal |
MODULE IntegerSequence;
IMPORT StdLog;
PROCEDURE Do*;
VAR
i: INTEGER;
BEGIN
FOR i := 0 TO MAX(INTEGER) DO;
StdLog.Int(i)
END;
StdLog.Ln
END Do;
END IntegerSequence.
|
http://rosettacode.org/wiki/Integer_sequence | Integer sequence | Task
Create a program that, when run, would display all integers from 1 to ∞ (or any relevant implementation limit), in sequence (i.e. 1, 2, 3, 4, etc) if given enough time.
An example may not be able to reach arbitrarily-large numbers based on implementations limits. For example, if integer... | #Computer.2Fzero_Assembly | Computer/zero Assembly | start: ADD one
JMP start
one: 1 |
http://rosettacode.org/wiki/Infinity | Infinity | Task
Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity. Otherwise, return the largest possible po... | #E | E | def infinityTask() {
return Infinity # predefined variable holding positive infinity
} |
http://rosettacode.org/wiki/Infinity | Infinity | Task
Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity. Otherwise, return the largest possible po... | #Eiffel | Eiffel |
class
APPLICATION
inherit
ARGUMENTS
create
make
feature {NONE} -- Initialization
number:REAL_64
make
-- Run application.
do
number := 2^2000
print(number)
print("%N")
print(number.is_positive_infinity)
print("%N")
end
end
|
http://rosettacode.org/wiki/Inheritance/Multiple | Inheritance/Multiple | Multiple inheritance allows to specify that one class is a subclass of several other classes.
Some languages allow multiple inheritance for arbitrary classes, others restrict it to interfaces, some don't allow it at all.
Task
Write two classes (or interfaces) Camera and MobilePhone, then write a class Camer... | #OCaml | OCaml | class camera =
object (self)
(*functions go here...*)
end |
http://rosettacode.org/wiki/Inheritance/Multiple | Inheritance/Multiple | Multiple inheritance allows to specify that one class is a subclass of several other classes.
Some languages allow multiple inheritance for arbitrary classes, others restrict it to interfaces, some don't allow it at all.
Task
Write two classes (or interfaces) Camera and MobilePhone, then write a class Camer... | #Oforth | Oforth | Property new: Camera
Property new: MobilePhone
Object Class new: CameraPhone
CameraPhone is: Camera
CameraPhone is: MobilePhone |
http://rosettacode.org/wiki/Inheritance/Multiple | Inheritance/Multiple | Multiple inheritance allows to specify that one class is a subclass of several other classes.
Some languages allow multiple inheritance for arbitrary classes, others restrict it to interfaces, some don't allow it at all.
Task
Write two classes (or interfaces) Camera and MobilePhone, then write a class Camer... | #ooRexx | ooRexx |
-- inherited classes must be created as mixinclasses.
::class phone mixinclass object
::class camera mixinclass object
-- not a direct subclass of either, but inherits both
::class cameraphone inherit phone camera
-- could also be
::class cameraphone1 subclass phone inherit camera
-- or
::class cameraphone2... |
http://rosettacode.org/wiki/Inheritance/Multiple | Inheritance/Multiple | Multiple inheritance allows to specify that one class is a subclass of several other classes.
Some languages allow multiple inheritance for arbitrary classes, others restrict it to interfaces, some don't allow it at all.
Task
Write two classes (or interfaces) Camera and MobilePhone, then write a class Camer... | #OxygenBasic | OxygenBasic | class Camera
string cbuf
method TakePhoto()
end method
method ViewPhoto()
end method
end class
class MobilePhone
string pbuf
method MakeCall()
end method
method TakeCall()
end method
end class
class CameraPhone
has Camera,MobilePhone
end class
CameraPhone cp
cp.ViewPhoto
cp.MakeCall |
http://rosettacode.org/wiki/Increasing_gaps_between_consecutive_Niven_numbers | Increasing gaps between consecutive Niven numbers | Note: Niven numbers are also called Harshad numbers.
They are also called multidigital numbers.
Niven numbers are positive integers which are evenly divisible by the sum of its
digits (expressed in base ten).
Evenly divisible means divisible with no remainder.
Task
find the gap (differen... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[NivenQ]
$HistoryLength = 0;
NivenQ[n_Integer] := Divisible[n, Total[IntegerDigits[n]]]
sel = Select[Range[100000000], NivenQ];
i = FoldPairList[{#2 > #1, Max[#1, #2]} &, 0, Differences[sel]];
gapindex = Range[Count[i, True]];
nivenindex = Pick[Range[Length[i]], i];
nivennumber = Pick[Most[sel], i];
gap = sel[[... |
http://rosettacode.org/wiki/Increasing_gaps_between_consecutive_Niven_numbers | Increasing gaps between consecutive Niven numbers | Note: Niven numbers are also called Harshad numbers.
They are also called multidigital numbers.
Niven numbers are positive integers which are evenly divisible by the sum of its
digits (expressed in base ten).
Evenly divisible means divisible with no remainder.
Task
find the gap (differen... | #Nim | Nim | import strformat
func digitsSum(n, sum: uint64): uint64 =
## Returns the sum of the digits of n given the sum of the digits of n - 1.
result = sum + 1
var n = n
while n > 0 and n mod 10 == 0:
dec result, 9
n = n div 10
func divisible(n, d: uint64): bool {.inline.} =
if (d and 1) == 0 and (n and 1)... |
http://rosettacode.org/wiki/Increasing_gaps_between_consecutive_Niven_numbers | Increasing gaps between consecutive Niven numbers | Note: Niven numbers are also called Harshad numbers.
They are also called multidigital numbers.
Niven numbers are positive integers which are evenly divisible by the sum of its
digits (expressed in base ten).
Evenly divisible means divisible with no remainder.
Task
find the gap (differen... | #Pascal | Pascal | program NivenGaps;
{$IFDEF FPC}
{$MODE DELPHI}
{$OPTIMIZATION ON,ALL}
{$ELSE}
{$APPTYPE DELPHI}
{$ENDIF}
uses
sysutils,
strutils;
const
base = 10;
type
tNum = Uint64;
const
cntbasedigits = ((trunc(ln(High(tNum))/ln(base))+1) DIV 8 +1) *8;
type
tSumDigit = record
sdDigits : array[... |
http://rosettacode.org/wiki/Integer_overflow | Integer overflow | Some languages support one or more integer types of the underlying processor.
This integer types have fixed size; usually 8-bit, 16-bit, 32-bit, or 64-bit.
The integers supported by such a type can be signed or unsigned.
Arithmetic for machine level integers can often be done by single CPU instruct... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | $MaxNumber +
10^-15.954589770191003298111788092733772206160314 $MaxNumber |
http://rosettacode.org/wiki/Integer_overflow | Integer overflow | Some languages support one or more integer types of the underlying processor.
This integer types have fixed size; usually 8-bit, 16-bit, 32-bit, or 64-bit.
The integers supported by such a type can be signed or unsigned.
Arithmetic for machine level integers can often be done by single CPU instruct... | #Nim | Nim | try:
var x: int32 = -2147483647
x = -(x - 1) # Raise overflow.
echo x
except OverflowDefect:
echo "Overflow detected" |
http://rosettacode.org/wiki/Input_loop | Input loop | Input loop is part of Short Circuit's Console Program Basics selection.
Task
Read from a text stream either word-by-word or line-by-line until the stream runs out of data.
The stream will have an unknown amount of data on it.
| #Euphoria | Euphoria | procedure process_line_by_line(integer fn)
object line
while 1 do
line = gets(fn)
if atom(line) then
exit
end if
-- process the line
end while
end procedure |
http://rosettacode.org/wiki/Input_loop | Input loop | Input loop is part of Short Circuit's Console Program Basics selection.
Task
Read from a text stream either word-by-word or line-by-line until the stream runs out of data.
The stream will have an unknown amount of data on it.
| #F.23 | F# |
let lines_of_file file =
seq { use stream = System.IO.File.OpenRead file
use reader = new System.IO.StreamReader(stream)
while not reader.EndOfStream do
yield reader.ReadLine() }
|
http://rosettacode.org/wiki/Isqrt_(integer_square_root)_of_X | Isqrt (integer square root) of X | Sometimes a function is needed to find the integer square root of X, where X can be a
real non─negative number.
Often X is actually a non─negative integer.
For the purposes of this task, X can be an integer or a real number, but if it
simplifies things in your computer programming language, assume... | #Raku | Raku | use Lingua::EN::Numbers;
sub isqrt ( \x ) { my ( $X, $q, $r, $t ) = x, 1, 0 ;
$q +<= 2 while $q ≤ $X ;
while $q > 1 {
$q +>= 2; $t = $X - $r - $q; $r +>= 1;
if $t ≥ 0 { $X = $t; $r += $q }
}
$r
}
say (^66)».&{ isqrt $_ }.Str ;
(1, 3…73)».&{ "7**$_: " ~ comma(isqrt 7**$_) }».say |
http://rosettacode.org/wiki/Inverted_index | Inverted index | An Inverted Index is a data structure used to create full text search.
Task
Given a set of text files, implement a program to create an inverted index.
Also create a user interface to do a search using that inverted index which returns a list of files that contain the query term / terms.
The search index can be i... | #Kotlin | Kotlin | // version 1.1.51
import java.io.File
val invIndex = mutableMapOf<String, MutableList<Location>>()
val fileNames = mutableListOf<String>()
val splitter = Regex("""\W+""")
class Location(val fileName: String, val wordNum: Int) {
override fun toString() = "{$fileName, word number $wordNum}"
}
fun indexFile(... |
http://rosettacode.org/wiki/Introspection | Introspection | Task
verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old.
check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs(bloop).
Extra credit
Repor... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | If[$VersionNumber < 8, Quit[]]
If[NameQ["bloop"] && NameQ["Abs"],
Print[Abs[bloop]]] |
http://rosettacode.org/wiki/Introspection | Introspection | Task
verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old.
check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs(bloop).
Extra credit
Repor... | #MATLAB_.2F_Octave | MATLAB / Octave | % convert version into numerical value
v = version;
v(v=='.')=' ';
v = str2num(v);
if v(2)>10; v(2) = v(2)/10; end;
ver = v(1)+v(2)/10;
if exist('OCTAVE_VERSION','builtin')
if ver < 3.0,
exit
end;
else
if ver < 7.0,
exit
end;
end
% test ... |
http://rosettacode.org/wiki/Josephus_problem | Josephus problem | Josephus problem is a math puzzle with a grim description:
n
{\displaystyle n}
prisoners are standing on a circle, sequentially numbered from
0
{\displaystyle 0}
to
n
−
1
{\displaystyle n-1}
.
An executioner walks along the circle, starting from prisoner
0
{\displaystyle 0}
,
removing eve... | #Nanoquery | Nanoquery | def j(n, k)
p = list(range(0, n-1))
i = 0
seq = {}
while len(p) > 0
i = (i+k-1) % len(p)
seq.append(p[i])
p.remove(i)
end
sur = seq[len(seq) - 1]; seq.remove(len(seq) - 1)
return format("Prisoner killing order: %s\nS... |
http://rosettacode.org/wiki/Interactive_programming_(repl) | Interactive programming (repl) | Many language implementations come with an interactive mode.
This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions.
An interactive mode may also be known as a command mode, a read-eval-print loop (REPL), or a shell.
Task
Show how to start this... | #Phix | Phix | C:\Program Files (x86)\Phix>p -repl
Warning: the repl is brand new, experimental, incomplete, and liable to crash!
Enter a statement such as "?remainder(floor(250/8),8)" or "puts(1,"Hi")"
>function f(string a,b,c) return a&c&c&b end function
>?f("Rosetta","Code",":")
"Rosetta::Code"
>quit
C:\Program Files (x86)\Phix... |
http://rosettacode.org/wiki/Interactive_programming_(repl) | Interactive programming (repl) | Many language implementations come with an interactive mode.
This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions.
An interactive mode may also be known as a command mode, a read-eval-print loop (REPL), or a shell.
Task
Show how to start this... | #Picat | Picat | Picat> cl
f(X,Y,Sep) = X ++ [Sep,Sep] ++ Y.
<Ctrl-D>
Picat> print(f("Rosetta","Code",':'))
Rosetta::Code
yes |
http://rosettacode.org/wiki/Interactive_programming_(repl) | Interactive programming (repl) | Many language implementations come with an interactive mode.
This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions.
An interactive mode may also be known as a command mode, a read-eval-print loop (REPL), or a shell.
Task
Show how to start this... | #PicoLisp | PicoLisp | $ pil + |
http://rosettacode.org/wiki/ISBN13_check_digit | ISBN13 check digit | Task
Validate the check digit of an ISBN-13 code:
Multiply every other digit by 3.
Add these numbers and the other digits.
Take the remainder of this number after division by 10.
If it is 0, the ISBN-13 check digit is correct.
Use the following codes for testing:
978-1734314502 (good)
... | #REXX | REXX | /*REXX pgm validates the check digit of an ISBN─13 code (it may have embedded minuses).*/
parse arg $ /*obtain optional arguments from the CL*/
if $='' | if $="," then $= '978-1734314502 978-1734314509 978-1788399081 978-1788399083'
@ISBN= "ISBN─13 code isn't" ... |
http://rosettacode.org/wiki/Jaro_similarity | Jaro similarity | The Jaro distance is a measure of edit distance between two strings; its inverse, called the Jaro similarity, is a measure of two strings' similarity: the higher the value, the more similar the strings are. The score is normalized such that 0 equates to no similarities and 1 is an exact match.
Definition
The... | #zkl | zkl | //-->String of matched characters, ordered
fcn _jaro(str1,str2, matchDistance){
cs:=Sink(String);
foreach i,c in ([0..].zip(str1)){
str2.find(c,(0).max(i - matchDistance),i + matchDistance) :
if(Void!=_) cs.write(c);
}
cs.close()
}
fcn jaro(str1,str2){
s1Len,s2Len,matchDistance := str1.l... |
http://rosettacode.org/wiki/Increment_a_numerical_string | Increment a numerical string | Task
Increment a numerical string.
| #Ada | Ada | S : String := "12345";
S := Ada.Strings.Fixed.Trim(Source => Integer'Image(Integer'Value(S) + 1), Side => Ada.Strings.Both); |
http://rosettacode.org/wiki/Integer_comparison | Integer comparison |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #Arturo | Arturo | a: to :integer input "enter a value for a: "
b: to :integer input "enter a value for b: "
if a<b [ print [ a "is less than" b ] ]
if a>b [ print [ a "is greater than" b ] ]
if a=b [ print [ a "is equal to" b ] ] |
http://rosettacode.org/wiki/Include_a_file | Include a file | Task
Demonstrate the language's ability to include source code from other files.
See Also
Compiler/Simple file inclusion pre processor
| #Applesoft_BASIC | Applesoft BASIC | 10 REMPROGRAM TWO
20 DEF FN A(X) = X * Y
30 PRINT FN A(2)
SAVE PROGRAM TWO |
http://rosettacode.org/wiki/Include_a_file | Include a file | Task
Demonstrate the language's ability to include source code from other files.
See Also
Compiler/Simple file inclusion pre processor
| #ARM_Assembly | ARM Assembly |
'file constantes.inc'
/************************************/
/* Constantes */
/************************************/
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall end program
.equ WRITE, 4 @ Linux syscall write
.equ BRK, 0x2d ... |
http://rosettacode.org/wiki/Inheritance/Single | Inheritance/Single | This task is about derived types; for implementation inheritance, see Polymorphism.
Inheritance is an operation of type algebra that creates a new type from one or several parent types.
The obtained type is called derived type.
It inherits some of the properties of its parent types.
Usually inherited properties... | #Go | Go | package main
type animal struct {
alive bool
}
type dog struct {
animal
obedienceTrained bool
}
type cat struct {
animal
litterBoxTrained bool
}
type lab struct {
dog
color string
}
type collie struct {
dog
catchesFrisbee bool
}
func main() {
var pet lab
pet.alive... |
http://rosettacode.org/wiki/Inheritance/Single | Inheritance/Single | This task is about derived types; for implementation inheritance, see Polymorphism.
Inheritance is an operation of type algebra that creates a new type from one or several parent types.
The obtained type is called derived type.
It inherits some of the properties of its parent types.
Usually inherited properties... | #Groovy | Groovy | class Animal{
//contents go here...
} |
http://rosettacode.org/wiki/Idiomatically_determine_all_the_lowercase_and_uppercase_letters | Idiomatically determine all the lowercase and uppercase letters |
Idiomatically determine all the lowercase and uppercase letters (of the Latin [English] alphabet) being used currently by a computer programming language.
The method should find the letters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other).
Task requirements
Display the set of... | #Arturo | Arturo | print ["lowercase letters:" `a`..`z`]
print ["uppercase letters:" `A`..`Z`] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.