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/Algebraic_data_types | Algebraic data types | Some languages offer direct support for algebraic data types and pattern matching on them. While this of course can always be simulated with manual tagging and conditionals, it allows for terse code which is easy to read, and can represent the algorithm directly.
Task
As an example, implement insertion in a red-bla... | #Erlang | Erlang |
-module(rbtree).
-export([insert/3, find/2]).
% Node structure: { Key, Value, Color, Smaller, Bigger }
find(_, nil) ->
not_found;
find(Key, { Key, Value, _, _, _ }) ->
{ found, { Key, Value } };
find(Key, { Key1, _, _, Left, _ }) when Key < Key1 ->
find(Key, Left);
find(Key, { Key1, _, _, _, Right }) when K... |
http://rosettacode.org/wiki/Almost_prime | Almost prime | A k-Almost-prime is a natural number
n
{\displaystyle n}
that is the product of
k
{\displaystyle k}
(possibly identical) primes.
Example
1-almost-primes, where
k
=
1
{\displaystyle k=1}
, are the prime numbers themselves.
2-almost-primes, where
k
=
2
{\displaystyl... | #CLU | CLU | kprime = proc (n,k: int) returns (bool)
f: int := 0
p: int := 2
while f<k & p*p<=n do
while n//p=0 do
n := n/p
f := f+1
end
p := p+1
end
if n>1 then f:=f+1 end
return(f=k)
end kprime
start_up = proc ()
po: stream := stream$primary_output()
... |
http://rosettacode.org/wiki/Almost_prime | Almost prime | A k-Almost-prime is a natural number
n
{\displaystyle n}
that is the product of
k
{\displaystyle k}
(possibly identical) primes.
Example
1-almost-primes, where
k
=
1
{\displaystyle k=1}
, are the prime numbers themselves.
2-almost-primes, where
k
=
2
{\displaystyl... | #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. ALMOST-PRIME.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 CONTROL-VARS.
03 K PIC 9.
03 I PIC 999.
03 SEEN PIC 99.
03 N PIC 999.
03 P PI... |
http://rosettacode.org/wiki/Anagrams | Anagrams | When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in them.
Related tasks
Word plays
... | #AutoHotkey | AutoHotkey | FileRead, Contents, unixdict.txt
Loop, Parse, Contents, % "`n", % "`r"
{ ; parsing each line of the file we just read
Loop, Parse, A_LoopField ; parsing each letter/character of the current word
Dummy .= "," A_LoopField
Sort, Dummy, % "D," ; sorting those letters before removing the delimiters (comma)
... |
http://rosettacode.org/wiki/Angle_difference_between_two_bearings | Angle difference between two bearings | Finding the angle between two bearings is often confusing.[1]
Task
Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings.
Input bearings are expressed in the range -180 to +180 degrees.
The result is also expressed in the range -180 to +180 degrees.
... | #Klingphix | Klingphix | include ..\Utilitys.tlhy
:bearing sub 360 mod 540 add 360 mod 180 sub ;
20 45 bearing
-45 45 bearing
-85 90 bearing
-95 90 bearing
-45 125 bearing
-45 145 bearing
29.4803 -88.6381 bearing
-78.3251 -159.036 bearing
-70099.74233810938 29840.67437876723 bearing
-165313.6666297357 33693.9894517456 bearing
1174.83805105... |
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams | Anagrams/Deranged anagrams | Two or more words are said to be anagrams if they have the same characters, but in a different order.
By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words.
Task[edit]
Use the word list at uni... | #ooRexx | ooRexx | -- This assumes you've already downloaded the following file and placed it
-- in the current directory: http://www.puzzlers.org/pub/wordlists/unixdict.txt
-- There are several different ways of reading the file. I chose the
-- supplier method just because I haven't used it yet in any other examples.
source = .stream... |
http://rosettacode.org/wiki/Anonymous_recursion | Anonymous recursion | While implementing a recursive function, it often happens that we must resort to a separate helper function to handle the actual recursion.
This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects, and/or the f... | #Klingphix | Klingphix | include ..\Utilitys.tlhy
:fib %f !f
%fr
[ %n !n
$n 2 <
( [$n]
[$n 1 - $fr eval $n 2 - $fr eval +] )
if
] !fr
$f 0 <
( ["Error: number is negative"]
[$f true $fr if] )
if
;
25 fib ?
msec ?
"End " input |
http://rosettacode.org/wiki/Amicable_pairs | Amicable pairs | Two integers
N
{\displaystyle N}
and
M
{\displaystyle M}
are said to be amicable pairs if
N
≠
M
{\displaystyle N\neq M}
and the sum of the proper divisors of
N
{\displaystyle N}
(
s
u
m
(
p
r
o
p
D
i
v
s
(
N
)
)
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (N))}
)
=
M
... | #GFA_Basic | GFA Basic |
OPENW 1
CLEARW 1
'
DIM f%(20001) ! sum of proper factors for each n
FOR i%=1 TO 20000
f%(i%)=@sum_proper_divisors(i%)
NEXT i%
' look for pairs
FOR i%=1 TO 20000
FOR j%=i%+1 TO 20000
IF f%(i%)=j% AND i%=f%(j%)
PRINT "Amicable pair ";i%;" ";j%
ENDIF
NEXT j%
NEXT i%
'
PRINT
PRINT "-- found all amicab... |
http://rosettacode.org/wiki/Animation | Animation |
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demonstrates this.
Task
Creat... | #Python | Python | #!/usr/bin/env python3
import sys
from PyQt5.QtCore import QBasicTimer, Qt
from PyQt5.QtGui import QFont
from PyQt5.QtWidgets import QApplication, QLabel
class Marquee(QLabel):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.right_to_left_direction = True
self.initUI()
... |
http://rosettacode.org/wiki/Animate_a_pendulum | Animate a pendulum |
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display.
The classic such physical system is a simple gravity pendulum.
Task
Create a simple physical model of a pendulum and animate it.
| #Liberty_BASIC | Liberty BASIC | nomainwin
WindowWidth = 400
WindowHeight = 300
open "Pendulum" for graphics_nsb_nf as #main
#main "down;fill white; flush"
#main "color black"
#main "trapclose [quit.main]"
Angle = asn(1)
DeltaT = 0.1
PendLength = 150
FixX = int(WindowWidth / 2)
FixY = 40
timer 30, ... |
http://rosettacode.org/wiki/Amb | Amb | Define and give an example of the Amb operator.
The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton").
The Amb operator takes a v... | #C.23 | C# | using System;
using System.Collections.Generic;
public class Amb : IDisposable
{
List<IValueSet> streams = new List<IValueSet>();
List<IAssertOrAction> assertsOrActions = new List<IAssertOrAction>();
volatile bool stopped = false;
public IAmbValue<T> DefineValues<T>(params T[] values)
{
... |
http://rosettacode.org/wiki/Aliquot_sequence_classifications | Aliquot sequence classifications | An aliquot sequence of a positive integer K is defined recursively as the first member
being K and subsequent members being the sum of the Proper divisors of the previous term.
If the terms eventually reach 0 then the series for K is said to terminate.
There are several classifications for non termination:
If the s... | #AppleScript | AppleScript | on aliquotSum(n)
if (n < 2) then return 0
set sum to 1
set sqrt to n ^ 0.5
set limit to sqrt div 1
if (limit = sqrt) then
set sum to sum + limit
set limit to limit - 1
end if
repeat with i from 2 to limit
if (n mod i is 0) then set sum to sum + i + n div i
end rep... |
http://rosettacode.org/wiki/Address_of_a_variable | Address of a variable |
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 | x: 2
xInfo: info.get 'x
print [
"address of x:" xInfo\address
"->" from.hex xInfo\address
] |
http://rosettacode.org/wiki/Address_of_a_variable | Address of a variable |
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 |... | #Astro | Astro | var num = 12
var pointer = ptr(num) # get pointer
print pointer # print address
@unsafe # bad idea!
pointer.addr = 0xFFFE # set the address
|
http://rosettacode.org/wiki/Address_of_a_variable | Address of a variable |
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 |... | #AutoHotkey | AutoHotkey | msgbox % &var |
http://rosettacode.org/wiki/AKS_test_for_primes | AKS test for primes | The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles.
The theorem on which the test is based can be stated as follows:
a number
p
{\displaystyle p}
is prime if and only if all the coefficients of the polynomial ... | #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B or android 64 bits */
/* program AKS64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../inclu... |
http://rosettacode.org/wiki/Additive_primes | Additive primes | Definitions
In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes.
Task
Write a program to determine (and show here) all additive primes less than 500.
Optionally, show the number of additive primes.
Also see
the OEIS entry: A046704 additive primes.
... | #ALGOL_68 | ALGOL 68 | BEGIN # find additive primes - primes whose digit sum is also prime #
# sieve the primes to max prime #
PR read "primes.incl.a68" PR
[]BOOL prime = PRIMESIEVE 499;
# find the additive primes #
INT additive count := 0;
FOR n TO UPB prime DO
IF prime[ n ] THEN
# have a prime #
... |
http://rosettacode.org/wiki/Algebraic_data_types | Algebraic data types | Some languages offer direct support for algebraic data types and pattern matching on them. While this of course can always be simulated with manual tagging and conditionals, it allows for terse code which is easy to read, and can represent the algorithm directly.
Task
As an example, implement insertion in a red-bla... | #F.23 | F# |
// Pattern Matching. Nigel Galloway: January 15th., 2021
type colour= |Red |Black
type rbT<'N>= |Empty |N of colour * rbT<'N> * rbT<'N> * 'N
let repair=function |Black,N(Red,N(Red,ll,lr,lv),rl,v),rr,rv
|Black,N(Red,ll,N(Red,lr,rl,v),lv),rr,rv
|Black,ll,N(Red,N(Red,lr,rl,v),rr,r... |
http://rosettacode.org/wiki/Algebraic_data_types | Algebraic data types | Some languages offer direct support for algebraic data types and pattern matching on them. While this of course can always be simulated with manual tagging and conditionals, it allows for terse code which is easy to read, and can represent the algorithm directly.
Task
As an example, implement insertion in a red-bla... | #Go | Go | package main
import "fmt"
type Color string
const (
R Color = "R"
B = "B"
)
type Tree interface {
ins(x int) Tree
}
type E struct{}
func (_ E) ins(x int) Tree {
return T{R, E{}, x, E{}}
}
func (_ E) String() string {
return "E"
}
type T struct {
cl Color
le Tree
aa ... |
http://rosettacode.org/wiki/Almost_prime | Almost prime | A k-Almost-prime is a natural number
n
{\displaystyle n}
that is the product of
k
{\displaystyle k}
(possibly identical) primes.
Example
1-almost-primes, where
k
=
1
{\displaystyle k=1}
, are the prime numbers themselves.
2-almost-primes, where
k
=
2
{\displaystyl... | #Common_Lisp | Common Lisp | (defun start ()
(loop for k from 1 to 5
do (format t "k = ~a: ~a~%" k (collect-k-almost-prime k))))
(defun collect-k-almost-prime (k &optional (d 2) (lst nil))
(cond ((= (length lst) 10) (reverse lst))
((= (?-primality d) k) (collect-k-almost-prime k (+ d 1) (cons d lst)))
(t (collect-k-almost... |
http://rosettacode.org/wiki/Anagrams | Anagrams | When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in them.
Related tasks
Word plays
... | #AWK | AWK | # JUMBLEA.AWK - words with the most duplicate spellings
# syntax: GAWK -f JUMBLEA.AWK UNIXDICT.TXT
{ for (i=1; i<=NF; i++) {
w = sortstr(toupper($i))
arr[w] = arr[w] $i " "
n = gsub(/ /,"&",arr[w])
if (max_n < n) { max_n = n }
}
}
END {
for (w in arr) {
if (gsub(/ /,"&",arr[w]) =... |
http://rosettacode.org/wiki/Angle_difference_between_two_bearings | Angle difference between two bearings | Finding the angle between two bearings is often confusing.[1]
Task
Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings.
Input bearings are expressed in the range -180 to +180 degrees.
The result is also expressed in the range -180 to +180 degrees.
... | #Kotlin | Kotlin | // version 1.1.2
class Angle(d: Double) {
val value = when {
d in -180.0 .. 180.0 -> d
d > 180.0 -> (d - 180.0) % 360.0 - 180.0
else -> (d + 180.0) % 360.0 + 180.0
}
operator fun minus(other: Angle) = Angle(this.value - other.value)
}
fun main(args: Arra... |
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams | Anagrams/Deranged anagrams | Two or more words are said to be anagrams if they have the same characters, but in a different order.
By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words.
Task[edit]
Use the word list at uni... | #PARI.2FGP | PARI/GP | dict=readstr("unixdict.txt");
len=apply(s->#s, dict);
getLen(L)=my(v=List()); for(i=1,#dict, if(len[i]==L, listput(v, dict[i]))); Vec(v);
letters(s)=vecsort(Vec(s));
getAnagrams(v)=my(u=List(),L=apply(letters,v),t,w); for(i=1,#v-1, w=List(); t=L[i]; for(j=i+1,#v, if(L[j]==t, listput(w, v[j]))); if(#w, listput(u, concat... |
http://rosettacode.org/wiki/Anonymous_recursion | Anonymous recursion | While implementing a recursive function, it often happens that we must resort to a separate helper function to handle the actual recursion.
This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects, and/or the f... | #Klong | Klong |
fib::{:[x<0;"error: negative":|x<2;x;.f(x-1)+.f(x-2)]}
|
http://rosettacode.org/wiki/Amicable_pairs | Amicable pairs | Two integers
N
{\displaystyle N}
and
M
{\displaystyle M}
are said to be amicable pairs if
N
≠
M
{\displaystyle N\neq M}
and the sum of the proper divisors of
N
{\displaystyle N}
(
s
u
m
(
p
r
o
p
D
i
v
s
(
N
)
)
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (N))}
)
=
M
... | #Go | Go | package main
import "fmt"
func pfacSum(i int) int {
sum := 0
for p := 1; p <= i/2; p++ {
if i%p == 0 {
sum += p
}
}
return sum
}
func main() {
var a[20000]int
for i := 1; i < 20000; i++ {
a[i] = pfacSum(i)
}
fmt.Println("The amicable pairs below ... |
http://rosettacode.org/wiki/Animation | Animation |
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demonstrates this.
Task
Creat... | #Quick_BASIC | Quick BASIC |
'here accordingly to the version, QB or QBX
REM $INCLUDE: 'QBX.BI'
DIM REGS AS REGTYPE
DIM C AS STRING, SIZ AS INTEGER
DIM I AS DOUBLE, DIRE AS INTEGER
C = "Hello World! "
SIZ = LEN(C)
SCREEN 12
'turn the cursor visible
REGS.AX = 1
INTERRUPT 51, REGS, REGS
DO
I = TIMER
LOCATE 1, 1
PRINT C
REGS.AX = 5 ... |
http://rosettacode.org/wiki/Animate_a_pendulum | Animate a pendulum |
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display.
The classic such physical system is a simple gravity pendulum.
Task
Create a simple physical model of a pendulum and animate it.
| #Lingo | Lingo | global RODLEN, GRAVITY, DT
global velocity, acceleration, angle, posX, posY
on startMovie
-- window properties
_movie.stage.title = "Pendulum"
_movie.stage.titlebarOptions.visible = TRUE
_movie.stage.rect = rect(0, 0, 400, 400)
_movie.centerStage = TRUE
_movie.puppetTempo(30)
RODLEN = ... |
http://rosettacode.org/wiki/Amb | Amb | Define and give an example of the Amb operator.
The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton").
The Amb operator takes a v... | #C.2B.2B | C++ | #include <iostream>
#include <string_view>
#include <boost/hana.hpp>
#include <boost/hana/experimental/printable.hpp>
using namespace std;
namespace hana = boost::hana;
// Define the Amb function. The first parameter is the constraint to be
// enforced followed by the potential values.
constexpr auto Amb(auto cons... |
http://rosettacode.org/wiki/Aliquot_sequence_classifications | Aliquot sequence classifications | An aliquot sequence of a positive integer K is defined recursively as the first member
being K and subsequent members being the sum of the Proper divisors of the previous term.
If the terms eventually reach 0 then the series for K is said to terminate.
There are several classifications for non termination:
If the s... | #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program aliquotSeq.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* for constantes see task include a fil... |
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user | Active Directory/Search for a user | Make sure you Connect to Active Directory
| #C | C | #include <ldap.h>
char *name, *password;
...
LDAP *ld = ldap_init("ldap.somewhere.com", 389);
ldap_simple_bind_s(ld, name, password);
LDAPMessage **result;
ldap_search_s(ld, "dc=somewhere,dc=com", LDAP_SCOPE_SUBTREE,
/* search for all persons whose names start with joe or shmoe */
"(&(objectclass=person)(|(cn=j... |
http://rosettacode.org/wiki/Address_of_a_variable | Address of a variable |
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 |... | #Axe | Axe | °A→B
.B now contains the address of A |
http://rosettacode.org/wiki/Address_of_a_variable | Address of a variable |
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 |... | #BaCon | BaCon |
'---get a variable's address
LOCAL x TYPE long
PRINT ADDRESS(x)
|
http://rosettacode.org/wiki/Address_of_a_variable | Address of a variable |
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 |... | #BASIC | BASIC | 'get a variable's address:
DIM x AS INTEGER, y AS LONG
y = VARPTR(x)
'can't set the address, but can access a given memory location... 1 byte at a time
DIM z AS INTEGER
z = PEEK(y)
z = z + (PEEK(y) * 256) |
http://rosettacode.org/wiki/AKS_test_for_primes | AKS test for primes | The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles.
The theorem on which the test is based can be stated as follows:
a number
p
{\displaystyle p}
is prime if and only if all the coefficients of the polynomial ... | #Ada | Ada | with Ada.Text_IO;
procedure Test_For_Primes is
type Pascal_Triangle_Type is array (Natural range <>) of Long_Long_Integer;
function Calculate_Pascal_Triangle (N : in Natural) return Pascal_Triangle_Type is
Pascal_Triangle : Pascal_Triangle_Type (0 .. N);
begin
Pascal_Triangle (0) := 1;
... |
http://rosettacode.org/wiki/Additive_primes | Additive primes | Definitions
In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes.
Task
Write a program to determine (and show here) all additive primes less than 500.
Optionally, show the number of additive primes.
Also see
the OEIS entry: A046704 additive primes.
... | #ALGOL_W | ALGOL W | begin % find some additive primes - primes whose digit sum is also prime %
% sets p( 1 :: n ) to a sieve of primes up to n %
procedure Eratosthenes ( logical array p( * ) ; integer value n ) ;
begin
p( 1 ) := false; p( 2 ) := true;
for i := 3 step 2 until n do p( i ) := true;
for i :... |
http://rosettacode.org/wiki/Additive_primes | Additive primes | Definitions
In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes.
Task
Write a program to determine (and show here) all additive primes less than 500.
Optionally, show the number of additive primes.
Also see
the OEIS entry: A046704 additive primes.
... | #APL | APL | ((+⌿(4/10)⊤P)∊P)/P←(~P∊P∘.×P)/P←1↓⍳500 |
http://rosettacode.org/wiki/Algebraic_data_types | Algebraic data types | Some languages offer direct support for algebraic data types and pattern matching on them. While this of course can always be simulated with manual tagging and conditionals, it allows for terse code which is easy to read, and can represent the algorithm directly.
Task
As an example, implement insertion in a red-bla... | #Haskell | Haskell | data Color = R | B
data Tree a = E | T Color (Tree a) a (Tree a)
balance :: Color -> Tree a -> a -> Tree a -> Tree a
balance B (T R (T R a x b) y c ) z d = T R (T B a x b) y (T B c z d)
balance B (T R a x (T R b y c)) z d = T R (T B a x b)... |
http://rosettacode.org/wiki/Algebraic_data_types | Algebraic data types | Some languages offer direct support for algebraic data types and pattern matching on them. While this of course can always be simulated with manual tagging and conditionals, it allows for terse code which is easy to read, and can represent the algorithm directly.
Task
As an example, implement insertion in a red-bla... | #J | J | insert=:{{
'R';'';y;a:
:
if. 0=#y do. insert x
elseif. 0=L.y do. x insert insert y
else.
'C e K w'=. y
select. *x - K
case. _1 do. balance C;(x insert e);K;<w
case. 0 do. y
case. 1 do. balance C;e;K;<x insert w
end.
end.
}}
NB. C: color, e: east, K: key, w: west
NB. two casc... |
http://rosettacode.org/wiki/Almost_prime | Almost prime | A k-Almost-prime is a natural number
n
{\displaystyle n}
that is the product of
k
{\displaystyle k}
(possibly identical) primes.
Example
1-almost-primes, where
k
=
1
{\displaystyle k=1}
, are the prime numbers themselves.
2-almost-primes, where
k
=
2
{\displaystyl... | #Cowgol | Cowgol | include "cowgol.coh";
sub kprime(n: uint8, k: uint8): (kp: uint8) is
var p: uint8 := 2;
var f: uint8 := 0;
while f < k and p*p <= n loop
while 0 == n % p loop
n := n / p;
f := f + 1;
end loop;
p := p + 1;
end loop;
if n > 1 then
f := f + 1;
... |
http://rosettacode.org/wiki/Almost_prime | Almost prime | A k-Almost-prime is a natural number
n
{\displaystyle n}
that is the product of
k
{\displaystyle k}
(possibly identical) primes.
Example
1-almost-primes, where
k
=
1
{\displaystyle k=1}
, are the prime numbers themselves.
2-almost-primes, where
k
=
2
{\displaystyl... | #D | D | import std.stdio, std.algorithm, std.traits;
Unqual!T[] decompose(T)(in T number) pure nothrow
in {
assert(number > 1);
} body {
typeof(return) result;
Unqual!T n = number;
for (Unqual!T i = 2; n % i == 0; n /= i)
result ~= i;
for (Unqual!T i = 3; n >= i * i; i += 2)
for (; n % i... |
http://rosettacode.org/wiki/Anagrams | Anagrams | When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in them.
Related tasks
Word plays
... | #BaCon | BaCon | OPTION COLLAPSE TRUE
DECLARE idx$ ASSOC STRING
FOR w$ IN LOAD$("unixdict.txt") STEP NL$
set$ = SORT$(EXPLODE$(w$, 1))
idx$(set$) = APPEND$(idx$(set$), 0, w$)
total = AMOUNT(idx$(set$))
IF MaxCount < total THEN MaxCount = total
NEXT
PRINT "Analyzing took ", TIMER, " msecs.", NL$
LOOKUP idx$... |
http://rosettacode.org/wiki/Angle_difference_between_two_bearings | Angle difference between two bearings | Finding the angle between two bearings is often confusing.[1]
Task
Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings.
Input bearings are expressed in the range -180 to +180 degrees.
The result is also expressed in the range -180 to +180 degrees.
... | #Lua | Lua | bearing = {degrees = 0} -- prototype object
function bearing:assign(angle)
angle = tonumber(angle) or 0
while angle > 180 do
angle = angle - 360
end
while angle < -180 do
angle = angle + 360
end
self.degrees = angle
end
function bearing:new(size)
local child_object = {}
setmetatable(child_object, {__ind... |
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams | Anagrams/Deranged anagrams | Two or more words are said to be anagrams if they have the same characters, but in a different order.
By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words.
Task[edit]
Use the word list at uni... | #Pascal | Pascal | program Anagrams_Deranged;
{$IFDEF FPC}
{$MODE Delphi}
{$Optimization ON,ALL}
uses
SysUtils,
Classes;
{$ELSE}
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.Classes,
{$R *.res}
{$ENDIF}
function Sort(const s: string):string;
//insertion sort
var
pRes : pchar;
i, j, aLength: NativeInt;
tmpc: Cha... |
http://rosettacode.org/wiki/Anonymous_recursion | Anonymous recursion | While implementing a recursive function, it often happens that we must resort to a separate helper function to handle the actual recursion.
This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects, and/or the f... | #Kotlin | Kotlin | fun fib(n: Int): Int {
require(n >= 0)
fun fib1(k: Int, a: Int, b: Int): Int =
if (k == 0) a else fib1(k - 1, b, a + b)
return fib1(n, 0, 1)
}
fun main(args: Array<String>) {
for (i in 0..20) print("${fib(i)} ")
println()
} |
http://rosettacode.org/wiki/Amicable_pairs | Amicable pairs | Two integers
N
{\displaystyle N}
and
M
{\displaystyle M}
are said to be amicable pairs if
N
≠
M
{\displaystyle N\neq M}
and the sum of the proper divisors of
N
{\displaystyle N}
(
s
u
m
(
p
r
o
p
D
i
v
s
(
N
)
)
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (N))}
)
=
M
... | #Haskell | Haskell | divisors :: (Integral a) => a -> [a]
divisors n = filter ((0 ==) . (n `mod`)) [1 .. (n `div` 2)]
main :: IO ()
main = do
let range = [1 .. 20000 :: Int]
divs = zip range $ map (sum . divisors) range
pairs = [(n, m) | (n, nd) <- divs, (m, md) <- divs,
n < m, nd == m, md == n]
print pairs |
http://rosettacode.org/wiki/Animation | Animation |
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demonstrates this.
Task
Creat... | #R | R |
rotate_string <- function(x, forwards)
{
nchx <- nchar(x)
if(forwards)
{
paste(substr(x, nchx, nchx), substr(x, 1, nchx - 1), sep = "")
} else
{
paste(substr(x, 2, nchx), substr(x, 1, 1), sep... |
http://rosettacode.org/wiki/Animation | Animation |
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demonstrates this.
Task
Creat... | #Racket | Racket |
#lang racket/gui
;; One of 'left or 'right
(define direction 'left)
;; Set up the GUI
(define animation-frame%
(class frame%
(super-new [label "Animation"])
;; reverse direction on a click
(define/override (on-subwindow-event win evt)
(when (send evt button-down?)
(... |
http://rosettacode.org/wiki/Animate_a_pendulum | Animate a pendulum |
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display.
The classic such physical system is a simple gravity pendulum.
Task
Create a simple physical model of a pendulum and animate it.
| #Logo | Logo | make "angle 45
make "L 1
make "bob 10
to draw.pendulum
clearscreen
seth :angle+180 ; down on screen is 180
forward :L*100-:bob
penup
forward :bob
pendown
arc 360 :bob
end
make "G 9.80665
make "dt 1/30
make "acc 0
make "vel 0
to step.pendulum
make "acc -:G / :L * sin :angle
make "vel :vel ... |
http://rosettacode.org/wiki/Amb | Amb | Define and give an example of the Amb operator.
The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton").
The Amb operator takes a v... | #Clojure | Clojure | (ns amb
(:use clojure.contrib.monads))
(defn amb [wss]
(let [valid-word (fn [w1 w2]
(if (and w1 (= (last w1) (first w2)))
(str w1 " " w2)))]
(filter #(reduce valid-word %)
(with-monad sequence-m (m-seq wss)))))
amb> (amb '(("the" "that" "a") ("frog" "e... |
http://rosettacode.org/wiki/Aliquot_sequence_classifications | Aliquot sequence classifications | An aliquot sequence of a positive integer K is defined recursively as the first member
being K and subsequent members being the sum of the Proper divisors of the previous term.
If the terms eventually reach 0 then the series for K is said to terminate.
There are several classifications for non termination:
If the s... | #AWK | AWK |
#!/bin/gawk -f
function sumprop(num, i,sum,root) {
if (num == 1) return 0
sum=1
root=sqrt(num)
for ( i=2; i < root; i++) {
if (num % i == 0 )
{
sum = sum + i + num/i
}
}
if (num % root == 0)
{
sum = sum + root
}
return sum
}
function class(k, oldk,newk,seq){
# first term
oldk ... |
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user | Active Directory/Search for a user | Make sure you Connect to Active Directory
| #D | D |
import openldap;
import std.stdio;
void main() {
// connect to server
auto ldap = LDAP("ldap://localhost");
// search for uid
auto r = ldap.search_s("dc=example,dc=com", LDAP_SCOPE_SUBTREE, "(uid=%s)".format("test"));
// show properties
writeln("Found dn: %s", r[0].dn);
foreach(k, v; r[0].entry)
... |
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user | Active Directory/Search for a user | Make sure you Connect to Active Directory
| #Eiffel | Eiffel |
feature -- Validation
is_user_credential_valid (a_domain, a_username, a_password: READABLE_STRING_GENERAL): BOOLEAN
-- Is the pair `a_username'/`a_password' a valid credential in `a_domain'?
local
l_domain, l_username, l_password: WEL_STRING
do
create l_domain.make (a_domain)
create l_username.make... |
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user | Active Directory/Search for a user | Make sure you Connect to Active Directory
| #Go | Go | package main
import (
"log"
"github.com/jtblin/go-ldap-client"
)
func main() {
client := &ldap.LDAPClient{
Base: "dc=example,dc=com",
Host: "ldap.example.com",
Port: 389,
GroupFilter: "(memberUid=%s)",
}
defer client.Close()
err := client.... |
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime | Add a variable to a class instance at runtime | Demonstrate how to dynamically add variables to an object (a class instance) at runtime.
This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is re... | #ActionScript | ActionScript | var object:Object = new Object();
object.foo = "bar"; |
http://rosettacode.org/wiki/Address_of_a_variable | Address of a variable |
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 |... | #BBC_BASIC | BBC BASIC | REM get a variable's address:
y% = ^x%
REM can't set a variable's address, but can access a given memory location (4 bytes):
x% = !y% |
http://rosettacode.org/wiki/Address_of_a_variable | Address of a variable |
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 |... | #C_.2F_C.2B.2B | C / C++ | int i;
void* address_of_i = &i; |
http://rosettacode.org/wiki/Address_of_a_variable | Address of a variable |
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 |... | #C.23 | C# | unsafe
{
int i = 5;
void* address_of_i = &i;
} |
http://rosettacode.org/wiki/AKS_test_for_primes | AKS test for primes | The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles.
The theorem on which the test is based can be stated as follows:
a number
p
{\displaystyle p}
is prime if and only if all the coefficients of the polynomial ... | #ALGOL_68 | ALGOL 68 |
BEGIN
COMMENT
Mathematical preliminaries.
First note that the homogeneous polynomial (a+b)^n is symmetrical
(to see this just swap the variables a and b). Therefore its
coefficients need be calculated only to that of (ab)^{n/2} for even
n or (ab)^{(n-1)/2} for odd n.
Second, the coefficients ar... |
http://rosettacode.org/wiki/Additive_primes | Additive primes | Definitions
In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes.
Task
Write a program to determine (and show here) all additive primes less than 500.
Optionally, show the number of additive primes.
Also see
the OEIS entry: A046704 additive primes.
... | #AppleScript | AppleScript | on sieveOfEratosthenes(limit)
script o
property numberList : {missing value}
end script
repeat with n from 2 to limit
set end of o's numberList to n
end repeat
repeat with n from 2 to (limit ^ 0.5) div 1
if (item n of o's numberList is n) then
repeat with mult... |
http://rosettacode.org/wiki/Algebraic_data_types | Algebraic data types | Some languages offer direct support for algebraic data types and pattern matching on them. While this of course can always be simulated with manual tagging and conditionals, it allows for terse code which is easy to read, and can represent the algorithm directly.
Task
As an example, implement insertion in a red-bla... | #jq | jq | # bindings($x) attempts to match . and $x structurally on the
# assumption that . is free of JSON objects, and that any objects in
# $x will have distinct, singleton keys that are to be interpreted as
# variables. These variables will match the corresponding entities in
# . if . and $x can be structurally matched.
#
#... |
http://rosettacode.org/wiki/Algebraic_data_types | Algebraic data types | Some languages offer direct support for algebraic data types and pattern matching on them. While this of course can always be simulated with manual tagging and conditionals, it allows for terse code which is easy to read, and can represent the algorithm directly.
Task
As an example, implement insertion in a red-bla... | #Julia | Julia | import Base.length
abstract type AbstractColoredNode end
struct RedNode <: AbstractColoredNode end; const R = RedNode()
struct BlackNode <: AbstractColoredNode end; const B = BlackNode()
struct Empty end; const E = Empty()
length(e::Empty) = 1
function balance(b::BlackNode, v::Vector, z, d)
if v[1] == R
... |
http://rosettacode.org/wiki/Almost_prime | Almost prime | A k-Almost-prime is a natural number
n
{\displaystyle n}
that is the product of
k
{\displaystyle k}
(possibly identical) primes.
Example
1-almost-primes, where
k
=
1
{\displaystyle k=1}
, are the prime numbers themselves.
2-almost-primes, where
k
=
2
{\displaystyl... | #Delphi | Delphi |
program AlmostPrime;
{$APPTYPE CONSOLE}
function IsKPrime(const n, k: Integer): Boolean;
var
p, f, v: Integer;
begin
f := 0;
p := 2;
v := n;
while (f < k) and (p*p <= n) do begin
while (v mod p) = 0 do begin
v := v div p;
Inc(f);
end;
Inc(p);
end;
if v > 1 then Inc(f);
Resu... |
http://rosettacode.org/wiki/Anagrams | Anagrams | When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in them.
Related tasks
Word plays
... | #BBC_BASIC | BBC BASIC | INSTALL @lib$+"SORTLIB"
sort% = FN_sortinit(0,0)
REM Count number of words in dictionary:
nwords% = 0
dict% = OPENIN("unixdict.txt")
WHILE NOT EOF#dict%
word$ = GET$#dict%
nwords% += 1
ENDWHILE
CLOSE #dict%
REM Create arrays big enough to contain... |
http://rosettacode.org/wiki/Angle_difference_between_two_bearings | Angle difference between two bearings | Finding the angle between two bearings is often confusing.[1]
Task
Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings.
Input bearings are expressed in the range -180 to +180 degrees.
The result is also expressed in the range -180 to +180 degrees.
... | #Maple | Maple | getDiff := proc(b1,b2)
local r:
r := frem(b2 - b1, 360):
if r >= 180 then r := r - 360: fi:
return r:
end proc:
getDiff(20,45);
getDiff(-45,45);
getDiff(-85,90);
getDiff(-95,90);
getDiff(-45,125);
getDiff(-45,145);
getDiff(29.4803, -88.6381);
getDiff(-78.3251,-159.036);
getDiff(-70099.74233810938,29840.67437876723)... |
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams | Anagrams/Deranged anagrams | Two or more words are said to be anagrams if they have the same characters, but in a different order.
By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words.
Task[edit]
Use the word list at uni... | #Perl | Perl | sub deranged { # only anagrams ever get here
my @a = split('', shift); # split word into letters
my @b = split('', shift);
for (0 .. $#a) {
$a[$_] eq $b[$_] and return;
}
return 1
}
sub find_deranged {
for my $i ( 0 ..... |
http://rosettacode.org/wiki/Anonymous_recursion | Anonymous recursion | While implementing a recursive function, it often happens that we must resort to a separate helper function to handle the actual recursion.
This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects, and/or the f... | #Lambdatalk | Lambdatalk |
1) defining a quasi-recursive function combined with a simple Ω-combinator:
{def fibo {lambda {:n}
{{{lambda {:f} {:f :f}}
{lambda {:f :n :a :b}
{if {< :n 0}
then the number must be positive!
else {if {< :n 1}
then :a
else {:f :f {- :n 1} {+ :a :b} :a}}}}} :n 1 0}}}
-> fibo
2) testing:
{fib... |
http://rosettacode.org/wiki/Amicable_pairs | Amicable pairs | Two integers
N
{\displaystyle N}
and
M
{\displaystyle M}
are said to be amicable pairs if
N
≠
M
{\displaystyle N\neq M}
and the sum of the proper divisors of
N
{\displaystyle N}
(
s
u
m
(
p
r
o
p
D
i
v
s
(
N
)
)
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (N))}
)
=
M
... | #J | J | factors=: [: /:~@, */&>@{@((^ i.@>:)&.>/)@q:~&__
properDivisors=: factors -. -.&1 |
http://rosettacode.org/wiki/Animation | Animation |
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demonstrates this.
Task
Creat... | #Raku | Raku | use GTK::Simple;
use GTK::Simple::App;
my $app = GTK::Simple::App.new(:title<Animation>);
my $button = GTK::Simple::Button.new(label => 'Hello World! ');
my $vbox = GTK::Simple::VBox.new($button);
my $repeat = $app.g-timeout(100); # milliseconds
my $dir = 1;
$button.clicked.tap({ $dir *= -1 });
$repeat.tap... |
http://rosettacode.org/wiki/Animate_a_pendulum | Animate a pendulum |
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display.
The classic such physical system is a simple gravity pendulum.
Task
Create a simple physical model of a pendulum and animate it.
| #Lua | Lua |
function degToRad( d )
return d * 0.01745329251
end
function love.load()
g = love.graphics
rodLen, gravity, velocity, acceleration = 260, 3, 0, 0
halfWid, damp = g.getWidth() / 2, .989
posX, posY, angle = halfWid
TWO_PI, angle = math.pi * 2, degToRad( 90 )
end
function love.update( dt )
... |
http://rosettacode.org/wiki/Amb | Amb | Define and give an example of the Amb operator.
The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton").
The Amb operator takes a v... | #Common_Lisp | Common Lisp | (define-condition amb-failure () ()
(:report "No amb alternative succeeded."))
(defun invoke-ambiguously (function thunks)
"Call function with successive values produced by successive
functions in thunks until some invocation of function does not signal
an amb-failure."
(do ((thunks thunks (rest thunks)))
... |
http://rosettacode.org/wiki/Active_Directory/Connect | Active Directory/Connect | The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server.
| #AutoHotkey | AutoHotkey | objConn := CreateObject("ADODB.Connection")
objCmd := CreateObject("ADODB.Command")
objConn.Provider := "ADsDSOObject"
objConn.Open() |
http://rosettacode.org/wiki/Aliquot_sequence_classifications | Aliquot sequence classifications | An aliquot sequence of a positive integer K is defined recursively as the first member
being K and subsequent members being the sum of the Proper divisors of the previous term.
If the terms eventually reach 0 then the series for K is said to terminate.
There are several classifications for non termination:
If the s... | #BASIC256 | BASIC256 | # Rosetta Code problem: http://rosettacode.org/wiki/Aliquot_sequence_classifications
# by Jjuanhdez, 06/2022
global limite
limite = 20000000
dim nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488}
for n = 0 to nums[?]-1
print "Number "; nums[n]; " : ";... |
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user | Active Directory/Search for a user | Make sure you Connect to Active Directory
| #Haskell | Haskell | {-# LANGUAGE OverloadedStrings #-}
module Main (main) where
import Data.Foldable (for_)
import qualified Data.Text.Encoding as Text (encodeUtf8)
import Ldap.Client (Attr(..), Filter(..))
import qualified Ldap.Client as Ldap (Dn(..), Host(..), search, with, typesOnly)
main :: IO ()
main = do
... |
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user | Active Directory/Search for a user | Make sure you Connect to Active Directory
| #Java | Java | import java.io.IOException;
import org.apache.directory.api.ldap.model.cursor.CursorException;
import org.apache.directory.api.ldap.model.cursor.EntryCursor;
import org.apache.directory.api.ldap.model.entry.Entry;
import org.apache.directory.api.ldap.model.exception.LdapException;
import org.apache.directory.api.ldap.m... |
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime | Add a variable to a class instance at runtime | Demonstrate how to dynamically add variables to an object (a class instance) at runtime.
This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is re... | #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure Dynamic is
package Abstract_Class is
type Class is limited interface;
function Boo (X : Class) return String is abstract;
end Abstract_Class;
use Abstract_Class;
package Base_Class is
type Base is new Class with null record;
overridin... |
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime | Add a variable to a class instance at runtime | Demonstrate how to dynamically add variables to an object (a class instance) at runtime.
This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is re... | #Arturo | Arturo | define :myClass [name,surname][]
myInstance: to :myClass ["John" "Doe"]
print myInstance
myInstance\age: 35
print myInstance |
http://rosettacode.org/wiki/Address_of_a_variable | Address of a variable |
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 |... | #COBOL | COBOL | data division.
working-storage section.
01 ptr usage pointer.
01 var pic x(64).
procedure division.
set ptr to address of var. |
http://rosettacode.org/wiki/Address_of_a_variable | Address of a variable |
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 |... | #Common_Lisp | Common Lisp | ;;; Demonstration of references by swapping two variables using a function rather than a macro
;;; Needs http://paste.lisp.org/display/71952
(defun swap (ref-left ref-right)
;; without with-refs we would have to write this:
;; (psetf (deref ref-left) (deref ref-right)
;; (deref ref-right) (deref ref-left))... |
http://rosettacode.org/wiki/Address_of_a_variable | Address of a variable |
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 |... | #Component_Pascal | Component Pascal |
MODULE AddressVar;
IMPORT SYSTEM,StdLog;
VAR
x: INTEGER;
PROCEDURE Do*;
BEGIN
StdLog.String("ADR(x):> ");StdLog.IntForm(SYSTEM.ADR(x),StdLog.hexadecimal,8,'0',TRUE);StdLog.Ln
END Do;
BEGIN
x := 10;
END AddressVar.
|
http://rosettacode.org/wiki/AKS_test_for_primes | AKS test for primes | The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles.
The theorem on which the test is based can be stated as follows:
a number
p
{\displaystyle p}
is prime if and only if all the coefficients of the polynomial ... | #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI or android 32 bits */
/* program AKS.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* for constantes see task ... |
http://rosettacode.org/wiki/Additive_primes | Additive primes | Definitions
In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes.
Task
Write a program to determine (and show here) all additive primes less than 500.
Optionally, show the number of additive primes.
Also see
the OEIS entry: A046704 additive primes.
... | #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program additivePrime.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* for constantes see task include a... |
http://rosettacode.org/wiki/Algebraic_data_types | Algebraic data types | Some languages offer direct support for algebraic data types and pattern matching on them. While this of course can always be simulated with manual tagging and conditionals, it allows for terse code which is easy to read, and can represent the algorithm directly.
Task
As an example, implement insertion in a red-bla... | #Kotlin | Kotlin | // version 1.1.51
import Color.*
enum class Color { R, B }
sealed class Tree<A : Comparable<A>> {
fun insert(x: A): Tree<A> {
val t = ins(x)
return when (t) {
is T -> {
val (_, a, y, b) = t
T(B, a, y, b)
}
is E -> E()
... |
http://rosettacode.org/wiki/Almost_prime | Almost prime | A k-Almost-prime is a natural number
n
{\displaystyle n}
that is the product of
k
{\displaystyle k}
(possibly identical) primes.
Example
1-almost-primes, where
k
=
1
{\displaystyle k=1}
, are the prime numbers themselves.
2-almost-primes, where
k
=
2
{\displaystyl... | #Draco | Draco | proc nonrec kprime(word n, k) bool:
word f, p;
f := 0;
p := 2;
while f < k and p*p <= n do
while n%p = 0 do
n := n/p;
f := f+1
od;
p := p+1
od;
if n>1 then f+1 = k
else f = k
fi
corp
proc nonrec main() void:
byte k, i, c;
for k fr... |
http://rosettacode.org/wiki/Almost_prime | Almost prime | A k-Almost-prime is a natural number
n
{\displaystyle n}
that is the product of
k
{\displaystyle k}
(possibly identical) primes.
Example
1-almost-primes, where
k
=
1
{\displaystyle k=1}
, are the prime numbers themselves.
2-almost-primes, where
k
=
2
{\displaystyl... | #EchoLisp | EchoLisp |
(define (almost-prime? p k)
(= k (length (prime-factors p))))
(define (almost-primes k nmax)
(take (filter (rcurry almost-prime? k) [2 ..]) nmax))
(define (task (kmax 6) (nmax 10))
(for ((k [1 .. kmax]))
(write 'k= k '|)
(for-each write (almost-primes k nmax))
(writeln)))
|
http://rosettacode.org/wiki/Anagrams | Anagrams | When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in them.
Related tasks
Word plays
... | #BQN | BQN | words ← •FLines "unixdict.txt"
•Show¨{𝕩/˜(⊢=⌈´)≠¨𝕩} (⊐∧¨)⊸⊔ words |
http://rosettacode.org/wiki/Angle_difference_between_two_bearings | Angle difference between two bearings | Finding the angle between two bearings is often confusing.[1]
Task
Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings.
Input bearings are expressed in the range -180 to +180 degrees.
The result is also expressed in the range -180 to +180 degrees.
... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[AngleDifference]
AngleDifference[b1_, b2_] := Mod[b2 - b1, 360, -180]
AngleDifference[20, 45]
AngleDifference[-45, 45]
AngleDifference[-85, 90]
AngleDifference[-95, 90]
AngleDifference[-45, 125]
AngleDifference[-45, 145]
AngleDifference[29.4803, -88.6381]
AngleDifference[-78.3251, -159.036]
AngleDifference[-70... |
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams | Anagrams/Deranged anagrams | Two or more words are said to be anagrams if they have the same characters, but in a different order.
By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words.
Task[edit]
Use the word list at uni... | #Phix | Phix | function deranged(string word1, word2)
return sum(sq_eq(word1,word2))=0
end function
integer fn = open("demo/unixdict.txt","r")
sequence words = {}, anagrams = {}, last="", letters
object word
integer maxlen = 1
while 1 do
word = trim(gets(fn))
if atom(word) then exit end if
if length(word) then
... |
http://rosettacode.org/wiki/Anonymous_recursion | Anonymous recursion | While implementing a recursive function, it often happens that we must resort to a separate helper function to handle the actual recursion.
This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects, and/or the f... | #Lingo | Lingo | on fib (n)
if n<0 then return _player.alert("negative arguments not allowed")
-- create instance of unnamed class in memory only (does not pollute namespace)
m = new(#script)
r = RETURN
m.scriptText = "on fib (me,n)"&r&"if n<2 then return n"&r&"return me.fib(n-1)+me.fib(n-2)"&r&"end"
aux = m.script.new()
... |
http://rosettacode.org/wiki/Amicable_pairs | Amicable pairs | Two integers
N
{\displaystyle N}
and
M
{\displaystyle M}
are said to be amicable pairs if
N
≠
M
{\displaystyle N\neq M}
and the sum of the proper divisors of
N
{\displaystyle N}
(
s
u
m
(
p
r
o
p
D
i
v
s
(
N
)
)
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (N))}
)
=
M
... | #Java | Java | import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.LongStream;
public class AmicablePairs {
public static void main(String[] args) {
int limit = 20_000;
Map<Long, Long> map = LongStream.rangeClosed(1, limit)
.pa... |
http://rosettacode.org/wiki/Animation | Animation |
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demonstrates this.
Task
Creat... | #REBOL | REBOL | rebol [
Title: "Basic Animation"
URL: http://rosettacode.org/wiki/Basic_Animation
]
message: "Hello World! " how: 1
roll: func [
"Shifts a text string right or left by one character."
text [string!] "Text to shift."
direction [integer!] "Direction to shift -- right: 1, left: -1."
/local h t
][
either direct... |
http://rosettacode.org/wiki/Animate_a_pendulum | Animate a pendulum |
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display.
The classic such physical system is a simple gravity pendulum.
Task
Create a simple physical model of a pendulum and animate it.
| #M2000_Interpreter | M2000 Interpreter |
Module Pendulum {
back()
degree=180/pi
THETA=Pi/2
SPEED=0
G=9.81
L=0.5
Profiler
lasttimecount=0
cc=40 ' 40 ms every draw
accold=0
Every cc {
ACCEL=G*SIN(THETA*degree)/L/50
SPEED+=ACCEL/cc
THETA+=SPEED
Pe... |
http://rosettacode.org/wiki/Amb | Amb | Define and give an example of the Amb operator.
The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton").
The Amb operator takes a v... | #D | D | import std.stdio, std.array;
/** This amb function takes a comparison function and
the possibilities that need to be checked.*/
//string[] amb(in bool function(in string, in string) pure comp,
const(string)[] amb(in bool function(in string, in string) pure comp,
in string[][] options,
... |
http://rosettacode.org/wiki/Active_Directory/Connect | Active Directory/Connect | The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server.
| #AutoIt | AutoIt | #include <AD.au3>
_AD_Open() |
http://rosettacode.org/wiki/Active_Directory/Connect | Active Directory/Connect | The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server.
| #C | C | #include <ldap.h>
...
char *name, *password;
...
LDAP *ld = ldap_init("ldap.somewhere.com", 389);
ldap_simple_bind_s(ld, name, password);
... after done with it...
ldap_unbind(ld); |
http://rosettacode.org/wiki/Active_Directory/Connect | Active Directory/Connect | The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server.
| #C.23 | C# |
// Requires adding a reference to System.DirectoryServices
var objDE = new System.DirectoryServices.DirectoryEntry("LDAP://DC=onecity,DC=corp,DC=fabrikam,DC=com");
|
http://rosettacode.org/wiki/Active_Directory/Connect | Active Directory/Connect | The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server.
| #ColdFusion | ColdFusion |
<cfldap
server = "#someip#"
action="query"
start="somestart#"
username = "#someusername#"
password = "#somepassowrd#"
name = "results"
scope="subtree"
attributes = "#attributeslist#"
>
|
http://rosettacode.org/wiki/Aliquot_sequence_classifications | Aliquot sequence classifications | An aliquot sequence of a positive integer K is defined recursively as the first member
being K and subsequent members being the sum of the Proper divisors of the previous term.
If the terms eventually reach 0 then the series for K is said to terminate.
There are several classifications for non termination:
If the s... | #C | C |
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
unsigned long long bruteForceProperDivisorSum(unsigned long long n){
unsigned long long i,sum = 0;
for(i=1;i<(n+1)/2;i++)
if(n%i==0 && n!=i)
sum += i;
return sum;
}
void printSeries(unsigned long long* arr,int size,char* type){
int i;
printf(... |
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user | Active Directory/Search for a user | Make sure you Connect to Active Directory
| #Julia | Julia | using LDAPClient
function searchLDAPusers(searchstring, uname, pword, host=["example", "com"])
conn = LDAPClient.LDAPConnection("ldap://ldap.server.net")
LDAPClient.simple_bind(conn, uname, pword)
search_string = "CN=Users,DC=$(host[1]),DC=$(host[2])"
scope = LDAPClient.LDAP_SCOPE_ONELEVEL
chain... |
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user | Active Directory/Search for a user | Make sure you Connect to Active Directory
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols binary
import org.apache.directory.ldap.client.api.LdapConnection
import org.apache.directory.ldap.client.api.LdapNetworkConnection
import org.apache.directory.shared.ldap.model.cursor.EntryCursor
import org.apache.directory.shared.ldap.model.entry.E... |
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime | Add a variable to a class instance at runtime | Demonstrate how to dynamically add variables to an object (a class instance) at runtime.
This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is re... | #AutoHotkey | AutoHotkey | e := {}
e.foo := 1 |
Subsets and Splits
Rosetta Code COBOL Python Hard Tasks
Identifies and retrieves challenging tasks that exist in both COBOL and Python, revealing cross-language programming patterns and difficulty levels for comparative analysis.
Rosetta Code Task Comparisons
Identifies tasks common to both COBOL and Python languages that are described as having difficulty levels, revealing cross-language task similarities and providing useful comparative programming examples.
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.