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/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 referred to as "monkeypatching" by Pythonistas and some others.
| #BBC_BASIC | BBC BASIC | INSTALL @lib$+"CLASSLIB"
REM Create a base class with no members:
DIM class{method}
PROC_class(class{})
REM Instantiate the class:
PROC_new(myobject{}, class{})
REM Add a member at run-time:
member$ = "mymember#"
PROCaddmember(myobject{}, member$, 8)
REM Test that the member can be accessed:
PROCassign("myobject." + member$, "PI")
PRINT EVAL("myobject." + member$)
END
DEF PROCaddmember(RETURN obj{}, mem$, size%)
LOCAL D%, F%, P%
DIM D% DIM(obj{}) + size% - 1, F% LEN(mem$) + 8
P% = !^obj{} + 4
WHILE !P% : P% = !P% : ENDWHILE : !P% = F%
$$(F%+4) = mem$ : F%!(LEN(mem$) + 5) = DIM(obj{})
!(^obj{} + 4) = D%
ENDPROC
DEF PROCassign(v$, n$)
IF EVAL("FNassign(" + v$ + "," + n$ + ")")
ENDPROC
DEF FNassign(RETURN n, v) : n = v : = 0 |
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 referred to as "monkeypatching" by Pythonistas and some others.
| #Bracmat | Bracmat | ( ( struktuur
= (aMember=) (aMethod=.!(its.aMember))
)
& new$struktuur:?object
& out$"Object as originally created:"
& lst$object
& A value:?(object..aMember)
& !object:(=?originalMembersAndMethods)
& new
$ (
' ( (anotherMember=)
(anotherMethod=.!(its.anotherMember))
()$originalMembersAndMethods
)
)
: ?object
& out
$ "
Object with additional member and method and with 'aMember' already set to some interesting value:"
& lst$object
& some other value:?(object..anotherMember)
& out$"
Call both methods and output their return values."
& out$("aMember contains:" (object..aMethod)$)
& out$("anotherMember contains:" (object..anotherMethod)$)
&); |
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 referred to as "monkeypatching" by Pythonistas and some others.
| #C.23 | C# | // ----------------------------------------------------------------------------------------------
//
// Program.cs - DynamicClassVariable
//
// Mikko Puonti, 2013
//
// ----------------------------------------------------------------------------------------------
using System;
using System.Dynamic;
namespace DynamicClassVariable
{
internal static class Program
{
#region Static Members
private static void Main()
{
// To enable late binding, we must use dynamic keyword
// ExpandoObject readily implements IDynamicMetaObjectProvider which allows us to do some dynamic magic
dynamic sampleObj = new ExpandoObject();
// Adding a new property
sampleObj.bar = 1;
Console.WriteLine( "sampleObj.bar = {0}", sampleObj.bar );
// We can also add dynamically methods and events to expando object
// More information: http://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject.aspx
// This sample only show very small part of dynamic language features - there is lot's more
Console.WriteLine( "< Press any key >" );
Console.ReadKey();
}
#endregion
}
} |
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 |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Demonstrate how to get the address of a variable and how to set the address of a variable.
| #Creative_Basic | Creative Basic |
== Get ==
To get the address of a variable without using the Windows API:
DEF X:INT
DEF pPointer:POINTER
pPointer=X
----
To get the address of a variable using the Windows API Lstrcpy function called in Creative Basic:
(This may give users of another language without a native way to get the address of a variable to work around that problem.)
DEF Win:WINDOW
DEF Close:CHAR
DEF ScreenSizeX,ScreenSizeY,Col:INT
'***Map Function***
DECLARE "Kernel32",Lstrcpy(P1:POINTER,P2:POINTER),INT
'The pointers replace the VB3 variable type of Any.
'Note: This is translated from VB3 or earlier code, and "Ptr" is *not* a Creative Basic pointer.
DEF Ptr:INT
DEF X1:INT
DEF X2:STRING
X1=123
'***Call function***
Ptr=Lstrcpy(X1,X1)
GETSCREENSIZE(ScreenSizeX,ScreenSizeY)
WINDOW Win,0,0,ScreenSizeX,ScreenSizeY,@MINBOX|@MAXBOX|@SIZE|@MAXIMIZED,0,"Skel Win",MainHandler
'***Display address***
PRINT Win, "The address of x1 is: " + Hex$(Ptr)
X2="X2"
WAITUNTIL Close=1
CLOSEWINDOW Win
END
SUB MainHandler
SELECT @CLASS
CASE @IDCLOSEWINDOW
Close=1
ENDSELECT
RETURN
Note: The Windows Dev Center (http://msdn.microsoft.com/en-us/library/windows/desktop/ms647490%28v=vs.85%29.aspx) says
improper use of the Lstrcpy function may compromise security. A person is advised to see the Windows Dev site before using
the Lstrcopy function.
== Set ==
It appears to the author the closest one can come to setting the address of a variable is to set which bytes will be
used to store a variable in a reserved block of memory:
DEF pMem as POINTER
pMem = NEW(CHAR,1000) : 'Get 1000 bytes to play with
#<STRING>pMem = "Copy a string into memory"
pMem += 100
#<UINT>pMem = 34234: 'Use bytes 100-103 to store a UINT
DELETE pMem
|
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 |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Demonstrate how to get the address of a variable and how to set the address of a variable.
| #D | D | int i;
int* ip = &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 |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Demonstrate how to get the address of a variable and how to set the address of a variable.
| #Delphi | Delphi | var
i: integer;
p: ^integer;
begin
p := @i;
writeLn(p^);
end; |
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 expansion of
(
x
−
1
)
p
−
(
x
p
−
1
)
{\displaystyle (x-1)^{p}-(x^{p}-1)}
are divisible by
p
{\displaystyle p}
.
Example
Using
p
=
3
{\displaystyle p=3}
:
(x-1)^3 - (x^3 - 1)
= (x^3 - 3x^2 + 3x - 1) - (x^3 - 1)
= -3x^2 + 3x
And all the coefficients are divisible by 3, so 3 is prime.
Note:
This task is not the AKS primality test. It is an inefficient exponential time algorithm discovered in the late 1600s and used as an introductory lemma in the AKS derivation.
Task
Create a function/subroutine/method that given
p
{\displaystyle p}
generates the coefficients of the expanded polynomial representation of
(
x
−
1
)
p
{\displaystyle (x-1)^{p}}
.
Use the function to show here the polynomial expansions of
(
x
−
1
)
p
{\displaystyle (x-1)^{p}}
for
p
{\displaystyle p}
in the range 0 to at least 7, inclusive.
Use the previous function in creating another function that when given
p
{\displaystyle p}
returns whether
p
{\displaystyle p}
is prime using the theorem.
Use your test to generate a list of all primes under 35.
As a stretch goal, generate all primes under 50 (needs integers larger than 31-bit).
References
Agrawal-Kayal-Saxena (AKS) primality test (Wikipedia)
Fool-Proof Test for Primes - Numberphile (Video). The accuracy of this video is disputed -- at best it is an oversimplification.
| #AutoHotkey | AutoHotkey | ; 1. Create a function/subroutine/method that given p generates the coefficients of the expanded polynomial representation of (x-1)^p.
; Function modified from http://rosettacode.org/wiki/Pascal%27s_triangle#AutoHotkey
pascalstriangle(n=8) ; n rows of Pascal's triangle
{
p := Object(), z:=Object()
Loop, % n
Loop, % row := A_Index
col := A_Index
, p[row, col] := row = 1 and col = 1
? 1
: (p[row-1, col-1] = "" ; math operations on blanks return blanks; I want to assume zero
? 0
: p[row-1, col-1])
- (p[row-1, col] = ""
? 0
: p[row-1, col])
Return p
}
; 2. Use the function to show here the polynomial expansions of p for p in the range 0 to at least 7, inclusive.
For k, v in pascalstriangle()
{
s .= "`n(x-1)^" k-1 . "="
For k, w in v
s .= "+" w "x^" k-1
}
s := RegExReplace(s, "\+-", "-")
s := RegExReplace(s, "x\^0", "")
s := RegExReplace(s, "x\^1", "x")
Msgbox % clipboard := s
; 3. Use the previous function in creating another function that when given p returns whether p is prime using the AKS test.
aks(n)
{
isnotprime := False
For k, v in pascalstriangle(n+1)[n+1]
(k != 1 and k != n+1) ? isnotprime |= !(v // n = v / n) ; if any is not divisible, returns true
Return !isnotprime
}
; 4. Use your AKS test to generate a list of all primes under 35.
i := 49
p := pascalstriangle(i+1)
Loop, % i
{
n := A_Index
isnotprime := False
For k, v in p[n+1]
(k != 1 and k != n+1) ? isnotprime |= !(v // n = v / n) ; if any is not divisible, returns true
t .= isnotprime ? "" : A_Index " "
}
Msgbox % t
Return |
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.
the prime-numbers entry: additive primes.
the geeks for geeks entry: additive prime number.
the prime-numbers fandom: additive primes.
| #Arturo | Arturo | additives: select 2..500 'x -> and? prime? x prime? sum digits x
loop split.every:10 additives 'a ->
print map a => [pad to :string & 4]
print ["\nFound" size additives "additive primes up to 500"] |
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.
the prime-numbers entry: additive primes.
the geeks for geeks entry: additive prime number.
the prime-numbers fandom: additive primes.
| #AWK | AWK |
# syntax: GAWK -f ADDITIVE_PRIMES.AWK
BEGIN {
start = 1
stop = 500
for (i=start; i<=stop; i++) {
if (is_prime(i) && is_prime(sum_digits(i))) {
printf("%4d%1s",i,++count%10?"":"\n")
}
}
printf("\nAdditive primes %d-%d: %d\n",start,stop,count)
exit(0)
}
function is_prime(x, i) {
if (x <= 1) {
return(0)
}
for (i=2; i<=int(sqrt(x)); i++) {
if (x % i == 0) {
return(0)
}
}
return(1)
}
function sum_digits(n, i,sum) {
for (i=1; i<=length(n); i++) {
sum += substr(n,i,1)
}
return(sum)
}
|
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-black-tree.
A red-black-tree is a binary tree where each internal node has a color attribute red or black. Moreover, no red node can have a red child, and every path from the root to an empty node must contain the same number of black nodes. As a consequence, the tree is balanced, and must be re-balanced after an insertion.
Reference
Red-Black Trees in a Functional Setting
| #Nim | Nim | import fusion/matching
{.experimental: "caseStmtMacros".}
type
Colour = enum Empty, Red, Black
RBTree[T] = ref object
colour: Colour
left, right: RBTree[T]
value: T
proc `[]`[T](r: RBTree[T], idx: static[FieldIndex]): auto =
## enables tuple syntax for unpacking and matching
when idx == 0: r.colour
elif idx == 1: r.left
elif idx == 2: r.value
elif idx == 3: r.right
template B[T](l: untyped, v: T, r): RBTree[T] =
RBTree[T](colour: Black, left: l, value: v, right: r)
template R[T](l: untyped, v: T, r): RBTree[T] =
RBTree[T](colour: Red, left: l, value: v, right: r)
template balImpl[T](t: typed): untyped =
case t
of (colour: Red | Empty): discard
of (Black, (Red, (Red, @a, @x, @b), @y, @c), @z, @d) |
(Black, (Red, @a, @x, (Red, @b, @y, @c)), @z, @d) |
(Black, @a, @x, (Red, (Red, @b, @y, @c), @z, @d)) |
(Black, @a, @x, (Red, @b, @y, (Red, @c, @z, @d))):
t = R(B(a, x, b), y, B(c, z, d))
proc balance*[T](t: var RBTree[T]) = balImpl[T](t)
template insImpl[T](t, x: typed): untyped =
template E: RBTree[T] = RBTree[T]()
case t
of (colour: Empty): t = R(E, x, E)
of (value: > x): t.left.ins(x); t.balance()
of (value: < x): t.right.ins(x); t.balance()
proc insert*[T](tt: var RBTree[T], xx: T) =
proc ins(t: var RBTree[T], x: T) = insImpl[T](t, x)
tt.ins(xx)
tt.colour = Black |
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-black-tree.
A red-black-tree is a binary tree where each internal node has a color attribute red or black. Moreover, no red node can have a red child, and every path from the root to an empty node must contain the same number of black nodes. As a consequence, the tree is balanced, and must be re-balanced after an insertion.
Reference
Red-Black Trees in a Functional Setting
| #OCaml | OCaml |
type color = R | B
type 'a tree = E | T of color * 'a tree * 'a * 'a tree
(** val balance : color * 'a tree * 'a * 'a tree -> 'a tree *)
let balance = function
| B, T (R, T (R,a,x,b), y, c), z, d
| B, T (R, a, x, T (R,b,y,c)), z, d
| B, a, x, T (R, T (R,b,y,c), z, d)
| B, a, x, T (R, b, y, T (R,c,z,d)) -> T (R, T (B,a,x,b), y, T (B,c,z,d))
| col, a, x, b -> T (col, a, x, b)
(** val insert : 'a -> 'a tree -> 'a tree *)
let insert x s =
let rec ins = function
| E -> T (R,E,x,E)
| T (col,a,y,b) as s ->
if x < y then
balance (col, ins a, y, b)
else if x > y then
balance (col, a, y, ins b)
else
s
in let T (_,a,y,b) = ins s
in T (B,a,y,b)
|
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
{\displaystyle k=2}
, are the semiprimes.
Task
Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for
1
<=
K
<=
5
{\displaystyle 1<=K<=5}
.
Related tasks
Semiprime
Category:Prime Numbers
| #Elixir | Elixir | defmodule Factors do
def factors(n), do: factors(n,2,[])
defp factors(1,_,acc), do: acc
defp factors(n,k,acc) when rem(n,k)==0, do: factors(div(n,k),k,[k|acc])
defp factors(n,k,acc) , do: factors(n,k+1,acc)
def kfactors(n,k), do: kfactors(n,k,1,1,[])
defp kfactors(_tn,tk,_n,k,_acc) when k == tk+1, do: IO.puts "done! "
defp kfactors(tn,tk,_n,k,acc) when length(acc) == tn do
IO.puts "K: #{k} #{inspect acc}"
kfactors(tn,tk,2,k+1,[])
end
defp kfactors(tn,tk,n,k,acc) do
case length(factors(n)) do
^k -> kfactors(tn,tk,n+1,k,acc++[n])
_ -> kfactors(tn,tk,n+1,k,acc)
end
end
end
Factors.kfactors(10,5) |
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
{\displaystyle k=2}
, are the semiprimes.
Task
Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for
1
<=
K
<=
5
{\displaystyle 1<=K<=5}
.
Related tasks
Semiprime
Category:Prime Numbers
| #Erlang | Erlang |
-module(factors).
-export([factors/1,kfactors/0,kfactors/2]).
factors(N) ->
factors(N,2,[]).
factors(1,_,Acc) -> Acc;
factors(N,K,Acc) when N rem K == 0 ->
factors(N div K,K, [K|Acc]);
factors(N,K,Acc) ->
factors(N,K+1,Acc).
kfactors() -> kfactors(10,5,1,1,[]).
kfactors(N,K) -> kfactors(N,K,1,1,[]).
kfactors(_Tn,Tk,_N,K,_Acc) when K == Tk+1 -> io:fwrite("Done! ");
kfactors(Tn,Tk,N,K,Acc) when length(Acc) == Tn ->
io:format("K: ~w ~w ~n", [K, Acc]),
kfactors(Tn,Tk,2,K+1,[]);
kfactors(Tn,Tk,N,K,Acc) ->
case length(factors(N)) of K ->
kfactors(Tn,Tk, N+1,K, Acc ++ [ N ] );
_ ->
kfactors(Tn,Tk, N+1,K, Acc) end.
|
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
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Bracmat | Bracmat | ( get$("unixdict.txt",STR):?list
& 1:?product
& whl
' ( @(!list:(%?word:?w) \n ?list)
& :?sum
& whl
' ( @(!w:%?let ?w)
& (!let:~#|str$(N !let))+!sum:?sum
)
& !sum^!word*!product:?product
)
& lst$(product,"product.txt",NEW)
& 0:?max
& :?group
& ( !product
: ?
* ?^(%+%:?exp)
* ( ?
& !exp
: ?
+ ( [>!max:[?max&!exp:?group
| [~<!max&!group !exp:?group
)
& ~
)
| out$!group
)
); |
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.
Compute the angle for the following pairs:
20 degrees (b1) and 45 degrees (b2)
-45 and 45
-85 and 90
-95 and 90
-45 and 125
-45 and 145
29.4803 and -88.6381
-78.3251 and -159.036
Optional extra
Allow the input bearings to be any (finite) value.
Test cases
-70099.74233810938 and 29840.67437876723
-165313.6666297357 and 33693.9894517456
1174.8380510598456 and -154146.66490124757
60175.77306795546 and 42213.07192354373
| #Modula-2 | Modula-2 | FROM Terminal IMPORT *;
PROCEDURE WriteRealLn(value : REAL);
VAR str : ARRAY[0..16] OF CHAR;
BEGIN
RealToStr(value, str);
WriteString(str);
WriteLn;
END WriteRealLn;
PROCEDURE AngleDifference(b1, b2 : REAL) : REAL;
VAR r : REAL;
BEGIN
r := (b2 - b1);
WHILE r < -180.0 DO
r := r + 360.0;
END;
WHILE r >= 180.0 DO
r := r - 360.0;
END;
RETURN r;
END AngleDifference;
BEGIN
WriteString('Input in -180 to +180 range');
WriteLn;
WriteRealLn(AngleDifference(20.0, 45.0));
WriteRealLn(AngleDifference(-45.0, 45.0));
WriteRealLn(AngleDifference(-85.0, 90.0));
WriteRealLn(AngleDifference(-95.0, 90.0));
WriteRealLn(AngleDifference(-45.0, 125.0));
WriteRealLn(AngleDifference(-45.0, 145.0));
WriteRealLn(AngleDifference(29.4803, -88.6381));
WriteRealLn(AngleDifference(-78.3251, -159.036));
WriteString('Input in wider range');
WriteLn;
WriteRealLn(AngleDifference(-70099.74233810938, 29840.67437876723));
WriteRealLn(AngleDifference(-165313.6666297357, 33693.9894517456));
WriteRealLn(AngleDifference(1174.8380510598456, -154146.66490124757));
WriteRealLn(AngleDifference(60175.77306795546, 42213.07192354373));
ReadChar;
END Bearings. |
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 unixdict to find and display the longest deranged anagram.
Related tasks
Permutations/Derangements
Best shuffle
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Phixmonti | Phixmonti | /# Rosetta Code problem: http://rosettacode.org/wiki/Anagrams/Deranged_anagrams
by Galileo, 06/2022 #/
include ..\Utilitys.pmt
"unixdict.txt" "r" fopen var f
( )
true while
f fgets
dup -1 == if
drop
f fclose
false
else
-1 del
dup sort swap 2 tolist
0 put
true
endif
endwhile
sort
0 var largest
( ) var candidate
( len 2 swap ) for var i
( i 1 ) sget >ps
( i 1 - 1 ) sget ps> == if
( i 2 ) sget >ps
( i 1 - 2 ) sget ps> len >ps
true var test
tps for var j
j get rot j get rot == if false var test exitfor endif
endfor
test tps largest > and if
ps> var largest
2 tolist var candidate
else
ps> drop drop drop
endif
endif
endfor
candidate print
|
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 function doesn't have the right arguments and/or return values.
So we end up inventing some silly name like foo2 or foo_helper. I have always found it painful to come up with a proper name, and see some disadvantages:
You have to think up a name, which then pollutes the namespace
Function is created which is called from nowhere else
The program flow in the source code is interrupted
Some languages allow you to embed recursion directly in-place. This might work via a label, a local gosub instruction, or some special keyword.
Anonymous recursion can also be accomplished using the Y combinator.
Task
If possible, demonstrate this by writing the recursive version of the fibonacci function (see Fibonacci sequence) which checks for a negative argument before doing the actual recursion.
| #LOLCODE | LOLCODE | HAI 1.3
HOW IZ I fib YR x
DIFFRINT x AN BIGGR OF x AN 0, O RLY?
YA RLY, FOUND YR "ERROR"
OIC
HOW IZ I fib_i YR n
DIFFRINT n AN BIGGR OF n AN 2, O RLY?
YA RLY, FOUND YR n
OIC
FOUND YR SUM OF...
I IZ fib_i YR DIFF OF n AN 2 MKAY AN...
I IZ fib_i YR DIFF OF n AN 1 MKAY
IF U SAY SO
FOUND YR I IZ fib_i YR x MKAY
IF U SAY SO
HOW IZ I fib_i YR n
VISIBLE "SRY U CANT HAS FIBS DIS TIEM"
IF U SAY SO
IM IN YR fibber UPPIN YR i TIL BOTH SAEM i AN 5
I HAS A i ITZ DIFF OF i AN 1
VISIBLE "fib(:{i}) = " I IZ fib YR i MKAY
IM OUTTA YR fibber
I IZ fib_i YR 3 MKAY
KTHXBYE |
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
{\displaystyle =M}
as well as
s
u
m
(
p
r
o
p
D
i
v
s
(
M
)
)
=
N
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (M))=N}
.
Example
1184 and 1210 are an amicable pair, with proper divisors:
1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592 and
1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605 respectively.
Task
Calculate and show here the Amicable pairs below 20,000; (there are eight).
Related tasks
Proper divisors
Abundant, deficient and perfect number classifications
Aliquot sequence classifications and its amicable classification.
| #JavaScript | JavaScript | (function (max) {
// Proper divisors
function properDivisors(n) {
if (n < 2) return [];
else {
var rRoot = Math.sqrt(n),
intRoot = Math.floor(rRoot),
lows = range(1, intRoot).filter(function (x) {
return (n % x) === 0;
});
return lows.concat(lows.slice(1).map(function (x) {
return n / x;
}).reverse().slice((rRoot === intRoot) | 0));
}
}
// [m..n]
function range(m, n) {
var a = Array(n - m + 1),
i = n + 1;
while (i--) a[i - 1] = i;
return a;
}
// Filter an array of proper divisor sums,
// reading the array index as a function of N (N-1)
// and the sum of proper divisors as a potential M
var pairs = range(1, max).map(function (x) {
return properDivisors(x).reduce(function (a, d) {
return a + d;
}, 0)
}).reduce(function (a, m, i, lst) {
var n = i + 1;
return (m > n) && lst[m - 1] === n ? a.concat([[n, m]]) : a;
}, []);
// [[a]] -> bool -> s -> s
function wikiTable(lstRows, blnHeaderRow, strStyle) {
return '{| class="wikitable" ' + (
strStyle ? 'style="' + strStyle + '"' : ''
) + lstRows.map(function (lstRow, iRow) {
var strDelim = ((blnHeaderRow && !iRow) ? '!' : '|');
return '\n|-\n' + strDelim + ' ' + lstRow.map(function (v) {
return typeof v === 'undefined' ? ' ' : v;
}).join(' ' + strDelim + strDelim + ' ');
}).join('') + '\n|}';
}
return wikiTable(
[['N', 'M']].concat(pairs),
true,
'text-align:center'
) + '\n\n' + JSON.stringify(pairs);
})(20000); |
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
Create a window containing the string "Hello World! " (the trailing space is significant).
Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front.
When the user clicks on the (windowed) text, it should reverse its direction.
| #Red | Red | Red ["Animation"]
rev: false
roule: does [e: back tail s: t/text either rev [move e s] [move s e]]
view [t: text "Hello world! " rate 5 [rev: not rev] on-time [roule]] |
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
Create a window containing the string "Hello World! " (the trailing space is significant).
Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front.
When the user clicks on the (windowed) text, it should reverse its direction.
| #REXX | REXX | /*REXX prg displays a text string (in one direction), and reverses when a key is pressed*/
parse upper version !ver !vernum .; !pcRexx= 'REXX/PERSONAL'==!ver | 'REXX/PC'==!ver
if \!pcRexx then do
say
say '***error*** This REXX program requires REXX/PERSONAL or REXX/PC.'
say
exit 1
end
parse arg $ /*obtain optional text message from CL.*/
if $='' then $= 'Hello World!' /*Not specified? Then use the default.*/
if right($, 1)\==' ' then $= $' ' /*ensure msg text has a trailing blank.*/
signal on halt /*handle a HALT if user quits this way.*/
way = 0 /*default direction for marquee display*/
y =
do until y=='Q'; 'CLS' /*if user presses Q or q, then quit.*/
call lineout ,$; call delay .2 /*display output; delay 1/5 of a second*/
y= inKey('Nowait'); upper y /*maybe get a pressed key; uppercase it*/
if y\=='' then way= \way /*change the direction of the marquee. */
if way then $= substr($, 2)left($, 1) /*display marquee in a direction or ···*/
else $= right($, 1)substr($, 1, length($) - 1) /* ··· the other·*/
end /*until*/
halt: /*stick a fork in it, we're all done. */ |
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.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | freq = 8; length = freq^(-1/2);
Animate[Graphics[
List[{Line[{{0, 0}, length {Sin[T], -Cos[T]}} /. {T -> (Pi/6) Cos[2 Pi freq t]}], PointSize[Large],
Point[{length {Sin[T], -Cos[T]}} /. {T -> (Pi/6) Cos[2 Pi freq t]}]}],
PlotRange -> {{-0.3, 0.3}, {-0.5, 0}}], {t, 0, 1}, AnimationRate -> 0.07] |
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 variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure.
Problems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent.
Essentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other "parallel universes" somehow go away. Amb called with no arguments fails.
For simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four.
A pseudo-code program which satisfies this constraint might look like:
let x = Amb(1, 2, 3)
let y = Amb(7, 6, 4, 5)
Amb(x * y = 8)
print x, y
The output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success.
Alternatively, failure could be represented using strictly Amb():
unless x * y = 8 do Amb()
Or else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints:
let x = Ambsel(1, 2, 3)
let y = Ambsel(4, 5, 6)
Ambassert(x * y = 8)
print x, y
where Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value.
The task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence:
"the" "that" "a"
"frog" "elephant" "thing"
"walked" "treaded" "grows"
"slowly" "quickly"
The constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor.
The only successful sentence is "that thing grows slowly"; other combinations do not satisfy the constraint and thus fail.
The goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.
| #E | E | pragma.enable("accumulator")
def [amb, unamb] := { # block hides internals
def Choice := Tuple[any, Map]
def [ambS, ambU] := <elib:sealing.makeBrand>("amb")
var counter := 0 # Used just for printing ambs
/** Check whether two sets of decisions are consistent */
def consistent(decA, decB) {
def overlap := decA.domain() & decB.domain()
for ambObj in overlap {
if (decA[ambObj] != decB[ambObj]) { return false }
}
return true
}
/** From an amb object, extract the possible choices */
def getChoices(obj, decisions) :List[Choice] {
if (decisions.maps(obj)) {
return [[decisions[obj], decisions]]
} else if (ambU.amplify(obj) =~ [[choices, _]]) {
return accum [] for [chosen, dec] ? (consistent(decisions, dec)) in choices { _ + getChoices(chosen, (decisions | dec).with(obj, chosen)) }
} else {
return [[obj, decisions]]
}
}
/** Construct an amb object with remembered decisions */
def ambDec(choices :List[Choice]) {
def serial := (counter += 1)
def ambObj {
to __printOn(out) {
out.print("<amb(", serial, ")")
for [chosen, decisions] in choices {
out.print(" ", chosen)
for k => v in decisions {
out.print(";", ambU.amplify(k)[0][1], "=", v)
}
}
out.print(">")
}
to __optSealedDispatch(brand) {
if (brand == ambS.getBrand()) {
return ambS.seal([choices, serial])
}
}
match [verb, args] {
var results := []
for [rec, rdec] in getChoices(ambObj, [].asMap()) {
def expandArgs(dec, prefix, choosing) {
switch (choosing) {
match [] { results with= [E.call(rec, verb, prefix), dec] }
match [argAmb] + moreArgs {
for [arg, adec] in getChoices(argAmb, dec) {
expandArgs(adec, prefix.with(arg), moreArgs)
}
}
}
}
expandArgs(rdec, [], args)
}
ambDec(results)
}
}
return ambObj
}
/** Construct an amb object with no remembered decisions. (public interface) */
def amb(choices) {
return ambDec(accum [] for c in choices { _.with([c, [].asMap()]) })
}
/** Get the possible results from an amb object, discarding decision info. (public interface) */
def unamb(ambObj) {
return accum [] for [c,_] in getChoices(ambObj, [].asMap()) { _.with(c) }
}
[amb, unamb]
} |
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.
| #D | D |
import openldap;
import std.stdio;
void main() {
auto ldap = LDAP("ldap://localhost");
auto r = ldap.search_s("dc=example,dc=com", LDAP_SCOPE_SUBTREE, "(uid=%s)".format("test"));
int b = ldap.bind_s(r[0].dn, "password");
scope(exit) ldap.unbind;
if (b)
{
writeln("error on binding");
return;
}
// do something
...
}
|
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.
| #Erlang | Erlang |
-module(ldap_example).
-export( [main/1] ).
main( [Host, DN, Password] ) ->
{ok, Handle} = eldap:open( [Host] ),
ok = eldap:simple_bind( Handle, DN, Password ),
eldap:close( Handle ).
|
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.
| #F.23 | F# | let adObject = new System.DirectoryServices.DirectoryEntry("LDAP://DC=onecity,DC=corp,DC=fabrikam,DC=com") |
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 second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called perfect.
If the third term would be repeating K then the sequence repeats with period 2 and K is called amicable.
If the Nth term would be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called sociable.
Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions...
Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence 95, 25, 6, 6, 6, ... such K are called aspiring.
K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence 562, 284, 220, 284, 220, ... such K are called cyclic.
And finally:
Some K form aliquot sequences that are not known to be either terminating or periodic; these K are to be called non-terminating.
For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating 16 terms or if any term of the sequence is greater than 2**47 = 140,737,488,355,328.
Task
Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above.
Use it to display the classification and sequences of the numbers one to ten inclusive.
Use it to show the classification and sequences of the following integers, in order:
11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080.
Show all output on this page.
Related tasks
Abundant, deficient and perfect number classifications. (Classifications from only the first two members of the whole sequence).
Proper divisors
Amicable pairs
| #C.2B.2B | C++ | #include <cstdint>
#include <iostream>
#include <string>
using integer = uint64_t;
// See https://en.wikipedia.org/wiki/Divisor_function
integer divisor_sum(integer n) {
integer total = 1, power = 2;
// Deal with powers of 2 first
for (; n % 2 == 0; power *= 2, n /= 2)
total += power;
// Odd prime factors up to the square root
for (integer p = 3; p * p <= n; p += 2) {
integer sum = 1;
for (power = p; n % p == 0; power *= p, n /= p)
sum += power;
total *= sum;
}
// If n > 1 then it's prime
if (n > 1)
total *= n + 1;
return total;
}
// See https://en.wikipedia.org/wiki/Aliquot_sequence
void classify_aliquot_sequence(integer n) {
constexpr int limit = 16;
integer terms[limit];
terms[0] = n;
std::string classification("non-terminating");
int length = 1;
for (int i = 1; i < limit; ++i) {
++length;
terms[i] = divisor_sum(terms[i - 1]) - terms[i - 1];
if (terms[i] == n) {
classification =
(i == 1 ? "perfect" : (i == 2 ? "amicable" : "sociable"));
break;
}
int j = 1;
for (; j < i; ++j) {
if (terms[i] == terms[i - j])
break;
}
if (j < i) {
classification = (j == 1 ? "aspiring" : "cyclic");
break;
}
if (terms[i] == 0) {
classification = "terminating";
break;
}
}
std::cout << n << ": " << classification << ", sequence: " << terms[0];
for (int i = 1; i < length && terms[i] != terms[i - 1]; ++i)
std::cout << ' ' << terms[i];
std::cout << '\n';
}
int main() {
for (integer i = 1; i <= 10; ++i)
classify_aliquot_sequence(i);
for (integer i : {11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562,
1064, 1488})
classify_aliquot_sequence(i);
classify_aliquot_sequence(15355717786080);
classify_aliquot_sequence(153557177860800);
return 0;
} |
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user | Active Directory/Search for a user | Make sure you Connect to Active Directory
| #ooRexx | ooRexx | /* Rexx */
do
LDAP_URL = 'ldap://localhost:11389'
LDAP_DN_STR = 'uid=admin,ou=system'
LDAP_CREDS = '********'
LDAP_BASE_DN = 'ou=users,o=mojo'
LDAP_SCOPE = 'sub'
LDAP_FILTER = '"(&(objectClass=person)(&(uid=*mil*)))"'
LDAP_ATTRIBUTES = '"dn" "cn" "sn" "uid"'
ldapCommand = ,
'ldapsearch' ,
'-s base' ,
'-H' LDAP_URL ,
'-LLL' ,
'-x' ,
'-v' ,
'-s' LDAP_SCOPE ,
'-D' LDAP_DN_STR ,
'-w' LDAP_CREDS ,
'-b' LDAP_BASE_DN ,
LDAP_FILTER ,
LDAP_ATTRIBUTES ,
'2>&1' ,
'|' ,
'rxqueue' ,
''
address command,
ldapCommand
ldapResult. = ''
loop ln = 1 to queued()
parse pull line
ldapResult.0 = ln
ldapResult.ln = line
end ln
loop ln = 1 to ldapResult.0
parse var ldapResult.ln 'dn:' dn_ ,
0 'uid:' uid_ ,
0 'sn:' sn_ ,
0 'cn:' cn_
select
when length(strip(dn_, 'b')) > 0 then dn = dn_
when length(strip(uid_, 'b')) > 0 then uid = uid_
when length(strip(sn_, 'b')) > 0 then sn = sn_
when length(strip(cn_, 'b')) > 0 then cn = cn_
otherwise nop
end
end ln
say 'Distiguished Name:' dn
say ' Common Name:' cn
say ' Surname:' sn
say ' userID:' uid
return
end
exit
|
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user | Active Directory/Search for a user | Make sure you Connect to Active Directory
| #Perl | Perl | # 20210306 Perl programming solution
use strict;
use warnings;
use Net::LDAP;
my $ldap = Net::LDAP->new( 'ldap://ldap.forumsys.com' ) or die "$@";
my $mesg = $ldap->bind( "cn=read-only-admin,dc=example,dc=com",
password => "password" );
$mesg->code and die $mesg->error;
my $srch = $ldap->search( base => "dc=example,dc=com",
filter => "(|(uid=gauss))" );
$srch->code and die $srch->error;
foreach my $entry ($srch->entries) { $entry->dump }
$mesg = $ldap->unbind; |
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 referred to as "monkeypatching" by Pythonistas and some others.
| #CoffeeScript | CoffeeScript | # CoffeeScript is dynamic, just like the Javascript it compiles to.
# You can dynamically add attributes to objects.
# First create an object very simply.
e = {}
e.foo = "bar"
e.yo = -> "baz"
console.log e.foo, e.yo()
# CS also has class syntax to instantiate objects, the details of which
# aren't shown here. The mechanism to add members is the same, though.
class Empty
# empty class
e = new Empty()
e.foo = "bar"
e.yo = -> "baz"
console.log e.foo, e.yo()
|
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 referred to as "monkeypatching" by Pythonistas and some others.
| #Common_Lisp | Common Lisp | (defun augment-instance-with-slots (instance slots)
(change-class instance
(make-instance 'standard-class
:direct-superclasses (list (class-of instance))
:direct-slots slots))) |
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 referred to as "monkeypatching" by Pythonistas and some others.
| #D | D | struct Dynamic(T) {
private T[string] vars;
@property T opDispatch(string key)() pure nothrow {
return vars[key];
}
@property void opDispatch(string key, U)(U value) pure nothrow {
vars[key] = value;
}
}
void main() {
import std.variant, std.stdio;
// If the type of the attributes is known at compile-time:
auto d1 = Dynamic!double();
d1.first = 10.5;
d1.second = 20.2;
writeln(d1.first, " ", d1.second);
// If the type of the attributes is mixed:
auto d2 = Dynamic!Variant();
d2.a = "Hello";
d2.b = 11;
d2.c = ['x':2, 'y':4];
d2.d = (int x) => x ^^ 3;
writeln(d2.a, " ", d2.b, " ", d2.c);
immutable int x = d2.b.get!int;
} |
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 |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Demonstrate how to get the address of a variable and how to set the address of a variable.
| #Draco | Draco | /* This code uses a CP/M-specific address to demonstrate fixed locations,
* so it will very likely only work under CP/M */
proc nonrec main() void:
/* When declaring a variable, you can let the compiler choose an address */
word var;
/* Or you can set the address manually using @, to a fixed address */
word memtop @ 0x6; /* CP/M stores the top of memory at 0x0006 */
/* or to the address of another variable, by naming that variable */
word var2 @ var; /* var2 will overlap var */
/* This works with both automatically and manually placed variables. */
word memtop2 @ memtop; /* same as "memtop2 @ 0x6" */
/* Once a variable is declared, you can't change its address at runtime. */
var := 1234; /* assign a value to var _and_ var2 */
/* The address of a variable can be retrieved using the & operator.
* However, this returns a pointer type, which is distinct from an
* integer type. To use it as a number, we have to coerce it to an integer
* first. */
writeln("var address=", pretend(&var,word):5, " value=", var:5);
writeln("memtop address=", pretend(&memtop,word):5, " value=", memtop:5);
writeln("var2 address=", pretend(&var2,word):5, " value=", var2:5);
writeln("memtop2 address=", pretend(&memtop2,word):5, " value=", memtop2:5)
corp |
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 |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Demonstrate how to get the address of a variable and how to set the address of a variable.
| #ERRE | ERRE |
........
A%=100
ADDR=VARPTR(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 |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Demonstrate how to get the address of a variable and how to set the address of a variable.
| #FBSL | FBSL | ReferenceOf a = b
|
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 expansion of
(
x
−
1
)
p
−
(
x
p
−
1
)
{\displaystyle (x-1)^{p}-(x^{p}-1)}
are divisible by
p
{\displaystyle p}
.
Example
Using
p
=
3
{\displaystyle p=3}
:
(x-1)^3 - (x^3 - 1)
= (x^3 - 3x^2 + 3x - 1) - (x^3 - 1)
= -3x^2 + 3x
And all the coefficients are divisible by 3, so 3 is prime.
Note:
This task is not the AKS primality test. It is an inefficient exponential time algorithm discovered in the late 1600s and used as an introductory lemma in the AKS derivation.
Task
Create a function/subroutine/method that given
p
{\displaystyle p}
generates the coefficients of the expanded polynomial representation of
(
x
−
1
)
p
{\displaystyle (x-1)^{p}}
.
Use the function to show here the polynomial expansions of
(
x
−
1
)
p
{\displaystyle (x-1)^{p}}
for
p
{\displaystyle p}
in the range 0 to at least 7, inclusive.
Use the previous function in creating another function that when given
p
{\displaystyle p}
returns whether
p
{\displaystyle p}
is prime using the theorem.
Use your test to generate a list of all primes under 35.
As a stretch goal, generate all primes under 50 (needs integers larger than 31-bit).
References
Agrawal-Kayal-Saxena (AKS) primality test (Wikipedia)
Fool-Proof Test for Primes - Numberphile (Video). The accuracy of this video is disputed -- at best it is an oversimplification.
| #Bracmat | Bracmat | ( (forceExpansion=.1+!arg+-1)
& (expandx-1P=.forceExpansion$((x+-1)^!arg))
& ( isPrime
=
. forceExpansion
$ (!arg^-1*(expandx-1P$!arg+-1*(x^!arg+-1)))
: ?+/*?+?
& ~`
|
)
& out$"Polynomial representations of (x-1)^p for p <= 7 :"
& -1:?n
& whl
' ( 1+!n:~>7:?n
& out$(str$("n=" !n ":") expandx-1P$!n)
)
& 1:?n
& :?primes
& whl
' ( 1+!n:~>50:?n
& ( isPrime$!n&!primes !n:?primes
|
)
)
& out$"2 <= Primes <= 50:"
& out$!primes
); |
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.
the prime-numbers entry: additive primes.
the geeks for geeks entry: additive prime number.
the prime-numbers fandom: additive primes.
| #BASIC | BASIC | 10 DEFINT A-Z: E=500
20 DIM P(E): P(0)=-1: P(1)=-1
30 FOR I=2 TO SQR(E)
40 IF NOT P(I) THEN FOR J=I*2 TO E STEP I: P(J)=-1: NEXT
50 NEXT
60 FOR I=B TO E: IF P(I) GOTO 100
70 J=I: S=0
80 IF J>0 THEN S=S+J MOD 10: J=J\10: GOTO 80
90 IF NOT P(S) THEN N=N+1: PRINT I,
100 NEXT
110 PRINT: PRINT N;" additive primes found below ";E |
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.
the prime-numbers entry: additive primes.
the geeks for geeks entry: additive prime number.
the prime-numbers fandom: additive primes.
| #BASIC256 | BASIC256 | print "Prime", "Digit Sum"
for i = 2 to 499
if isprime(i) then
s = digSum(i)
if isPrime(s) then print i, s
end if
next i
end
function isPrime(v)
if v < 2 then return False
if v mod 2 = 0 then return v = 2
if v mod 3 = 0 then return v = 3
d = 5
while d * d <= v
if v mod d = 0 then return False else d += 2
end while
return True
end function
function digsum(n)
s = 0
while n
s += n mod 10
n /= 10
end while
return s
end function |
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-black-tree.
A red-black-tree is a binary tree where each internal node has a color attribute red or black. Moreover, no red node can have a red child, and every path from the root to an empty node must contain the same number of black nodes. As a consequence, the tree is balanced, and must be re-balanced after an insertion.
Reference
Red-Black Trees in a Functional Setting
| #Oz | Oz | fun {Balance Col A X B}
case Col#A#X#B
of b#t(r t(r A X B) Y C )#Z#D then t(r t(b A X B) Y t(b C Z D))
[] b#t(r A X t(r B Y C))#Z#D then t(r t(b A X B) Y t(b C Z D))
[] b#A #X#t(r t(r B Y C) Z D) then t(r t(b A X B) Y t(b C Z D))
[] b#A #X#t(r B Y t(r C Z D)) then t(r t(b A X B) Y t(b C Z D))
else t(Col A X B)
end
end
fun {Insert X S}
fun {Ins S}
case S of e then t(r e X e)
[] t(Col A Y B) then
if X < Y then {Balance Col {Ins A} Y B}
elseif X > Y then {Balance Col A Y {Ins B}}
else S
end
end
end
t(_ A Y B) = {Ins S}
in
t(b A Y B)
end |
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
{\displaystyle k=2}
, are the semiprimes.
Task
Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for
1
<=
K
<=
5
{\displaystyle 1<=K<=5}
.
Related tasks
Semiprime
Category:Prime Numbers
| #ERRE | ERRE |
PROGRAM ALMOST_PRIME
!
! for rosettacode.org
!
!$INTEGER
PROCEDURE KPRIME(N,K->KP)
LOCAL P,F
FOR P=2 TO 999 DO
EXIT IF NOT((F<K) AND (P*P<=N))
WHILE (N MOD P)=0 DO
N/=P
F+=1
END WHILE
END FOR
KP=(F-(N>1)=K)
END PROCEDURE
BEGIN
PRINT(CHR$(12);) !CLS
FOR K=1 TO 5 DO
PRINT("k =";K;":";)
C=0
FOR I=2 TO 999 DO
EXIT IF NOT(C<10)
KPRIME(I,K->KP)
IF KP THEN
PRINT(I;)
C+=1
END IF
END FOR
PRINT
END FOR
END PROGRAM
|
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
{\displaystyle k=2}
, are the semiprimes.
Task
Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for
1
<=
K
<=
5
{\displaystyle 1<=K<=5}
.
Related tasks
Semiprime
Category:Prime Numbers
| #F.23 | F# | let rec genFactor (f, n) =
if f > n then None
elif n % f = 0 then Some (f, (f, n/f))
else genFactor (f+1, n)
let factorsOf (num) =
Seq.unfold (fun (f, n) -> genFactor (f, n)) (2, num)
let kFactors k = Seq.unfold (fun n ->
let rec loop m =
if Seq.length (factorsOf m) = k then m
else loop (m+1)
let next = loop n
Some(next, next+1)) 2
[1 .. 5]
|> List.iter (fun k ->
printfn "%A" (Seq.take 10 (kFactors k) |> Seq.toList)) |
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
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
char *sortedWord(const char *word, char *wbuf)
{
char *p1, *p2, *endwrd;
char t;
int swaps;
strcpy(wbuf, word);
endwrd = wbuf+strlen(wbuf);
do {
swaps = 0;
p1 = wbuf; p2 = endwrd-1;
while (p1<p2) {
if (*p2 > *p1) {
t = *p2; *p2 = *p1; *p1 = t;
swaps = 1;
}
p1++; p2--;
}
p1 = wbuf; p2 = p1+1;
while(p2 < endwrd) {
if (*p2 > *p1) {
t = *p2; *p2 = *p1; *p1 = t;
swaps = 1;
}
p1++; p2++;
}
} while (swaps);
return wbuf;
}
static
short cxmap[] = {
0x06, 0x1f, 0x4d, 0x0c, 0x5c, 0x28, 0x5d, 0x0e, 0x09, 0x33, 0x31, 0x56,
0x52, 0x19, 0x29, 0x53, 0x32, 0x48, 0x35, 0x55, 0x5e, 0x14, 0x27, 0x24,
0x02, 0x3e, 0x18, 0x4a, 0x3f, 0x4c, 0x45, 0x30, 0x08, 0x2c, 0x1a, 0x03,
0x0b, 0x0d, 0x4f, 0x07, 0x20, 0x1d, 0x51, 0x3b, 0x11, 0x58, 0x00, 0x49,
0x15, 0x2d, 0x41, 0x17, 0x5f, 0x39, 0x16, 0x42, 0x37, 0x22, 0x1c, 0x0f,
0x43, 0x5b, 0x46, 0x4b, 0x0a, 0x26, 0x2e, 0x40, 0x12, 0x21, 0x3c, 0x36,
0x38, 0x1e, 0x01, 0x1b, 0x05, 0x4e, 0x44, 0x3d, 0x04, 0x10, 0x5a, 0x2a,
0x23, 0x34, 0x25, 0x2f, 0x2b, 0x50, 0x3a, 0x54, 0x47, 0x59, 0x13, 0x57,
};
#define CXMAP_SIZE (sizeof(cxmap)/sizeof(short))
int Str_Hash( const char *key, int ix_max )
{
const char *cp;
short mash;
int hash = 33501551;
for (cp = key; *cp; cp++) {
mash = cxmap[*cp % CXMAP_SIZE];
hash = (hash >>4) ^ 0x5C5CF5C ^ ((hash<<1) + (mash<<5));
hash &= 0x3FFFFFFF;
}
return hash % ix_max;
}
typedef struct sDictWord *DictWord;
struct sDictWord {
const char *word;
DictWord next;
};
typedef struct sHashEntry *HashEntry;
struct sHashEntry {
const char *key;
HashEntry next;
DictWord words;
HashEntry link;
short wordCount;
};
#define HT_SIZE 8192
HashEntry hashTable[HT_SIZE];
HashEntry mostPerms = NULL;
int buildAnagrams( FILE *fin )
{
char buffer[40];
char bufr2[40];
char *hkey;
int hix;
HashEntry he, *hep;
DictWord we;
int maxPC = 2;
int numWords = 0;
while ( fgets(buffer, 40, fin)) {
for(hkey = buffer; *hkey && (*hkey!='\n'); hkey++);
*hkey = 0;
hkey = sortedWord(buffer, bufr2);
hix = Str_Hash(hkey, HT_SIZE);
he = hashTable[hix]; hep = &hashTable[hix];
while( he && strcmp(he->key , hkey) ) {
hep = &he->next;
he = he->next;
}
if ( ! he ) {
he = malloc(sizeof(struct sHashEntry));
he->next = NULL;
he->key = strdup(hkey);
he->wordCount = 0;
he->words = NULL;
he->link = NULL;
*hep = he;
}
we = malloc(sizeof(struct sDictWord));
we->word = strdup(buffer);
we->next = he->words;
he->words = we;
he->wordCount++;
if ( maxPC < he->wordCount) {
maxPC = he->wordCount;
mostPerms = he;
he->link = NULL;
}
else if (maxPC == he->wordCount) {
he->link = mostPerms;
mostPerms = he;
}
numWords++;
}
printf("%d words in dictionary max ana=%d\n", numWords, maxPC);
return maxPC;
}
int main( )
{
HashEntry he;
DictWord we;
FILE *f1;
f1 = fopen("unixdict.txt","r");
buildAnagrams(f1);
fclose(f1);
f1 = fopen("anaout.txt","w");
// f1 = stdout;
for (he = mostPerms; he; he = he->link) {
fprintf(f1,"%d:", he->wordCount);
for(we = he->words; we; we = we->next) {
fprintf(f1,"%s, ", we->word);
}
fprintf(f1, "\n");
}
fclose(f1);
return 0;
} |
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.
Compute the angle for the following pairs:
20 degrees (b1) and 45 degrees (b2)
-45 and 45
-85 and 90
-95 and 90
-45 and 125
-45 and 145
29.4803 and -88.6381
-78.3251 and -159.036
Optional extra
Allow the input bearings to be any (finite) value.
Test cases
-70099.74233810938 and 29840.67437876723
-165313.6666297357 and 33693.9894517456
1174.8380510598456 and -154146.66490124757
60175.77306795546 and 42213.07192354373
| #NewLISP | NewLISP |
#!/usr/bin/env newlisp
(define (bearing- bearing heading) (sub (mod (add (mod (sub bearing heading) 360.0) 540.0) 360.0) 180.0))
(bearing- 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.8380510598456 -154146.66490124757)
(bearing- 60175.77306795546 42213.07192354373))
|
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 unixdict to find and display the longest deranged anagram.
Related tasks
Permutations/Derangements
Best shuffle
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #PHP | PHP | <?php
$words = file(
'http://www.puzzlers.org/pub/wordlists/unixdict.txt',
FILE_IGNORE_NEW_LINES
);
$length = 0;
foreach ($words as $word) {
$chars = str_split($word);
sort($chars);
$chars = implode("", $chars);
$length = strlen($chars);
$anagrams[$length][$chars][] = $word;
}
krsort($anagrams);
foreach ($anagrams as $anagram) {
$final_words = array();
foreach ($anagram as $words) {
if (count($words) >= 2) {
$counts = array();
foreach ($words as $word) {
$counts[$word] = array($word);
foreach ($words as $second_word) {
for ($i = 0, $length = strlen($word); $i < $length; $i++) {
if ($word[$i] === $second_word[$i]) continue 2;
}
$counts[$word][] = $second_word;
}
}
$max = 0;
$max_key = '';
foreach ($counts as $name => $count) {
if (count($count) > $max) {
$max = count($count);
$max_key = $name;
}
}
if ($max > 1) {
$final_words[] = $counts[$max_key];
}
}
}
if ($final_words) break;
}
foreach ($final_words as $final_word) {
echo implode(" ", $final_word), "\n";
}
?> |
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 function doesn't have the right arguments and/or return values.
So we end up inventing some silly name like foo2 or foo_helper. I have always found it painful to come up with a proper name, and see some disadvantages:
You have to think up a name, which then pollutes the namespace
Function is created which is called from nowhere else
The program flow in the source code is interrupted
Some languages allow you to embed recursion directly in-place. This might work via a label, a local gosub instruction, or some special keyword.
Anonymous recursion can also be accomplished using the Y combinator.
Task
If possible, demonstrate this by writing the recursive version of the fibonacci function (see Fibonacci sequence) which checks for a negative argument before doing the actual recursion.
| #Lua | Lua | local function Y(x) return (function (f) return f(f) end)(function(y) return x(function(z) return y(y)(z) end) end) end
return Y(function(fibs)
return function(n)
return n < 2 and 1 or fibs(n - 1) + fibs(n - 2)
end
end) |
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
{\displaystyle =M}
as well as
s
u
m
(
p
r
o
p
D
i
v
s
(
M
)
)
=
N
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (M))=N}
.
Example
1184 and 1210 are an amicable pair, with proper divisors:
1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592 and
1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605 respectively.
Task
Calculate and show here the Amicable pairs below 20,000; (there are eight).
Related tasks
Proper divisors
Abundant, deficient and perfect number classifications
Aliquot sequence classifications and its amicable classification.
| #jq | jq | # unordered
def proper_divisors:
. as $n
| if $n > 1 then 1,
(sqrt|floor as $s
| range(2; $s+1) as $i
| if ($n % $i) == 0 then $i,
(if $i * $i == $n then empty else ($n / $i) end)
else empty
end)
else empty
end;
def addup(stream): reduce stream as $i (0; . + $i);
def task(n):
(reduce range(0; n+1) as $n
( []; . + [$n | addup(proper_divisors)] )) as $listing
| range(1;n+1) as $j
| range(1;$j) as $k
| if $listing[$j] == $k and $listing[$k] == $j
then "\($k) and \($j) are amicable"
else empty
end ;
task(20000) |
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
Create a window containing the string "Hello World! " (the trailing space is significant).
Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front.
When the user clicks on the (windowed) text, it should reverse its direction.
| #Ring | Ring |
# Project : Animation
Load "guilib.ring"
load "stdlib.ring"
rotate = false
MyApp = New qApp {
win1 = new qWidget() {
setwindowtitle("Hello World")
setGeometry(100,100,370,250)
lineedit1 = new qlineedit(win1) {
setGeometry(10,100,350,30)
lineedit1.settext(" Hello World! ")
myfilter = new qallevents(lineedit1)
myfilter.setMouseButtonPressevent("rotatetext()")
installeventfilter(myfilter)}
show()}
exec()}
func rotatetext()
rotate = not rotate
strold = " Hello World! "
for n = 1 to 15
if rotate = true
see "str = " + '"' + strold + '"' + nl
strnew = right(strold, 1) + left(strold, len(strold) - 1)
lineedit1.settext(strnew)
strold = strnew
sleep(1)
ok
if rotate = false
see "str = " + '"' + strold + '"' + nl
strnew = right(strold, len(strold) - 1) + left(strold, 1)
lineedit1.settext(strnew)
strold = strnew
sleep(1)
ok
next
see nl
|
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
Create a window containing the string "Hello World! " (the trailing space is significant).
Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front.
When the user clicks on the (windowed) text, it should reverse its direction.
| #Ruby | Ruby | require 'tk'
$str = TkVariable.new("Hello World! ")
$dir = :right
def animate
$str.value = shift_char($str.value, $dir)
$root.after(125) {animate}
end
def shift_char(str, dir)
case dir
when :right then str[-1,1] + str[0..-2]
when :left then str[1..-1] + str[0,1]
end
end
$root = TkRoot.new("title" => "Basic Animation")
TkLabel.new($root) do
textvariable $str
font "Courier 14"
pack {side 'top'}
bind("ButtonPress-1") {$dir = {:right=>:left,:left=>:right}[$dir]}
end
animate
Tk.mainloop |
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.
| #MATLAB | MATLAB | %This is a numerical simulation of a pendulum with a massless pivot arm.
%% User Defined Parameters
%Define external parameters
g = -9.8;
deltaTime = 1/50; %Decreasing this will increase simulation accuracy
endTime = 16;
%Define pendulum
rodPivotPoint = [2 2]; %rectangular coordinates
rodLength = 1;
mass = 1; %of the bob
radius = .2; %of the bob
theta = 45; %degrees, defines initial position of the bob
velocity = [0 0]; %cylindrical coordinates; first entry is radial velocity,
%second entry is angular velocity
%% Simulation
assert(radius < rodLength,'Pendulum bob radius must be less than the length of the rod.');
position = rodPivotPoint - (rodLength*[-sind(theta) cosd(theta)]); %in rectangular coordinates
%Generate graphics, render pendulum
figure;
axesHandle = gca;
xlim(axesHandle, [(rodPivotPoint(1) - rodLength - radius) (rodPivotPoint(1) + rodLength + radius)] );
ylim(axesHandle, [(rodPivotPoint(2) - rodLength - radius) (rodPivotPoint(2) + rodLength + radius)] );
rectHandle = rectangle('Position',[(position - radius/2) radius radius],...
'Curvature',[1,1],'FaceColor','g'); %Pendulum bob
hold on
plot(rodPivotPoint(1),rodPivotPoint(2),'^'); %pendulum pivot
lineHandle = line([rodPivotPoint(1) position(1)],...
[rodPivotPoint(2) position(2)]); %pendulum rod
hold off
%Run simulation, all calculations are performed in cylindrical coordinates
for time = (deltaTime:deltaTime:endTime)
drawnow; %Forces MATLAB to render the pendulum
%Find total force
gravitationalForceCylindrical = [mass*g*cosd(theta) mass*g*sind(theta)];
%This code is just incase you want to add more forces,e.g friction
totalForce = gravitationalForceCylindrical;
%If the rod isn't massless or is a spring, etc., modify this line
%accordingly
rodForce = [-totalForce(1) 0]; %cylindrical coordinates
totalForce = totalForce + rodForce;
acceleration = totalForce / mass; %F = ma
velocity = velocity + acceleration * deltaTime;
rodLength = rodLength + velocity(1) * deltaTime;
theta = theta + velocity(2) * deltaTime; % Attention!! Mistake here.
% Velocity needs to be divided by pendulum length and scaled to degrees:
% theta = theta + velocity(2) * deltaTime/rodLength/pi*180;
position = rodPivotPoint - (rodLength*[-sind(theta) cosd(theta)]);
%Update figure with new position info
set(rectHandle,'Position',[(position - radius/2) radius radius]);
set(lineHandle,'XData',[rodPivotPoint(1) position(1)],'YData',...
[rodPivotPoint(2) position(2)]);
end |
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 variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure.
Problems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent.
Essentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other "parallel universes" somehow go away. Amb called with no arguments fails.
For simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four.
A pseudo-code program which satisfies this constraint might look like:
let x = Amb(1, 2, 3)
let y = Amb(7, 6, 4, 5)
Amb(x * y = 8)
print x, y
The output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success.
Alternatively, failure could be represented using strictly Amb():
unless x * y = 8 do Amb()
Or else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints:
let x = Ambsel(1, 2, 3)
let y = Ambsel(4, 5, 6)
Ambassert(x * y = 8)
print x, y
where Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value.
The task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence:
"the" "that" "a"
"frog" "elephant" "thing"
"walked" "treaded" "grows"
"slowly" "quickly"
The constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor.
The only successful sentence is "that thing grows slowly"; other combinations do not satisfy the constraint and thus fail.
The goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.
| #Egison | Egison |
; We don't need 'amb' in the code since pattern-matching of Egison automatically do backtracking.
(match-all {{"the" "that" "a"} {"frog" "elephant" "thing"} {"walked" "treaded" "grows"} {"slowly" "quickly"}} (list (multiset string))
[<cons <cons (& <snoc $c_1 _> $w_1) _>
(loop $i [2 $n]
<cons <cons (& <cons ,c_(- i 1) <snoc $c_i _>> $w_i) _> ...>
<nil>)>
(map (lambda [$i] w_i) (between 1 n))])
|
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.
| #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,
UseSSL: false,
BindDN: "uid=readonlyuser,ou=People,dc=example,dc=com",
BindPassword: "readonlypassword",
UserFilter: "(uid=%s)",
GroupFilter: "(memberUid=%s)",
Attributes: []string{"givenName", "sn", "mail", "uid"},
}
defer client.Close()
err := client.Connect()
if err != nil {
log.Fatalf("Failed to connect : %+v", err)
}
// Do something
} |
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.
| #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
entries <- Ldap.with (Ldap.Plain "localhost") 389 $ \ldap ->
Ldap.search ldap (Ldap.Dn "o=example.com") (Ldap.typesOnly True) (Attr "uid" := Text.encodeUtf8 "user") []
for_ entries $ \entry ->
print entry |
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.
| #Java | Java | import java.io.IOException;
import org.apache.directory.api.ldap.model.exception.LdapException;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.directory.ldap.client.api.LdapNetworkConnection;
public class LdapConnectionDemo {
public static void main(String[] args) throws LdapException, IOException {
try (LdapConnection connection = new LdapNetworkConnection("localhost", 10389)) {
connection.bind();
connection.unBind();
}
}
} |
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 second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called perfect.
If the third term would be repeating K then the sequence repeats with period 2 and K is called amicable.
If the Nth term would be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called sociable.
Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions...
Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence 95, 25, 6, 6, 6, ... such K are called aspiring.
K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence 562, 284, 220, 284, 220, ... such K are called cyclic.
And finally:
Some K form aliquot sequences that are not known to be either terminating or periodic; these K are to be called non-terminating.
For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating 16 terms or if any term of the sequence is greater than 2**47 = 140,737,488,355,328.
Task
Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above.
Use it to display the classification and sequences of the numbers one to ten inclusive.
Use it to show the classification and sequences of the following integers, in order:
11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080.
Show all output on this page.
Related tasks
Abundant, deficient and perfect number classifications. (Classifications from only the first two members of the whole sequence).
Proper divisors
Amicable pairs
| #CLU | CLU | % This program uses the 'bigint' cluster from PCLU's 'misc.lib'
% Remove leading and trailing whitespace (bigint$unparse adds a lot)
strip = proc (s: string) returns (string)
ac = array[char]
sc = sequence[char]
cs: ac := string$s2ac(s)
while ~ac$empty(cs) cand ac$bottom(cs)=' ' do ac$reml(cs) end
while ~ac$empty(cs) cand ac$top(cs)=' ' do ac$remh(cs) end
% There's a bug in ac2s that makes it not return all elements
% This is a workaround
return(string$sc2s(sc$a2s(cs)))
end strip
divisor_sum = proc (n: bigint) returns (bigint)
own zero: bigint := bigint$i2bi(0)
own one: bigint := bigint$i2bi(1)
own two: bigint := bigint$i2bi(2)
own three: bigint := bigint$i2bi(3)
total: bigint := one
power: bigint := two
while n//two=zero do
total := total + power
power := power * two
n := n / two
end
p: bigint := three
while p*p <= n do
sum: bigint := one
power := p
while n//p = zero do
sum := sum + power
power := power * p
n := n/p
end
total := total * sum
p := p + two
end
if n>one then total := total * (n+one) end
return(total)
end divisor_sum
classify_aliquot_sequence = proc (n: bigint)
LIMIT = 16
abi = array[bigint]
own zero: bigint := bigint$i2bi(0)
po: stream := stream$primary_output()
terms: array[bigint] := abi$predict(0,LIMIT)
abi$addh(terms, n)
classification: string := "non-terminating"
for i: int in int$from_to(1, limit-1) do
abi$addh(terms, divisor_sum(abi$top(terms)) - abi$top(terms))
if abi$top(terms) = n then
if i=1 then classification := "perfect"
elseif i=2 then classification := "amicable"
else classification := "sociable"
end
break
end
j: int := 1
while j<i cand terms[i] ~= terms[i-j] do j := j+1 end
if j<i then
if j=1 then classification := "aspiring"
else classification := "cyclic"
end
break
end
if abi$top(terms) = zero then
classification := "terminating"
break
end
end
stream$puts(po, strip(bigint$unparse(n)) || ": " || classification || ", sequence: "
|| strip(bigint$unparse(terms[0])))
for i: int in int$from_to(1, abi$high(terms)) do
if terms[i] = terms[i-1] then break end
stream$puts(po, " " || strip(bigint$unparse(terms[i])))
end
stream$putl(po, "")
end classify_aliquot_sequence
start_up = proc ()
for i: int in int$from_to(1, 10) do
classify_aliquot_sequence(bigint$i2bi(i))
end
for i: int in array[int]$elements(array[int]$
[11,12,28,496,220,1184,12496,1264460,790,909,562,1064,1488]) do
classify_aliquot_sequence(bigint$i2bi(i))
end
classify_aliquot_sequence(bigint$parse("15355717786080"))
classify_aliquot_sequence(bigint$parse("153557177860800"))
end start_up |
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user | Active Directory/Search for a user | Make sure you Connect to Active Directory
| #Phix | Phix | include builtins/ldap.e
constant servers = {
"ldap.somewhere.com",
}
--...
string name="name", password="passwd"
--...
for i=1 to length(servers) do
atom ld = ldap_init(servers[i])
integer res = ldap_simple_bind_s(ld, name, password)
printf(1,"%s: %d [%s]\n",{servers[i],res,ldap_err_desc(res)})
if res=LDAP_SUCCESS then
{res, atom pMsg} = 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=joe*)(cn=shmoe*)))",
NULL, -- return all attributes
0) -- want both types and values of attrs
-- arduously do stuff here to result, with ldap_first_message(), ldap_parse_result(), etc.
ldap_msgfree(pMsg) -- free messages (embedded NULL check)
end if
--... after done with it...
ldap_unbind(ld)
end for
|
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user | Active Directory/Search for a user | Make sure you Connect to Active Directory
| #PHP | PHP | <?php
$l = ldap_connect('ldap.example.com');
ldap_set_option($l, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($l, LDAP_OPT_REFERRALS, false);
$bind = ldap_bind($l, '[email protected]', 'password');
$base = 'dc=example, dc=com';
$criteria = '(&(objectClass=user)(sAMAccountName=username))';
$attributes = array('displayName', 'company');
$search = ldap_search($l, $base, $criteria, $attributes);
$entries = ldap_get_entries($l, $search);
var_dump($entries); |
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 referred to as "monkeypatching" by Pythonistas and some others.
| #Elena | Elena | import extensions;
class Extender : BaseExtender
{
prop object foo;
constructor(object)
{
theObject := object
}
}
public program()
{
var object := 234;
// extending an object with a field
object := new Extender(object);
object.foo := "bar";
console.printLine(object,".foo=",object.foo);
console.readChar()
} |
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 referred to as "monkeypatching" by Pythonistas and some others.
| #Falcon | Falcon | vect = [ 'alpha', 'beta', 'gamma' ]
vect.dump = function ()
for n in [0: self.len()]
> @"$(n): ", self[n]
end
end
vect += 'delta'
vect.dump() |
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 referred to as "monkeypatching" by Pythonistas and some others.
| #FBSL | FBSL | #APPTYPE CONSOLE
CLASS Growable
PRIVATE:
DIM instructions AS STRING = "Sleep(1)"
:ExecCode
DIM dummy AS INTEGER = EXECLINE(instructions, 1)
PUBLIC:
METHOD Absorb(code AS STRING)
instructions = code
GOTO ExecCode
END METHOD
METHOD Yield() AS VARIANT
RETURN result
END METHOD
END CLASS
DIM Sponge AS NEW Growable()
Sponge.Absorb("DIM b AS VARIANT = 1234567890: DIM result AS VARIANT = b")
PRINT Sponge.Yield()
Sponge.Absorb("b = ""Hello world!"": result = b")
PRINT Sponge.Yield()
PAUSE |
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 |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Demonstrate how to get the address of a variable and how to set the address of a variable.
| #Forth | Forth | variable foo
foo . \ some large number, an address
8 foo !
foo @ . \ 8
|
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 |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Demonstrate how to get the address of a variable and how to set the address of a variable.
| #Fortran | Fortran | program test_loc
implicit none
integer :: i
real :: r
i = loc(r)
print *, i
end program |
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 |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Demonstrate how to get the address of a variable and how to set the address of a variable.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Dim a As Integer = 3
Dim p As Integer Ptr = @a
Print a, p |
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 expansion of
(
x
−
1
)
p
−
(
x
p
−
1
)
{\displaystyle (x-1)^{p}-(x^{p}-1)}
are divisible by
p
{\displaystyle p}
.
Example
Using
p
=
3
{\displaystyle p=3}
:
(x-1)^3 - (x^3 - 1)
= (x^3 - 3x^2 + 3x - 1) - (x^3 - 1)
= -3x^2 + 3x
And all the coefficients are divisible by 3, so 3 is prime.
Note:
This task is not the AKS primality test. It is an inefficient exponential time algorithm discovered in the late 1600s and used as an introductory lemma in the AKS derivation.
Task
Create a function/subroutine/method that given
p
{\displaystyle p}
generates the coefficients of the expanded polynomial representation of
(
x
−
1
)
p
{\displaystyle (x-1)^{p}}
.
Use the function to show here the polynomial expansions of
(
x
−
1
)
p
{\displaystyle (x-1)^{p}}
for
p
{\displaystyle p}
in the range 0 to at least 7, inclusive.
Use the previous function in creating another function that when given
p
{\displaystyle p}
returns whether
p
{\displaystyle p}
is prime using the theorem.
Use your test to generate a list of all primes under 35.
As a stretch goal, generate all primes under 50 (needs integers larger than 31-bit).
References
Agrawal-Kayal-Saxena (AKS) primality test (Wikipedia)
Fool-Proof Test for Primes - Numberphile (Video). The accuracy of this video is disputed -- at best it is an oversimplification.
| #C | C | #include <stdio.h>
#include <stdlib.h>
long long c[100];
void coef(int n)
{
int i, j;
if (n < 0 || n > 63) abort(); // gracefully deal with range issue
for (c[i=0] = 1; i < n; c[0] = -c[0], i++)
for (c[1 + (j=i)] = 1; j > 0; j--)
c[j] = c[j-1] - c[j];
}
int is_prime(int n)
{
int i;
coef(n);
c[0] += 1, c[i=n] -= 1;
while (i-- && !(c[i] % n));
return i < 0;
}
void show(int n)
{
do printf("%+lldx^%d", c[n], n); while (n--);
}
int main(void)
{
int n;
for (n = 0; n < 10; n++) {
coef(n);
printf("(x-1)^%d = ", n);
show(n);
putchar('\n');
}
printf("\nprimes (never mind the 1):");
for (n = 1; n <= 63; n++)
if (is_prime(n))
printf(" %d", n);
putchar('\n');
return 0;
} |
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.
the prime-numbers entry: additive primes.
the geeks for geeks entry: additive prime number.
the prime-numbers fandom: additive primes.
| #BCPL | BCPL | get "libhdr"
manifest $( limit = 500 $)
let dsum(n) =
n=0 -> 0,
dsum(n/10) + n rem 10
let sieve(prime, n) be
$( 0!prime := false
1!prime := false
for i=2 to n do i!prime := true
for i=2 to n/2
if i!prime
$( let j=i+i
while j<=n
$( j!prime := false
j := j+i
$)
$)
$)
let additive(prime, n) = n!prime & dsum(n)!prime
let start() be
$( let prime = vec limit
let num = 0
sieve(prime, limit)
for i=2 to limit
if additive(prime,i)
$( writed(i,5)
num := num + 1
if num rem 10 = 0 then wrch('*N')
$)
writef("*N*NFound %N additive primes < %N.*N", num, limit)
$) |
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.
the prime-numbers entry: additive primes.
the geeks for geeks entry: additive prime number.
the prime-numbers fandom: additive primes.
| #C | C |
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
void memoizeIsPrime( bool * result, const int N )
{
result[2] = true;
result[3] = true;
int prime[N];
prime[0] = 3;
int end = 1;
for (int n = 5; n < N; n += 2)
{
bool n_is_prime = true;
for (int i = 0; i < end; ++i)
{
const int PRIME = prime[i];
if (n % PRIME == 0)
{
n_is_prime = false;
break;
}
if (PRIME * PRIME > n)
{
break;
}
}
if (n_is_prime)
{
prime[end++] = n;
result[n] = true;
}
}
}/* memoizeIsPrime */
int sumOfDecimalDigits( int n )
{
int sum = 0;
while (n > 0)
{
sum += n % 10;
n /= 10;
}
return sum;
}/* sumOfDecimalDigits */
int main( void )
{
const int N = 500;
printf( "Rosetta Code: additive primes less than %d:\n", N );
bool is_prime[N];
memset( is_prime, 0, sizeof(is_prime) );
memoizeIsPrime( is_prime, N );
printf( " 2" );
int count = 1;
for (int i = 3; i < N; i += 2)
{
if (is_prime[i] && is_prime[sumOfDecimalDigits( i )])
{
printf( "%4d", i );
++count;
if ((count % 10) == 0)
{
printf( "\n" );
}
}
}
printf( "\nThose were %d additive primes.\n", count );
return 0;
}/* main */
|
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-black-tree.
A red-black-tree is a binary tree where each internal node has a color attribute red or black. Moreover, no red node can have a red child, and every path from the root to an empty node must contain the same number of black nodes. As a consequence, the tree is balanced, and must be re-balanced after an insertion.
Reference
Red-Black Trees in a Functional Setting
| #Perl | Perl | #!perl
use 5.010;
use strict;
use warnings qw(FATAL all);
my $balanced = qr{([^<>,]++|<(?-1),(?-1),(?-1),(?-1)>)};
my ($a, $b, $c, $d, $x, $y, $z) = map +qr((?<$_>$balanced)),
'a'..'d', 'x'..'z';
my $col = qr{(?<col>[RB])};
sub balance {
local $_ = shift;
if( /^<B,<R,<R,$a,$x,$b>,$y,$c>,$z,$d>\z/ or
/^<B,<R,$a,$x,<R,$b,$y,$c>>,$z,$d>\z/ or
/^<B,$a,$x,<R,<R,$b,$y,$c>,$z,$d>>\z/ or
/^<B,$a,$x,<R,$b,$y,<R,$c,$z,$d>>>\z/ )
{
my ($aa, $bb, $cc, $dd) = @+{'a'..'d'};
my ($xx, $yy, $zz) = @+{'x'..'z'};
"<R,<B,$aa,$xx,$bb>,$yy,<B,$cc,$zz,$dd>>";
} else {
$_;
}
}
sub ins {
my ($xx, $tree) = @_;
if($tree =~ m{^<$col,$a,$y,$b>\z} ) {
my ($color, $aa, $bb, $yy) = @+{qw(col a b y)};
if( $xx < $yy ) {
return balance "<$color,".ins($xx,$aa).",$yy,$bb>";
} elsif( $xx > $yy ) {
return balance "<$color,$aa,$yy,".ins($xx,$bb).">";
} else {
return $tree;
}
} elsif( $tree !~ /,/) {
return "<R,_,$xx,_>";
} else {
print "Unexpected failure!\n";
print "Tree parts are: \n";
print $_, "\n" for $tree =~ /$balanced/g;
exit;
}
}
sub insert {
my $tree = ins(@_);
$tree =~ m{^<$col,$a,$y,$b>\z} or die;
"<B,$+{a},$+{y},$+{b}>";
}
MAIN: {
my @a = 1..10;
for my $aa ( 1 .. $#a ) {
my $bb = int rand( 1 + $aa );
@a[$aa, $bb] = @a[$bb, $aa];
}
my $t = "!";
for( @a ) {
$t = insert( $_, $t );
print "Tree: $t.\n";
}
}
print "Done\n";
|
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
{\displaystyle k=2}
, are the semiprimes.
Task
Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for
1
<=
K
<=
5
{\displaystyle 1<=K<=5}
.
Related tasks
Semiprime
Category:Prime Numbers
| #Factor | Factor | USING: formatting fry kernel lists lists.lazy locals
math.combinatorics math.primes.factors math.ranges sequences ;
IN: rosetta-code.almost-prime
: k-almost-prime? ( n k -- ? )
'[ factors _ <combinations> [ product ] map ]
[ [ = ] curry ] bi any? ;
:: first10 ( k -- seq )
10 0 lfrom [ k k-almost-prime? ] lfilter ltake list>array ;
5 [1,b] [ dup first10 "K = %d: %[%3d, %]\n" printf ] each |
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
{\displaystyle k=2}
, are the semiprimes.
Task
Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for
1
<=
K
<=
5
{\displaystyle 1<=K<=5}
.
Related tasks
Semiprime
Category:Prime Numbers
| #FOCAL | FOCAL | 01.10 F K=1,5;D 3
01.20 Q
02.10 S N=I;S P=1;S G=0
02.20 S P=P+1
02.30 I (K-G)2.7,2.7;I (N-P*P)2.7
02.40 S Z=FITR(N/P)
02.50 I (Z*P-N)2.2
02.60 S N=Z;S G=G+1;G 2.4
02.70 I (1-N)2.8;R
02.80 S G=G+1
03.10 T "K",%1,K,":"
03.20 S I=2;S C=0
03.30 D 2;I (G-K)3.6,3.4,3.6
03.40 T " ",%3,I
03.50 S C=C+1
03.60 S I=I+1
03.70 I (C-10)3.3
03.80 T ! |
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
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #C.23 | C# | using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
namespace Anagram
{
class Program
{
const string DICO_URL = "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt";
static void Main( string[] args )
{
WebRequest request = WebRequest.Create(DICO_URL);
string[] words;
using (StreamReader sr = new StreamReader(request.GetResponse().GetResponseStream(), true)) {
words = Regex.Split(sr.ReadToEnd(), @"\r?\n");
}
var groups = from string w in words
group w by string.Concat(w.OrderBy(x => x)) into c
group c by c.Count() into d
orderby d.Key descending
select d;
foreach (var c in groups.First()) {
Console.WriteLine(string.Join(" ", c));
}
}
}
} |
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.
Compute the angle for the following pairs:
20 degrees (b1) and 45 degrees (b2)
-45 and 45
-85 and 90
-95 and 90
-45 and 125
-45 and 145
29.4803 and -88.6381
-78.3251 and -159.036
Optional extra
Allow the input bearings to be any (finite) value.
Test cases
-70099.74233810938 and 29840.67437876723
-165313.6666297357 and 33693.9894517456
1174.8380510598456 and -154146.66490124757
60175.77306795546 and 42213.07192354373
| #Nim | Nim | import math
import strutils
proc delta(b1, b2: float) : float =
result = (b2 - b1) mod 360.0
if result < -180.0:
result += 360.0
elif result >= 180.0:
result -= 360.0
let testVectors : seq[tuple[b1, b2: float]] = @[
(20.00, 45.00 ),
(-45.00, 45.00 ),
(-85.00, 90.00 ),
(-95.00, 90.00 ),
(-45.00, 125.00 ),
(-45.00, 145.00 ),
( 29.48, -88.64 ),
(-78.33, -159.04 ),
(-70099.74, 29840.67 ),
(-165313.67, 33693.99 ),
(1174.84, -154146.66 ),
(60175.77, 42213.07 ) ]
for vector in testVectors:
echo vector.b1.formatFloat(ffDecimal, 2).align(13) &
vector.b2.formatFloat(ffDecimal, 2).align(13) &
delta(vector.b1, vector.b2).formatFloat(ffDecimal, 2).align(13)
|
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 unixdict to find and display the longest deranged anagram.
Related tasks
Permutations/Derangements
Best shuffle
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Picat | Picat | go =>
M = [W:W in read_file_lines("unixdict.txt")].group(sort),
Deranged = [Value : _Key=Value in M, Value.length > 1, allderanged(Value)],
MaxLen = max([V[1].length : V in Deranged]),
println([V : V in Deranged, V[1].length==MaxLen]),
nl.
% A and B are deranged: i.e. there is no
% position with the same character.
deranged(A,B) =>
foreach(I in 1..A.length)
A[I] != B[I]
end.
% All words in list Value are deranged anagrams of each other.
allderanged(Value) =>
IsDeranged = 1,
foreach(V1 in Value, V2 in Value, V1 @< V2, IsDeranged = 1)
if not deranged(V1,V2) then
IsDeranged := 0
end
end,
IsDeranged == 1.
% Groups the element in List according to the function F
group(List, F) = P, list(List) =>
P = new_map(),
foreach(E in List)
V = apply(F,E),
P.put(V, P.get(V,[]) ++ [E])
end. |
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 function doesn't have the right arguments and/or return values.
So we end up inventing some silly name like foo2 or foo_helper. I have always found it painful to come up with a proper name, and see some disadvantages:
You have to think up a name, which then pollutes the namespace
Function is created which is called from nowhere else
The program flow in the source code is interrupted
Some languages allow you to embed recursion directly in-place. This might work via a label, a local gosub instruction, or some special keyword.
Anonymous recursion can also be accomplished using the Y combinator.
Task
If possible, demonstrate this by writing the recursive version of the fibonacci function (see Fibonacci sequence) which checks for a negative argument before doing the actual recursion.
| #M2000_Interpreter | M2000 Interpreter |
A$={{ Module "Fibonacci" : Read X :If X<0 then {Error {X<0}} Else Fib=Lambda (x)->if(x>1->fib(x-1)+fib(x-2), x) : =fib(x)}}
Try Ok {
Print Function(A$, -12)
}
If Error or Not Ok Then Print Error$
Print Function(A$, 12)=144 ' true
|
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
{\displaystyle =M}
as well as
s
u
m
(
p
r
o
p
D
i
v
s
(
M
)
)
=
N
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (M))=N}
.
Example
1184 and 1210 are an amicable pair, with proper divisors:
1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592 and
1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605 respectively.
Task
Calculate and show here the Amicable pairs below 20,000; (there are eight).
Related tasks
Proper divisors
Abundant, deficient and perfect number classifications
Aliquot sequence classifications and its amicable classification.
| #Julia | Julia | using Primes, Printf
function pcontrib(p::Int64, a::Int64)
n = one(p)
pcon = one(p)
for i in 1:a
n *= p
pcon += n
end
return pcon
end
function divisorsum(n::Int64)
dsum = one(n)
for (p, a) in factor(n)
dsum *= pcontrib(p, a)
end
dsum -= n
end
function amicables(L = 2*10^7)
acnt = 0
println("Amicable pairs not greater than ", L)
for i in 2:L
!isprime(i) || continue
j = divisorsum(i)
j < i && divisorsum(j) == i || continue
acnt += 1
println(@sprintf("%4d", acnt), " => ", j, ", ", i)
end
end
amicables()
|
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
Create a window containing the string "Hello World! " (the trailing space is significant).
Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front.
When the user clicks on the (windowed) text, it should reverse its direction.
| #Rust | Rust | #[cfg(feature = "gtk")]
mod graphical {
extern crate gtk;
use self::gtk::traits::*;
use self::gtk::{Inhibit, Window, WindowType};
use std::ops::Not;
use std::sync::{Arc, RwLock};
pub fn create_window() {
gtk::init().expect("Failed to initialize GTK");
let window = Window::new(WindowType::Toplevel);
window.connect_delete_event(|_, _| {
gtk::main_quit();
Inhibit(false)
});
let button = gtk::Button::new_with_label("Hello World! ");
window.add(&button);
let lock = Arc::new(RwLock::new(false));
let lock_button = lock.clone();
button.connect_clicked(move |_| {
let mut reverse = lock_button.write().unwrap();
*reverse = reverse.not();
});
let lock_thread = lock.clone();
gtk::timeout_add(100, move || {
let reverse = lock_thread.read().unwrap();
let mut text = button.get_label().unwrap();
let len = &text.len();
if *reverse {
let begin = &text.split_off(1);
text.insert_str(0, begin);
} else {
let end = &text.split_off(len - 1);
text.insert_str(0, end);
}
button.set_label(&text);
gtk::Continue(true)
});
window.show_all();
gtk::main();
}
}
#[cfg(feature = "gtk")]
fn main() {
graphical::create_window();
}
#[cfg(not(feature = "gtk"))]
fn main() {} |
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
Create a window containing the string "Hello World! " (the trailing space is significant).
Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front.
When the user clicks on the (windowed) text, it should reverse its direction.
| #Scala | Scala | import scala.actors.Actor.{actor, loop, reactWithin, exit}
import scala.actors.TIMEOUT
import scala.swing.{SimpleSwingApplication, MainFrame, Label}
import scala.swing.event.MouseClicked
case object Revert
object BasicAnimation extends SimpleSwingApplication {
val label = new Label("Hello World! ")
val rotator = actor {
var goingRight = true
loop {
reactWithin(250 /*ms*/) {
case Revert => goingRight = !goingRight
case TIMEOUT =>
if (goingRight)
label.text = label.text.last + label.text.init
else
label.text = label.text.tail + label.text.head
case unknown => println("Unknown message "+unknown); exit()
}
}
}
def top = new MainFrame {
title = "Basic Animation"
contents = label
}
listenTo(label.mouse.clicks) // use "Mouse" instead of "mouse" on Scala 2.7
reactions += {
case _ : MouseClicked => rotator ! Revert
}
} |
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.
| #Nim | Nim | # Pendulum simulation.
import math
import times
import opengl
import opengl/glut
var
# Simulation variables.
lg: float # Pendulum length.
g: float # Gravity (should be positive).
currTime: Time # Current time.
theta0: float # Initial angle.
theta: float # Current angle.
omega: float # Angular velocity = derivative of theta.
accel: float # Angular acceleration = derivative of omega.
e: float # Total energy.
#---------------------------------------------------------------------------------------------------
proc initSimulation(length, gravitation, start: float) =
## Initialize the simulation.
lg = length
g = gravitation
currTime = getTime()
theta0 = start # Initial angle for which omega = 0.
theta = start
omega = 0
accel = -g / lg * sin(theta0)
e = g * lg * (1 - cos(theta0)) # Total energy = potential energy when starting.
#---------------------------------------------------------------------------------------------------
proc elapsed(): float =
## Return the elapsed time since previous call, expressed in seconds.
let nextTime = getTime()
result = (nextTime - currTime).inMicroseconds.float / 1e6
currTime = nextTime
#---------------------------------------------------------------------------------------------------
proc resize(w, h: GLsizei) =
## Resize the window.
glViewport(0, 0, w, h)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glOrtho(0, GLdouble(w), GLdouble(h), 0, -1, 1)
#---------------------------------------------------------------------------------------------------
proc render() {.cdecl.} =
## Render the window.
# Compute the position of the mass.
var x = 320 + 300 * sin(theta)
var y = 300 * cos(theta)
resize(640, 320)
glClear(GL_COLOR_BUFFER_BIT)
# Draw the line from pivot to mass.
glBegin(GL_LINES)
glVertex2d(320, 0)
glVertex2d(x, y)
glEnd()
glFlush()
# Update theta and omega.
let dt = elapsed()
theta += (omega + dt * accel / 2) * dt
omega += accel * dt
# If, due to computation errors, potential energy is greater than total energy,
# reset theta to ±theta0 and omega to 0.
if lg * g * (1 - cos(theta)) >= e:
theta = sgn(theta).toFloat * theta0
omega = 0
accel = -g / lg * sin(theta)
#---------------------------------------------------------------------------------------------------
proc initGfx(argc: ptr cint; argv: pointer) =
## Initialize OpenGL rendering.
glutInit(argc, argv)
glutInitDisplayMode(GLUT_RGB)
glutInitWindowSize(640, 320)
glutIdleFunc(render)
discard glutCreateWindow("Pendulum")
glutDisplayFunc(render)
loadExtensions()
#———————————————————————————————————————————————————————————————————————————————————————————————————
initSimulation(length = 5, gravitation = 9.81, start = PI / 3)
var argc: cint = 0
initGfx(addr(argc), nil)
glutMainLoop() |
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 variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure.
Problems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent.
Essentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other "parallel universes" somehow go away. Amb called with no arguments fails.
For simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four.
A pseudo-code program which satisfies this constraint might look like:
let x = Amb(1, 2, 3)
let y = Amb(7, 6, 4, 5)
Amb(x * y = 8)
print x, y
The output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success.
Alternatively, failure could be represented using strictly Amb():
unless x * y = 8 do Amb()
Or else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints:
let x = Ambsel(1, 2, 3)
let y = Ambsel(4, 5, 6)
Ambassert(x * y = 8)
print x, y
where Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value.
The task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence:
"the" "that" "a"
"frog" "elephant" "thing"
"walked" "treaded" "grows"
"slowly" "quickly"
The constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor.
The only successful sentence is "that thing grows slowly"; other combinations do not satisfy the constraint and thus fail.
The goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.
| #Ela | Ela | open list core
amb xs = x where
(Some x) = & join xs ""
join (x::xs) = amb' x (join xs)
join [] = \_ -> Some ""
eq' [] x = true
eq' w x = last w == head x
amb' [] _ _ = None
amb' (x::xs) n w
| eq' w x =
match n x with
Some v = Some (x ++ " " ++ v)
_ = amb' xs n w
| else = amb' xs n w |
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.
| #Julia | Julia | using LDAPClient
conn = LDAPClient.LDAPConnection("ldap://localhost:10389")
LDAPClient.simple_bind(conn, "user", "password")
LDAPClient.unbind(conn)
|
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.
| #Kotlin | Kotlin |
import org.apache.directory.api.ldap.model.exception.LdapException
import org.apache.directory.ldap.client.api.LdapNetworkConnection
import java.io.IOException
import java.util.logging.Level
import java.util.logging.Logger
class LDAP(map: Map<String, String>) {
fun run() {
var connection: LdapNetworkConnection? = null
try {
if (info) log.info("LDAP Connection to $hostname on port $port")
connection = LdapNetworkConnection(hostname, port.toInt())
try {
if (info) log.info("LDAP bind")
connection.bind()
} catch (e: LdapException) {
log.severe(e.toString())
}
try {
if (info) log.info("LDAP unbind")
connection.unBind()
} catch (e: LdapException) {
log.severe(e.toString())
}
} finally {
try {
if (info) log.info("LDAP close connection")
connection!!.close()
} catch (e: IOException) {
log.severe(e.toString())
}
}
}
private val log = Logger.getLogger(LDAP::class.java.name)
private val info = log.isLoggable(Level.INFO)
private val hostname: String by map
private val port: String by map
}
fun main(args: Array<String>) = LDAP(mapOf("hostname" to "localhost", "port" to "10389")).run()
|
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Use the following text to test your programs:
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #11l | 11l | V txt = ‘Given$a$txt$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.’
V parts = txt.split("\n").map(line -> line.rtrim(‘$’).split(‘$’))
V max_widths = [0] * parts[0].len
L(line) parts
L(word) line
max_widths[L.index] = max(max_widths[L.index], word.len)
((String, Int) -> String) ljust = (s, w) -> s‘’(‘ ’ * (w - s.len))
((String, Int) -> String) centr = (s, w) -> (‘ ’ * (w - s.len - (w I/ 2 - s.len I/ 2)))‘’s‘’(‘ ’ * (w I/ 2 - s.len I/ 2))
((String, Int) -> String) rjust = (s, w) -> (‘ ’ * (w - s.len))‘’s
L(justify) [ljust, centr, rjust]
print([‘Left’, ‘Center’, ‘Right’][L.index]‘ column-aligned output:’)
L(line) parts
L(word) line
print(justify(word, max_widths[L.index]), end' ‘ ’)
print()
print(‘- ’ * 52) |
http://rosettacode.org/wiki/Active_object | Active object | In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such methods must have a certain synchronization mechanism with the encapsulated task in order to prevent object's state corruption.
A typical instance of an active object is an animation widget. The widget state changes with the time, while as an object it has all properties of a normal widget.
The task
Implement an active integrator object. The object has an input and output. The input can be set using the method Input. The input is a function of time. The output can be queried using the method Output. The object integrates its input over the time and the result becomes the object's output. So if the input is K(t) and the output is S, the object state S is changed to S + (K(t1) + K(t0)) * (t1 - t0) / 2, i.e. it integrates K using the trapeze method. Initially K is constant 0 and S is 0.
In order to test the object:
set its input to sin (2π f t), where the frequency f=0.5Hz. The phase is irrelevant.
wait 2s
set the input to constant 0
wait 0.5s
Verify that now the object's output is approximately 0 (the sine has the period of 2s). The accuracy of the result will depend on the OS scheduler time slicing and the accuracy of the clock.
| #Ada | Ada | with Ada.Calendar; use Ada.Calendar;
with Ada.Numerics; use Ada.Numerics;
with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions;
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Integrator is
type Func is access function (T : Time) return Float;
function Zero (T : Time) return Float is
begin
return 0.0;
end Zero;
Epoch : constant Time := Clock;
function Sine (T : Time) return Float is
begin
return Sin (Pi * Float (T - Epoch));
end Sine;
task type Integrator is
entry Input (Value : Func);
entry Output (Value : out Float);
entry Shut_Down;
end Integrator;
task body Integrator is
K : Func := Zero'Access;
S : Float := 0.0;
F0 : Float := 0.0;
F1 : Float;
T0 : Time := Clock;
T1 : Time;
begin
loop
select
accept Input (Value : Func) do
K := Value;
end Input;
or accept Output (Value : out Float) do
Value := S;
end Output;
or accept Shut_Down;
exit;
else
T1 := Clock;
F1 := K (T1);
S := S + 0.5 * (F1 + F0) * Float (T1 - T0);
T0 := T1;
F0 := F1;
end select;
end loop;
end Integrator;
I : Integrator;
S : Float;
begin
I.Input (Sine'Access);
delay 2.0;
I.Input (Zero'Access);
delay 0.5;
I.Output (S);
Put_Line ("Integrated" & Float'Image (S) & "s");
I.Shut_Down;
end Test_Integrator; |
http://rosettacode.org/wiki/Achilles_numbers | Achilles numbers |
This page uses content from Wikipedia. The original article was at Achilles number. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
An Achilles number is a number that is powerful but imperfect. Named after Achilles, a hero of the Trojan war, who was also powerful but imperfect.
A positive integer n is a powerful number if, for every prime factor p of n, p2 is also a divisor.
In other words, every prime factor appears at least squared in the factorization.
All Achilles numbers are powerful. However, not all powerful numbers are Achilles numbers: only those that cannot be represented as mk, where m and k are positive integers greater than 1.
A strong Achilles number is an Achilles number whose Euler totient (𝜑) is also an Achilles number.
E.G.
108 is a powerful number. Its prime factorization is 22 × 33, and thus its prime factors are 2 and 3. Both 22 = 4 and 32 = 9 are divisors of 108. However, 108 cannot be represented as mk, where m and k are positive integers greater than 1, so 108 is an Achilles number.
360 is not an Achilles number because it is not powerful. One of its prime factors is 5 but 360 is not divisible by 52 = 25.
Finally, 784 is not an Achilles number. It is a powerful number, because not only are 2 and 7 its only prime factors, but also 22 = 4 and 72 = 49 are divisors of it. Nonetheless, it is a perfect power; its square root is an even integer, so it is not an Achilles number.
500 = 22 × 53 is a strong Achilles number as its Euler totient, 𝜑(500), is 200 = 23 × 52 which is also an Achilles number.
Task
Find and show the first 50 Achilles numbers.
Find and show at least the first 20 strong Achilles numbers.
For at least 2 through 5, show the count of Achilles numbers with that many digits.
See also
Wikipedia: Achilles number
OEIS:A052486 - Achilles numbers - powerful but imperfect numbers
OEIS:A194085 - Strong Achilles numbers: Achilles numbers m such that phi(m) is also an Achilles number
Related task: Powerful numbers
Related task: Totient function
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program achilleNumber.s */
/************************************/
/* Constantes */
/************************************/
.include "../includeConstantesARM64.inc"
.equ NBFACT, 33
.equ MAXI, 50
.equ MAXI1, 20
.equ MAXI2, 1000000
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessNumber: .asciz " @ "
szCarriageReturn: .asciz "\n"
szErrorGen: .asciz "Program error !!!\n"
szMessPrime: .asciz "This number is prime.\n"
szMessErrGen: .asciz "Error end program.\n"
szMessNbPrem: .asciz "This number is prime !!!.\n"
szMessOverflow: .asciz "Overflow function isPrime.\n"
szMessError: .asciz "\033[31mError !!!\n"
szMessTitAchille: .asciz "First 50 Achilles Numbers:\n"
szMessTitStrong: .asciz "First 20 Strong Achilles Numbers:\n"
szMessDigitsCounter: .asciz "Numbers with @ digits : @ \n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
tbZoneDecom: .skip 16 * NBFACT // factor 8 bytes, number of each factor 8 bytes
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdrszMessTitAchille
bl affichageMess
mov x4,#1 // start number
mov x5,#0 // total counter
mov x6,#0 // line display counter
1:
mov x0,x4
bl controlAchille
cmp x0,#0 // achille number ?
beq 2f // no
mov x0,x4
ldr x1,qAdrsZoneConv
bl conversion10 // call décimal conversion
ldr x0,qAdrszMessNumber
ldr x1,qAdrsZoneConv // insert conversion in message
bl strInsertAtCharInc
bl affichageMess // display message
add x5,x5,#1 // increment counter
add x6,x6,#1 // increment indice line display
cmp x6,#10 // if = 10 new line
bne 2f
mov x6,#0
ldr x0,qAdrszCarriageReturn
bl affichageMess
2:
add x4,x4,#1 // increment number
cmp x5,#MAXI
blt 1b // and loop
ldr x0,qAdrszMessTitStrong
bl affichageMess
mov x4,#1 // start number
mov x5,#0 // total counter
mov x6,#0
3:
mov x0,x4
bl controlAchille
cmp x0,#0
beq 4f
mov x0,x4
bl computeTotient
bl controlAchille
cmp x0,#0
beq 4f
mov x0,x4
ldr x1,qAdrsZoneConv
bl conversion10 // call décimal conversion
ldr x0,qAdrszMessNumber
ldr x1,qAdrsZoneConv // insert conversion in message
bl strInsertAtCharInc
bl affichageMess // display message
add x5,x5,#1
add x6,x6,#1
cmp x6,#10
bne 4f
mov x6,#0
ldr x0,qAdrszCarriageReturn
bl affichageMess
4:
add x4,x4,#1
cmp x5,#MAXI1
blt 3b
ldr x3,icstMaxi2
mov x4,#1 // start number
mov x6,#0 // total counter 2 digits
mov x7,#0 // total counter 3 digits
mov x8,#0 // total counter 4 digits
mov x9,#0 // total counter 5 digits
mov x10,#0 // total counter 6 digits
5:
mov x0,x4
bl controlAchille
cmp x0,#0
beq 10f
mov x0,x4
ldr x1,qAdrsZoneConv
bl conversion10 // call décimal conversion x0 return digit number
cmp x0,#6
bne 6f
add x10,x10,#1
beq 10f
6:
cmp x0,#5
bne 7f
add x9,x9,#1
b 10f
7:
cmp x0,#4
bne 8f
add x8,x8,#1
b 10f
8:
cmp x0,#3
bne 9f
add x7,x7,#1
b 10f
9:
cmp x0,#2
bne 10f
add x6,x6,#1
10:
add x4,x4,#1
cmp x4,x3
blt 5b
mov x0,#2
mov x1,x6
bl displayCounter
mov x0,#3
mov x1,x7
bl displayCounter
mov x0,#4
mov x1,x8
bl displayCounter
mov x0,#5
mov x1,x9
bl displayCounter
mov x0,#6
mov x1,x10
bl displayCounter
b 100f
98:
ldr x0,qAdrszErrorGen
bl affichageMess
100: // standard end of the program
mov x0, #0 // return code
mov x8,EXIT
svc #0 // perform the system call
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrszErrorGen: .quad szErrorGen
qAdrsZoneConv: .quad sZoneConv
qAdrtbZoneDecom: .quad tbZoneDecom
qAdrszMessNumber: .quad szMessNumber
qAdrszMessTitAchille: .quad szMessTitAchille
qAdrszMessTitStrong: .quad szMessTitStrong
icstMaxi2: .quad MAXI2
/******************************************************************/
/* display digit counter */
/******************************************************************/
/* x0 contains limit */
/* x1 contains counter */
displayCounter:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
mov x2,x1
ldr x1,qAdrsZoneConv
bl conversion10 // call décimal conversion
ldr x0,qAdrszMessDigitsCounter
ldr x1,qAdrsZoneConv // insert conversion in message
bl strInsertAtCharInc
mov x3,x0
mov x0,x2
ldr x1,qAdrsZoneConv
bl conversion10 // call décimal conversion
mov x0,x3
ldr x1,qAdrsZoneConv // insert conversion in message
bl strInsertAtCharInc
bl affichageMess // display message
100:
ldp x2,x3,[sp],16 // restaur registers
ldp x1,lr,[sp],16 // restaur registers
ret
qAdrszMessDigitsCounter: .quad szMessDigitsCounter
/******************************************************************/
/* control if number is Achille number */
/******************************************************************/
/* x0 contains number */
/* x0 return 0 if not else return 1 */
controlAchille:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
mov x4,x0
ldr x1,qAdrtbZoneDecom
bl decompFact // factor decomposition
cmp x0,#-1
beq 99f // error ?
cmp x0,#1 // one only factor or prime ?
ble 98f
mov x1,x0
ldr x0,qAdrtbZoneDecom
mov x2,x4
bl controlDivisor
b 100f
98:
mov x0,#0
b 100f
99:
ldr x0,qAdrszErrorGen
bl affichageMess
100:
ldp x4,x5,[sp],16 // restaur registers
ldp x2,x3,[sp],16 // restaur registers
ldp x1,lr,[sp],16 // restaur registers
ret
/******************************************************************/
/* control divisors function */
/******************************************************************/
/* x0 contains address of divisors area */
/* x1 contains the number of area items */
/* x2 contains number */
controlDivisor:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
stp x6,x7,[sp,-16]! // save registers
stp x8,x9,[sp,-16]! // save registers
stp x10,x11,[sp,-16]! // save registers
mov x6,x1 // factors number
mov x8,x2 // save number
mov x9,#0 // indice
mov x4,x0 // save area address
add x5,x4,x9,lsl #4 // compute address first factor
ldr x7,[x5,#8] // load first exposant of factor
add x2,x9,#1
1:
add x5,x4,x2,lsl #4 // compute address next factor
ldr x3,[x5,#8] // load exposant of factor
cmp x3,x7 // factor exposant <> ?
bne 2f // yes -> end verif
add x2,x2,#1 // increment indice
cmp x2,x6 // factor maxi ?
blt 1b // no -> loop
mov x0,#0
b 100f // all exposants are equals
2:
mov x10,x2 // save indice
21:
bge 22f
mov x2,x7 // if x3 < x7 -> inversion
mov x7,x3
mov x3,x2 // x7 is the smaller exposant
22:
mov x0,x3
mov x1,x7 // x7 < x3
bl calPGCDmod
cmp x0,#1
beq 24f // no commun multiple -> ne peux donc pas etre une puissance
23:
add x10,x10,#1 // increment indice
cmp x10,x6 // factor maxi ?
bge 99f // yes -> all exposants are multiples to smaller
add x5,x4,x10,lsl #4
ldr x3,[x5,#8] // load exposant of next factor
cmp x3,x7
beq 23b // for next
b 21b // for compare the 2 exposants
24:
mov x9,#0 // indice
3:
add x5,x4,x9,lsl #4
ldr x7,[x5] // load factor
mul x1,x7,x7 // factor square
udiv x2,x8,x1
msub x3,x1,x2,x8 // compute remainder
cmp x3,#0 // remainder null ?
bne 99f
add x9,x9,#1 // other factor
cmp x9,x6 // factors maxi ?
blt 3b
mov x0,#1 // achille number ok
b 100f
99: // achille not ok
mov x0,0
100:
ldp x10,x11,[sp],16 // restaur registers
ldp x8,x9,[sp],16 // restaur registers
ldp x6,x7,[sp],16 // restaur registers
ldp x4,x5,[sp],16 // restaur registers
ldp x2,x3,[sp],16 // restaur registers
ldp x1,lr,[sp],16 // restaur registers
ret
/***************************************************/
/* Compute pgcd modulo use */
/***************************************************/
/* x0 contains first number */
/* x1 contains second number */
/* x0 return PGCD */
/* if error carry set to 1 */
calPGCDmod:
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
cbz x0,99f // if = 0 error
cbz x1,99f
cmp x0,0
bgt 1f
neg x0,x0 // if negative inversion number 1
1:
cmp x1,0
bgt 2f
neg x1,x1 // if negative inversion number 2
2:
cmp x0,x1 // compare two numbers
bgt 3f
mov x2,x0 // inversion
mov x0,x1
mov x1,x2
3:
udiv x2,x0,x1 // division
msub x0,x2,x1,x0 // compute remainder
cmp x0,0
bgt 2b // loop
mov x0,x1
cmn x0,0 // clear carry
b 100f
99: // error
mov x0,0
cmp x0,0 // set carry
100:
ldp x2,x3,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret // retour adresse lr x30
/******************************************************************/
/* compute totient of number */
/******************************************************************/
/* x0 contains number */
computeTotient:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
mov x4,x0 // totient
mov x5,x0 // save number
mov x1,#0 // for first divisor
1: // begin loop
mul x3,x1,x1 // compute square
cmp x3,x5 // compare number
bgt 4f // end
add x1,x1,#2 // next divisor
udiv x2,x5,x1
msub x3,x1,x2,x5 // compute remainder
cmp x3,#0 // remainder null ?
bne 3f
2: // begin loop 2
udiv x2,x5,x1
msub x3,x1,x2,x5 // compute remainder
cmp x3,#0
csel x5,x2,x5,eq // new value = quotient
beq 2b
udiv x2,x4,x1 // divide totient
sub x4,x4,x2 // compute new totient
3:
cmp x1,#2 // first divisor ?
mov x0,1
csel x1,x0,x1,eq // divisor = 1
b 1b // and loop
4:
cmp x5,#1 // final value > 1
ble 5f
mov x0,x4 // totient
mov x1,x5 // divide by value
udiv x2,x4,x5 // totient divide by value
sub x4,x4,x2 // compute new totient
5:
mov x0,x4
100:
ldp x4,x5,[sp],16 // restaur registers
ldp x2,x3,[sp],16 // restaur registers
ldp x1,lr,[sp],16 // restaur registers
ret
/******************************************************************/
/* factor decomposition */
/******************************************************************/
/* x0 contains number */
/* x1 contains address of divisors area */
/* x0 return divisors items in table */
decompFact:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
stp x6,x7,[sp,-16]! // save registers
stp x8,x9,[sp,-16]! // save registers
mov x5,x1
mov x8,x0 // save number
bl isPrime // prime ?
cmp x0,#1
beq 98f // yes is prime
mov x4,#0 // raz indice
mov x1,#2 // first divisor
mov x6,#0 // previous divisor
mov x7,#0 // number of same divisors
2:
udiv x2,x8,x1 // divide number or other result
msub x3,x2,x1,x8 // compute remainder
cmp x3,#0
bne 5f // if remainder <> zero -> no divisor
mov x8,x2 // else quotient -> new dividende
cmp x1,x6 // same divisor ?
beq 4f // yes
cmp x6,#0 // no but is the first divisor ?
beq 3f // yes
str x6,[x5,x4,lsl #3] // else store in the table
add x4,x4,#1 // and increment counter
str x7,[x5,x4,lsl #3] // store counter
add x4,x4,#1 // next item
mov x7,#0 // and raz counter
3:
mov x6,x1 // new divisor
4:
add x7,x7,#1 // increment counter
b 7f // and loop
/* not divisor -> increment next divisor */
5:
cmp x1,#2 // if divisor = 2 -> add 1
mov x0,#1
mov x3,#2 // else add 2
csel x3,x0,x3,eq
add x1,x1,x3
b 2b
/* divisor -> test if new dividende is prime */
7:
mov x3,x1 // save divisor
cmp x8,#1 // dividende = 1 ? -> end
beq 10f
mov x0,x8 // new dividende is prime ?
mov x1,#0
bl isPrime // the new dividende is prime ?
cmp x0,#1
bne 10f // the new dividende is not prime
cmp x8,x6 // else dividende is same divisor ?
beq 9f // yes
cmp x6,#0 // no but is the first divisor ?
beq 8f // yes it is a first
str x6,[x5,x4,lsl #3] // else store in table
add x4,x4,#1 // and increment counter
str x7,[x5,x4,lsl #3] // and store counter
add x4,x4,#1 // next item
8:
mov x6,x8 // new dividende -> divisor prec
mov x7,#0 // and raz counter
9:
add x7,x7,#1 // increment counter
b 11f
10:
mov x1,x3 // current divisor = new divisor
cmp x1,x8 // current divisor > new dividende ?
ble 2b // no -> loop
/* end decomposition */
11:
str x6,[x5,x4,lsl #3] // store last divisor
add x4,x4,#1
str x7,[x5,x4,lsl #3] // and store last number of same divisors
add x4,x4,#1
lsr x0,x4,#1 // return number of table items
mov x3,#0
str x3,[x5,x4,lsl #3] // store zéro in last table item
add x4,x4,#1
str x3,[x5,x4,lsl #3] // and zero in counter same divisor
b 100f
98:
//ldr x0,qAdrszMessPrime
//bl affichageMess
mov x0,#0 // return code 0 = number is prime
b 100f
99:
ldr x0,qAdrszMessErrGen
bl affichageMess
mov x0,#-1 // error code
b 100f
100:
ldp x8,x9,[sp],16 // restaur registers
ldp x6,x7,[sp],16 // restaur registers
ldp x4,x5,[sp],16 // restaur registers
ldp x2,x3,[sp],16 // restaur registers
ldp x1,lr,[sp],16 // restaur registers
ret
qAdrszMessErrGen: .quad szMessErrGen
/***************************************************/
/* Verification si un nombre est premier */
/***************************************************/
/* x0 contient le nombre à verifier */
/* x0 retourne 1 si premier 0 sinon */
isPrime:
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
mov x2,x0
sub x1,x0,#1
cmp x2,0
beq 99f // retourne zéro
cmp x2,2 // pour 1 et 2 retourne 1
ble 2f
mov x0,#2
bl moduloPur64
bcs 100f // erreur overflow
cmp x0,#1
bne 99f // Pas premier
cmp x2,3
beq 2f
mov x0,#3
bl moduloPur64
blt 100f // erreur overflow
cmp x0,#1
bne 99f
cmp x2,5
beq 2f
mov x0,#5
bl moduloPur64
bcs 100f // erreur overflow
cmp x0,#1
bne 99f // Pas premier
cmp x2,7
beq 2f
mov x0,#7
bl moduloPur64
bcs 100f // erreur overflow
cmp x0,#1
bne 99f // Pas premier
cmp x2,11
beq 2f
mov x0,#11
bl moduloPur64
bcs 100f // erreur overflow
cmp x0,#1
bne 99f // Pas premier
cmp x2,13
beq 2f
mov x0,#13
bl moduloPur64
bcs 100f // erreur overflow
cmp x0,#1
bne 99f // Pas premier
cmp x2,17
beq 2f
mov x0,#17
bl moduloPur64
bcs 100f // erreur overflow
cmp x0,#1
bne 99f // Pas premier
2:
cmn x0,0 // carry à zero pas d'erreur
mov x0,1 // premier
b 100f
99:
cmn x0,0 // carry à zero pas d'erreur
mov x0,#0 // Pas premier
100:
ldp x2,x3,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret // retour adresse lr x30
/**************************************************************/
/********************************************************/
/* Calcul modulo de b puissance e modulo m */
/* Exemple 4 puissance 13 modulo 497 = 445 */
/********************************************************/
/* x0 nombre */
/* x1 exposant */
/* x2 modulo */
moduloPur64:
stp x1,lr,[sp,-16]! // save registres
stp x3,x4,[sp,-16]! // save registres
stp x5,x6,[sp,-16]! // save registres
stp x7,x8,[sp,-16]! // save registres
stp x9,x10,[sp,-16]! // save registres
cbz x0,100f
cbz x1,100f
mov x8,x0
mov x7,x1
mov x6,1 // resultat
udiv x4,x8,x2
msub x9,x4,x2,x8 // contient le reste
1:
tst x7,1
beq 2f
mul x4,x9,x6
umulh x5,x9,x6
//cbnz x5,99f
mov x6,x4
mov x0,x6
mov x1,x5
bl divisionReg128U
cbnz x1,99f // overflow
mov x6,x3
2:
mul x8,x9,x9
umulh x5,x9,x9
mov x0,x8
mov x1,x5
bl divisionReg128U
cbnz x1,99f // overflow
mov x9,x3
lsr x7,x7,1
cbnz x7,1b
mov x0,x6 // result
cmn x0,0 // carry à zero pas d'erreur
b 100f
99:
ldr x0,qAdrszMessOverflow
bl affichageMess
cmp x0,0 // carry à un car erreur
mov x0,-1 // code erreur
100:
ldp x9,x10,[sp],16 // restaur des 2 registres
ldp x7,x8,[sp],16 // restaur des 2 registres
ldp x5,x6,[sp],16 // restaur des 2 registres
ldp x3,x4,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret // retour adresse lr x30
qAdrszMessOverflow: .quad szMessOverflow
/***************************************************/
/* division d un nombre de 128 bits par un nombre de 64 bits */
/***************************************************/
/* x0 contient partie basse dividende */
/* x1 contient partie haute dividente */
/* x2 contient le diviseur */
/* x0 retourne partie basse quotient */
/* x1 retourne partie haute quotient */
/* x3 retourne le reste */
divisionReg128U:
stp x6,lr,[sp,-16]! // save registres
stp x4,x5,[sp,-16]! // save registres
mov x5,#0 // raz du reste R
mov x3,#128 // compteur de boucle
mov x4,#0 // dernier bit
1:
lsl x5,x5,#1 // on decale le reste de 1
tst x1,1<<63 // test du bit le plus à gauche
lsl x1,x1,#1 // on decale la partie haute du quotient de 1
beq 2f
orr x5,x5,#1 // et on le pousse dans le reste R
2:
tst x0,1<<63
lsl x0,x0,#1 // puis on decale la partie basse
beq 3f
orr x1,x1,#1 // et on pousse le bit de gauche dans la partie haute
3:
orr x0,x0,x4 // position du dernier bit du quotient
mov x4,#0 // raz du bit
cmp x5,x2
blt 4f
sub x5,x5,x2 // on enleve le diviseur du reste
mov x4,#1 // dernier bit à 1
4:
// et boucle
subs x3,x3,#1
bgt 1b
lsl x1,x1,#1 // on decale le quotient de 1
tst x0,1<<63
lsl x0,x0,#1 // puis on decale la partie basse
beq 5f
orr x1,x1,#1
5:
orr x0,x0,x4 // position du dernier bit du quotient
mov x3,x5
100:
ldp x4,x5,[sp],16 // restaur des 2 registres
ldp x6,lr,[sp],16 // restaur des 2 registres
ret // retour adresse lr x30
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../includeARM64.inc"
|
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 second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called perfect.
If the third term would be repeating K then the sequence repeats with period 2 and K is called amicable.
If the Nth term would be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called sociable.
Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions...
Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence 95, 25, 6, 6, 6, ... such K are called aspiring.
K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence 562, 284, 220, 284, 220, ... such K are called cyclic.
And finally:
Some K form aliquot sequences that are not known to be either terminating or periodic; these K are to be called non-terminating.
For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating 16 terms or if any term of the sequence is greater than 2**47 = 140,737,488,355,328.
Task
Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above.
Use it to display the classification and sequences of the numbers one to ten inclusive.
Use it to show the classification and sequences of the following integers, in order:
11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080.
Show all output on this page.
Related tasks
Abundant, deficient and perfect number classifications. (Classifications from only the first two members of the whole sequence).
Proper divisors
Amicable pairs
| #Common_Lisp | Common Lisp | (defparameter *nlimit* 16)
(defparameter *klimit* (expt 2 47))
(defparameter *asht* (make-hash-table))
(load "proper-divisors")
(defun ht-insert (v n)
(setf (gethash v *asht*) n))
(defun ht-find (v n)
(let ((nprev (gethash v *asht*)))
(if nprev (- n nprev) nil)))
(defun ht-list ()
(defun sort-keys (&optional (res '()))
(maphash #'(lambda (k v) (push (cons k v) res)) *asht*)
(sort (copy-list res) #'< :key (lambda (p) (cdr p))))
(let ((sorted (sort-keys)))
(dotimes (i (length sorted)) (format t "~A " (car (nth i sorted))))))
(defun aliquot-generator (K1)
"integer->function::fn to generate aliquot sequence"
(let ((Kn K1))
#'(lambda () (setf Kn (reduce #'+ (proper-divisors-recursive Kn) :initial-value 0)))))
(defun aliquot (K1)
"integer->symbol|nil::classify aliquot sequence"
(defun aliquot-sym (Kn n)
(let* ((period (ht-find Kn n))
(sym (if period
(cond ; period event
((= Kn K1)
(case period (1 'PERF) (2 'AMIC) (otherwise 'SOCI)))
((= period 1) 'ASPI)
(t 'CYCL))
(cond ; else check for limit event
((= Kn 0) 'TERM)
((> Kn *klimit*) 'TLIM)
((= n *nlimit*) 'NLIM)
(t nil)))))
;; if period event store the period, if no event insert the value
(if sym (when period (setf (symbol-plist sym) (list period)))
(ht-insert Kn n))
sym))
(defun aliquot-str (sym &optional (period 0))
(case sym (TERM "terminating") (PERF "perfect") (AMIC "amicable") (ASPI "aspiring")
(SOCI (format nil "sociable (period ~A)" (car (symbol-plist sym))))
(CYCL (format nil "cyclic (period ~A)" (car (symbol-plist sym))))
(NLIM (format nil "non-terminating (no classification before added term limit of ~A)" *nlimit*))
(TLIM (format nil "non-terminating (term threshold of ~A exceeded)" *klimit*))
(otherwise "unknown")))
(clrhash *asht*)
(let ((fgen (aliquot-generator K1)))
(setf (symbol-function 'aliseq) #'(lambda () (funcall fgen))))
(ht-insert K1 0)
(do* ((n 1 (1+ n))
(Kn (aliseq) (aliseq))
(alisym (aliquot-sym Kn n) (aliquot-sym Kn n)))
(alisym (format t "~A:" (aliquot-str alisym)) (ht-list) (format t "~A~%" Kn) alisym)))
(defun main ()
(princ "The last item in each sequence triggers classification.") (terpri)
(dotimes (k 10)
(aliquot (+ k 1)))
(dolist (k '(11 12 28 496 220 1184 12496 1264460 790 909 562 1064 1488 15355717786080))
(aliquot k))) |
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user | Active Directory/Search for a user | Make sure you Connect to Active Directory
| #PicoLisp | PicoLisp | (de ldapsearch (Sn)
(in
(list "ldapsearch" "-xH" "ldap://db.debian.org"
"-b" "dc=debian,dc=org"
(pack "sn=" Sn) )
(list
(cons 'cn (prog (from "cn: ") (line T)))
(cons 'uid (prog (from "uid: ") (line T))) ) ) ) |
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user | Active Directory/Search for a user | Make sure you Connect to Active Directory
| #PowerShell | PowerShell |
Import-Module ActiveDirectory
$searchData = "user name"
$searchBase = "DC=example,DC=com"
#searches by some of the most common unique identifiers
get-aduser -Filter((DistinguishedName -eq $searchdata) -or (UserPrincipalName -eq $searchdata) -or (SamAccountName -eq $searchdata)) -SearchBase $searchBase
|
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user | Active Directory/Search for a user | Make sure you Connect to Active Directory
| #Python | Python | import ldap
l = ldap.initialize("ldap://ldap.example.com")
try:
l.protocol_version = ldap.VERSION3
l.set_option(ldap.OPT_REFERRALS, 0)
bind = l.simple_bind_s("[email protected]", "password")
base = "dc=example, dc=com"
criteria = "(&(objectClass=user)(sAMAccountName=username))"
attributes = ['displayName', 'company']
result = l.search_s(base, ldap.SCOPE_SUBTREE, criteria, attributes)
results = [entry for dn, entry in result if isinstance(entry, dict)]
print results
finally:
l.unbind()
|
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user | Active Directory/Search for a user | Make sure you Connect to Active Directory
| #Raku | Raku |
# 20190718 Raku programming solution
# https://github.com/perl6/doc/issues/2898
# https://www.facebook.com/groups/perl6/permalink/2379873082279037/
# Reference:
# https://github.com/Altai-man/cro-ldap
# https://www.forumsys.com/tutorials/integration-how-to/ldap/online-ldap-test-server/
use v6.d;
use Cro::LDAP::Client;
my $client = await Cro::LDAP::Client.connect('ldap://ldap.forumsys.com');
my $bind = await $client.bind(
name=>'cn=read-only-admin,dc=example,dc=com',password=>'password'
);
die $bind.error-message if $bind.result-code;
my $resp = $client.search(
:dn<dc=example,dc=com>, base=>"ou=mathematicians", filter=>'(&(uid=gauss))'
);
react {
whenever $resp -> $entry {
for $entry.attributes.kv -> $k, $v {
my $value-str = $v ~~ Blob ?? $v.decode !! $v.map(*.decode);
note "$k -> $value-str";
}
}
} |
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 referred to as "monkeypatching" by Pythonistas and some others.
| #Forth | Forth | include FMS-SI.f
include FMS-SILib.f
\ We can add any number of variables at runtime by adding
\ objects of any type to an instance at run time. The added
\ objects are then accessible via an index number.
:class foo
object-list inst-objects \ a dynamically growable object container
:m init: inst-objects init: ;m
:m add: ( obj -- ) inst-objects add: ;m
:m at: ( idx -- obj ) inst-objects at: ;m
;class
foo foo1
: main
heap> string foo1 add:
heap> fvar foo1 add:
s" Now is the time " 0 foo1 at: !:
3.14159e 1 foo1 at: !:
0 foo1 at: p: \ send the print message to indexed object 0
1 foo1 at: p: \ send the print message to indexed object 1
;
main \ => Now is the time 3.14159
|
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 referred to as "monkeypatching" by Pythonistas and some others.
| #FreeBASIC | FreeBASIC |
' Class ... End Class
' Esta característica aún no está implementada en el compilador.
|
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 referred to as "monkeypatching" by Pythonistas and some others.
| #Go | Go | package main
import (
"bufio"
"fmt"
"log"
"os"
)
type SomeStruct struct {
runtimeFields map[string]string
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
ss := SomeStruct{make(map[string]string)}
scanner := bufio.NewScanner(os.Stdin)
fmt.Println("Create two fields at runtime: ")
for i := 1; i <= 2; i++ {
fmt.Printf(" Field #%d:\n", i)
fmt.Print(" Enter name : ")
scanner.Scan()
name := scanner.Text()
fmt.Print(" Enter value : ")
scanner.Scan()
value := scanner.Text()
check(scanner.Err())
ss.runtimeFields[name] = value
fmt.Println()
}
for {
fmt.Print("Which field do you want to inspect ? ")
scanner.Scan()
name := scanner.Text()
check(scanner.Err())
value, ok := ss.runtimeFields[name]
if !ok {
fmt.Println("There is no field of that name, try again")
} else {
fmt.Printf("Its value is '%s'\n", value)
return
}
}
} |
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 |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Demonstrate how to get the address of a variable and how to set the address of a variable.
| #FutureBasic | FutureBasic | window 1
short i = 575
ptr j
j = @i
printf @"Address of i = %ld",j
print @"Value of i = ";peek word(j)
HandleEvents |
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 |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Demonstrate how to get the address of a variable and how to set the address of a variable.
| #Go | Go | package main
import (
"fmt"
"unsafe"
)
func main() {
myVar := 3.14
myPointer := &myVar
fmt.Println("Address:", myPointer, &myVar)
fmt.Printf("Address: %p %p\n", myPointer, &myVar)
var addr64 int64
var addr32 int32
ptr := unsafe.Pointer(myPointer)
if unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr64) {
addr64 = int64(uintptr(ptr))
fmt.Printf("Pointer stored in int64: %#016x\n", addr64)
}
if unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr32) {
// Only runs on architectures where a pointer is <= 32 bits
addr32 = int32(uintptr(ptr))
fmt.Printf("Pointer stored in int32: %#08x\n", addr32)
}
addr := uintptr(ptr)
fmt.Printf("Pointer stored in uintptr: %#08x\n", addr)
fmt.Println("value as float:", myVar)
i := (*int32)(unsafe.Pointer(&myVar))
fmt.Printf("value as int32: %#08x\n", *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 expansion of
(
x
−
1
)
p
−
(
x
p
−
1
)
{\displaystyle (x-1)^{p}-(x^{p}-1)}
are divisible by
p
{\displaystyle p}
.
Example
Using
p
=
3
{\displaystyle p=3}
:
(x-1)^3 - (x^3 - 1)
= (x^3 - 3x^2 + 3x - 1) - (x^3 - 1)
= -3x^2 + 3x
And all the coefficients are divisible by 3, so 3 is prime.
Note:
This task is not the AKS primality test. It is an inefficient exponential time algorithm discovered in the late 1600s and used as an introductory lemma in the AKS derivation.
Task
Create a function/subroutine/method that given
p
{\displaystyle p}
generates the coefficients of the expanded polynomial representation of
(
x
−
1
)
p
{\displaystyle (x-1)^{p}}
.
Use the function to show here the polynomial expansions of
(
x
−
1
)
p
{\displaystyle (x-1)^{p}}
for
p
{\displaystyle p}
in the range 0 to at least 7, inclusive.
Use the previous function in creating another function that when given
p
{\displaystyle p}
returns whether
p
{\displaystyle p}
is prime using the theorem.
Use your test to generate a list of all primes under 35.
As a stretch goal, generate all primes under 50 (needs integers larger than 31-bit).
References
Agrawal-Kayal-Saxena (AKS) primality test (Wikipedia)
Fool-Proof Test for Primes - Numberphile (Video). The accuracy of this video is disputed -- at best it is an oversimplification.
| #C.23 | C# |
using System;
public class AksTest
{
static long[] c = new long[100];
static void Main(string[] args)
{
for (int n = 0; n < 10; n++) {
coef(n);
Console.Write("(x-1)^" + n + " = ");
show(n);
Console.WriteLine("");
}
Console.Write("Primes:");
for (int n = 1; n <= 63; n++)
if (is_prime(n))
Console.Write(n + " ");
Console.WriteLine('\n');
Console.ReadLine();
}
static void coef(int n)
{
int i, j;
if (n < 0 || n > 63) System.Environment.Exit(0);// gracefully deal with range issue
for (c[i = 0] = 1L; i < n; c[0] = -c[0], i++)
for (c[1 + (j = i)] = 1L; j > 0; j--)
c[j] = c[j - 1] - c[j];
}
static bool is_prime(int n)
{
int i;
coef(n);
c[0] += 1;
c[i = n] -= 1;
while (i-- != 0 && (c[i] % n) == 0) ;
return i < 0;
}
static void show(int n)
{
do {
Console.Write("+" + c[n] + "x^" + n);
}while (n-- != 0);
}
}
|
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.
the prime-numbers entry: additive primes.
the geeks for geeks entry: additive prime number.
the prime-numbers fandom: additive primes.
| #C.2B.2B | C++ | #include <iomanip>
#include <iostream>
bool is_prime(unsigned int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (unsigned int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
return false;
}
return true;
}
unsigned int digit_sum(unsigned int n) {
unsigned int sum = 0;
for (; n > 0; n /= 10)
sum += n % 10;
return sum;
}
int main() {
const unsigned int limit = 500;
std::cout << "Additive primes less than " << limit << ":\n";
unsigned int count = 0;
for (unsigned int n = 1; n < limit; ++n) {
if (is_prime(digit_sum(n)) && is_prime(n)) {
std::cout << std::setw(3) << n;
if (++count % 10 == 0)
std::cout << '\n';
else
std::cout << ' ';
}
}
std::cout << '\n' << count << " additive primes found.\n";
} |
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-black-tree.
A red-black-tree is a binary tree where each internal node has a color attribute red or black. Moreover, no red node can have a red child, and every path from the root to an empty node must contain the same number of black nodes. As a consequence, the tree is balanced, and must be re-balanced after an insertion.
Reference
Red-Black Trees in a Functional Setting
| #Phix | Phix | --
-- demo\rosetta\Pattern_matching.exw
-- =================================
--
-- 1). Lightly modified copy of demo\rosetta\VisualiseTree.exw
with javascript_semantics
-- To the theme tune of the Milk Tray Ad iyrt,
-- All because the Windows console hates utf8:
constant TL = '\#DA', -- aka '┌'
VT = '\#B3', -- aka '│'
BL = '\#C0', -- aka '└'
HZ = '\#C4', -- aka '─'
HS = "\#C4" -- (string version of HZ)
function w1252_to_utf8(string s)
if platform()!=WINDOWS then
s = substitute_all(s,{ TL, VT, BL, HZ},
{"┌","│","└","─"})
end if
return s
end function
--</hates utf8>
procedure visualise_tree(object tree, string root=HS)
if atom(tree) then
puts(1,"<empty>\n")
else
object {colour,left,v,right} = tree
integer g = root[$]
if sequence(left) then
root[$] = iff(g=TL or g=HZ?' ':VT)
visualise_tree(left,root&TL)
end if
root[$] = g
printf(1,"%s%s%v\n",{w1252_to_utf8(root),colour,v})
if sequence(right) then
root[$] = iff(g=TL?VT:' ')
visualise_tree(right,root&BL)
end if
end if
end procedure
--</copy VisualiseTree>
-- 2). Imagine the following is in a file, say algebraic_data_types.e - not quite generic enough
-- for inclusion in builtins, but not exactly difficult to copy/maintain per-project either.
function match_one(sequence key, object t)
sequence res = {}
if sequence(t)
and length(key)==length(t) then
for i=1 to length(key) do
object ki = key[i], ti = t[i]
if sequence(ki) and not string(ki) then
sequence r2 = match_one(ki,ti)
if r2={} then res = {} exit end if
res &= r2
else
if ki=0 then
res = append(res,ti)
else
if ki!=ti then res = {} exit end if
end if
end if
end for
end if
return res
end function
/*global*/ function match_algebraic(sequence set, t)
sequence s
for i=1 to length(set) do
s = match_one(set[i],t)
if length(s) then exit end if
end for
return s
end function
--</algebraic_data_types.e>
-- 3). The actual task
constant B = "B", R = "R"
function balance(sequence t)
sequence s = match_algebraic({{B,{R,{R,0,0,0},0,0},0,0},
{B,{R,0,0,{R,0,0,0}},0,0},
{B,0,0,{R,{R,0,0,0},0,0}},
{B,0,0,{R,0,0,{R,0,0,0}}}},t)
if length(s) then
object {a,x,b,y,c,z,d} = s
t = {R,{B,a,x,b},y,{B,c,z,d}}
end if
return t
end function
function ins(object tree, object leaf)
if tree=NULL then
tree = {R,NULL,leaf,NULL}
else
object {c,l,k,r} = tree
if leaf!=k then
if leaf<k then l = ins(l,leaf)
else r = ins(r,leaf)
end if
tree = balance({c,l,k,r})
end if
end if
return tree
end function
function tree_insert(object tree, object leaf)
tree = ins(tree,leaf)
tree[1] = B
return tree
end function
sequence stuff = shuffle(tagset(10))
object tree = NULL
for i=1 to length(stuff) do
tree = tree_insert(tree,stuff[i])
end for
visualise_tree(tree)
?"done"
{} = wait_key()
|
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
{\displaystyle k=2}
, are the semiprimes.
Task
Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for
1
<=
K
<=
5
{\displaystyle 1<=K<=5}
.
Related tasks
Semiprime
Category:Prime Numbers
| #Fortran | Fortran |
program almost_prime
use iso_fortran_env, only: output_unit
implicit none
integer :: i, c, k
do k = 1, 5
write(output_unit,'(A3,x,I0,x,A1,x)', advance="no") "k =", k, ":"
i = 2
c = 0
do
if (c >= 10) exit
if (kprime(i, k)) then
write(output_unit,'(I0,x)', advance="no") i
c = c + 1
end if
i = i + 1
end do
write(output_unit,*)
end do
contains
pure function kprime(n, k)
integer, intent(in) :: n, k
logical :: kprime
integer :: p, f, i
kprime = .false.
f = 0
i = n
do p = 2, n
do
if (modulo(i, p) /= 0) exit
if (f == k) return
f = f + 1
i = i / p
end do
end do
kprime = f==k
end function kprime
end program almost_prime
|
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
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #C.2B.2B | C++ | #include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <vector>
#include <algorithm>
#include <iterator>
int main() {
std::ifstream in("unixdict.txt");
typedef std::map<std::string, std::vector<std::string> > AnagramMap;
AnagramMap anagrams;
std::string word;
size_t count = 0;
while (std::getline(in, word)) {
std::string key = word;
std::sort(key.begin(), key.end());
// note: the [] op. automatically inserts a new value if key does not exist
AnagramMap::mapped_type & v = anagrams[key];
v.push_back(word);
count = std::max(count, v.size());
}
in.close();
for (AnagramMap::const_iterator it = anagrams.begin(), e = anagrams.end();
it != e; it++)
if (it->second.size() >= count) {
std::copy(it->second.begin(), it->second.end(),
std::ostream_iterator<std::string>(std::cout, ", "));
std::cout << std::endl;
}
return 0;
} |
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.
Compute the angle for the following pairs:
20 degrees (b1) and 45 degrees (b2)
-45 and 45
-85 and 90
-95 and 90
-45 and 125
-45 and 145
29.4803 and -88.6381
-78.3251 and -159.036
Optional extra
Allow the input bearings to be any (finite) value.
Test cases
-70099.74233810938 and 29840.67437876723
-165313.6666297357 and 33693.9894517456
1174.8380510598456 and -154146.66490124757
60175.77306795546 and 42213.07192354373
| #Objeck | Objeck | class AngleBearings {
function : Main(args : String[]) ~ Nil {
"Input in -180 to +180 range"->PrintLine();
GetDifference(20.0, 45.0)->PrintLine();
GetDifference(-45.0, 45.0)->PrintLine();
GetDifference(-85.0, 90.0)->PrintLine();
GetDifference(-95.0, 90.0)->PrintLine();
GetDifference(-45.0, 125.0)->PrintLine();
GetDifference(-45.0, 145.0)->PrintLine();
GetDifference(-45.0, 125.0)->PrintLine();
GetDifference(-45.0, 145.0)->PrintLine();
GetDifference(29.4803, -88.6381)->PrintLine();
GetDifference(-78.3251, -159.036)->PrintLine();
"Input in wider range"->PrintLine();
GetDifference(-70099.74233810938, 29840.67437876723)->PrintLine();
GetDifference(-165313.6666297357, 33693.9894517456)->PrintLine();
GetDifference(1174.8380510598456, -154146.66490124757)->PrintLine();
GetDifference(60175.77306795546, 42213.07192354373)->PrintLine();
}
function : native : GetDifference(b1 : Float, b2 : Float) ~ Float {
r := Float->Mod(b2 - b1, 360.0);
if (r < -180.0) {
r += 360.0;
};
if (r >= 180.0) {
r -= 360.0;
};
return r;
}
} |
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 unixdict to find and display the longest deranged anagram.
Related tasks
Permutations/Derangements
Best shuffle
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #PicoLisp | PicoLisp | (let Words NIL
(in "unixdict.txt"
(while (line)
(let (Word @ Key (pack (sort (copy @))))
(if (idx 'Words Key T)
(push (car @) Word)
(set Key (list Word)) ) ) ) )
(maxi '((X) (length (car X)))
(extract
'((Key)
(pick
'((Lst)
(and
(find
'((L) (not (find = L Lst)))
(val Key) )
(cons (pack @) (pack Lst)) ) )
(val Key) ) )
(idx 'Words) ) ) ) |
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 function doesn't have the right arguments and/or return values.
So we end up inventing some silly name like foo2 or foo_helper. I have always found it painful to come up with a proper name, and see some disadvantages:
You have to think up a name, which then pollutes the namespace
Function is created which is called from nowhere else
The program flow in the source code is interrupted
Some languages allow you to embed recursion directly in-place. This might work via a label, a local gosub instruction, or some special keyword.
Anonymous recursion can also be accomplished using the Y combinator.
Task
If possible, demonstrate this by writing the recursive version of the fibonacci function (see Fibonacci sequence) which checks for a negative argument before doing the actual recursion.
| #Maple | Maple |
Fib := proc( n :: nonnegint )
proc( k )
option remember; # automatically memoise
if k = 0 then
0
elif k = 1 then
1
else
# Recurse, anonymously
thisproc( k - 1 ) + thisproc( k - 2 )
end
end( n )
end proc:
|
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
{\displaystyle =M}
as well as
s
u
m
(
p
r
o
p
D
i
v
s
(
M
)
)
=
N
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (M))=N}
.
Example
1184 and 1210 are an amicable pair, with proper divisors:
1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592 and
1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605 respectively.
Task
Calculate and show here the Amicable pairs below 20,000; (there are eight).
Related tasks
Proper divisors
Abundant, deficient and perfect number classifications
Aliquot sequence classifications and its amicable classification.
| #K | K |
propdivs:{1+&0=x!'1+!x%2}
(8,2)#v@&{(x=+/propdivs[a])&~x=a:+/propdivs[x]}' v:1+!20000
(220 284
1184 1210
2620 2924
5020 5564
6232 6368
10744 10856
12285 14595
17296 18416)
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.