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/Arithmetic/Rational | Arithmetic/Rational | Task
Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language.
Example
Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number).
Further define the appropriate rational unary operators abs and '-', with the binary operators for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠').
Define standard coercion operators for casting int to frac etc.
If space allows, define standard increment and decrement operators (e.g. '+:=' & '-:=' etc.).
Finally test the operators:
Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors.
Related task
Perfect Numbers
| #Sidef | Sidef | for n in (1 .. 2**19) {
var frac = 0
n.divisors.each {|d|
frac += 1/d
}
if (frac.is_int) {
say "Sum of reciprocal divisors of #{n} = #{frac} exactly #{
frac == 2 ? '- perfect!' : ''
}"
}
} |
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, you may also try something like:
x = 0
y = 0
z = x**y
say 'z=' z
Show the result here.
And of course use any symbols or notation that is supported in your computer programming language for exponentiation.
See also
The Wiki entry: Zero to the power of zero.
The Wiki entry: History of differing points of view.
The MathWorld™ entry: exponent laws.
Also, in the above MathWorld™ entry, see formula (9):
x
0
=
1
{\displaystyle x^{0}=1}
.
The OEIS entry: The special case of zero to the zeroth power
| #Lua | Lua | print(0^0) |
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, you may also try something like:
x = 0
y = 0
z = x**y
say 'z=' z
Show the result here.
And of course use any symbols or notation that is supported in your computer programming language for exponentiation.
See also
The Wiki entry: Zero to the power of zero.
The Wiki entry: History of differing points of view.
The MathWorld™ entry: exponent laws.
Also, in the above MathWorld™ entry, see formula (9):
x
0
=
1
{\displaystyle x^{0}=1}
.
The OEIS entry: The special case of zero to the zeroth power
| #M2000_Interpreter | M2000 Interpreter |
Module Checkit {
x=0
y=0
Print x**y=1, x^y=1 ' True True
}
Checkit
|
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, you may also try something like:
x = 0
y = 0
z = x**y
say 'z=' z
Show the result here.
And of course use any symbols or notation that is supported in your computer programming language for exponentiation.
See also
The Wiki entry: Zero to the power of zero.
The Wiki entry: History of differing points of view.
The MathWorld™ entry: exponent laws.
Also, in the above MathWorld™ entry, see formula (9):
x
0
=
1
{\displaystyle x^{0}=1}
.
The OEIS entry: The special case of zero to the zeroth power
| #Maple | Maple | 0^0 |
http://rosettacode.org/wiki/Zebra_puzzle | Zebra puzzle | Zebra puzzle
You are encouraged to solve this task according to the task description, using any language you may know.
The Zebra puzzle, a.k.a. Einstein's Riddle,
is a logic puzzle which is to be solved programmatically.
It has several variants, one of them this:
There are five houses.
The English man lives in the red house.
The Swede has a dog.
The Dane drinks tea.
The green house is immediately to the left of the white house.
They drink coffee in the green house.
The man who smokes Pall Mall has birds.
In the yellow house they smoke Dunhill.
In the middle house they drink milk.
The Norwegian lives in the first house.
The man who smokes Blend lives in the house next to the house with cats.
In a house next to the house where they have a horse, they smoke Dunhill.
The man who smokes Blue Master drinks beer.
The German smokes Prince.
The Norwegian lives next to the blue house.
They drink water in a house next to the house where they smoke Blend.
The question is, who owns the zebra?
Additionally, list the solution for all the houses.
Optionally, show the solution is unique.
Related tasks
Dinesman's multiple-dwelling problem
Twelve statements
| #AutoHotkey | AutoHotkey | REM The names (only used for printing the results):
DIM Drink$(4), Nation$(4), Colr$(4), Smoke$(4), Animal$(4)
Drink$() = "Beer", "Coffee", "Milk", "Tea", "Water"
Nation$() = "Denmark", "England", "Germany", "Norway", "Sweden"
Colr$() = "Blue", "Green", "Red", "White", "Yellow"
Smoke$() = "Blend", "BlueMaster", "Dunhill", "PallMall", "Prince"
Animal$() = "Birds", "Cats", "Dog", "Horse", "Zebra"
REM Some single-character tags:
a$ = "A" : b$ = "B" : c$ = "C" : d$ = "D" : e$ = "E"
REM BBC BASIC Doesn't have enumerations!
Beer$=a$ : Coffee$=b$ : Milk$=c$ : Tea$=d$ : Water$=e$
Denmark$=a$ : England$=b$ : Germany$=c$ : Norway$=d$ : Sweden$=e$
Blue$=a$ : Green$=b$ : Red$=c$ : White$=d$ : Yellow$=e$
Blend$=a$ : BlueMaster$=b$ : Dunhill$=c$ : PallMall$=d$ : Prince$=e$
Birds$=a$ : Cats$=b$ : Dog$=c$ : Horse$=d$ : Zebra$=e$
REM Create the 120 permutations of 5 objects:
DIM perm$(120), x$(4) : x$() = a$, b$, c$, d$, e$
REPEAT
p% += 1
perm$(p%) = x$(0)+x$(1)+x$(2)+x$(3)+x$(4)
UNTIL NOT FNperm(x$())
REM Express the statements as conditional expressions:
ex2$ = "INSTR(Nation$,England$) = INSTR(Colr$,Red$)"
ex3$ = "INSTR(Nation$,Sweden$) = INSTR(Animal$,Dog$)"
ex4$ = "INSTR(Nation$,Denmark$) = INSTR(Drink$,Tea$)"
ex5$ = "INSTR(Colr$,Green$+White$) <> 0"
ex6$ = "INSTR(Drink$,Coffee$) = INSTR(Colr$,Green$)"
ex7$ = "INSTR(Smoke$,PallMall$) = INSTR(Animal$,Birds$)"
ex8$ = "INSTR(Smoke$,Dunhill$) = INSTR(Colr$,Yellow$)"
ex9$ = "MID$(Drink$,3,1) = Milk$"
ex10$ = "LEFT$(Nation$,1) = Norway$"
ex11$ = "ABS(INSTR(Smoke$,Blend$)-INSTR(Animal$,Cats$)) = 1"
ex12$ = "ABS(INSTR(Smoke$,Dunhill$)-INSTR(Animal$,Horse$)) = 1"
ex13$ = "INSTR(Smoke$,BlueMaster$) = INSTR(Drink$,Beer$)"
ex14$ = "INSTR(Nation$,Germany$) = INSTR(Smoke$,Prince$)"
ex15$ = "ABS(INSTR(Nation$,Norway$)-INSTR(Colr$,Blue$)) = 1"
ex16$ = "ABS(INSTR(Smoke$,Blend$)-INSTR(Drink$,Water$)) = 1"
REM Solve:
solutions% = 0
TIME = 0
FOR nation% = 1 TO 120
Nation$ = perm$(nation%)
IF EVAL(ex10$) THEN
FOR colr% = 1 TO 120
Colr$ = perm$(colr%)
IF EVAL(ex5$) IF EVAL(ex2$) IF EVAL(ex15$) THEN
FOR drink% = 1 TO 120
Drink$ = perm$(drink%)
IF EVAL(ex9$) IF EVAL(ex4$) IF EVAL(ex6$) THEN
FOR smoke% = 1 TO 120
Smoke$ = perm$(smoke%)
IF EVAL(ex14$) IF EVAL(ex13$) IF EVAL(ex16$) IF EVAL(ex8$) THEN
FOR animal% = 1 TO 120
Animal$ = perm$(animal%)
IF EVAL(ex3$) IF EVAL(ex7$) IF EVAL(ex11$) IF EVAL(ex12$) THEN
PRINT "House Drink Nation Colour Smoke Animal"
FOR house% = 1 TO 5
PRINT ; house% ,;
PRINT Drink$(ASCMID$(Drink$,house%)-65),;
PRINT Nation$(ASCMID$(Nation$,house%)-65),;
PRINT Colr$(ASCMID$(Colr$,house%)-65),;
PRINT Smoke$(ASCMID$(Smoke$,house%)-65),;
PRINT Animal$(ASCMID$(Animal$,house%)-65)
NEXT
solutions% += 1
ENDIF
NEXT animal%
ENDIF
NEXT smoke%
ENDIF
NEXT drink%
ENDIF
NEXT colr%
ENDIF
NEXT nation%
PRINT '"Number of solutions = "; solutions%
PRINT "Solved in " ; TIME/100 " seconds"
END
DEF FNperm(x$())
LOCAL i%, j%
FOR i% = DIM(x$(),1)-1 TO 0 STEP -1
IF x$(i%) < x$(i%+1) EXIT FOR
NEXT
IF i% < 0 THEN = FALSE
j% = DIM(x$(),1)
WHILE x$(j%) <= x$(i%) j% -= 1 : ENDWHILE
SWAP x$(i%), x$(j%)
i% += 1
j% = DIM(x$(),1)
WHILE i% < j%
SWAP x$(i%), x$(j%)
i% += 1
j% -= 1
ENDWHILE
= TRUE |
http://rosettacode.org/wiki/XML/XPath | XML/XPath | Perform the following three XPath queries on the XML Document below:
//item[1]: Retrieve the first "item" element
//price/text(): Perform an action on each "price" element (print it out)
//name: Get an array of all the "name" elements
XML Document:
<inventory title="OmniCorp Store #45x10^3">
<section name="health">
<item upc="123456789" stock="12">
<name>Invisibility Cream</name>
<price>14.50</price>
<description>Makes you invisible</description>
</item>
<item upc="445322344" stock="18">
<name>Levitation Salve</name>
<price>23.99</price>
<description>Levitate yourself for up to 3 hours per application</description>
</item>
</section>
<section name="food">
<item upc="485672034" stock="653">
<name>Blork and Freen Instameal</name>
<price>4.95</price>
<description>A tasty meal in a tablet; just add water</description>
</item>
<item upc="132957764" stock="44">
<name>Grob winglets</name>
<price>3.56</price>
<description>Tender winglets of Grob. Just add water</description>
</item>
</section>
</inventory>
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program xpathXml.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
.equ NBMAXELEMENTS, 100
/*******************************************/
/* Structures */
/********************************************/
/* structure xmlNode*/
.struct 0
xmlNode_private: @ application data
.struct xmlNode_private + 4
xmlNode_type: @ type number, must be second !
.struct xmlNode_type + 4
xmlNode_name: @ the name of the node, or the entity
.struct xmlNode_name + 4
xmlNode_children: @ parent->childs link
.struct xmlNode_children + 4
xmlNode_last: @ last child link
.struct xmlNode_last + 4
xmlNode_parent: @ child->parent link
.struct xmlNode_parent + 4
xmlNode_next: @ next sibling link
.struct xmlNode_next + 4
xmlNode_prev: @ previous sibling link
.struct xmlNode_prev + 4
xmlNode_doc: @ the containing document
.struct xmlNode_doc + 4
xmlNode_ns: @ pointer to the associated namespace
.struct xmlNode_ns + 4
xmlNode_content: @ the content
.struct xmlNode_content + 4
xmlNode_properties: @ properties list
.struct xmlNode_properties + 4
xmlNode_nsDef: @ namespace definitions on this node
.struct xmlNode_nsDef + 4
xmlNode_psvi: @ for type/PSVI informations
.struct xmlNode_psvi + 4
xmlNode_line: @ line number
.struct xmlNode_line + 4
xmlNode_extra: @ extra data for XPath/XSLT
.struct xmlNode_extra + 4
xmlNode_fin:
/********************************************/
/* structure xmlNodeSet*/
.struct 0
xmlNodeSet_nodeNr: @ number of nodes in the set
.struct xmlNodeSet_nodeNr + 4
xmlNodeSet_nodeMax: @ size of the array as allocated
.struct xmlNodeSet_nodeMax + 4
xmlNodeSet_nodeTab: @ array of nodes in no particular order
.struct xmlNodeSet_nodeTab + 4
xmlNodeSet_fin:
/********************************************/
/* structure xmlXPathObject*/
.struct 0
xmlPathObj_type: @
.struct xmlPathObj_type + 4
xmlPathObj_nodesetval: @
.struct xmlPathObj_nodesetval + 4
xmlPathObj_boolval: @
.struct xmlPathObj_boolval + 4
xmlPathObj_floatval: @
.struct xmlPathObj_floatval + 4
xmlPathObj_stringval: @
.struct xmlPathObj_stringval + 4
xmlPathObj_user: @
.struct xmlPathObj_user + 4
xmlPathObj_index: @
.struct xmlPathObj_index + 4
xmlPathObj_user2: @
.struct xmlPathObj_user2 + 4
xmlPathObj_index2: @
.struct xmlPathObj_index2 + 4
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessEndpgm: .asciz "\nNormal end of program.\n"
szMessDisVal: .asciz "\nDisplay set values.\n"
szMessDisArea: .asciz "\nDisplay area values.\n"
szFileName: .asciz "testXml.xml"
szMessError: .asciz "Error detected !!!!. \n"
szLibName: .asciz "name"
szLibPrice: .asciz "//price"
szLibExtName: .asciz "//name"
szCarriageReturn: .asciz "\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
.align 4
tbExtract: .skip 4 * NBMAXELEMENTS @ result extract area
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r0,iAdrszFileName
bl xmlParseFile @ create doc
mov r9,r0 @ doc address
mov r0,r9 @ doc
bl xmlDocGetRootElement @ get root
bl xmlFirstElementChild @ get first section
bl xmlFirstElementChild @ get first item
bl xmlFirstElementChild @ get first name
bl xmlNodeGetContent @ extract content
bl affichageMess @ for display
ldr r0,iAdrszCarriageReturn
bl affichageMess
ldr r0,iAdrszMessDisVal
bl affichageMess
mov r0,r9
ldr r1,iAdrszLibPrice @ extract prices
bl extractValue
mov r0,r9
ldr r1,iAdrszLibExtName @ extact names
bl extractValue
ldr r0,iAdrszMessDisArea
bl affichageMess
mov r4,#0 @ display string result area
ldr r5,iAdrtbExtract
1:
ldr r0,[r5,r4,lsl #2]
cmp r0,#0
beq 2f
bl affichageMess
ldr r0,iAdrszCarriageReturn
bl affichageMess
add r4,#1
b 1b
2:
mov r0,r9
bl xmlFreeDoc
bl xmlCleanupParser
ldr r0,iAdrszMessEndpgm
bl affichageMess
b 100f
99:
@ error
ldr r0,iAdrszMessError
bl affichageMess
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrszMessError: .int szMessError
iAdrszMessEndpgm: .int szMessEndpgm
iAdrszLibName: .int szLibName
iAdrszLibPrice: .int szLibPrice
iAdrszCarriageReturn: .int szCarriageReturn
iAdrszFileName: .int szFileName
iAdrszLibExtName: .int szLibExtName
iAdrtbExtract: .int tbExtract
iAdrszMessDisVal: .int szMessDisVal
iAdrszMessDisArea: .int szMessDisArea
/******************************************************************/
/* extract value of set */
/******************************************************************/
/* r0 contains the doc address
/* r1 contains the address of the libel to extract */
extractValue:
push {r1-r10,lr} @ save registres
mov r4,r1 @ save address libel
mov r9,r0 @ save doc
ldr r8,iAdrtbExtract
bl xmlXPathNewContext @ create context
mov r10,r0
mov r1,r0
mov r0,r4
bl xmlXPathEvalExpression
mov r5,r0
mov r0,r10
bl xmlXPathFreeContext @ free context
cmp r5,#0
beq 100f
ldr r4,[r5,#xmlPathObj_nodesetval] @ values set
ldr r6,[r4,#xmlNodeSet_nodeNr] @ set size
mov r7,#0 @ index
ldr r4,[r4,#xmlNodeSet_nodeTab] @ area of nods
1: @ start loop
ldr r3,[r4,r7,lsl #2] @ load node
mov r0,r9
ldr r1,[r3,#xmlNode_children] @ load string value
mov r2,#1
bl xmlNodeListGetString
str r0,[r8,r7,lsl #2] @ store string pointer in area
bl affichageMess @ and display string result
ldr r0,iAdrszCarriageReturn
bl affichageMess
add r7,#1
cmp r7,r6
blt 1b
100:
pop {r1-r10,lr} @ restaur registers */
bx lr @ return
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registres
mov r2,#0 @ counter length
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call systeme
pop {r0,r1,r2,r7,lr} @ restaur registers */
bx lr @ return
|
http://rosettacode.org/wiki/Yin_and_yang | Yin and yang | One well-known symbol of the philosophy of duality known as yin and yang is the taijitu.
Task
Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.
Generate and display the symbol for two different (small) sizes.
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program yingyang.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/***************************************************************/
/* File Constantes see task Include a file for arm assembly */
/***************************************************************/
.include "../constantes.inc"
.equ SIZEMAXI, 78
/******************************************/
/* Initialized data */
/******************************************/
.data
szMessDebutPgm: .asciz "Start program.\n"
szMessFinPgm: .asciz "Program End ok.\n"
szRetourLigne: .asciz "\n"
szMessErrComm: .asciz "Incomplete Command line : yingyang <size> \n"
/******************************************/
/* UnInitialized data */
/******************************************/
.bss
szLine: .skip SIZEMAXI
/******************************************/
/* code section */
/******************************************/
.text
.global main
main: @ entry of program
mov fp,sp // copy stack address register r29 fp
ldr r0,iAdrszMessDebutPgm
bl affichageMess
ldr r0,[fp] // parameter number command line
cmp r0,#1 // correct ?
ble erreurCommande // error
add r0,fp,#8 // address parameter 2
ldr r0,[r0]
bl conversionAtoD
cmp r0,#SIZEMAXI / 2
movgt r0,#(SIZEMAXI / 2) - 1 // limit size
mov r10,r0 // size
lsr r11,r10,#1 // R = size / 2 radius great circle
mul r9,r11,r11 // R^2
lsr r12,r11,#1 // radius median circle
lsr r8,r12,#1 // radius little circle
mov r2,#0 // y
ldr r0,iAdrszLine
1:
mov r1,#0 // x
mov r5,#' '
mov r3,#SIZEMAXI
11: // move spaces in display line
strb r5,[r0,r1]
add r1,#1
cmp r1,r3
blt 11b
mov r1,#0 // x
2: // begin loop
sub r3,r1,r11 // x1 = x - R
mul r4,r3,r3 // x1^2
sub r5,r2,r11 // y1 = y - R
mul r6,r5,r5 // y1^2
add r6,r4 // add x1^2 y1^2
cmp r6,r9 // compare R^2
ble 3f
mov r5,#' ' // not in great circle
strb r5,[r0,r1,lsl #1]
b 20f
3: // compute quadrant
cmp r1,r11
bgt 10f // x > R
cmp r2,r11
bgt 5f // y > R
// quadrant 1 x < R and y < R
sub r5,r2,r12
mul r7,r5,r5 // y1^2
add r7,r4 // y1^2 + x1^2
mul r6,r8,r8 // little r ^2
cmp r7,r8
bgt 4f
mov r5,#' ' // in little circle
strb r5,[r0,r1,lsl #1]
b 20f
4: // in other part of great circle
mov r5,#'.'
strb r5,[r0,r1,lsl #1]
b 20f
5: // quadrant 3 x < R and y > R
mov r5,#3
mul r5,r10,r5
lsr r5,#2
sub r6,r2,r5 // y1 - pos little circle (= (size / 3) * 4
mul r7,r6,r6 // y1^2
add r7,r4 // y1^2 + x1^2
mul r6,r8,r8 // r little
cmp r7,r8
bgt 6f
mov r5,#' ' // in little circle
strb r5,[r0,r1,lsl #1]
b 20f
6:
mul r6,r12,r12
cmp r7,r6
bge 7f
mov r5,#'#' // in median circle
strb r5,[r0,r1,lsl #1]
b 20f
7:
mov r5,#'.' // not in median
strb r5,[r0,r1,lsl #1]
b 20f
10:
cmp r2,r11
bgt 15f
// quadrant 2
sub r5,r2,r12 // y - center little
mul r6,r5,r5
add r7,r4,r6
mul r6,r8,r8
cmp r7,r6
bge 11f
mov r5,#' ' // in little circle
strb r5,[r0,r1,lsl #1]
b 20f
11:
mul r6,r12,r12
cmp r7,r6
bge 12f
mov r5,#'.' // in median circle
strb r5,[r0,r1,lsl #1]
b 20f
12:
mov r5,#'#' // in great circle
strb r5,[r0,r1,lsl #1]
b 20f
15:
// quadrant 4
mov r5,#3
mul r5,r10,r5
lsr r5,#2
sub r6,r2,r5 // y1 - pos little
mul r7,r6,r6 // y1^2
add r7,r4 // y1^2 + x1^2
mul r6,r8,r8 // little r ^2
cmp r7,r8
bgt 16f
mov r5,#' ' // in little circle
strb r5,[r0,r1,lsl #1]
b 20f
16:
mov r5,#'#'
strb r5,[r0,r1,lsl #1]
b 20f
20:
add r1,#1 // increment x
cmp r1,r10 // size ?
ble 2b // no -> loop
lsl r1,#1
mov r5,#'\n' // add return line
strb r5,[r0,r1]
add r1,#1
mov r5,#0 // add final zéro
strb r5,[r0,r1]
bl affichageMess // and display line
add r2,r2,#1 // increment y
cmp r2,r10 // size ?
ble 1b // no -> loop
ldr r0,iAdrszMessFinPgm
bl affichageMess
b 100f
erreurCommande:
ldr r0,iAdrszMessErrComm
bl affichageMess
mov r0,#1 // error code
b 100f
100: // standard end of the program
mov r0, #0 // return code
mov r7, #EXIT // request to exit program
svc 0 // perform the system call
iAdrszMessDebutPgm: .int szMessDebutPgm
iAdrszMessFinPgm: .int szMessFinPgm
iAdrszMessErrComm: .int szMessErrComm
iAdrszLine: .int szLine
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"
|
http://rosettacode.org/wiki/Y_combinator | Y combinator | In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions.
This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function.
The Y combinator is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function.
The Y combinator is the simplest of the class of such functions, called fixed-point combinators.
Task
Define the stateless Y combinator and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions.
Cf
Jim Weirich: Adventures in Functional Programming
| #ATS | ATS |
(* ****** ****** *)
//
#include "share/atspre_staload.hats"
//
(* ****** ****** *)
//
fun
myfix
{a:type}
(
f: lazy(a) -<cloref1> a
) : lazy(a) = $delay(f(myfix(f)))
//
val
fact =
myfix{int-<cloref1>int}
(
lam(ff) => lam(x) => if x > 0 then x * !ff(x-1) else 1
)
(* ****** ****** *)
//
implement main0 () = println! ("fact(10) = ", !fact(10))
//
(* ****** ****** *)
|
http://rosettacode.org/wiki/Zig-zag_matrix | Zig-zag matrix | Task
Produce a zig-zag array.
A zig-zag array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you zig-zag along the array's anti-diagonals.
For a graphical representation, see JPG zigzag (JPG uses such arrays to encode images).
For example, given 5, produce this array:
0 1 5 6 14
2 4 7 13 15
3 8 12 16 21
9 11 17 20 22
10 18 19 23 24
Related tasks
Spiral matrix
Identity matrix
Ulam spiral (for primes)
See also
Wiktionary entry: anti-diagonals
| #AutoHotkey | AutoHotkey | n = 5 ; size
v := x := y := 1 ; initial values
Loop % n*n { ; for every array element
a_%x%_%y% := v++ ; assign the next index
If ((x+y)&1) ; odd diagonal
If (x < n) ; while inside the square
y -= y<2 ? 0 : 1, x++ ; move right-up
Else y++ ; on the edge increment y, but not x: to even diagonal
Else ; even diagonal
If (y < n) ; while inside the square
x -= x<2 ? 0 : 1, y++ ; move left-down
Else x++ ; on the edge increment x, but not y: to odd diagonal
}
Loop %n% { ; generate printout
x := A_Index ; for each row
Loop %n% ; and for each column
t .= a_%x%_%A_Index% "`t" ; attach stored index
t .= "`n" ; row is complete
}
MsgBox %t% ; show output |
http://rosettacode.org/wiki/Yellowstone_sequence | Yellowstone sequence | The Yellowstone sequence, also called the Yellowstone permutation, is defined as:
For n <= 3,
a(n) = n
For n >= 4,
a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and
is not relatively prime to a(n-2).
The sequence is a permutation of the natural numbers, and gets its name from what its authors felt was a spiking, geyser like appearance of a plot of the sequence.
Example
a(4) is 4 because 4 is the smallest number following 1, 2, 3 in the sequence that is relatively prime to the entry before it (3), and is not relatively prime to the number two entries before it (2).
Task
Find and show as output the first 30 Yellowstone numbers.
Extra
Demonstrate how to plot, with x = n and y coordinate a(n), the first 100 Yellowstone numbers.
Related tasks
Greatest common divisor.
Plot coordinate pairs.
See also
The OEIS entry: A098550 The Yellowstone permutation.
Applegate et al, 2015: The Yellowstone Permutation [1].
| #JavaScript | JavaScript | (() => {
'use strict';
// yellowstone :: Generator [Int]
function* yellowstone() {
// A non finite stream of terms in the
// Yellowstone permutation of the natural numbers.
// OEIS A098550
const nextWindow = ([p2, p1, rest]) => {
const [rp2, rp1] = [p2, p1].map(
relativelyPrime
);
const go = xxs => {
const [x, xs] = Array.from(
uncons(xxs).Just
);
return rp1(x) && !rp2(x) ? (
Tuple(x)(xs)
) : secondArrow(cons(x))(
go(xs)
);
};
return [p1, ...Array.from(go(rest))];
};
const A098550 = fmapGen(x => x[1])(
iterate(nextWindow)(
[2, 3, enumFrom(4)]
)
);
yield 1
yield 2
while (true)(
yield A098550.next().value
)
};
// relativelyPrime :: Int -> Int -> Bool
const relativelyPrime = a =>
// True if a is relatively prime to b.
b => 1 === gcd(a)(b);
// ------------------------TEST------------------------
const main = () => console.log(
take(30)(
yellowstone()
)
);
// -----------------GENERIC FUNCTIONS------------------
// Just :: a -> Maybe a
const Just = x => ({
type: 'Maybe',
Nothing: false,
Just: x
});
// Nothing :: Maybe a
const Nothing = () => ({
type: 'Maybe',
Nothing: true,
});
// Tuple (,) :: a -> b -> (a, b)
const Tuple = a =>
b => ({
type: 'Tuple',
'0': a,
'1': b,
length: 2
});
// abs :: Num -> Num
const abs =
// Absolute value of a given number - without the sign.
Math.abs;
// cons :: a -> [a] -> [a]
const cons = x =>
xs => Array.isArray(xs) ? (
[x].concat(xs)
) : 'GeneratorFunction' !== xs
.constructor.constructor.name ? (
x + xs
) : ( // cons(x)(Generator)
function*() {
yield x;
let nxt = xs.next()
while (!nxt.done) {
yield nxt.value;
nxt = xs.next();
}
}
)();
// enumFrom :: Enum a => a -> [a]
function* enumFrom(x) {
// A non-finite succession of enumerable
// values, starting with the value x.
let v = x;
while (true) {
yield v;
v = 1 + v;
}
}
// fmapGen <$> :: (a -> b) -> Gen [a] -> Gen [b]
const fmapGen = f =>
function*(gen) {
let v = take(1)(gen);
while (0 < v.length) {
yield(f(v[0]))
v = take(1)(gen)
}
};
// gcd :: Int -> Int -> Int
const gcd = x => y => {
const
_gcd = (a, b) => (0 === b ? a : _gcd(b, a % b)),
abs = Math.abs;
return _gcd(abs(x), abs(y));
};
// iterate :: (a -> a) -> a -> Gen [a]
const iterate = f =>
function*(x) {
let v = x;
while (true) {
yield(v);
v = f(v);
}
};
// length :: [a] -> Int
const length = xs =>
// Returns Infinity over objects without finite
// length. This enables zip and zipWith to choose
// the shorter argument when one is non-finite,
// like cycle, repeat etc
(Array.isArray(xs) || 'string' === typeof xs) ? (
xs.length
) : Infinity;
// secondArrow :: (a -> b) -> ((c, a) -> (c, b))
const secondArrow = f => xy =>
// A function over a simple value lifted
// to a function over a tuple.
// f (a, b) -> (a, f(b))
Tuple(xy[0])(
f(xy[1])
);
// take :: Int -> [a] -> [a]
// take :: Int -> String -> String
const take = n =>
// The first n elements of a list,
// string of characters, or stream.
xs => 'GeneratorFunction' !== xs
.constructor.constructor.name ? (
xs.slice(0, n)
) : [].concat.apply([], Array.from({
length: n
}, () => {
const x = xs.next();
return x.done ? [] : [x.value];
}));
// uncons :: [a] -> Maybe (a, [a])
const uncons = xs => {
// Just a tuple of the head of xs and its tail,
// Or Nothing if xs is an empty list.
const lng = length(xs);
return (0 < lng) ? (
Infinity > lng ? (
Just(Tuple(xs[0])(xs.slice(1))) // Finite list
) : (() => {
const nxt = take(1)(xs);
return 0 < nxt.length ? (
Just(Tuple(nxt[0])(xs))
) : Nothing();
})() // Lazy generator
) : Nothing();
};
// MAIN ---
return main();
})(); |
http://rosettacode.org/wiki/Yahoo!_search_interface | Yahoo! search interface | Create a class for searching Yahoo! results.
It must implement a Next Page method, and read URL, Title and Content from results.
| #Icon_and_Unicon | Icon and Unicon | link printf,strings
procedure main()
YS := YahooSearch("rosettacode")
every 1 to 2 do { # 2 pages
YS.readnext()
YS.showinfo()
}
end
class YahooSearch(urlpat,page,response) #: class for Yahoo Search
method readnext() #: read the next page of search results
self.page +:= 1 # can't find as w|w/o self
readurl()
end
method readurl() #: read the url
url := sprintf(self.urlpat,(self.page-1)*10+1)
m := open(url,"m") | stop("Unable to open : ",url)
every (self.response := "") ||:= |read(m)
close(m)
self.response := deletec(self.response,"\x00") # kill stray NULs
end
method showinfo() #: show the info of interest
self.response ? repeat {
(tab(find("<")) & ="<a class=\"yschttl spt\" href=\"") | break
url := tab(find("\"")) & tab(find(">")+1)
title := tab(find("<")) & ="</a></h3></div>"
tab(find("<")) & =("<div class=\"abstr\">" | "<div class=\"sm-abs\">")
abstr := tab(find("<")) & ="</div>"
printf("\nTitle : %i\n",title)
printf("URL : %i\n",url)
printf("Abstr : %i\n",abstr)
}
end
initially(searchtext) #: initialize each instance
urlpat := sprintf("http://search.yahoo.com/search?p=%s&b=%%d",searchtext)
page := 0
end |
http://rosettacode.org/wiki/Arithmetic_evaluation | Arithmetic evaluation | Create a program which parses and evaluates arithmetic expressions.
Requirements
An abstract-syntax tree (AST) for the expression must be created from parsing the input.
The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.)
The expression will be a string or list of symbols like "(1+3)*7".
The four symbols + - * / must be supported as binary operators with conventional precedence rules.
Precedence-control parentheses must also be supported.
Note
For those who don't remember, mathematical precedence is as follows:
Parentheses
Multiplication/Division (left to right)
Addition/Subtraction (left to right)
C.f
24 game Player.
Parsing/RPN calculator algorithm.
Parsing/RPN to infix conversion.
| #TXR | TXR | @(next :args)
@(define space)@/ */@(end)
@(define mulop (nod))@\
@(local op)@\
@(space)@\
@(cases)@\
@{op /[*]/}@(bind nod @(intern op *user-package*))@\
@(or)@\
@{op /\//}@(bind (nod) @(list 'trunc))@\
@(end)@\
@(space)@\
@(end)
@(define addop (nod))@\
@(local op)@(space)@{op /[+\-]/}@(space)@\
@(bind nod @(intern op *user-package*))@\
@(end)
@(define number (nod))@\
@(local n)@(space)@{n /[0-9]+/}@(space)@\
@(bind nod @(int-str n 10))@\
@(end)
@(define factor (nod))@(cases)(@(expr nod))@(or)@(number nod)@(end)@(end)
@(define term (nod))@\
@(local op nod1 nod2)@\
@(cases)@\
@(factor nod1)@\
@(cases)@(mulop op)@(term nod2)@(bind nod (op nod1 nod2))@\
@(or)@(bind nod nod1)@\
@(end)@\
@(or)@\
@(addop op)@(factor nod1)@\
@(bind nod (op nod1))@\
@(end)@\
@(end)
@(define expr (nod))@\
@(local op nod1 nod2)@\
@(term nod1)@\
@(cases)@(addop op)@(expr nod2)@(bind nod (op nod1 nod2))@\
@(or)@(bind nod nod1)@\
@(end)@\
@(end)
@(cases)
@ {source (expr e)}
@ (output)
source: @source
AST: @(format nil "~s" e)
value: @(eval e nil)
@ (end)
@(or)
@ (maybe)@(expr e)@(end)@bad
@ (output)
erroneous suffix "@bad"
@ (end)
@(end) |
http://rosettacode.org/wiki/Arithmetic_evaluation | Arithmetic evaluation | Create a program which parses and evaluates arithmetic expressions.
Requirements
An abstract-syntax tree (AST) for the expression must be created from parsing the input.
The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.)
The expression will be a string or list of symbols like "(1+3)*7".
The four symbols + - * / must be supported as binary operators with conventional precedence rules.
Precedence-control parentheses must also be supported.
Note
For those who don't remember, mathematical precedence is as follows:
Parentheses
Multiplication/Division (left to right)
Addition/Subtraction (left to right)
C.f
24 game Player.
Parsing/RPN calculator algorithm.
Parsing/RPN to infix conversion.
| #Ursala | Ursala | #import std
#import nat
#import flo
lex = ~=' '*~F+ rlc both -=digits # separate into tokens
parse = # build a tree
--<';'>; @iNX ~&l->rh ^/~< cases~&lhh\~&lhPNVrC {
'*/': ^|C/~&hNV associate '*/',
'+-': ^|C/~&hNV associate '*/+-',
');': @r ~&htitBPC+ associate '*/+-'}
associate "ops" = ~&tihdh2B-="ops"-> ~&thd2tth2hNCCVttt2C
traverse = *^ ~&v?\%ep ^H\~&vhthPX '+-*/'-$<plus,minus,times,div>@dh
evaluate = traverse+ parse+ lex |
http://rosettacode.org/wiki/Zeckendorf_arithmetic | Zeckendorf arithmetic | This task is a total immersion zeckendorf task; using decimal numbers will attract serious disapprobation.
The task is to implement addition, subtraction, multiplication, and division using Zeckendorf number representation. Optionally provide decrement, increment and comparitive operation functions.
Addition
Like binary 1 + 1 = 10, note carry 1 left. There the similarity ends. 10 + 10 = 101, note carry 1 left and 1 right. 100 + 100 = 1001, note carry 1 left and 2 right, this is the general case.
Occurrences of 11 must be changed to 100. Occurrences of 111 may be changed from the right by replacing 11 with 100, or from the left converting 111 to 100 + 100;
Subtraction
10 - 1 = 1. The general rule is borrow 1 right carry 1 left. eg:
abcde
10100 -
1000
_____
100 borrow 1 from a leaves 100
+ 100 add the carry
_____
1001
A larger example:
abcdef
100100 -
1000
______
1*0100 borrow 1 from b
+ 100 add the carry
______
1*1001
Sadly we borrowed 1 from b which didn't have it to lend. So now b borrows from a:
1001
+ 1000 add the carry
____
10100
Multiplication
Here you teach your computer its zeckendorf tables. eg. 101 * 1001:
a = 1 * 101 = 101
b = 10 * 101 = a + a = 10000
c = 100 * 101 = b + a = 10101
d = 1000 * 101 = c + b = 101010
1001 = d + a therefore 101 * 1001 =
101010
+ 101
______
1000100
Division
Lets try 1000101 divided by 101, so we can use the same table used for multiplication.
1000101 -
101010 subtract d (1000 * 101)
_______
1000 -
101 b and c are too large to subtract, so subtract a
____
1 so 1000101 divided by 101 is d + a (1001) remainder 1
Efficient algorithms for Zeckendorf arithmetic is interesting. The sections on addition and subtraction are particularly relevant for this task.
| #Vlang | Vlang | import strings
const (
dig = ["00", "01", "10"]
dig1 = ["", "1", "10"]
)
struct Zeckendorf {
mut:
d_val int
d_len int
}
fn new_zeck(xx string) Zeckendorf {
mut z := Zeckendorf{}
mut x := xx
if x == "" {
x = "0"
}
mut q := 1
mut i := x.len - 1
z.d_len = i / 2
for ; i >= 0; i-- {
z.d_val += int(x[i]-'0'[0]) * q
q *= 2
}
return z
}
fn (mut z Zeckendorf) a(ii int) {
mut i:=ii
for ; ; i++ {
if z.d_len < i {
z.d_len = i
}
j := (z.d_val >> u32(i*2)) & 3
if j in [0, 1] {
return
} else if j==2 {
if ((z.d_val >> (u32(i+1) * 2)) & 1) != 1 {
return
}
z.d_val += 1 << u32(i*2+1)
return
} else {// 3
z.d_val &= ~(3 << u32(i*2))
z.b((i + 1) * 2)
}
}
}
fn (mut z Zeckendorf) b(p int) {
mut pos := p
if pos == 0 {
z.inc()
return
}
if ((z.d_val >> u32(pos)) & 1) == 0 {
z.d_val += 1 << u32(pos)
z.a(pos / 2)
if pos > 1 {
z.a(pos/2 - 1)
}
} else {
z.d_val &= ~(1 << u32(pos))
z.b(pos + 1)
mut temp := 1
if pos > 1 {
temp = 2
}
z.b(pos - temp)
}
}
fn (mut z Zeckendorf) c(p int) {
mut pos := p
if ((z.d_val >> u32(pos)) & 1) == 1 {
z.d_val &= ~(1 << u32(pos))
return
}
z.c(pos + 1)
if pos > 0 {
z.b(pos - 1)
} else {
z.inc()
}
}
fn (mut z Zeckendorf) inc() {
z.d_val++
z.a(0)
}
fn (mut z1 Zeckendorf) plus_assign(z2 Zeckendorf) {
for gn := 0; gn < (z2.d_len+1)*2; gn++ {
if ((z2.d_val >> u32(gn)) & 1) == 1 {
z1.b(gn)
}
}
}
fn (mut z1 Zeckendorf) minus_assign(z2 Zeckendorf) {
for gn := 0; gn < (z2.d_len+1)*2; gn++ {
if ((z2.d_val >> u32(gn)) & 1) == 1 {
z1.c(gn)
}
}
for z1.d_len > 0 && ((z1.d_val>>u32(z1.d_len*2))&3) == 0 {
z1.d_len--
}
}
fn (mut z1 Zeckendorf) times_assign(z2 Zeckendorf) {
mut na := z2.copy()
mut nb := z2.copy()
mut nr := Zeckendorf{}
for i := 0; i <= (z1.d_len+1)*2; i++ {
if ((z1.d_val >> u32(i)) & 1) > 0 {
nr.plus_assign(nb)
}
nt := nb.copy()
nb.plus_assign(na)
na = nt.copy()
}
z1.d_val = nr.d_val
z1.d_len = nr.d_len
}
fn (z Zeckendorf) copy() Zeckendorf {
return Zeckendorf{z.d_val, z.d_len}
}
fn (z1 Zeckendorf) compare(z2 Zeckendorf) int {
if z1.d_val < z2.d_val {
return -1
} else if z1.d_val > z2.d_val {
return 1
} else {
return 0
}
}
fn (z Zeckendorf) str() string {
if z.d_val == 0 {
return "0"
}
mut sb := strings.new_builder(128)
sb.write_string(dig1[(z.d_val>>u32(z.d_len*2))&3])
for i := z.d_len - 1; i >= 0; i-- {
sb.write_string(dig[(z.d_val>>u32(i*2))&3])
}
return sb.str()
}
fn main() {
println("Addition:")
mut g := new_zeck("10")
g.plus_assign(new_zeck("10"))
println(g)
g.plus_assign(new_zeck("10"))
println(g)
g.plus_assign(new_zeck("1001"))
println(g)
g.plus_assign(new_zeck("1000"))
println(g)
g.plus_assign(new_zeck("10101"))
println(g)
println("\nSubtraction:")
g = new_zeck("1000")
g.minus_assign(new_zeck("101"))
println(g)
g = new_zeck("10101010")
g.minus_assign(new_zeck("1010101"))
println(g)
println("\nMultiplication:")
g = new_zeck("1001")
g.times_assign(new_zeck("101"))
println(g)
g = new_zeck("101010")
g.plus_assign(new_zeck("101"))
println(g)
} |
http://rosettacode.org/wiki/Zeckendorf_arithmetic | Zeckendorf arithmetic | This task is a total immersion zeckendorf task; using decimal numbers will attract serious disapprobation.
The task is to implement addition, subtraction, multiplication, and division using Zeckendorf number representation. Optionally provide decrement, increment and comparitive operation functions.
Addition
Like binary 1 + 1 = 10, note carry 1 left. There the similarity ends. 10 + 10 = 101, note carry 1 left and 1 right. 100 + 100 = 1001, note carry 1 left and 2 right, this is the general case.
Occurrences of 11 must be changed to 100. Occurrences of 111 may be changed from the right by replacing 11 with 100, or from the left converting 111 to 100 + 100;
Subtraction
10 - 1 = 1. The general rule is borrow 1 right carry 1 left. eg:
abcde
10100 -
1000
_____
100 borrow 1 from a leaves 100
+ 100 add the carry
_____
1001
A larger example:
abcdef
100100 -
1000
______
1*0100 borrow 1 from b
+ 100 add the carry
______
1*1001
Sadly we borrowed 1 from b which didn't have it to lend. So now b borrows from a:
1001
+ 1000 add the carry
____
10100
Multiplication
Here you teach your computer its zeckendorf tables. eg. 101 * 1001:
a = 1 * 101 = 101
b = 10 * 101 = a + a = 10000
c = 100 * 101 = b + a = 10101
d = 1000 * 101 = c + b = 101010
1001 = d + a therefore 101 * 1001 =
101010
+ 101
______
1000100
Division
Lets try 1000101 divided by 101, so we can use the same table used for multiplication.
1000101 -
101010 subtract d (1000 * 101)
_______
1000 -
101 b and c are too large to subtract, so subtract a
____
1 so 1000101 divided by 101 is d + a (1001) remainder 1
Efficient algorithms for Zeckendorf arithmetic is interesting. The sections on addition and subtraction are particularly relevant for this task.
| #Wren | Wren | import "/trait" for Comparable
class Zeckendorf is Comparable {
static dig { ["00", "01", "10"] }
static dig1 { ["", "1", "10"] }
construct new(x) {
var q = 1
var i = x.count - 1
_dLen = (i / 2).floor
_dVal = 0
while (i >= 0) {
_dVal = _dVal + (x[i].bytes[0] - 48) * q
q = q * 2
i = i - 1
}
}
dLen { _dLen }
dVal { _dVal }
dLen=(v) { _dLen = v }
dVal=(v) { _dVal = v }
a(n) {
var i = n
while (true) {
if (_dLen < i) _dLen = i
var j = (_dVal >> (i * 2)) & 3
if (j == 0 || j == 1) return
if (j == 2) {
if (((_dVal >> ((i + 1) * 2)) & 1) != 1) return
_dVal = _dVal + (1 << (i * 2 + 1))
return
}
if (j == 3) {
_dVal = _dVal & ~(3 << (i * 2))
b((i + 1) * 2)
}
i = i + 1
}
}
b(pos) {
if (pos == 0) {
var thiz = this
thiz.inc
return
}
if (((_dVal >> pos) & 1) == 0) {
_dVal = _dVal + (1 << pos)
a((pos / 2).floor)
if (pos > 1) a((pos / 2).floor - 1)
} else {
_dVal = _dVal & ~(1 << pos)
b(pos + 1)
b(pos - ((pos > 1) ? 2 : 1))
}
}
c(pos) {
if (((_dVal >> pos) & 1) == 1) {
_dVal = _dVal & ~(1 << pos)
return
}
c(pos + 1)
if (pos > 0) {
b(pos - 1)
} else {
var thiz = this
thiz.inc
}
}
inc {
_dVal = _dVal + 1
a(0)
return this
}
plusAssign(other) {
for (gn in 0...(other.dLen + 1) * 2) {
if (((other.dVal >> gn) & 1) == 1) b(gn)
}
}
minusAssign(other) {
for (gn in 0...(other.dLen + 1) * 2) {
if (((other.dVal >> gn) & 1) == 1) c(gn)
}
while ((((_dVal >> _dLen * 2) & 3) == 0) || (_dLen == 0)) _dLen = _dLen - 1
}
timesAssign(other) {
var na = other.copy()
var nb = other.copy()
var nr = Zeckendorf.new("0")
for (i in 0..(_dLen + 1) * 2) {
if (((_dVal >> i) & 1) > 0) nr.plusAssign(nb)
var nt = nb.copy()
nb.plusAssign(na)
na = nt.copy()
}
_dVal = nr.dVal
_dLen = nr.dLen
}
compare(other) { (_dVal - other.dVal).sign }
toString {
if (_dVal == 0) return "0"
var sb = Zeckendorf.dig1[(_dVal >> (_dLen * 2)) & 3]
if (_dLen > 0) {
for (i in _dLen - 1..0) {
sb = sb + Zeckendorf.dig[(_dVal >> (i * 2)) & 3]
}
}
return sb
}
copy() {
var z = Zeckendorf.new("0")
z.dVal = _dVal
z.dLen = _dLen
return z
}
}
var Z = Zeckendorf // type alias
System.print("Addition:")
var g = Z.new("10")
g.plusAssign(Z.new("10"))
System.print(g)
g.plusAssign(Z.new("10"))
System.print(g)
g.plusAssign(Z.new("1001"))
System.print(g)
g.plusAssign(Z.new("1000"))
System.print(g)
g.plusAssign(Z.new("10101"))
System.print(g)
System.print("\nSubtraction:")
g = Z.new("1000")
g.minusAssign(Z.new("101"))
System.print(g)
g = Z.new("10101010")
g.minusAssign(Z.new("1010101"))
System.print(g)
System.print("\nMultiplication:")
g = Z.new("1001")
g.timesAssign(Z.new("101"))
System.print(g)
g = Z.new("101010")
g.plusAssign(Z.new("101"))
System.print(g) |
http://rosettacode.org/wiki/Zumkeller_numbers | Zumkeller numbers | Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that the two partition sums are equal.
E.G.
6 is a Zumkeller number; The divisors {1 2 3 6} can be partitioned into two groups {1 2 3} and {6} that both sum to 6.
10 is not a Zumkeller number; The divisors {1 2 5 10} can not be partitioned into two groups in any way that will both sum to the same value.
12 is a Zumkeller number; The divisors {1 2 3 4 6 12} can be partitioned into two groups {1 3 4 6} and {2 12} that both sum to 14.
Even Zumkeller numbers are common; odd Zumkeller numbers are much less so. For values below 10^6, there is at least one Zumkeller number in every 12 consecutive integers, and the vast majority of them are even. The odd Zumkeller numbers are very similar to the list from the task Abundant odd numbers; they are nearly the same except for the further restriction that the abundance (A(n) = sigma(n) - 2n), must be even: A(n) mod 2 == 0
Task
Write a routine (function, procedure, whatever) to find Zumkeller numbers.
Use the routine to find and display here, on this page, the first 220 Zumkeller numbers.
Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers.
Optional, stretch goal: Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers that don't end with 5.
See Also
OEIS:A083207 - Zumkeller numbers to get an impression of different partitions OEIS:A083206 Zumkeller partitions
OEIS:A174865 - Odd Zumkeller numbers
Related Tasks
Abundant odd numbers
Abundant, deficient and perfect number classifications
Proper divisors , Factors of an integer | #Ring | Ring |
load "stdlib.ring"
see "working..." + nl
see "The first 220 Zumkeller numbers are:" + nl
permut = []
zumind = []
zumodd = []
limit = 19305
num1 = 0
num2 = 0
for n = 2 to limit
zumkeller = []
zumList = []
permut = []
calmo = []
zumind = []
num = 0
nold = 0
for m = 1 to n
if n % m = 0
num = num + 1
add(zumind,m)
ok
next
for p = 1 to num
add(zumList,1)
add(zumList,2)
next
permut(zumList)
lenZum = len(zumList)
for n2 = 1 to len(permut)/lenZum
str = ""
for m = (n2-1)*lenZum+1 to n2*lenZum
str = str + string(permut[m])
next
if str != ""
strNum = number(str)
add(calmo,strNum)
ok
next
calmo = sort(calmo)
for x = len(calmo) to 2 step -1
if calmo[x] = calmo[x-1]
del(calmo,x)
ok
next
zumkeller = []
calmoLen = len(string(calmo[1]))
calmoLen2 = calmoLen/2
for y = 1 to len(calmo)
tmpStr = string(calmo[y])
tmp1 = left(tmpStr,calmoLen2)
tmp2 = number(tmp1)
add(zumkeller,tmp2)
next
zumkeller = sort(zumkeller)
for x = len(zumkeller) to 2 step -1
if zumkeller[x] = zumkeller[x-1]
del(zumkeller,x)
ok
next
for z = 1 to len(zumkeller)
zumsum1 = 0
zumsum2 = 0
zum1 = []
zum2 = []
for m = 1 to len(string(zumkeller[z]))
zumstr = string(zumkeller[z])
tmp = number(zumstr[m])
if tmp = 1
add(zum1,zumind[m])
else
add(zum2,zumind[m])
ok
next
for z1 = 1 to len(zum1)
zumsum1 = zumsum1 + zum1[z1]
next
for z2 = 1 to len(zum2)
zumsum2 = zumsum2 + zum2[z2]
next
if zumsum1 = zumsum2
num1 = num1 + 1
if n != nold
if num1 < 221
if (n-1)%22 = 0
see nl + " " + n
else
see " " + n
ok
ok
if zumsum1%2 = 1
num2 = num2 + 1
if num2 < 41
add(zumodd,n)
ok
ok
ok
nold = n
ok
next
next
see "The first 40 odd Zumkeller numbers are:" + nl
for n = 1 to len(zumodd)
if (n-1)%8 = 0
see nl + " " + zumodd[n]
else
see " " + zumodd[n]
ok
next
see nl + "done..." + nl
func permut(list)
for perm = 1 to factorial(len(list))
for i = 1 to len(list)
add(permut,list[i])
next
perm(list)
next
func perm(a)
elementcount = len(a)
if elementcount < 1
return
ok
pos = elementcount-1
while a[pos] >= a[pos+1]
pos -= 1
if pos <= 0 permutationReverse(a, 1, elementcount)
return
ok
end
last = elementcount
while a[last] <= a[pos]
last -= 1
end
temp = a[pos]
a[pos] = a[last]
a[last] = temp
permReverse(a, pos+1, elementcount)
func permReverse(a,first,last)
while first < last
temp = a[first]
a[first] = a[last]
a[last] = temp
first += 1
last -= 1
end
|
http://rosettacode.org/wiki/Zumkeller_numbers | Zumkeller numbers | Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that the two partition sums are equal.
E.G.
6 is a Zumkeller number; The divisors {1 2 3 6} can be partitioned into two groups {1 2 3} and {6} that both sum to 6.
10 is not a Zumkeller number; The divisors {1 2 5 10} can not be partitioned into two groups in any way that will both sum to the same value.
12 is a Zumkeller number; The divisors {1 2 3 4 6 12} can be partitioned into two groups {1 3 4 6} and {2 12} that both sum to 14.
Even Zumkeller numbers are common; odd Zumkeller numbers are much less so. For values below 10^6, there is at least one Zumkeller number in every 12 consecutive integers, and the vast majority of them are even. The odd Zumkeller numbers are very similar to the list from the task Abundant odd numbers; they are nearly the same except for the further restriction that the abundance (A(n) = sigma(n) - 2n), must be even: A(n) mod 2 == 0
Task
Write a routine (function, procedure, whatever) to find Zumkeller numbers.
Use the routine to find and display here, on this page, the first 220 Zumkeller numbers.
Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers.
Optional, stretch goal: Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers that don't end with 5.
See Also
OEIS:A083207 - Zumkeller numbers to get an impression of different partitions OEIS:A083206 Zumkeller partitions
OEIS:A174865 - Odd Zumkeller numbers
Related Tasks
Abundant odd numbers
Abundant, deficient and perfect number classifications
Proper divisors , Factors of an integer | #Ruby | Ruby | class Integer
def divisors
res = [1, self]
(2..Integer.sqrt(self)).each do |n|
div, mod = divmod(n)
res << n << div if mod.zero?
end
res.uniq.sort
end
def zumkeller?
divs = divisors
sum = divs.sum
return false unless sum.even? && sum >= self*2
half = sum / 2
max_combi_size = divs.size / 2
1.upto(max_combi_size).any? do |combi_size|
divs.combination(combi_size).any?{|combi| combi.sum == half}
end
end
end
def p_enum(enum, cols = 10, col_width = 8)
enum.each_slice(cols) {|slice| puts "%#{col_width}d"*slice.size % slice}
end
puts "#{n=220} Zumkeller numbers:"
p_enum 1.step.lazy.select(&:zumkeller?).take(n), 14, 6
puts "\n#{n=40} odd Zumkeller numbers:"
p_enum 1.step(by: 2).lazy.select(&:zumkeller?).take(n)
puts "\n#{n=40} odd Zumkeller numbers not ending with 5:"
p_enum 1.step(by: 2).lazy.select{|x| x % 5 > 0 && x.zumkeller?}.take(n)
|
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included) | Arbitrary-precision integers (included) | Using the in-built capabilities of your language, calculate the integer value of:
5
4
3
2
{\displaystyle 5^{4^{3^{2}}}}
Confirm that the first and last twenty digits of the answer are:
62060698786608744707...92256259918212890625
Find and show the number of decimal digits in the answer.
Note: Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead.
Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value.
Related tasks
Long multiplication
Exponentiation order
exponentiation operator
Exponentiation with infix operators in (or operating on) the base
| #Frink | Frink | a = 5^4^3^2
as = "$a" // Coerce to string
println["Length=" + length[as] + ", " + left[as,20] + "..." + right[as,20]] |
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included) | Arbitrary-precision integers (included) | Using the in-built capabilities of your language, calculate the integer value of:
5
4
3
2
{\displaystyle 5^{4^{3^{2}}}}
Confirm that the first and last twenty digits of the answer are:
62060698786608744707...92256259918212890625
Find and show the number of decimal digits in the answer.
Note: Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead.
Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value.
Related tasks
Long multiplication
Exponentiation order
exponentiation operator
Exponentiation with infix operators in (or operating on) the base
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | n:=5^(4^(3^2));;
s := String(n);;
m := Length(s);
# 183231
s{[1..20]};
# "62060698786608744707"
s{[m-19..m]};
# "92256259918212890625" |
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included) | Arbitrary-precision integers (included) | Using the in-built capabilities of your language, calculate the integer value of:
5
4
3
2
{\displaystyle 5^{4^{3^{2}}}}
Confirm that the first and last twenty digits of the answer are:
62060698786608744707...92256259918212890625
Find and show the number of decimal digits in the answer.
Note: Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead.
Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value.
Related tasks
Long multiplication
Exponentiation order
exponentiation operator
Exponentiation with infix operators in (or operating on) the base
| #GAP | GAP | n:=5^(4^(3^2));;
s := String(n);;
m := Length(s);
# 183231
s{[1..20]};
# "62060698786608744707"
s{[m-19..m]};
# "92256259918212890625" |
http://rosettacode.org/wiki/Zhang-Suen_thinning_algorithm | Zhang-Suen thinning algorithm | This is an algorithm used to thin a black and white i.e. one bit per pixel images.
For example, with an input image of:
################# #############
################## ################
################### ##################
######## ####### ###################
###### ####### ####### ######
###### ####### #######
################# #######
################ #######
################# #######
###### ####### #######
###### ####### #######
###### ####### ####### ######
######## ####### ###################
######## ####### ###### ################## ######
######## ####### ###### ################ ######
######## ####### ###### ############# ######
It produces the thinned output:
# ########## #######
## # #### #
# # ##
# # #
# # #
# # #
############ #
# # #
# # #
# # #
# # #
# ##
# ############
### ###
Algorithm
Assume black pixels are one and white pixels zero, and that the input image is a rectangular N by M array of ones and zeroes.
The algorithm operates on all black pixels P1 that can have eight neighbours.
The neighbours are, in order, arranged as:
P9 P2 P3
P8 P1 P4
P7 P6 P5
Obviously the boundary pixels of the image cannot have the full eight neighbours.
Define
A
(
P
1
)
{\displaystyle A(P1)}
= the number of transitions from white to black, (0 -> 1) in the sequence P2,P3,P4,P5,P6,P7,P8,P9,P2. (Note the extra P2 at the end - it is circular).
Define
B
(
P
1
)
{\displaystyle B(P1)}
= The number of black pixel neighbours of P1. ( = sum(P2 .. P9) )
Step 1
All pixels are tested and pixels satisfying all the following conditions (simultaneously) are just noted at this stage.
(0) The pixel is black and has eight neighbours
(1)
2
<=
B
(
P
1
)
<=
6
{\displaystyle 2<=B(P1)<=6}
(2) A(P1) = 1
(3) At least one of P2 and P4 and P6 is white
(4) At least one of P4 and P6 and P8 is white
After iterating over the image and collecting all the pixels satisfying all step 1 conditions, all these condition satisfying pixels are set to white.
Step 2
All pixels are again tested and pixels satisfying all the following conditions are just noted at this stage.
(0) The pixel is black and has eight neighbours
(1)
2
<=
B
(
P
1
)
<=
6
{\displaystyle 2<=B(P1)<=6}
(2) A(P1) = 1
(3) At least one of P2 and P4 and P8 is white
(4) At least one of P2 and P6 and P8 is white
After iterating over the image and collecting all the pixels satisfying all step 2 conditions, all these condition satisfying pixels are again set to white.
Iteration
If any pixels were set in this round of either step 1 or step 2 then all steps are repeated until no image pixels are so changed.
Task
Write a routine to perform Zhang-Suen thinning on an image matrix of ones and zeroes.
Use the routine to thin the following image and show the output here on this page as either a matrix of ones and zeroes, an image, or an ASCII-art image of space/non-space characters.
00000000000000000000000000000000
01111111110000000111111110000000
01110001111000001111001111000000
01110000111000001110000111000000
01110001111000001110000000000000
01111111110000001110000000000000
01110111100000001110000111000000
01110011110011101111001111011100
01110001111011100111111110011100
00000000000000000000000000000000
Reference
Zhang-Suen Thinning Algorithm, Java Implementation by Nayef Reza.
"Character Recognition Systems: A Guide for Students and Practitioners" By Mohamed Cheriet, Nawwaf Kharma, Cheng-Lin Liu, Ching Suen
| #Ruby | Ruby | class ZhangSuen
NEIGHBOUR8 = [[-1,0],[-1,1],[0,1],[1,1],[1,0],[1,-1],[0,-1],[-1,-1]] # 8 neighbors
CIRCULARS = NEIGHBOUR8 + [NEIGHBOUR8.first] # P2, ... P9, P2
def initialize(str, black="#")
s1 = str.each_line.map{|line| line.chomp.each_char.map{|c| c==black ? 1 : 0}}
s2 = s1.map{|line| line.map{0}}
xrange = 1 ... s1.size-1
yrange = 1 ... s1[0].size-1
printout(s1)
begin
@r = 0
xrange.each{|x| yrange.each{|y| s2[x][y] = s1[x][y] - zs(s1,x,y,1)}} # Step 1
xrange.each{|x| yrange.each{|y| s1[x][y] = s2[x][y] - zs(s2,x,y,0)}} # Step 2
end until @r == 0
printout(s1)
end
def zs(ng,x,y,g)
return 0 if ng[x][y] == 0 or # P1
(ng[x-1][y] + ng[x][y+1] + ng[x+g][y-1+g]) == 3 or # P2, P4, P6/P8
(ng[x-1+g][y+g] + ng[x+1][y] + ng[x][y-1]) == 3 # P4/P2, P6, P8
bp1 = NEIGHBOUR8.inject(0){|res,(i,j)| res += ng[x+i][y+j]} # B(P1)
return 0 if bp1 < 2 or 6 < bp1
ap1 = CIRCULARS.map{|i,j| ng[x+i][y+j]}.each_cons(2).count{|a,b| a<b} # A(P1)
return 0 if ap1 != 1
@r = 1
end
def printout(image)
puts image.map{|row| row.map{|col| " #"[col]}.join}
end
end
str = <<EOS
...........................................................
.#################...................#############.........
.##################...............################.........
.###################............##################.........
.########.....#######..........###################.........
...######.....#######.........#######.......######.........
...######.....#######........#######.......................
...#################.........#######.......................
...################..........#######.......................
...#################.........#######.......................
...######.....#######........#######.......................
...######.....#######........#######.......................
...######.....#######.........#######.......######.........
.########.....#######..........###################.........
.########.....#######.######....##################.######..
.########.....#######.######......################.######..
.########.....#######.######.........#############.######..
...........................................................
EOS
ZhangSuen.new(str)
task_example = <<EOS
00000000000000000000000000000000
01111111110000000111111110000000
01110001111000001111001111000000
01110000111000001110000111000000
01110001111000001110000000000000
01111111110000001110000000000000
01110111100000001110000111000000
01110011110011101111001111011100
01110001111011100111111110011100
00000000000000000000000000000000
EOS
ZhangSuen.new(task_example, "1") |
http://rosettacode.org/wiki/Zeckendorf_number_representation | Zeckendorf number representation | Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series.
Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13.
The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100.
10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that no two consecutive Fibonacci numbers can be used which leads to the former unique solution.
Task
Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order.
The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task.
Also see
OEIS A014417 for the the sequence of required results.
Brown's Criterion - Numberphile
Related task
Fibonacci sequence
| #Java | Java | import java.util.*;
class Zeckendorf
{
public static String getZeckendorf(int n)
{
if (n == 0)
return "0";
List<Integer> fibNumbers = new ArrayList<Integer>();
fibNumbers.add(1);
int nextFib = 2;
while (nextFib <= n)
{
fibNumbers.add(nextFib);
nextFib += fibNumbers.get(fibNumbers.size() - 2);
}
StringBuilder sb = new StringBuilder();
for (int i = fibNumbers.size() - 1; i >= 0; i--)
{
int fibNumber = fibNumbers.get(i);
sb.append((fibNumber <= n) ? "1" : "0");
if (fibNumber <= n)
n -= fibNumber;
}
return sb.toString();
}
public static void main(String[] args)
{
for (int i = 0; i <= 20; i++)
System.out.println("Z(" + i + ")=" + getZeckendorf(i));
}
} |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #CLIPS | CLIPS | (deffacts initial-state
(door-count 100)
)
(deffunction toggle
(?state)
(switch ?state
(case "open" then "closed")
(case "closed" then "open")
)
)
(defrule create-doors-and-visits
(door-count ?count)
=>
(loop-for-count (?num 1 ?count) do
(assert (door ?num "closed"))
(assert (visit-from ?num ?num))
)
(assert (doors initialized))
)
(defrule visit
(door-count ?max)
?visit <- (visit-from ?num ?step)
?door <- (door ?num ?state)
=>
(retract ?visit)
(retract ?door)
(assert (door ?num (toggle ?state)))
(if
(<= (+ ?num ?step) ?max)
then
(assert (visit-from (+ ?num ?step) ?step))
)
)
(defrule start-printing
(doors initialized)
(not (visit-from ? ?))
=>
(printout t "These doors are open:" crlf)
(assert (print-from 1))
)
(defrule print-door
(door-count ?max)
?pf <- (print-from ?num)
(door ?num ?state)
=>
(retract ?pf)
(if
(= 0 (str-compare "open" ?state))
then
(printout t ?num " ")
)
(if
(< ?num ?max)
then
(assert (print-from (+ ?num 1)))
else
(printout t crlf "All other doors are closed." crlf)
)
) |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #Forth | Forth | create MyArray 1 , 2 , 3 , 4 , 5 , 5 cells allot
here constant MyArrayEnd
30 MyArray 7 cells + !
MyArray 7 cells + @ . \ 30
: .array MyArrayEnd MyArray do I @ . cell +loop ; |
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part", where the imaginary part is the number to be multiplied by
i
{\displaystyle i}
.
Task
Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.)
Print the results for each operation tested.
Optional: Show complex conjugation.
By definition, the complex conjugate of
a
+
b
i
{\displaystyle a+bi}
is
a
−
b
i
{\displaystyle a-bi}
Some languages have complex number libraries available. If your language does, show the operations. If your language does not, also show the definition of this type.
| #REXX | REXX | /*REXX program demonstrates how to support some math functions for complex numbers. */
x = '(5,3i)' /*define X ─── can use I i J or j */
y = "( .5, 6j)" /*define Y " " " " " " " */
say ' addition: ' x " + " y ' = ' Cadd(x, y)
say ' subtraction: ' x " - " y ' = ' Csub(x, y)
say 'multiplication: ' x " * " y ' = ' Cmul(x, y)
say ' division: ' x " ÷ " y ' = ' Cdiv(x, y)
say ' inverse: ' x " = " Cinv(x, y)
say ' conjugate of: ' x " = " Conj(x, y)
say ' negation of: ' x " = " Cneg(x, y)
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
Conj: procedure; parse arg a ',' b,c ',' d; call C#; return C$( a , -b )
Cadd: procedure; parse arg a ',' b,c ',' d; call C#; return C$( a+c , b+d )
Csub: procedure; parse arg a ',' b,c ',' d; call C#; return C$( a-c , b-d )
Cmul: procedure; parse arg a ',' b,c ',' d; call C#; return C$( ac-bd , bc+ad)
Cdiv: procedure; parse arg a ',' b,c ',' d; call C#; return C$((ac+bd)/s, (bc-ad)/s)
Cinv: return Cdiv(1, arg(1))
Cneg: return Cmul(arg(1), -1)
C_: return word(translate(arg(1), , '{[(JjIi)]}') 0, 1) /*get # or 0*/
C#: a=C_(a); b=C_(b); c=C_(c); d=C_(d); ac=a*c; ad=a*d; bc=b*c; bd=b*d;s=c*c+d*d; return
C$: parse arg r,c; _='['r; if c\=0 then _=_","c'j'; return _"]" /*uses j */ |
http://rosettacode.org/wiki/Arithmetic/Rational | Arithmetic/Rational | Task
Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language.
Example
Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number).
Further define the appropriate rational unary operators abs and '-', with the binary operators for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠').
Define standard coercion operators for casting int to frac etc.
If space allows, define standard increment and decrement operators (e.g. '+:=' & '-:=' etc.).
Finally test the operators:
Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors.
Related task
Perfect Numbers
| #Slate | Slate | 54 / 7.
20 reciprocal.
(5 / 6) reciprocal.
(5 / 6) as: Float. |
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, you may also try something like:
x = 0
y = 0
z = x**y
say 'z=' z
Show the result here.
And of course use any symbols or notation that is supported in your computer programming language for exponentiation.
See also
The Wiki entry: Zero to the power of zero.
The Wiki entry: History of differing points of view.
The MathWorld™ entry: exponent laws.
Also, in the above MathWorld™ entry, see formula (9):
x
0
=
1
{\displaystyle x^{0}=1}
.
The OEIS entry: The special case of zero to the zeroth power
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | 0^0 |
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, you may also try something like:
x = 0
y = 0
z = x**y
say 'z=' z
Show the result here.
And of course use any symbols or notation that is supported in your computer programming language for exponentiation.
See also
The Wiki entry: Zero to the power of zero.
The Wiki entry: History of differing points of view.
The MathWorld™ entry: exponent laws.
Also, in the above MathWorld™ entry, see formula (9):
x
0
=
1
{\displaystyle x^{0}=1}
.
The OEIS entry: The special case of zero to the zeroth power
| #MATLAB_.2F_Octave | MATLAB / Octave | 0^0
complex(0,0)^0 |
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, you may also try something like:
x = 0
y = 0
z = x**y
say 'z=' z
Show the result here.
And of course use any symbols or notation that is supported in your computer programming language for exponentiation.
See also
The Wiki entry: Zero to the power of zero.
The Wiki entry: History of differing points of view.
The MathWorld™ entry: exponent laws.
Also, in the above MathWorld™ entry, see formula (9):
x
0
=
1
{\displaystyle x^{0}=1}
.
The OEIS entry: The special case of zero to the zeroth power
| #Maxima | Maxima | 0^0; |
http://rosettacode.org/wiki/Zebra_puzzle | Zebra puzzle | Zebra puzzle
You are encouraged to solve this task according to the task description, using any language you may know.
The Zebra puzzle, a.k.a. Einstein's Riddle,
is a logic puzzle which is to be solved programmatically.
It has several variants, one of them this:
There are five houses.
The English man lives in the red house.
The Swede has a dog.
The Dane drinks tea.
The green house is immediately to the left of the white house.
They drink coffee in the green house.
The man who smokes Pall Mall has birds.
In the yellow house they smoke Dunhill.
In the middle house they drink milk.
The Norwegian lives in the first house.
The man who smokes Blend lives in the house next to the house with cats.
In a house next to the house where they have a horse, they smoke Dunhill.
The man who smokes Blue Master drinks beer.
The German smokes Prince.
The Norwegian lives next to the blue house.
They drink water in a house next to the house where they smoke Blend.
The question is, who owns the zebra?
Additionally, list the solution for all the houses.
Optionally, show the solution is unique.
Related tasks
Dinesman's multiple-dwelling problem
Twelve statements
| #BBC_BASIC | BBC BASIC | REM The names (only used for printing the results):
DIM Drink$(4), Nation$(4), Colr$(4), Smoke$(4), Animal$(4)
Drink$() = "Beer", "Coffee", "Milk", "Tea", "Water"
Nation$() = "Denmark", "England", "Germany", "Norway", "Sweden"
Colr$() = "Blue", "Green", "Red", "White", "Yellow"
Smoke$() = "Blend", "BlueMaster", "Dunhill", "PallMall", "Prince"
Animal$() = "Birds", "Cats", "Dog", "Horse", "Zebra"
REM Some single-character tags:
a$ = "A" : b$ = "B" : c$ = "C" : d$ = "D" : e$ = "E"
REM BBC BASIC Doesn't have enumerations!
Beer$=a$ : Coffee$=b$ : Milk$=c$ : Tea$=d$ : Water$=e$
Denmark$=a$ : England$=b$ : Germany$=c$ : Norway$=d$ : Sweden$=e$
Blue$=a$ : Green$=b$ : Red$=c$ : White$=d$ : Yellow$=e$
Blend$=a$ : BlueMaster$=b$ : Dunhill$=c$ : PallMall$=d$ : Prince$=e$
Birds$=a$ : Cats$=b$ : Dog$=c$ : Horse$=d$ : Zebra$=e$
REM Create the 120 permutations of 5 objects:
DIM perm$(120), x$(4) : x$() = a$, b$, c$, d$, e$
REPEAT
p% += 1
perm$(p%) = x$(0)+x$(1)+x$(2)+x$(3)+x$(4)
UNTIL NOT FNperm(x$())
REM Express the statements as conditional expressions:
ex2$ = "INSTR(Nation$,England$) = INSTR(Colr$,Red$)"
ex3$ = "INSTR(Nation$,Sweden$) = INSTR(Animal$,Dog$)"
ex4$ = "INSTR(Nation$,Denmark$) = INSTR(Drink$,Tea$)"
ex5$ = "INSTR(Colr$,Green$+White$) <> 0"
ex6$ = "INSTR(Drink$,Coffee$) = INSTR(Colr$,Green$)"
ex7$ = "INSTR(Smoke$,PallMall$) = INSTR(Animal$,Birds$)"
ex8$ = "INSTR(Smoke$,Dunhill$) = INSTR(Colr$,Yellow$)"
ex9$ = "MID$(Drink$,3,1) = Milk$"
ex10$ = "LEFT$(Nation$,1) = Norway$"
ex11$ = "ABS(INSTR(Smoke$,Blend$)-INSTR(Animal$,Cats$)) = 1"
ex12$ = "ABS(INSTR(Smoke$,Dunhill$)-INSTR(Animal$,Horse$)) = 1"
ex13$ = "INSTR(Smoke$,BlueMaster$) = INSTR(Drink$,Beer$)"
ex14$ = "INSTR(Nation$,Germany$) = INSTR(Smoke$,Prince$)"
ex15$ = "ABS(INSTR(Nation$,Norway$)-INSTR(Colr$,Blue$)) = 1"
ex16$ = "ABS(INSTR(Smoke$,Blend$)-INSTR(Drink$,Water$)) = 1"
REM Solve:
solutions% = 0
TIME = 0
FOR nation% = 1 TO 120
Nation$ = perm$(nation%)
IF EVAL(ex10$) THEN
FOR colr% = 1 TO 120
Colr$ = perm$(colr%)
IF EVAL(ex5$) IF EVAL(ex2$) IF EVAL(ex15$) THEN
FOR drink% = 1 TO 120
Drink$ = perm$(drink%)
IF EVAL(ex9$) IF EVAL(ex4$) IF EVAL(ex6$) THEN
FOR smoke% = 1 TO 120
Smoke$ = perm$(smoke%)
IF EVAL(ex14$) IF EVAL(ex13$) IF EVAL(ex16$) IF EVAL(ex8$) THEN
FOR animal% = 1 TO 120
Animal$ = perm$(animal%)
IF EVAL(ex3$) IF EVAL(ex7$) IF EVAL(ex11$) IF EVAL(ex12$) THEN
PRINT "House Drink Nation Colour Smoke Animal"
FOR house% = 1 TO 5
PRINT ; house% ,;
PRINT Drink$(ASCMID$(Drink$,house%)-65),;
PRINT Nation$(ASCMID$(Nation$,house%)-65),;
PRINT Colr$(ASCMID$(Colr$,house%)-65),;
PRINT Smoke$(ASCMID$(Smoke$,house%)-65),;
PRINT Animal$(ASCMID$(Animal$,house%)-65)
NEXT
solutions% += 1
ENDIF
NEXT animal%
ENDIF
NEXT smoke%
ENDIF
NEXT drink%
ENDIF
NEXT colr%
ENDIF
NEXT nation%
PRINT '"Number of solutions = "; solutions%
PRINT "Solved in " ; TIME/100 " seconds"
END
DEF FNperm(x$())
LOCAL i%, j%
FOR i% = DIM(x$(),1)-1 TO 0 STEP -1
IF x$(i%) < x$(i%+1) EXIT FOR
NEXT
IF i% < 0 THEN = FALSE
j% = DIM(x$(),1)
WHILE x$(j%) <= x$(i%) j% -= 1 : ENDWHILE
SWAP x$(i%), x$(j%)
i% += 1
j% = DIM(x$(),1)
WHILE i% < j%
SWAP x$(i%), x$(j%)
i% += 1
j% -= 1
ENDWHILE
= TRUE |
http://rosettacode.org/wiki/XML/XPath | XML/XPath | Perform the following three XPath queries on the XML Document below:
//item[1]: Retrieve the first "item" element
//price/text(): Perform an action on each "price" element (print it out)
//name: Get an array of all the "name" elements
XML Document:
<inventory title="OmniCorp Store #45x10^3">
<section name="health">
<item upc="123456789" stock="12">
<name>Invisibility Cream</name>
<price>14.50</price>
<description>Makes you invisible</description>
</item>
<item upc="445322344" stock="18">
<name>Levitation Salve</name>
<price>23.99</price>
<description>Levitate yourself for up to 3 hours per application</description>
</item>
</section>
<section name="food">
<item upc="485672034" stock="653">
<name>Blork and Freen Instameal</name>
<price>4.95</price>
<description>A tasty meal in a tablet; just add water</description>
</item>
<item upc="132957764" stock="44">
<name>Grob winglets</name>
<price>3.56</price>
<description>Tender winglets of Grob. Just add water</description>
</item>
</section>
</inventory>
| #AutoHotkey | AutoHotkey | FileRead, inventory, xmlfile.xml
RegExMatch(inventory, "<item.*?</item>", item1)
MsgBox % item1
pos = 1
While, pos := RegExMatch(inventory, "<price>(.*?)</price>", price, pos + 1)
MsgBox % price1
While, pos := RegExMatch(inventory, "<name>.*?</name>", name, pos + 1)
names .= name . "`n"
MsgBox % names |
http://rosettacode.org/wiki/XML/XPath | XML/XPath | Perform the following three XPath queries on the XML Document below:
//item[1]: Retrieve the first "item" element
//price/text(): Perform an action on each "price" element (print it out)
//name: Get an array of all the "name" elements
XML Document:
<inventory title="OmniCorp Store #45x10^3">
<section name="health">
<item upc="123456789" stock="12">
<name>Invisibility Cream</name>
<price>14.50</price>
<description>Makes you invisible</description>
</item>
<item upc="445322344" stock="18">
<name>Levitation Salve</name>
<price>23.99</price>
<description>Levitate yourself for up to 3 hours per application</description>
</item>
</section>
<section name="food">
<item upc="485672034" stock="653">
<name>Blork and Freen Instameal</name>
<price>4.95</price>
<description>A tasty meal in a tablet; just add water</description>
</item>
<item upc="132957764" stock="44">
<name>Grob winglets</name>
<price>3.56</price>
<description>Tender winglets of Grob. Just add water</description>
</item>
</section>
</inventory>
| #Bracmat | Bracmat | {Retrieve the first "item" element}
( nestML$(get$("doc.xml",X,ML))
: ?
( inventory
. ?,? (section.?,? ((item.?):?item) ?) ?
)
?
& out$(toML$!item)
)
{Perform an action on each "price" element (print it out)}
( nestML$(get$("doc.xml",X,ML))
: ?
( inventory
. ?
, ?
( section
. ?
, ?
( item
. ?
, ?
( price
. ?
, ?price
& out$!price
& ~
)
?
)
?
)
?
)
?
|
)
{Get an array of all the "name" elements}
( :?anArray
& nestML$(get$("doc.xml",X,ML))
: ?
( inventory
. ?
, ?
( section
. ?
, ?
( item
. ?
, ?
( name
. ?
, ?name
& !anArray !name:?anArray
& ~
)
?
)
?
)
?
)
?
| out$!anArray {Not truly an array, but a list.}
); |
http://rosettacode.org/wiki/Yin_and_yang | Yin and yang | One well-known symbol of the philosophy of duality known as yin and yang is the taijitu.
Task
Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.
Generate and display the symbol for two different (small) sizes.
| #Asymptote | Asymptote | unitsize(1 inch);
fill(scale(6)*unitsquare, invisible);
picture yinyang(pair center, real radius) {
picture p;
fill(p, unitcircle, white);
fill(p, arc(0, S, N) -- cycle, black);
fill(p, circle(N/2, 1/2), white);
fill(p, circle(S/2, 1/2), black);
fill(p, circle(N/2, 1/5), black);
fill(p, circle(S/2, 1/5), white);
draw(p, unitcircle, linewidth((1/32) * inch) + gray(0.5));
return shift(center) * scale(radius) * p;
}
add(yinyang((1 + 1/4, 4 + 3/4), 1));
add(yinyang((3 + 3/4, 2 + 1/4), 2)); |
http://rosettacode.org/wiki/Y_combinator | Y combinator | In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions.
This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function.
The Y combinator is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function.
The Y combinator is the simplest of the class of such functions, called fixed-point combinators.
Task
Define the stateless Y combinator and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions.
Cf
Jim Weirich: Adventures in Functional Programming
| #BlitzMax | BlitzMax | SuperStrict
'Boxed type so we can just use object arrays for argument lists
Type Integer
Field val:Int
Function Make:Integer(_val:Int)
Local i:Integer = New Integer
i.val = _val
Return i
End Function
End Type
'Higher-order function type - just a procedure attached to a scope
Type Func Abstract
Method apply:Object(args:Object[]) Abstract
End Type
'Function definitions - extend with fields as locals and implement apply as body
Type Scope Extends Func Abstract
Field env:Scope
'Constructor - bind an environment to a procedure
Function lambda:Scope(env:Scope) Abstract
Method _init:Scope(_env:Scope) 'Helper to keep constructors small
env = _env ; Return Self
End Method
End Type
'Based on the following definition:
'(define (Y f)
' (let ((_r (lambda (r) (f (lambda a (apply (r r) a))))))
' (_r _r)))
'Y (outer)
Type Y Extends Scope
Field f:Func 'Parameter - gets closed over
Function lambda:Scope(env:Scope) 'Necessary due to highly limited constructor syntax
Return (New Y)._init(env)
End Function
Method apply:Func(args:Object[])
f = Func(args[0])
Local _r:Func = YInner1.lambda(Self)
Return Func(_r.apply([_r]))
End Method
End Type
'First lambda within Y
Type YInner1 Extends Scope
Field r:Func 'Parameter - gets closed over
Function lambda:Scope(env:Scope)
Return (New YInner1)._init(env)
End Function
Method apply:Func(args:Object[])
r = Func(args[0])
Return Func(Y(env).f.apply([YInner2.lambda(Self)]))
End Method
End Type
'Second lambda within Y
Type YInner2 Extends Scope
Field a:Object[] 'Parameter - not really needed, but good for clarity
Function lambda:Scope(env:Scope)
Return (New YInner2)._init(env)
End Function
Method apply:Object(args:Object[])
a = args
Local r:Func = YInner1(env).r
Return Func(r.apply([r])).apply(a)
End Method
End Type
'Based on the following definition:
'(define fac (Y (lambda (f)
' (lambda (x)
' (if (<= x 0) 1 (* x (f (- x 1)))))))
Type FacL1 Extends Scope
Field f:Func 'Parameter - gets closed over
Function lambda:Scope(env:Scope)
Return (New FacL1)._init(env)
End Function
Method apply:Object(args:Object[])
f = Func(args[0])
Return FacL2.lambda(Self)
End Method
End Type
Type FacL2 Extends Scope
Function lambda:Scope(env:Scope)
Return (New FacL2)._init(env)
End Function
Method apply:Object(args:Object[])
Local x:Int = Integer(args[0]).val
If x <= 0 Then Return Integer.Make(1) ; Else Return Integer.Make(x * Integer(FacL1(env).f.apply([Integer.Make(x - 1)])).val)
End Method
End Type
'Based on the following definition:
'(define fib (Y (lambda (f)
' (lambda (x)
' (if (< x 2) x (+ (f (- x 1)) (f (- x 2)))))))
Type FibL1 Extends Scope
Field f:Func 'Parameter - gets closed over
Function lambda:Scope(env:Scope)
Return (New FibL1)._init(env)
End Function
Method apply:Object(args:Object[])
f = Func(args[0])
Return FibL2.lambda(Self)
End Method
End Type
Type FibL2 Extends Scope
Function lambda:Scope(env:Scope)
Return (New FibL2)._init(env)
End Function
Method apply:Object(args:Object[])
Local x:Int = Integer(args[0]).val
If x < 2
Return Integer.Make(x)
Else
Local f:Func = FibL1(env).f
Local x1:Int = Integer(f.apply([Integer.Make(x - 1)])).val
Local x2:Int = Integer(f.apply([Integer.Make(x - 2)])).val
Return Integer.Make(x1 + x2)
EndIf
End Method
End Type
'Now test
Local _Y:Func = Y.lambda(Null)
Local fac:Func = Func(_Y.apply([FacL1.lambda(Null)]))
Print Integer(fac.apply([Integer.Make(10)])).val
Local fib:Func = Func(_Y.apply([FibL1.lambda(Null)]))
Print Integer(fib.apply([Integer.Make(10)])).val |
http://rosettacode.org/wiki/Zig-zag_matrix | Zig-zag matrix | Task
Produce a zig-zag array.
A zig-zag array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you zig-zag along the array's anti-diagonals.
For a graphical representation, see JPG zigzag (JPG uses such arrays to encode images).
For example, given 5, produce this array:
0 1 5 6 14
2 4 7 13 15
3 8 12 16 21
9 11 17 20 22
10 18 19 23 24
Related tasks
Spiral matrix
Identity matrix
Ulam spiral (for primes)
See also
Wiktionary entry: anti-diagonals
| #AutoIt | AutoIt |
#include <Array.au3>
$Array = ZigZag(5)
_ArrayDisplay($Array)
Func ZigZag($int)
Local $av_array[$int][$int]
Local $x = 1, $y = 1
For $I = 0 To $int ^ 2 -1
$av_array[$x-1][$y-1] = $I
If Mod(($x + $y), 2) = 0 Then ;Even
if ($y < $int) Then
$y += 1
Else
$x += 2
EndIf
if ($x > 1) Then $x -= 1
Else ; ODD
if ($x < $int) Then
$x += 1
Else
$y += 2
EndIf
If $y > 1 Then $y -= 1
EndIf
Next
Return $av_array
EndFunc ;==>ZigZag
|
http://rosettacode.org/wiki/Yellowstone_sequence | Yellowstone sequence | The Yellowstone sequence, also called the Yellowstone permutation, is defined as:
For n <= 3,
a(n) = n
For n >= 4,
a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and
is not relatively prime to a(n-2).
The sequence is a permutation of the natural numbers, and gets its name from what its authors felt was a spiking, geyser like appearance of a plot of the sequence.
Example
a(4) is 4 because 4 is the smallest number following 1, 2, 3 in the sequence that is relatively prime to the entry before it (3), and is not relatively prime to the number two entries before it (2).
Task
Find and show as output the first 30 Yellowstone numbers.
Extra
Demonstrate how to plot, with x = n and y coordinate a(n), the first 100 Yellowstone numbers.
Related tasks
Greatest common divisor.
Plot coordinate pairs.
See also
The OEIS entry: A098550 The Yellowstone permutation.
Applegate et al, 2015: The Yellowstone Permutation [1].
| #jq | jq |
# jq optimizes the recursive call of _gcd in the following:
def gcd(a;b):
def _gcd:
if .[1] != 0 then [.[1], .[0] % .[1]] | _gcd else .[0] end;
[a,b] | _gcd ;
# emit the yellowstone sequence as a stream
def yellowstone:
1,2,3,
({ a: [2, 3], # the last two items only
b: {"1": true, "2": true, "3" : true}, # a record, to avoid having to save the entire history
start: 4 }
| foreach range(1; infinite) as $n (.;
first(
.b as $b
| .start = first( range(.start;infinite) | select($b[tostring]|not) )
| foreach range(.start; infinite) as $i (.;
.emit = null
| ($i|tostring) as $is
| if .b[$is] then .
# "a(n) is relatively prime to a(n-1) and is not relatively prime to a(n-2)"
elif (gcd($i; .a[1]) == 1) and (gcd($i; .a[0]) > 1)
then .emit = $i
| .a = [.a[1], $i]
| .b[$is] = true
else .
end;
select(.emit)) );
.emit ));
|
http://rosettacode.org/wiki/Yellowstone_sequence | Yellowstone sequence | The Yellowstone sequence, also called the Yellowstone permutation, is defined as:
For n <= 3,
a(n) = n
For n >= 4,
a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and
is not relatively prime to a(n-2).
The sequence is a permutation of the natural numbers, and gets its name from what its authors felt was a spiking, geyser like appearance of a plot of the sequence.
Example
a(4) is 4 because 4 is the smallest number following 1, 2, 3 in the sequence that is relatively prime to the entry before it (3), and is not relatively prime to the number two entries before it (2).
Task
Find and show as output the first 30 Yellowstone numbers.
Extra
Demonstrate how to plot, with x = n and y coordinate a(n), the first 100 Yellowstone numbers.
Related tasks
Greatest common divisor.
Plot coordinate pairs.
See also
The OEIS entry: A098550 The Yellowstone permutation.
Applegate et al, 2015: The Yellowstone Permutation [1].
| #Julia | Julia | using Plots
function yellowstone(N)
a = [1, 2, 3]
b = Dict(1 => 1, 2 => 1, 3 => 1)
start = 4
while length(a) < N
inseries = true
for i in start:typemax(Int)
if haskey(b, i)
if inseries
start += 1
end
else
inseries = false
end
if !haskey(b, i) && (gcd(i, a[end]) == 1) && (gcd(i, a[end - 1]) > 1)
push!(a, i)
b[i] = 1
break
end
end
end
return a
end
println("The first 30 entries of the Yellowstone permutation:\n", yellowstone(30))
x = 1:100
y = yellowstone(100)
plot(x, y)
|
http://rosettacode.org/wiki/Yahoo!_search_interface | Yahoo! search interface | Create a class for searching Yahoo! results.
It must implement a Next Page method, and read URL, Title and Content from results.
| #Java | Java | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class YahooSearch {
private String query;
// Page number
private int page = 1;
// Regexp to look for the individual results in the returned page
private static final Pattern pattern = Pattern.compile(
"<a class=\"yschttl spt\" href=\"[^*]+?\\*\\*([^\"]+?)\">(.+?)</a></h3>.*?<div class=\"(?:sm-abs|abstr)\">(.+?)</div>");
public YahooSearch(String query) {
this.query = query;
}
public List<YahooResult> search() throws MalformedURLException, URISyntaxException, IOException {
// Build the search string, starting with the Yahoo search URL,
// then appending the query and optionally the page number (if > 1)
StringBuilder searchUrl = new StringBuilder("http://search.yahoo.com/search?");
searchUrl.append("p=").append(URLEncoder.encode(query, "UTF-8"));
if (page > 1) {searchUrl.append("&b=").append((page - 1) * 10 + 1);}
// Query the Yahoo search engine
URL url = new URL(searchUrl.toString());
List<YahooResult> result = new ArrayList<YahooResult>();
StringBuilder sb = new StringBuilder();
// Get the search results using a buffered reader
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(url.openStream()));
// Read the results line by line
String line = in.readLine();
while (line != null) {
sb.append(line);
line = in.readLine();
}
}
catch (IOException ioe) {
ioe.printStackTrace();
}
finally {
try {in.close();} catch (Exception ignoreMe) {}
}
String searchResult = sb.toString();
// Look for the individual results by matching the regexp pattern
Matcher matcher = pattern.matcher(searchResult);
while (matcher.find()) {
// Extract the result URL, title and excerpt
String resultUrl = URLDecoder.decode(matcher.group(1), "UTF-8");
String resultTitle = matcher.group(2).replaceAll("</?b>", "").replaceAll("<wbr ?/?>", "");
String resultContent = matcher.group(3).replaceAll("</?b>", "").replaceAll("<wbr ?/?>", "");
// Create a new YahooResult and add to the list
result.add(new YahooResult(resultUrl, resultTitle, resultContent));
}
return result;
}
public List<YahooResult> search(int page) throws MalformedURLException, URISyntaxException, IOException {
// Set the page number and search
this.page = page;
return search();
}
public List<YahooResult> nextPage() throws MalformedURLException, URISyntaxException, IOException {
// Increment the page number and search
page++;
return search();
}
public List<YahooResult> previousPage() throws MalformedURLException, URISyntaxException, IOException {
// Decrement the page number and search; if the page number is 1 return an empty list
if (page > 1) {
page--;
return search();
} else return new ArrayList<YahooResult>();
}
}
class YahooResult {
private URL url;
private String title;
private String content;
public URL getUrl() {
return url;
}
public void setUrl(URL url) {
this.url = url;
}
public void setUrl(String url) throws MalformedURLException {
this.url = new URL(url);
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public YahooResult(URL url, String title, String content) {
setUrl(url);
setTitle(title);
setContent(content);
}
public YahooResult(String url, String title, String content) throws MalformedURLException {
setUrl(url);
setTitle(title);
setContent(content);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if (title != null) {
sb.append(",title=").append(title);
}
if (url != null) {
sb.append(",url=").append(url);
}
return sb.charAt(0) == ',' ? sb.substring(1) : sb.toString();
}
}
public class TestYahooSearch {
public static void main(String[] args) throws MalformedURLException, URISyntaxException, IOException {
// Create a new search
YahooSearch search = new YahooSearch("Rosetta code");
// Get the search results
List<YahooResult> results = search.search();
// Show the search results
for (YahooResult result : results) {
System.out.println(result.toString());
}
}
} |
http://rosettacode.org/wiki/Arithmetic_evaluation | Arithmetic evaluation | Create a program which parses and evaluates arithmetic expressions.
Requirements
An abstract-syntax tree (AST) for the expression must be created from parsing the input.
The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.)
The expression will be a string or list of symbols like "(1+3)*7".
The four symbols + - * / must be supported as binary operators with conventional precedence rules.
Precedence-control parentheses must also be supported.
Note
For those who don't remember, mathematical precedence is as follows:
Parentheses
Multiplication/Division (left to right)
Addition/Subtraction (left to right)
C.f
24 game Player.
Parsing/RPN calculator algorithm.
Parsing/RPN to infix conversion.
| #Wren | Wren | import "/pattern" for Pattern
/* if string is empty, returns zero */
var toDoubleOrZero = Fn.new { |s|
var n = Num.fromString(s)
return n ? n : 0
}
var multiply = Fn.new { |s|
var b = s.split("*").map { |t| toDoubleOrZero.call(t) }.toList
return (b[0] * b[1]).toString
}
var divide = Fn.new { |s|
var b = s.split("/").map { |t| toDoubleOrZero.call(t) }.toList
return (b[0] / b[1]).toString
}
var add = Fn.new { |s|
var p1 = Pattern.new("/+", Pattern.start)
var p2 = Pattern.new("+1/+")
var t = p1.replaceAll(s, "")
t = p2.replaceAll(t, "+")
var b = t.split("+").map { |u| toDoubleOrZero.call(u) }.toList
return (b[0] + b[1]).toString
}
var subtract = Fn.new { |s|
var p = Pattern.new("[/+-|-/+]")
var t = p.replaceAll(s, "-")
if (t.contains("--")) return add.call(t.replace("--", "+"))
var b = t.split("-").map { |u| toDoubleOrZero.call(u) }.toList
return ((b.count == 3) ? -b[1] - b[2] : b[0] - b[1]).toString
}
var evalExp = Fn.new { |s|
var p = Pattern.new("[(|)|/s]")
var t = p.replaceAll(s, "")
var i = "*/"
var pMD = Pattern.new("+1/f/i~/n+1/f", Pattern.within, i)
var pM = Pattern.new("*")
var pAS = Pattern.new("~-+1/f+1/n+1/f")
var pA = Pattern.new("/d/+")
while (true) {
var match = pMD.find(t)
if (!match) break
var exp = match.text
var match2 = pM.find(exp)
t = match2 ? t.replace(exp, multiply.call(exp)) : t.replace(exp, divide.call(exp))
}
while (true) {
var match = pAS.find(t)
if (!match) break
var exp = match.text
var match2 = pA.find(exp)
t = match2 ? t.replace(exp, add.call(exp)) : t.replace(exp, subtract.call(exp))
}
return t
}
var evalArithmeticExp = Fn.new { |s|
var p1 = Pattern.new("/s")
var p2 = Pattern.new("/+", Pattern.start)
var t = p1.replaceAll(s, "")
t = p2.replaceAll(t, "")
var i = "()"
var pPara = Pattern.new("(+0/I)", Pattern.within, i)
while (true) {
var match = pPara.find(t)
if (!match) break
var exp = match.text
t = t.replace(exp, evalExp.call(exp))
}
return toDoubleOrZero.call(evalExp.call(t))
}
[
"2+3",
"2+3/4",
"2*3-4",
"2*(3+4)+5/6",
"2 * (3 + (4 * 5 + (6 * 7) * 8) - 9) * 10",
"2*-3--4+-0.25",
"-4 - 3",
"((((2))))+ 3 * 5",
"1 + 2 * (3 + (4 * 5 + 6 * 7 * 8) - 9) / 10",
"1 + 2*(3 - 2*(3 - 2)*((2 - 4)*5 - 22/(7 + 2*(3 - 1)) - 1)) + 1"
].each { |s| System.print("%(s) = %(evalArithmeticExp.call(s))") } |
http://rosettacode.org/wiki/Zumkeller_numbers | Zumkeller numbers | Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that the two partition sums are equal.
E.G.
6 is a Zumkeller number; The divisors {1 2 3 6} can be partitioned into two groups {1 2 3} and {6} that both sum to 6.
10 is not a Zumkeller number; The divisors {1 2 5 10} can not be partitioned into two groups in any way that will both sum to the same value.
12 is a Zumkeller number; The divisors {1 2 3 4 6 12} can be partitioned into two groups {1 3 4 6} and {2 12} that both sum to 14.
Even Zumkeller numbers are common; odd Zumkeller numbers are much less so. For values below 10^6, there is at least one Zumkeller number in every 12 consecutive integers, and the vast majority of them are even. The odd Zumkeller numbers are very similar to the list from the task Abundant odd numbers; they are nearly the same except for the further restriction that the abundance (A(n) = sigma(n) - 2n), must be even: A(n) mod 2 == 0
Task
Write a routine (function, procedure, whatever) to find Zumkeller numbers.
Use the routine to find and display here, on this page, the first 220 Zumkeller numbers.
Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers.
Optional, stretch goal: Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers that don't end with 5.
See Also
OEIS:A083207 - Zumkeller numbers to get an impression of different partitions OEIS:A083206 Zumkeller partitions
OEIS:A174865 - Odd Zumkeller numbers
Related Tasks
Abundant odd numbers
Abundant, deficient and perfect number classifications
Proper divisors , Factors of an integer | #Rust | Rust |
use std::convert::TryInto;
/// Gets all divisors of a number, including itself
fn get_divisors(n: u32) -> Vec<u32> {
let mut results = Vec::new();
for i in 1..(n / 2 + 1) {
if n % i == 0 {
results.push(i);
}
}
results.push(n);
results
}
/// Calculates whether the divisors can be partitioned into two disjoint
/// sets that sum to the same value
fn is_summable(x: i32, divisors: &[u32]) -> bool {
if !divisors.is_empty() {
if divisors.contains(&(x as u32)) {
return true;
} else if let Some((first, t)) = divisors.split_first() {
return is_summable(x - *first as i32, &t) || is_summable(x, &t);
}
}
false
}
/// Calculates whether the number is a Zumkeller number
/// Zumkeller numbers are the set of numbers whose divisors can be partitioned
/// into two disjoint sets that sum to the same value. Each sum must contain
/// divisor values that are not in the other sum, and all of the divisors must
/// be in one or the other.
fn is_zumkeller_number(number: u32) -> bool {
if number % 18 == 6 || number % 18 == 12 {
return true;
}
let div = get_divisors(number);
let divisor_sum: u32 = div.iter().sum();
if divisor_sum == 0 {
return false;
}
if divisor_sum % 2 == 1 {
return false;
}
// numbers where n is odd and the abundance is even are Zumkeller numbers
let abundance = divisor_sum as i32 - 2 * number as i32;
if number % 2 == 1 && abundance > 0 && abundance % 2 == 0 {
return true;
}
let half = divisor_sum / 2;
return div.contains(&half)
|| (div.iter().filter(|&&d| d < half).count() > 0
&& is_summable(half.try_into().unwrap(), &div));
}
fn main() {
println!("\nFirst 220 Zumkeller numbers:");
let mut counter: u32 = 0;
let mut i: u32 = 0;
while counter < 220 {
if is_zumkeller_number(i) {
print!("{:>3}", i);
counter += 1;
print!("{}", if counter % 20 == 0 { "\n" } else { "," });
}
i += 1;
}
println!("\nFirst 40 odd Zumkeller numbers:");
let mut counter: u32 = 0;
let mut i: u32 = 3;
while counter < 40 {
if is_zumkeller_number(i) {
print!("{:>5}", i);
counter += 1;
print!("{}", if counter % 20 == 0 { "\n" } else { "," });
}
i += 2;
}
}
|
http://rosettacode.org/wiki/Zumkeller_numbers | Zumkeller numbers | Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that the two partition sums are equal.
E.G.
6 is a Zumkeller number; The divisors {1 2 3 6} can be partitioned into two groups {1 2 3} and {6} that both sum to 6.
10 is not a Zumkeller number; The divisors {1 2 5 10} can not be partitioned into two groups in any way that will both sum to the same value.
12 is a Zumkeller number; The divisors {1 2 3 4 6 12} can be partitioned into two groups {1 3 4 6} and {2 12} that both sum to 14.
Even Zumkeller numbers are common; odd Zumkeller numbers are much less so. For values below 10^6, there is at least one Zumkeller number in every 12 consecutive integers, and the vast majority of them are even. The odd Zumkeller numbers are very similar to the list from the task Abundant odd numbers; they are nearly the same except for the further restriction that the abundance (A(n) = sigma(n) - 2n), must be even: A(n) mod 2 == 0
Task
Write a routine (function, procedure, whatever) to find Zumkeller numbers.
Use the routine to find and display here, on this page, the first 220 Zumkeller numbers.
Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers.
Optional, stretch goal: Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers that don't end with 5.
See Also
OEIS:A083207 - Zumkeller numbers to get an impression of different partitions OEIS:A083206 Zumkeller partitions
OEIS:A174865 - Odd Zumkeller numbers
Related Tasks
Abundant odd numbers
Abundant, deficient and perfect number classifications
Proper divisors , Factors of an integer | #Sidef | Sidef | func is_Zumkeller(n) {
return false if n.is_prime
return false if n.is_square
var sigma = n.sigma
# n must have an even abundance
return false if (sigma.is_odd || (sigma < 2*n))
# true if n is odd and has an even abundance
return true if n.is_odd # conjecture
var divisors = n.divisors
for k in (2 .. divisors.end) {
divisors.combinations(k, {|*a|
if (2*a.sum == sigma) {
return true
}
})
}
return false
}
say "First 220 Zumkeller numbers:"
say (1..Inf -> lazy.grep(is_Zumkeller).first(220).join(' '))
say "\nFirst 40 odd Zumkeller numbers: "
say (1..Inf `by` 2 -> lazy.grep(is_Zumkeller).first(40).join(' '))
say "\nFirst 40 odd Zumkeller numbers not divisible by 5: "
say (1..Inf `by` 2 -> lazy.grep { _ % 5 != 0 }.grep(is_Zumkeller).first(40).join(' ')) |
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included) | Arbitrary-precision integers (included) | Using the in-built capabilities of your language, calculate the integer value of:
5
4
3
2
{\displaystyle 5^{4^{3^{2}}}}
Confirm that the first and last twenty digits of the answer are:
62060698786608744707...92256259918212890625
Find and show the number of decimal digits in the answer.
Note: Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead.
Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value.
Related tasks
Long multiplication
Exponentiation order
exponentiation operator
Exponentiation with infix operators in (or operating on) the base
| #Go | Go | package main
import (
"fmt"
"math/big"
)
func main() {
x := big.NewInt(2)
x = x.Exp(big.NewInt(3), x, nil)
x = x.Exp(big.NewInt(4), x, nil)
x = x.Exp(big.NewInt(5), x, nil)
str := x.String()
fmt.Printf("5^(4^(3^2)) has %d digits: %s ... %s\n",
len(str),
str[:20],
str[len(str)-20:],
)
} |
http://rosettacode.org/wiki/Zhang-Suen_thinning_algorithm | Zhang-Suen thinning algorithm | This is an algorithm used to thin a black and white i.e. one bit per pixel images.
For example, with an input image of:
################# #############
################## ################
################### ##################
######## ####### ###################
###### ####### ####### ######
###### ####### #######
################# #######
################ #######
################# #######
###### ####### #######
###### ####### #######
###### ####### ####### ######
######## ####### ###################
######## ####### ###### ################## ######
######## ####### ###### ################ ######
######## ####### ###### ############# ######
It produces the thinned output:
# ########## #######
## # #### #
# # ##
# # #
# # #
# # #
############ #
# # #
# # #
# # #
# # #
# ##
# ############
### ###
Algorithm
Assume black pixels are one and white pixels zero, and that the input image is a rectangular N by M array of ones and zeroes.
The algorithm operates on all black pixels P1 that can have eight neighbours.
The neighbours are, in order, arranged as:
P9 P2 P3
P8 P1 P4
P7 P6 P5
Obviously the boundary pixels of the image cannot have the full eight neighbours.
Define
A
(
P
1
)
{\displaystyle A(P1)}
= the number of transitions from white to black, (0 -> 1) in the sequence P2,P3,P4,P5,P6,P7,P8,P9,P2. (Note the extra P2 at the end - it is circular).
Define
B
(
P
1
)
{\displaystyle B(P1)}
= The number of black pixel neighbours of P1. ( = sum(P2 .. P9) )
Step 1
All pixels are tested and pixels satisfying all the following conditions (simultaneously) are just noted at this stage.
(0) The pixel is black and has eight neighbours
(1)
2
<=
B
(
P
1
)
<=
6
{\displaystyle 2<=B(P1)<=6}
(2) A(P1) = 1
(3) At least one of P2 and P4 and P6 is white
(4) At least one of P4 and P6 and P8 is white
After iterating over the image and collecting all the pixels satisfying all step 1 conditions, all these condition satisfying pixels are set to white.
Step 2
All pixels are again tested and pixels satisfying all the following conditions are just noted at this stage.
(0) The pixel is black and has eight neighbours
(1)
2
<=
B
(
P
1
)
<=
6
{\displaystyle 2<=B(P1)<=6}
(2) A(P1) = 1
(3) At least one of P2 and P4 and P8 is white
(4) At least one of P2 and P6 and P8 is white
After iterating over the image and collecting all the pixels satisfying all step 2 conditions, all these condition satisfying pixels are again set to white.
Iteration
If any pixels were set in this round of either step 1 or step 2 then all steps are repeated until no image pixels are so changed.
Task
Write a routine to perform Zhang-Suen thinning on an image matrix of ones and zeroes.
Use the routine to thin the following image and show the output here on this page as either a matrix of ones and zeroes, an image, or an ASCII-art image of space/non-space characters.
00000000000000000000000000000000
01111111110000000111111110000000
01110001111000001111001111000000
01110000111000001110000111000000
01110001111000001110000000000000
01111111110000001110000000000000
01110111100000001110000111000000
01110011110011101111001111011100
01110001111011100111111110011100
00000000000000000000000000000000
Reference
Zhang-Suen Thinning Algorithm, Java Implementation by Nayef Reza.
"Character Recognition Systems: A Guide for Students and Practitioners" By Mohamed Cheriet, Nawwaf Kharma, Cheng-Lin Liu, Ching Suen
| #Sidef | Sidef | class ZhangSuen(str, black="1") {
const NEIGHBOURS = [[-1,0],[-1,1],[0,1],[1,1],[1,0],[1,-1],[0,-1],[-1,-1]] # 8 neighbors
const CIRCULARS = (NEIGHBOURS + [NEIGHBOURS.first]) # P2, ... P9, P2
has r = 0
has image = [[]]
method init {
var s1 = str.lines.map{|line| line.chars.map{|c| c==black ? 1 : 0 }}
var s2 = s1.len.of { s1[0].len.of(0) }
var xr = range(1, s1.end-1)
var yr = range(1, s1[0].end-1)
do {
r = 0
xr.each{|x| yr.each{|y| s2[x][y] = (s1[x][y] - self.zs(s1,x,y,1)) }} # Step 1
xr.each{|x| yr.each{|y| s1[x][y] = (s2[x][y] - self.zs(s2,x,y,0)) }} # Step 2
} while !r.is_zero
image = s1
}
method zs(ng,x,y,g) {
(ng[x][y] == 0) ->
|| (ng[x-1][y] + ng[x][y+1] + ng[x+g][y+g - 1] == 3) ->
|| (ng[x+g - 1][y+g] + ng[x+1][y] + ng[x][y-1] == 3) ->
&& return 0
var bp1 = NEIGHBOURS.map {|p| ng[x+p[0]][y+p[1]] }.sum # B(P1)
return 0 if ((bp1 < 2) || (6 < bp1))
var ap1 = 0
CIRCULARS.map {|p| ng[x+p[0]][y+p[1]] }.each_cons(2, {|a,b|
++ap1 if (a < b) # A(P1)
})
return 0 if (ap1 != 1)
r = 1
}
method display {
image.each{|row| say row.map{|col| col ? '#' : ' ' }.join }
}
}
var text = <<EOS
00000000000000000000000000000000
01111111110000000111111110000000
01110001111000001111001111000000
01110000111000001110000111000000
01110001111000001110000000000000
01111111110000001110000000000000
01110111100000001110000111000000
01110011110011101111001111011100
01110001111011100111111110011100
00000000000000000000000000000000
EOS
ZhangSuen.new(text, black: "1").display |
http://rosettacode.org/wiki/Zeckendorf_number_representation | Zeckendorf number representation | Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series.
Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13.
The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100.
10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that no two consecutive Fibonacci numbers can be used which leads to the former unique solution.
Task
Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order.
The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task.
Also see
OEIS A014417 for the the sequence of required results.
Brown's Criterion - Numberphile
Related task
Fibonacci sequence
| #JavaScript | JavaScript | (() => {
'use strict';
const main = () =>
unlines(
map(n => concat(zeckendorf(n)),
enumFromTo(0, 20)
)
);
// zeckendorf :: Int -> String
const zeckendorf = n => {
const go = (n, x) =>
n < x ? (
Tuple(n, '0')
) : Tuple(n - x, '1')
return 0 < n ? (
snd(mapAccumL(
go, n,
reverse(fibUntil(n))
))
) : ['0'];
};
// fibUntil :: Int -> [Int]
const fibUntil = n =>
cons(1, takeWhile(x => n >= x,
map(snd, iterateUntil(
tpl => n <= fst(tpl),
tpl => {
const x = snd(tpl);
return Tuple(x, x + fst(tpl));
},
Tuple(1, 2)
))));
// GENERIC FUNCTIONS ----------------------------
// Tuple (,) :: a -> b -> (a, b)
const Tuple = (a, b) => ({
type: 'Tuple',
'0': a,
'1': b,
length: 2
});
// concat :: [[a]] -> [a]
// concat :: [String] -> String
const concat = xs =>
0 < xs.length ? (() => {
const unit = 'string' !== typeof xs[0] ? (
[]
) : '';
return unit.concat.apply(unit, xs);
})() : [];
// cons :: a -> [a] -> [a]
const cons = (x, xs) =>
Array.isArray(xs) ? (
[x].concat(xs)
) : (x + xs);
// enumFromTo :: Int -> Int -> [Int]
const enumFromTo = (m, n) =>
m <= n ? iterateUntil(
x => n <= x,
x => 1 + x,
m
) : [];
// fst :: (a, b) -> a
const fst = tpl => tpl[0];
// iterateUntil :: (a -> Bool) -> (a -> a) -> a -> [a]
const iterateUntil = (p, f, x) => {
const vs = [x];
let h = x;
while (!p(h))(h = f(h), vs.push(h));
return vs;
};
// map :: (a -> b) -> [a] -> [b]
const map = (f, xs) => xs.map(f);
// 'The mapAccumL function behaves like a combination of map and foldl;
// it applies a function to each element of a list, passing an accumulating
// parameter from left to right, and returning a final value of this
// accumulator together with the new list.' (See Hoogle)
// mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
const mapAccumL = (f, acc, xs) =>
xs.reduce((a, x, i) => {
const pair = f(a[0], x, i);
return Tuple(pair[0], a[1].concat(pair[1]));
}, Tuple(acc, []));
// reverse :: [a] -> [a]
const reverse = xs =>
'string' !== typeof xs ? (
xs.slice(0).reverse()
) : xs.split('').reverse().join('');
// snd :: (a, b) -> b
const snd = tpl => tpl[1];
// tail :: [a] -> [a]
const tail = xs => 0 < xs.length ? xs.slice(1) : [];
// takeWhile :: (a -> Bool) -> [a] -> [a]
// takeWhile :: (Char -> Bool) -> String -> String
const takeWhile = (p, xs) => {
const lng = xs.length;
return 0 < lng ? xs.slice(
0,
until(
i => i === lng || !p(xs[i]),
i => 1 + i,
0
)
) : [];
};
// unlines :: [String] -> String
const unlines = xs => xs.join('\n');
// until :: (a -> Bool) -> (a -> a) -> a -> a
const until = (p, f, x) => {
let v = x;
while (!p(v)) v = f(v);
return v;
};
// MAIN ---
return main();
})(); |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Clojure | Clojure | (defn doors []
(let [doors (into-array (repeat 100 false))]
(doseq [pass (range 1 101)
i (range (dec pass) 100 pass) ]
(aset doors i (not (aget doors i))))
doors))
(defn open-doors [] (for [[d n] (map vector (doors) (iterate inc 1)) :when d] n))
(defn print-open-doors []
(println
"Open doors after 100 passes:"
(apply str (interpose ", " (open-doors))))) |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #Fortran | Fortran | integer a (10) |
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part", where the imaginary part is the number to be multiplied by
i
{\displaystyle i}
.
Task
Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.)
Print the results for each operation tested.
Optional: Show complex conjugation.
By definition, the complex conjugate of
a
+
b
i
{\displaystyle a+bi}
is
a
−
b
i
{\displaystyle a-bi}
Some languages have complex number libraries available. If your language does, show the operations. If your language does not, also show the definition of this type.
| #RLaB | RLaB |
>> x = sqrt(-1)
0 + 1i
>> y = 10 + 5i
10 + 5i
>> z = 5*x-y
-10 + 0i
>> isreal(z)
1
|
http://rosettacode.org/wiki/Arithmetic/Rational | Arithmetic/Rational | Task
Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language.
Example
Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number).
Further define the appropriate rational unary operators abs and '-', with the binary operators for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠').
Define standard coercion operators for casting int to frac etc.
If space allows, define standard increment and decrement operators (e.g. '+:=' & '-:=' etc.).
Finally test the operators:
Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors.
Related task
Perfect Numbers
| #Smalltalk | Smalltalk | st> 54/7
54/7
st> 54/7 + 1
61/7
st> 54/7 < 50
true
st> 20 reciprocal
1/20
st> (5/6) reciprocal
6/5
st> (5/6) asFloat
0.8333333333333334
|
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, you may also try something like:
x = 0
y = 0
z = x**y
say 'z=' z
Show the result here.
And of course use any symbols or notation that is supported in your computer programming language for exponentiation.
See also
The Wiki entry: Zero to the power of zero.
The Wiki entry: History of differing points of view.
The MathWorld™ entry: exponent laws.
Also, in the above MathWorld™ entry, see formula (9):
x
0
=
1
{\displaystyle x^{0}=1}
.
The OEIS entry: The special case of zero to the zeroth power
| #Mercury | Mercury | :- module zero_to_the_zero_power.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module float, int, integer, list, string.
main(!IO) :-
io.format(" int.pow(0, 0) = %d\n", [i(pow(0, 0))], !IO),
io.format("integer.pow(zero, zero) = %s\n",
[s(to_string(pow(zero, zero)))], !IO),
io.format(" float.pow(0.0, 0) = %.1f\n", [f(pow(0.0, 0))], !IO).
:- end_module zero_to_the_zero_power. |
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, you may also try something like:
x = 0
y = 0
z = x**y
say 'z=' z
Show the result here.
And of course use any symbols or notation that is supported in your computer programming language for exponentiation.
See also
The Wiki entry: Zero to the power of zero.
The Wiki entry: History of differing points of view.
The MathWorld™ entry: exponent laws.
Also, in the above MathWorld™ entry, see formula (9):
x
0
=
1
{\displaystyle x^{0}=1}
.
The OEIS entry: The special case of zero to the zeroth power
| #Microsoft_Small_Basic | Microsoft Small Basic | TextWindow.WriteLine(Math.Power(0,0)) |
http://rosettacode.org/wiki/Zebra_puzzle | Zebra puzzle | Zebra puzzle
You are encouraged to solve this task according to the task description, using any language you may know.
The Zebra puzzle, a.k.a. Einstein's Riddle,
is a logic puzzle which is to be solved programmatically.
It has several variants, one of them this:
There are five houses.
The English man lives in the red house.
The Swede has a dog.
The Dane drinks tea.
The green house is immediately to the left of the white house.
They drink coffee in the green house.
The man who smokes Pall Mall has birds.
In the yellow house they smoke Dunhill.
In the middle house they drink milk.
The Norwegian lives in the first house.
The man who smokes Blend lives in the house next to the house with cats.
In a house next to the house where they have a horse, they smoke Dunhill.
The man who smokes Blue Master drinks beer.
The German smokes Prince.
The Norwegian lives next to the blue house.
They drink water in a house next to the house where they smoke Blend.
The question is, who owns the zebra?
Additionally, list the solution for all the houses.
Optionally, show the solution is unique.
Related tasks
Dinesman's multiple-dwelling problem
Twelve statements
| #Bracmat | Bracmat | ( (English Swede Dane Norwegian German,)
(red green white yellow blue,(red.English.))
(dog birds cats horse zebra,(dog.?.Swede.))
( tea coffee milk beer water
, (tea.?.?.Dane.) (coffee.?.green.?.)
)
( "Pall Mall" Dunhill Blend "Blue Master" Prince
, ("Blue Master".beer.?.?.?.)
("Pall Mall".?.birds.?.?.)
(Dunhill.?.?.yellow.?.)
(Prince.?.?.?.German.)
)
( 1 2 3 4 5
, (3.?.milk.?.?.?.) (1.?.?.?.?.Norwegian.)
)
: ?properties
& ( relations
= next leftOf
. ( next
= a b A B
. !arg:(?S,?A,?B)
& !S:? (?a.!A) ?:? (?b.!B) ?
& (!a+1:!b|!b+1:!a)
)
& ( leftOf
= a b A B
. !arg:(?S,?A,?B)
& !S:? (?a.!A) ?:? (?b.!B) ?
& !a+1:!b
)
& leftOf
$ (!arg,(?.?.?.green.?.),(?.?.?.white.?.))
& next$(!arg,(Blend.?.?.?.?.),(?.?.cats.?.?.))
& next
$ (!arg,(?.?.horse.?.?.),(Dunhill.?.?.?.?.))
& next
$ (!arg,(?.?.?.?.Norwegian.),(?.?.?.blue.?.))
& next$(!arg,(?.water.?.?.?.),(Blend.?.?.?.?.))
)
& ( props
= a constraint constraints house houses
, remainingToDo shavedToDo toDo value values z
. !arg:(?toDo.?shavedToDo.?house.?houses)
& ( !toDo:(?values,?constraints) ?remainingToDo
& !values
: ( ?a
( %@?value
& !constraints
: ( ?
( !value
. ?constraint
& !house:!constraint
)
?
| ~( ?
( ?
. ?constraint
& !house:!constraint
)
?
| ? (!value.?) ?
)
)
)
( ?z
& props
$ ( !remainingToDo
. !shavedToDo (!a !z,!constraints)
. (!value.!house)
. !houses
)
)
|
& relations$!houses
& out$(Solution !houses)
)
| !toDo:
& props$(!shavedToDo...!house !houses)
)
)
& props$(!properties...)
& done
); |
http://rosettacode.org/wiki/XML/XPath | XML/XPath | Perform the following three XPath queries on the XML Document below:
//item[1]: Retrieve the first "item" element
//price/text(): Perform an action on each "price" element (print it out)
//name: Get an array of all the "name" elements
XML Document:
<inventory title="OmniCorp Store #45x10^3">
<section name="health">
<item upc="123456789" stock="12">
<name>Invisibility Cream</name>
<price>14.50</price>
<description>Makes you invisible</description>
</item>
<item upc="445322344" stock="18">
<name>Levitation Salve</name>
<price>23.99</price>
<description>Levitate yourself for up to 3 hours per application</description>
</item>
</section>
<section name="food">
<item upc="485672034" stock="653">
<name>Blork and Freen Instameal</name>
<price>4.95</price>
<description>A tasty meal in a tablet; just add water</description>
</item>
<item upc="132957764" stock="44">
<name>Grob winglets</name>
<price>3.56</price>
<description>Tender winglets of Grob. Just add water</description>
</item>
</section>
</inventory>
| #C | C |
#include <libxml/parser.h>
#include <libxml/xpath.h>
xmlDocPtr getdoc (char *docname) {
xmlDocPtr doc;
doc = xmlParseFile(docname);
return doc;
}
xmlXPathObjectPtr getnodeset (xmlDocPtr doc, xmlChar *xpath){
xmlXPathContextPtr context;
xmlXPathObjectPtr result;
context = xmlXPathNewContext(doc);
result = xmlXPathEvalExpression(xpath, context);
xmlXPathFreeContext(context);
return result;
}
int main(int argc, char **argv) {
if (argc <= 2) {
printf("Usage: %s <XML Document Name> <XPath expression>\n", argv[0]);
return 0;
}
char *docname;
xmlDocPtr doc;
xmlChar *xpath = (xmlChar*) argv[2];
xmlNodeSetPtr nodeset;
xmlXPathObjectPtr result;
int i;
xmlChar *keyword;
docname = argv[1];
doc = getdoc(docname);
result = getnodeset (doc, xpath);
if (result) {
nodeset = result->nodesetval;
for (i=0; i < nodeset->nodeNr; i++) {
xmlNodePtr titleNode = nodeset->nodeTab[i];
keyword = xmlNodeListGetString(doc, titleNode->xmlChildrenNode, 1);
printf("Value %d: %s\n",i+1, keyword);
xmlFree(keyword);
}
xmlXPathFreeObject (result);
}
xmlFreeDoc(doc);
xmlCleanupParser();
return 0;
}
|
http://rosettacode.org/wiki/Yin_and_yang | Yin and yang | One well-known symbol of the philosophy of duality known as yin and yang is the taijitu.
Task
Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.
Generate and display the symbol for two different (small) sizes.
| #AutoHotkey | AutoHotkey | Yin_and_Yang(50, 50, A_ScriptDir "\YinYang1.png")
Yin_and_Yang(300, 300,A_ScriptDir "\YinYang2.png")
Yin_and_Yang(width, height, fileName
, color1=0xFFFFFFFF, color2=0xFF000000, outlineWidth=1){
pToken := gdip_Startup()
pBitmap := gdip_CreateBitmap(w := width, h := height)
w-=1, h-=1
pGraphics:= gdip_GraphicsFromImage(pBitmap)
pBrushW := gdip_BrushCreateSolid(color1)
pBrushB := gdip_BrushCreateSolid(color2)
gdip_SetSmoothingMode(pGraphics, 4) ; Antialiasing
If (outlineWidth){
pPen := gdip_CreatePen(0xFF000000, outlineWidth)
gdip_DrawEllipse(pGraphics, pPen, 0, 0, w, h)
gdip_DeletePen(pPen)
}
gdip_FillPie(pGraphics, pBrushB, 0, 0, w, h, -90, 180)
gdip_FillPie(pGraphics, pBrushW, 0, 0, w, h, 90, 180)
gdip_FillEllipse(pGraphics, pBrushB, w//4, h//2, w//2, h//2)
gdip_FillEllipse(pGraphics, pBrushW, w//4, 0 , w//2, h//2)
gdip_FillEllipse(pGraphics, pBrushB, 5*w//12, h//6, w//6, h//6)
gdip_FillEllipse(pGraphics, pBrushW, 5*w//12, 4*h//6,w//6,h//6)
r := gdip_SaveBitmapToFile(pBitmap, filename)
; cleanup:
gdip_DeleteBrush(pBrushW), gdip_deleteBrush(pBrushB)
gdip_DisposeImage(pBitmap)
gdip_DeleteGraphics(pGraphics)
gdip_Shutdown(pToken)
return r
} |
http://rosettacode.org/wiki/Y_combinator | Y combinator | In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions.
This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function.
The Y combinator is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function.
The Y combinator is the simplest of the class of such functions, called fixed-point combinators.
Task
Define the stateless Y combinator and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions.
Cf
Jim Weirich: Adventures in Functional Programming
| #Bracmat | Bracmat | (λx.x)y |
http://rosettacode.org/wiki/Zig-zag_matrix | Zig-zag matrix | Task
Produce a zig-zag array.
A zig-zag array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you zig-zag along the array's anti-diagonals.
For a graphical representation, see JPG zigzag (JPG uses such arrays to encode images).
For example, given 5, produce this array:
0 1 5 6 14
2 4 7 13 15
3 8 12 16 21
9 11 17 20 22
10 18 19 23 24
Related tasks
Spiral matrix
Identity matrix
Ulam spiral (for primes)
See also
Wiktionary entry: anti-diagonals
| #AWK | AWK |
# syntax: GAWK -f ZIG-ZAG_MATRIX.AWK [-v offset={0|1}] [size]
BEGIN {
# offset: "0" prints 0 to size^2-1 while "1" prints 1 to size^2
offset = (offset == "") ? 0 : offset
size = (ARGV[1] == "") ? 5 : ARGV[1]
if (offset !~ /^[01]$/) { exit(1) }
if (size !~ /^[0-9]+$/) { exit(1) }
width = length(size ^ 2 - 1 + offset) + 1
i = j = 1
for (n=0; n<=size^2-1; n++) { # build array
arr[i-1,j-1] = n + offset
if ((i+j) % 2 == 0) {
if (j < size) { j++ } else { i+=2 }
if (i > 1) { i-- }
}
else {
if (i < size) { i++ } else { j+=2 }
if (j > 1) { j-- }
}
}
for (row=0; row<size; row++) { # show array
for (col=0; col<size; col++) {
printf("%*d",width,arr[row,col])
}
printf("\n")
}
exit(0)
}
|
http://rosettacode.org/wiki/Yellowstone_sequence | Yellowstone sequence | The Yellowstone sequence, also called the Yellowstone permutation, is defined as:
For n <= 3,
a(n) = n
For n >= 4,
a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and
is not relatively prime to a(n-2).
The sequence is a permutation of the natural numbers, and gets its name from what its authors felt was a spiking, geyser like appearance of a plot of the sequence.
Example
a(4) is 4 because 4 is the smallest number following 1, 2, 3 in the sequence that is relatively prime to the entry before it (3), and is not relatively prime to the number two entries before it (2).
Task
Find and show as output the first 30 Yellowstone numbers.
Extra
Demonstrate how to plot, with x = n and y coordinate a(n), the first 100 Yellowstone numbers.
Related tasks
Greatest common divisor.
Plot coordinate pairs.
See also
The OEIS entry: A098550 The Yellowstone permutation.
Applegate et al, 2015: The Yellowstone Permutation [1].
| #Kotlin | Kotlin | fun main() {
println("First 30 values in the yellowstone sequence:")
println(yellowstoneSequence(30))
}
private fun yellowstoneSequence(sequenceCount: Int): List<Int> {
val yellowstoneList = mutableListOf(1, 2, 3)
var num = 4
val notYellowstoneList = mutableListOf<Int>()
var yellowSize = 3
while (yellowSize < sequenceCount) {
var found = -1
for (index in notYellowstoneList.indices) {
val test = notYellowstoneList[index]
if (gcd(yellowstoneList[yellowSize - 2], test) > 1 && gcd(
yellowstoneList[yellowSize - 1], test
) == 1
) {
found = index
break
}
}
if (found >= 0) {
yellowstoneList.add(notYellowstoneList.removeAt(found))
yellowSize++
} else {
while (true) {
if (gcd(yellowstoneList[yellowSize - 2], num) > 1 && gcd(
yellowstoneList[yellowSize - 1], num
) == 1
) {
yellowstoneList.add(num)
yellowSize++
num++
break
}
notYellowstoneList.add(num)
num++
}
}
}
return yellowstoneList
}
private fun gcd(a: Int, b: Int): Int {
return if (b == 0) {
a
} else gcd(b, a % b)
} |
http://rosettacode.org/wiki/Yahoo!_search_interface | Yahoo! search interface | Create a class for searching Yahoo! results.
It must implement a Next Page method, and read URL, Title and Content from results.
| #Julia | Julia | """ Rosetta Code Yahoo search task. https://rosettacode.org/wiki/Yahoo!_search_interface """
using EzXML
using HTTP
using Logging
const pagesize = 7
const URI = "https://search.yahoo.com/search?fr=opensearch&pz=$pagesize&"
struct SearchResults
title::String
content::String
url::String
end
mutable struct YahooSearch
search::String
yahoourl::String
currentpage::Int
usedpages::Vector{Int}
results::Vector{SearchResults}
end
YahooSearch(s, url = URI) = YahooSearch(s, url, 1, Int[], SearchResults[])
function NextPage(yah::YahooSearch, link, pagenum)
oldpage = yah.currentpage
yah.currentpage = pagenum
search(yah)
yah.currentpage = oldpage
end
function search(yah::YahooSearch)
push!(yah.usedpages, yah.currentpage)
queryurl = yah.yahoourl * "b=$(yah.currentpage)&p=" * HTTP.escapeuri(yah.search)
req = HTTP.request("GET", queryurl)
# Yahoo's HTML is nonstandard, so send excess warnings from the parser to NullLogger
html = with_logger(NullLogger()) do
parsehtml(String(req.body))
end
for div in findall("//li/div", html)
if haskey(div, "class")
if startswith(div["class"], "dd algo") &&
(a = findfirst("div/h3/a", div)) != nothing &&
haskey(a, "href")
url, title, content = a["href"], nodecontent(a), "None"
for span in findall("div/p/span", div)
if haskey(span, "class") && occursin("fc-falcon", span["class"])
content = nodecontent(span)
end
end
push!(yah.results, SearchResults(title, content, url))
elseif startswith(div["class"], "dd pagination")
for a in findall("div/div/a", div)
if haskey(a, "href")
lnk, n = a["href"], tryparse(Int, nodecontent(a))
!isnothing(n) && !(n in yah.usedpages) && NextPage(yah, lnk, n)
end
end
end
end
end
end
ysearch = YahooSearch("RosettaCode")
search(ysearch)
println("Searching Yahoo for `RosettaCode`:")
println(
"Found ",
length(ysearch.results),
" entries on ",
length(ysearch.usedpages),
" pages.\n",
)
for res in ysearch.results
println("Title: ", res.title)
println("Content: ", res.content)
println("URL: ", res.url, "\n")
end
|
http://rosettacode.org/wiki/Yahoo!_search_interface | Yahoo! search interface | Create a class for searching Yahoo! results.
It must implement a Next Page method, and read URL, Title and Content from results.
| #Kotlin | Kotlin | // version 1.2.0
import java.net.URL
val rx = Regex("""<div class=\"yst result\">.+?<a href=\"(.*?)\" class=\"\">(.*?)</a>.+?class="abstract ellipsis">(.*?)</p>""")
class YahooResult(var title: String, var link: String, var text: String) {
override fun toString() = "\nTitle: $title\nLink : $link\nText : $text"
}
class YahooSearch(val query: String, val page: Int = 0) {
private val content: String
init {
val yahoo = "http://search.yahoo.com/search?"
val url = URL("${yahoo}p=$query&b=${page * 10 + 1}")
content = url.readText()
}
val results: MutableList<YahooResult>
get() {
val list = mutableListOf<YahooResult>()
for (mr in rx.findAll(content)) {
val title = mr.groups[2]!!.value.replace("<b>", "").replace("</b>", "")
val link = mr.groups[1]!!.value
val text = mr.groups[3]!!.value.replace("<b>", "").replace("</b>", "")
list.add (YahooResult(title, link, text))
}
return list
}
fun nextPage() = YahooSearch(query, page + 1)
fun getPage(newPage: Int) = YahooSearch(query, newPage)
}
fun main(args: Array<String>) {
for (page in 0..1) {
val x = YahooSearch("rosettacode", page)
println("\nPAGE ${page + 1} =>")
for (result in x.results.take(3)) println(result)
}
} |
http://rosettacode.org/wiki/Arithmetic_evaluation | Arithmetic evaluation | Create a program which parses and evaluates arithmetic expressions.
Requirements
An abstract-syntax tree (AST) for the expression must be created from parsing the input.
The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.)
The expression will be a string or list of symbols like "(1+3)*7".
The four symbols + - * / must be supported as binary operators with conventional precedence rules.
Precedence-control parentheses must also be supported.
Note
For those who don't remember, mathematical precedence is as follows:
Parentheses
Multiplication/Division (left to right)
Addition/Subtraction (left to right)
C.f
24 game Player.
Parsing/RPN calculator algorithm.
Parsing/RPN to infix conversion.
| #zkl | zkl | Compiler.Parser.parseText("(1+3)*7").dump();
Compiler.Parser.parseText("1+3*7").dump(); |
http://rosettacode.org/wiki/Arithmetic_evaluation | Arithmetic evaluation | Create a program which parses and evaluates arithmetic expressions.
Requirements
An abstract-syntax tree (AST) for the expression must be created from parsing the input.
The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.)
The expression will be a string or list of symbols like "(1+3)*7".
The four symbols + - * / must be supported as binary operators with conventional precedence rules.
Precedence-control parentheses must also be supported.
Note
For those who don't remember, mathematical precedence is as follows:
Parentheses
Multiplication/Division (left to right)
Addition/Subtraction (left to right)
C.f
24 game Player.
Parsing/RPN calculator algorithm.
Parsing/RPN to infix conversion.
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 PRINT "Use integer numbers and signs"'"+ - * / ( )"''
20 LET s$="": REM last symbol
30 LET pc=0: REM parenthesis counter
40 LET i$="1+2*(3+(4*5+6*7*8)-9)/10"
50 PRINT "Input = ";i$
60 FOR n=1 TO LEN i$
70 LET c$=i$(n)
80 IF c$>="0" AND c$<="9" THEN GO SUB 170: GO TO 130
90 IF c$="+" OR c$="-" THEN GO SUB 200: GO TO 130
100 IF c$="*" OR c$="/" THEN GO SUB 200: GO TO 130
110 IF c$="(" OR c$=")" THEN GO SUB 230: GO TO 130
120 GO TO 300
130 NEXT n
140 IF pc>0 THEN PRINT FLASH 1;"Parentheses not paired.": BEEP 1,-25: STOP
150 PRINT "Result = ";VAL i$
160 STOP
170 IF s$=")" THEN GO TO 300
180 LET s$=c$
190 RETURN
200 IF (NOT (s$>="0" AND s$<="9")) AND s$<>")" THEN GO TO 300
210 LET s$=c$
220 RETURN
230 IF c$="(" AND ((s$>="0" AND s$<="9") OR s$=")") THEN GO TO 300
240 IF c$=")" AND ((NOT (s$>="0" AND s$<="9")) OR s$="(") THEN GO TO 300
250 LET s$=c$
260 IF c$="(" THEN LET pc=pc+1: RETURN
270 LET pc=pc-1
280 IF pc<0 THEN GO TO 300
290 RETURN
300 PRINT FLASH 1;"Invalid symbol ";c$;" detected in pos ";n: BEEP 1,-25
310 STOP
|
http://rosettacode.org/wiki/Zumkeller_numbers | Zumkeller numbers | Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that the two partition sums are equal.
E.G.
6 is a Zumkeller number; The divisors {1 2 3 6} can be partitioned into two groups {1 2 3} and {6} that both sum to 6.
10 is not a Zumkeller number; The divisors {1 2 5 10} can not be partitioned into two groups in any way that will both sum to the same value.
12 is a Zumkeller number; The divisors {1 2 3 4 6 12} can be partitioned into two groups {1 3 4 6} and {2 12} that both sum to 14.
Even Zumkeller numbers are common; odd Zumkeller numbers are much less so. For values below 10^6, there is at least one Zumkeller number in every 12 consecutive integers, and the vast majority of them are even. The odd Zumkeller numbers are very similar to the list from the task Abundant odd numbers; they are nearly the same except for the further restriction that the abundance (A(n) = sigma(n) - 2n), must be even: A(n) mod 2 == 0
Task
Write a routine (function, procedure, whatever) to find Zumkeller numbers.
Use the routine to find and display here, on this page, the first 220 Zumkeller numbers.
Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers.
Optional, stretch goal: Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers that don't end with 5.
See Also
OEIS:A083207 - Zumkeller numbers to get an impression of different partitions OEIS:A083206 Zumkeller partitions
OEIS:A174865 - Odd Zumkeller numbers
Related Tasks
Abundant odd numbers
Abundant, deficient and perfect number classifications
Proper divisors , Factors of an integer | #Standard_ML | Standard ML |
exception Found of string ;
val divisors = fn n =>
let
val rec divr = fn ( c, divlist ,i) =>
if c <2*i then c::divlist
else divr (if c mod i = 0 then (c,i::divlist,i+1) else (c,divlist,i+1) )
in
divr (n,[],1)
end;
val subsetSums = fn M => fn input =>
let
val getnrs = fn (v,x) => (* out: list of numbers index where v is true + x *)
let
val rec runthr = fn (v,i,x,lst)=> if i>=M then (v,i,x,lst) else runthr (v,i+1,x,if Vector.sub(v,i) then (i+x)::lst else lst) ;
in
#4 (runthr (v,0,x,[]))
end;
val nwVec = fn (v,nrs) =>
let
val rec upd = fn (v,i,[]) => (v,i,[])
| (v,i,h::t) => upd ( case Int.compare (h,M) of
LESS => ( Vector.update (v,h,true),i+1,t)
| GREATER => (v,i+1,t)
| EQUAL => raise Found ("done "^(Int.toString h)) )
in
#1 (upd (v,0,nrs))
end;
val rec setSums = fn ([],v) => ([],v)
| (x::t,v) => setSums(t, nwVec(v, getnrs (v,x)))
in
#2 (setSums (input,Vector.tabulate (M+1,fn 0=> true|_=>false) ))
end;
val rec Zumkeller = fn n =>
let
val d = divisors n;
val s = List.foldr op+ 0 d ;
val hs = s div 2 -n ;
in
if s mod 2 = 1 orelse 0 > hs then false else
Vector.sub ( subsetSums hs (tl d) ,hs) handle Found nr => true
end;
|
http://rosettacode.org/wiki/Zumkeller_numbers | Zumkeller numbers | Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that the two partition sums are equal.
E.G.
6 is a Zumkeller number; The divisors {1 2 3 6} can be partitioned into two groups {1 2 3} and {6} that both sum to 6.
10 is not a Zumkeller number; The divisors {1 2 5 10} can not be partitioned into two groups in any way that will both sum to the same value.
12 is a Zumkeller number; The divisors {1 2 3 4 6 12} can be partitioned into two groups {1 3 4 6} and {2 12} that both sum to 14.
Even Zumkeller numbers are common; odd Zumkeller numbers are much less so. For values below 10^6, there is at least one Zumkeller number in every 12 consecutive integers, and the vast majority of them are even. The odd Zumkeller numbers are very similar to the list from the task Abundant odd numbers; they are nearly the same except for the further restriction that the abundance (A(n) = sigma(n) - 2n), must be even: A(n) mod 2 == 0
Task
Write a routine (function, procedure, whatever) to find Zumkeller numbers.
Use the routine to find and display here, on this page, the first 220 Zumkeller numbers.
Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers.
Optional, stretch goal: Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers that don't end with 5.
See Also
OEIS:A083207 - Zumkeller numbers to get an impression of different partitions OEIS:A083206 Zumkeller partitions
OEIS:A174865 - Odd Zumkeller numbers
Related Tasks
Abundant odd numbers
Abundant, deficient and perfect number classifications
Proper divisors , Factors of an integer | #Swift | Swift | import Foundation
extension BinaryInteger {
@inlinable
public var isZumkeller: Bool {
let divs = factors(sorted: false)
let sum = divs.reduce(0, +)
guard sum & 1 != 1 else {
return false
}
guard self & 1 != 1 else {
let abundance = sum - 2*self
return abundance > 0 && abundance & 1 == 0
}
return isPartSum(divs: divs[...], sum: sum / 2)
}
@inlinable
public func factors(sorted: Bool = true) -> [Self] {
let maxN = Self(Double(self).squareRoot())
var res = Set<Self>()
for factor in stride(from: 1, through: maxN, by: 1) where self % factor == 0 {
res.insert(factor)
res.insert(self / factor)
}
return sorted ? res.sorted() : Array(res)
}
}
@usableFromInline
func isPartSum<T: BinaryInteger>(divs: ArraySlice<T>, sum: T) -> Bool {
guard sum != 0 else {
return true
}
guard !divs.isEmpty else {
return false
}
let last = divs.last!
if last > sum {
return isPartSum(divs: divs.dropLast(), sum: sum)
}
return isPartSum(divs: divs.dropLast(), sum: sum) || isPartSum(divs: divs.dropLast(), sum: sum - last)
}
let zums = (2...).lazy.filter({ $0.isZumkeller })
let oddZums = zums.filter({ $0 & 1 == 1 })
let oddZumsWithout5 = oddZums.filter({ String($0).last! != "5" })
print("First 220 zumkeller numbers are \(Array(zums.prefix(220)))")
print("First 40 odd zumkeller numbers are \(Array(oddZums.prefix(40)))")
print("First 40 odd zumkeller numbers that don't end in a 5 are: \(Array(oddZumsWithout5.prefix(40)))") |
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included) | Arbitrary-precision integers (included) | Using the in-built capabilities of your language, calculate the integer value of:
5
4
3
2
{\displaystyle 5^{4^{3^{2}}}}
Confirm that the first and last twenty digits of the answer are:
62060698786608744707...92256259918212890625
Find and show the number of decimal digits in the answer.
Note: Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead.
Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value.
Related tasks
Long multiplication
Exponentiation order
exponentiation operator
Exponentiation with infix operators in (or operating on) the base
| #Golfscript | Golfscript | 5 4 3 2??? # Calculate 5^(4^(3^2))
`.. # Convert to string and make two copies
20<p # Print the first 20 digits
-20>p # Print the last 20 digits
,p # Print the length |
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included) | Arbitrary-precision integers (included) | Using the in-built capabilities of your language, calculate the integer value of:
5
4
3
2
{\displaystyle 5^{4^{3^{2}}}}
Confirm that the first and last twenty digits of the answer are:
62060698786608744707...92256259918212890625
Find and show the number of decimal digits in the answer.
Note: Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead.
Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value.
Related tasks
Long multiplication
Exponentiation order
exponentiation operator
Exponentiation with infix operators in (or operating on) the base
| #Groovy | Groovy | def bigNumber = 5G ** (4 ** (3 ** 2)) |
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included) | Arbitrary-precision integers (included) | Using the in-built capabilities of your language, calculate the integer value of:
5
4
3
2
{\displaystyle 5^{4^{3^{2}}}}
Confirm that the first and last twenty digits of the answer are:
62060698786608744707...92256259918212890625
Find and show the number of decimal digits in the answer.
Note: Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead.
Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value.
Related tasks
Long multiplication
Exponentiation order
exponentiation operator
Exponentiation with infix operators in (or operating on) the base
| #Haskell | Haskell | main :: IO ()
main = do
let y = show (5 ^ 4 ^ 3 ^ 2)
let l = length y
putStrLn
("5**4**3**2 = " ++
take 20 y ++ "..." ++ drop (l - 20) y ++ " and has " ++ show l ++ " digits") |
http://rosettacode.org/wiki/Zhang-Suen_thinning_algorithm | Zhang-Suen thinning algorithm | This is an algorithm used to thin a black and white i.e. one bit per pixel images.
For example, with an input image of:
################# #############
################## ################
################### ##################
######## ####### ###################
###### ####### ####### ######
###### ####### #######
################# #######
################ #######
################# #######
###### ####### #######
###### ####### #######
###### ####### ####### ######
######## ####### ###################
######## ####### ###### ################## ######
######## ####### ###### ################ ######
######## ####### ###### ############# ######
It produces the thinned output:
# ########## #######
## # #### #
# # ##
# # #
# # #
# # #
############ #
# # #
# # #
# # #
# # #
# ##
# ############
### ###
Algorithm
Assume black pixels are one and white pixels zero, and that the input image is a rectangular N by M array of ones and zeroes.
The algorithm operates on all black pixels P1 that can have eight neighbours.
The neighbours are, in order, arranged as:
P9 P2 P3
P8 P1 P4
P7 P6 P5
Obviously the boundary pixels of the image cannot have the full eight neighbours.
Define
A
(
P
1
)
{\displaystyle A(P1)}
= the number of transitions from white to black, (0 -> 1) in the sequence P2,P3,P4,P5,P6,P7,P8,P9,P2. (Note the extra P2 at the end - it is circular).
Define
B
(
P
1
)
{\displaystyle B(P1)}
= The number of black pixel neighbours of P1. ( = sum(P2 .. P9) )
Step 1
All pixels are tested and pixels satisfying all the following conditions (simultaneously) are just noted at this stage.
(0) The pixel is black and has eight neighbours
(1)
2
<=
B
(
P
1
)
<=
6
{\displaystyle 2<=B(P1)<=6}
(2) A(P1) = 1
(3) At least one of P2 and P4 and P6 is white
(4) At least one of P4 and P6 and P8 is white
After iterating over the image and collecting all the pixels satisfying all step 1 conditions, all these condition satisfying pixels are set to white.
Step 2
All pixels are again tested and pixels satisfying all the following conditions are just noted at this stage.
(0) The pixel is black and has eight neighbours
(1)
2
<=
B
(
P
1
)
<=
6
{\displaystyle 2<=B(P1)<=6}
(2) A(P1) = 1
(3) At least one of P2 and P4 and P8 is white
(4) At least one of P2 and P6 and P8 is white
After iterating over the image and collecting all the pixels satisfying all step 2 conditions, all these condition satisfying pixels are again set to white.
Iteration
If any pixels were set in this round of either step 1 or step 2 then all steps are repeated until no image pixels are so changed.
Task
Write a routine to perform Zhang-Suen thinning on an image matrix of ones and zeroes.
Use the routine to thin the following image and show the output here on this page as either a matrix of ones and zeroes, an image, or an ASCII-art image of space/non-space characters.
00000000000000000000000000000000
01111111110000000111111110000000
01110001111000001111001111000000
01110000111000001110000111000000
01110001111000001110000000000000
01111111110000001110000000000000
01110111100000001110000111000000
01110011110011101111001111011100
01110001111011100111111110011100
00000000000000000000000000000000
Reference
Zhang-Suen Thinning Algorithm, Java Implementation by Nayef Reza.
"Character Recognition Systems: A Guide for Students and Practitioners" By Mohamed Cheriet, Nawwaf Kharma, Cheng-Lin Liu, Ching Suen
| #Swift | Swift | import UIKit
// testing examples
let beforeTxt = """
1100111
1100111
1100111
1100111
1100110
1100110
1100110
1100110
1100110
1100110
1100110
1100110
1111110
0000000
"""
let smallrc01 = """
00000000000000000000000000000000
01111111110000000111111110000000
01110001111000001111001111000000
01110000111000001110000111000000
01110001111000001110000000000000
01111111110000001110000000000000
01110111100000001110000111000000
01110011110011101111001111011100
01110001111011100111111110011100
00000000000000000000000000000000
"""
let rc01 = """
00000000000000000000000000000000000000000000000000000000000
01111111111111111100000000000000000001111111111111000000000
01111111111111111110000000000000001111111111111111000000000
01111111111111111111000000000000111111111111111111000000000
01111111100000111111100000000001111111111111111111000000000
00011111100000111111100000000011111110000000111111000000000
00011111100000111111100000000111111100000000000000000000000
00011111111111111111000000000111111100000000000000000000000
00011111111111111110000000000111111100000000000000000000000
00011111111111111111000000000111111100000000000000000000000
00011111100000111111100000000111111100000000000000000000000
00011111100000111111100000000111111100000000000000000000000
00011111100000111111100000000011111110000000111111000000000
01111111100000111111100000000001111111111111111111000000000
01111111100000111111101111110000111111111111111111011111100
01111111100000111111101111110000001111111111111111011111100
01111111100000111111101111110000000001111111111111011111100
00000000000000000000000000000000000000000000000000000000000
"""
// Zhang-Suen thinning algorithm in Swift
/// function to thin the image
func zhangSuen(image: inout [[Int]]) -> [[Int]] {
// array of x, y position where need to changed to be white
var changing1, changing2: [(Int, Int)]
repeat {
// set to empty array
changing1 = []
changing2 = []
// Step 1
// loop through row of image
for y in 1..<image.count-1 {
// loop through column of image
for x in 1..<image[0].count-1 {
// get neighbours of P1
var nb = neighbours(x: x, y: y, image: image)
// set P2, P4, P6, P8 from neighbours
let P2 = nb[0], P4 = nb[2], P6 = nb[4], P8 = nb[6]
// reference: https://www.hackingwithswift.com/example-code/language/how-to-sum-an-array-of-numbers-using-reduce
// reference: https://www.hackingwithswift.com/articles/90/how-to-check-whether-a-value-is-inside-a-range
if (image[y][x] == 1 && // Condision 0
(2...6).contains(nb.reduce(0, +)) && // Condision 1
transitions(neighbours: &nb) == 1 && // Condision 2
P2 * P4 * P6 == 0 && // Condision 3
P4 * P6 * P8 == 0 // Condision 4
) {
// add to step1 changing1 list
changing1.append((x,y))
}
}
}
// loop through step1 changing1 list and change to white
for (x, y) in changing1 {
image[y][x] = 0
}
// Step 2
// loop through row of image
for y in 1..<image.count-1 {
// loop through column of image
for x in 1..<image[0].count-1 {
// get neighbours of P1
var nb = neighbours(x: x, y: y, image: image)
// set P2, P4, P6, P8 from neighbours
let P2 = nb[0], P4 = nb[2], P6 = nb[4], P8 = nb[6]
if (image[y][x] == 1 && // Condision 0
(2...6).contains(nb.reduce(0, +)) && // Condision 1
transitions(neighbours: &nb) == 1 && // Condision 2
P2 * P4 * P8 == 0 && // Condision 3
P2 * P6 * P8 == 0 // Condision 4
) {
// add to step2 changing2 list
changing2.append((x,y))
}
}
}
// loop through step2 changing2 list and change to white
for (x, y) in changing2 {
image[y][x] = 0
}
// finish loop when there's no more place to change to white, when changing1, changing2 are empty
} while !changing1.isEmpty && !changing2.isEmpty
// return updated image
return image
}
/// function to convert multiline string of 1/0 into 2D Int array
func intarray(binstring: String) -> [[Int]] {
// reference: https://stackoverflow.com/questions/28611336/how-to-convert-a-string-numeric-in-a-int-array-in-swift
// map through each char of input String to convert to Int
return binstring.split(separator: "\n").map {$0.compactMap{$0.wholeNumberValue}}
}
/// function to convert 2D Int array of 1/0 into multiline String of ‘#’ and ‘.’
func toTxt(intmatrix: [[Int]]) -> String {
// map through each array of parent array and
// map through element of child array and convert to '#' when 1 and to '.' when 0
return intmatrix.map {$0.map { $0 == 1 ? "#" : "."}.joined(separator: "")}.joined(separator: "\n")
}
/// function to get neighbours of P1 = [P2,P3,P4,P5,P6,P7,P8,P9]
func neighbours(x: Int, y: Int, image: [[Int]]) -> [Int] {
let i = image
// set x, y positions of P1 neighbours
let x1 = x+1, y1 = y-1, x_1 = x-1, y_1 = y+1
// return neighbours of P1
return [i[y1][x], i[y1][x1], i[y][x1], i[y_1][x1], // P2,P3,P4,P5
i[y_1][x], i[y_1][x_1], i[y][x_1], i[y1][x_1]] // P6,P7,P8,P9
}
/// function to get the number of transitions from white to black, (0 -> 1) in the sequence P2,P3,P4,P5,P6,P7,P8,P9,P2.
func transitions(neighbours: inout [Int]) -> Int {
// add P2 at the end of neighbours array
let n = neighbours + [neighbours[0]]
var result = 0
// reference: https://www.marcosantadev.com/arrayslice-in-swift/
// compare between each element of neightbour and next element of the element to check if the transition is 0 -> 1
for (n1, n2) in zip(n, n.suffix(n.count - 1)) {
// if the pattern matches, increament result to 1
if (n1, n2) == (0, 1) { result += 1 }
}
// return number of transitions from 0 to 1
return result
}
// run testing
// array of test examples
let testCases: [String] = [beforeTxt, smallrc01, rc01]
for picture in testCases {
// convert string to 2D Int array
var image = intarray(binstring: picture)
// print the result
print("\nFrom:\n\(toTxt(intmatrix: image))")
// run through Zhang-Suen thinning algorithm
let after = zhangSuen(image: &image)
// print the result
print("\nTo thinned:\n\(toTxt(intmatrix: after))")
} |
http://rosettacode.org/wiki/Zeckendorf_number_representation | Zeckendorf number representation | Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series.
Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13.
The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100.
10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that no two consecutive Fibonacci numbers can be used which leads to the former unique solution.
Task
Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order.
The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task.
Also see
OEIS A014417 for the the sequence of required results.
Brown's Criterion - Numberphile
Related task
Fibonacci sequence
| #jq | jq | def zeckendorf:
def fibs($n):
# input: [f(i-2), f(i-1)]
[1,1] | [recurse(select(.[1] < $n) | [.[1], add]) | .[1]] ;
# Emit an array of 0s and 1s corresponding to the Zeckendorf encoding
# $f should be the relevant Fibonacci numbers in increasing order.
def loop($f):
[ recurse(. as [$n, $ix]
| select( $ix > -1 )
| $f[$ix] as $next
| if $n >= $next
then [$n - $next, $ix-1, 1]
else [$n, $ix-1, 0]
end )
| .[2] // empty ]
# remove any superfluous leading 0:
# remove leading 0 if any unless length==1
| if length>1 and .[0] == 0 then .[1:] else . end ;
# state: [$n, index_in_fibs, digit ]
fibs(.) as $f
| [., ($f|length)-1]
| loop($f)
| join("") ; |
http://rosettacode.org/wiki/Zeckendorf_number_representation | Zeckendorf number representation | Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series.
Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13.
The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100.
10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that no two consecutive Fibonacci numbers can be used which leads to the former unique solution.
Task
Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order.
The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task.
Also see
OEIS A014417 for the the sequence of required results.
Brown's Criterion - Numberphile
Related task
Fibonacci sequence
| #Julia | Julia | function zeck(n)
n <= 0 && return 0
fib = [2,1]; while fib[1] < n unshift!(fib,sum(fib[1:2])) end
dig = Int[]; for f in fib f <= n ? (push!(dig,1); n = n-f;) : push!(dig,0) end
return dig[1] == 0 ? dig[2:end] : dig
end |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #CLU | CLU | start_up = proc ()
max = 100
po: stream := stream$primary_output()
open: array[bool] := array[bool]$fill(1, max, false)
for pass: int in int$from_to(1, max) do
for door: int in int$from_to_by(pass, max, pass) do
open[door] := ~open[door]
end
end
for door: int in array[bool]$indexes(open) do
if open[door] then
stream$putl(po, "Door " || int$unparse(door) || " is open.")
end
end
end start_up |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #FreeBASIC | FreeBASIC | ' compile with: FBC -s console.
' compile with: FBC -s console -exx to have boundary checks.
Dim As Integer a(5) ' from s(0) to s(5)
Dim As Integer num = 1
Dim As String s(-num To num) ' s1(-1), s1(0) and s1(1)
Static As UByte c(5) ' create a array with 6 elements (0 to 5)
'dimension array and initializing it with Data
Dim d(1 To 2, 1 To 5) As Integer => {{1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}}
Print " The first dimension has a lower bound of"; LBound(d);_
" and a upper bound of"; UBound(d)
Print " The second dimension has a lower bound of"; LBound(d,2);_
" and a upper bound of"; UBound(d,2)
Print : Print
Dim Shared As UByte u(0 To 3) ' make a shared array of UByte with 4 elements
Dim As UInteger pow() ' make a variable length array
' you must Dim the array before you can use ReDim
ReDim pow(num) ' pow now has 1 element
pow(num) = 10 ' lets fill it with 10 and print it
Print " The value of pow(num) = "; pow(num)
ReDim pow(10) ' make pow a 10 element array
Print
Print " Pow now has"; UBound(pow) - LBound(pow) +1; " elements"
' the value of pow(num) is gone now
Print " The value of pow(num) = "; pow(num); ", should be 0"
Print
For i As Integer = LBound(pow) To UBound(pow)
pow(i) = i * i
Print pow(i),
Next
Print:Print
ReDim Preserve pow(3 To 7)
' the first five elements will be preserved, not elements 3 to 7
Print
Print " The lower bound is now"; LBound(pow);_
" and the upper bound is"; UBound(pow)
Print " Pow now has"; UBound(pow) - LBound(pow) +1; " elements"
Print
For i As Integer = LBound(pow) To UBound(pow)
Print pow(i),
Next
Print : Print
'erase the variable length array
Erase pow
Print " The lower bound is now"; LBound(pow);_
" and the upper bound is "; UBound(pow)
Print " If the lower bound is 0 and the upper bound is -1 it means,"
Print " that the array has no elements, it's completely removed"
Print : Print
'erase the fixed length array
Print " Display the contents of the array d"
For i As Integer = 1 To 2 : For j As Integer = 1 To 5
Print d(i,j);" ";
Next : Next : Print : Print
Erase d
Print " We have erased array d"
Print " The first dimension has a lower bound of"; LBound(d);_
" and a upper bound of"; UBound(d)
Print " The second dimension has a lower bound of"; LBound(d,2);_
" and a upper bound of"; UBound(d,2)
Print
For i As Integer = 1 To 2 : For j As Integer = 1 To 5
Print d(i,j);" ";
Next : Next
Print
Print " The elements self are left untouched but there content is set to 0"
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End |
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part", where the imaginary part is the number to be multiplied by
i
{\displaystyle i}
.
Task
Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.)
Print the results for each operation tested.
Optional: Show complex conjugation.
By definition, the complex conjugate of
a
+
b
i
{\displaystyle a+bi}
is
a
−
b
i
{\displaystyle a-bi}
Some languages have complex number libraries available. If your language does, show the operations. If your language does not, also show the definition of this type.
| #Ruby | Ruby |
# Four ways to write complex numbers:
a = Complex(1, 1) # 1. call Kernel#Complex
i = Complex::I # 2. use Complex::I
b = 3.14159 + 1.25 * i
c = '1/2+3/4i'.to_c # 3. Use the .to_c method from String, result ((1/2)+(3/4)*i)
c = 1.0/2+3/4i # (0.5-(3/4)*i)
# Operations:
puts a + b # addition
puts a * b # multiplication
puts -a # negation
puts 1.quo a # multiplicative inverse
puts a.conjugate # complex conjugate
puts a.conj # alias for complex conjugate |
http://rosettacode.org/wiki/Arithmetic/Rational | Arithmetic/Rational | Task
Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language.
Example
Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number).
Further define the appropriate rational unary operators abs and '-', with the binary operators for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠').
Define standard coercion operators for casting int to frac etc.
If space allows, define standard increment and decrement operators (e.g. '+:=' & '-:=' etc.).
Finally test the operators:
Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors.
Related task
Perfect Numbers
| #Swift | Swift | import Foundation
extension BinaryInteger {
@inlinable
public func gcd(with other: Self) -> Self {
var gcd = self
var b = other
while b != 0 {
(gcd, b) = (b, gcd % b)
}
return gcd
}
@inlinable
public func lcm(with other: Self) -> Self {
let g = gcd(with: other)
return self / g * other
}
}
public struct Frac<NumType: BinaryInteger & SignedNumeric>: Equatable {
@usableFromInline
var _num: NumType
@usableFromInline
var _dom: NumType
@usableFromInline
init(_num: NumType, _dom: NumType) {
self._num = _num
self._dom = _dom
}
@inlinable
public init(numerator: NumType, denominator: NumType) {
let divisor = numerator.gcd(with: denominator)
self._num = numerator / divisor
self._dom = denominator / divisor
}
@inlinable
public static func + (lhs: Frac, rhs: Frac) -> Frac {
let multiplier = lhs._dom.lcm(with: rhs.denominator)
return Frac(
numerator: lhs._num * multiplier / lhs._dom + rhs._num * multiplier / rhs._dom,
denominator: multiplier
)
}
@inlinable
public static func += (lhs: inout Frac, rhs: Frac) {
lhs = lhs + rhs
}
@inlinable
public static func - (lhs: Frac, rhs: Frac) -> Frac {
return lhs + -rhs
}
@inlinable
public static func -= (lhs: inout Frac, rhs: Frac) {
lhs = lhs + -rhs
}
@inlinable
public static func * (lhs: Frac, rhs: Frac) -> Frac {
return Frac(numerator: lhs._num * rhs._num, denominator: lhs._dom * rhs._dom)
}
@inlinable
public static func *= (lhs: inout Frac, rhs: Frac) {
lhs = lhs * rhs
}
@inlinable
public static func / (lhs: Frac, rhs: Frac) -> Frac {
return lhs * Frac(_num: rhs._dom, _dom: rhs._num)
}
@inlinable
public static func /= (lhs: inout Frac, rhs: Frac) {
lhs = lhs / rhs
}
@inlinable
prefix static func - (rhs: Frac) -> Frac {
return Frac(_num: -rhs._num, _dom: rhs._dom)
}
}
extension Frac {
@inlinable
public var numerator: NumType {
get { _num }
set {
let divisor = newValue.gcd(with: denominator)
_num = newValue / divisor
_dom = denominator / divisor
}
}
@inlinable
public var denominator: NumType {
get { _dom }
set {
let divisor = newValue.gcd(with: numerator)
_num = numerator / divisor
_dom = newValue / divisor
}
}
}
extension Frac: CustomStringConvertible {
public var description: String {
let neg = numerator < 0 || denominator < 0
return "Frac(\(neg ? "-" : "")\(abs(numerator)) / \(abs(denominator)))"
}
}
extension Frac: Comparable {
@inlinable
public static func <(lhs: Frac, rhs: Frac) -> Bool {
return lhs._num * rhs._dom < lhs._dom * rhs._num
}
}
extension Frac: ExpressibleByIntegerLiteral {
public init(integerLiteral value: Int) {
self._num = NumType(value)
self._dom = 1
}
}
for candidate in 2..<1<<19 {
var sum = Frac(numerator: 1, denominator: candidate)
let m = Int(ceil(Double(candidate).squareRoot()))
for factor in 2..<m where candidate % factor == 0 {
sum += Frac(numerator: 1, denominator: factor)
sum += Frac(numerator: 1, denominator: candidate / factor)
}
if sum == 1 {
print("\(candidate) is perfect")
}
} |
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, you may also try something like:
x = 0
y = 0
z = x**y
say 'z=' z
Show the result here.
And of course use any symbols or notation that is supported in your computer programming language for exponentiation.
See also
The Wiki entry: Zero to the power of zero.
The Wiki entry: History of differing points of view.
The MathWorld™ entry: exponent laws.
Also, in the above MathWorld™ entry, see formula (9):
x
0
=
1
{\displaystyle x^{0}=1}
.
The OEIS entry: The special case of zero to the zeroth power
| #min | min | 0 0 pow puts |
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, you may also try something like:
x = 0
y = 0
z = x**y
say 'z=' z
Show the result here.
And of course use any symbols or notation that is supported in your computer programming language for exponentiation.
See also
The Wiki entry: Zero to the power of zero.
The Wiki entry: History of differing points of view.
The MathWorld™ entry: exponent laws.
Also, in the above MathWorld™ entry, see formula (9):
x
0
=
1
{\displaystyle x^{0}=1}
.
The OEIS entry: The special case of zero to the zeroth power
| #MiniScript | MiniScript | print "The result of zero to the zero power is " + 0^0 |
http://rosettacode.org/wiki/Zebra_puzzle | Zebra puzzle | Zebra puzzle
You are encouraged to solve this task according to the task description, using any language you may know.
The Zebra puzzle, a.k.a. Einstein's Riddle,
is a logic puzzle which is to be solved programmatically.
It has several variants, one of them this:
There are five houses.
The English man lives in the red house.
The Swede has a dog.
The Dane drinks tea.
The green house is immediately to the left of the white house.
They drink coffee in the green house.
The man who smokes Pall Mall has birds.
In the yellow house they smoke Dunhill.
In the middle house they drink milk.
The Norwegian lives in the first house.
The man who smokes Blend lives in the house next to the house with cats.
In a house next to the house where they have a horse, they smoke Dunhill.
The man who smokes Blue Master drinks beer.
The German smokes Prince.
The Norwegian lives next to the blue house.
They drink water in a house next to the house where they smoke Blend.
The question is, who owns the zebra?
Additionally, list the solution for all the houses.
Optionally, show the solution is unique.
Related tasks
Dinesman's multiple-dwelling problem
Twelve statements
| #C | C | #include <stdio.h>
#include <string.h>
enum HouseStatus { Invalid, Underfull, Valid };
enum Attrib { C, M, D, A, S };
// Unfilled attributes are represented by -1
enum Colors { Red, Green, White, Yellow, Blue };
enum Mans { English, Swede, Dane, German, Norwegian };
enum Drinks { Tea, Coffee, Milk, Beer, Water };
enum Animals { Dog, Birds, Cats, Horse, Zebra };
enum Smokes { PallMall, Dunhill, Blend, BlueMaster, Prince };
void printHouses(int ha[5][5]) {
const char *color[] = { "Red", "Green", "White", "Yellow", "Blue" };
const char *man[] = { "English", "Swede", "Dane", "German", "Norwegian" };
const char *drink[] = { "Tea", "Coffee", "Milk", "Beer", "Water" };
const char *animal[] = { "Dog", "Birds", "Cats", "Horse", "Zebra" };
const char *smoke[] = { "PallMall", "Dunhill", "Blend", "BlueMaster", "Prince" };
printf("%-10.10s%-10.10s%-10.10s%-10.10s%-10.10s%-10.10s\n",
"House", "Color", "Man", "Drink", "Animal", "Smoke");
for (int i = 0; i < 5; i++) {
printf("%-10d", i);
if (ha[i][C] >= 0)
printf("%-10.10s", color[ha[i][C]]);
else
printf("%-10.10s", "-");
if (ha[i][M] >= 0)
printf("%-10.10s", man[ha[i][M]]);
else
printf("%-10.10s", "-");
if (ha[i][D] >= 0)
printf("%-10.10s", drink[ha[i][D]]);
else
printf("%-10.10s", "-");
if (ha[i][A] >= 0)
printf("%-10.10s", animal[ha[i][A]]);
else
printf("%-10.10s", "-");
if (ha[i][S] >= 0)
printf("%-10.10s\n", smoke[ha[i][S]]);
else
printf("-\n");
}
}
int checkHouses(int ha[5][5]) {
int c_add = 0, c_or = 0;
int m_add = 0, m_or = 0;
int d_add = 0, d_or = 0;
int a_add = 0, a_or = 0;
int s_add = 0, s_or = 0;
// Cond 9: In the middle house they drink milk.
if (ha[2][D] >= 0 && ha[2][D] != Milk)
return Invalid;
// Cond 10: The Norwegian lives in the first house.
if (ha[0][M] >= 0 && ha[0][M] != Norwegian)
return Invalid;
for (int i = 0; i < 5; i++) {
// Uniqueness tests.
if (ha[i][C] >= 0) {
c_add += (1 << ha[i][C]);
c_or |= (1 << ha[i][C]);
}
if (ha[i][M] >= 0) {
m_add += (1 << ha[i][M]);
m_or |= (1 << ha[i][M]);
}
if (ha[i][D] >= 0) {
d_add += (1 << ha[i][D]);
d_or |= (1 << ha[i][D]);
}
if (ha[i][A] >= 0) {
a_add += (1 << ha[i][A]);
a_or |= (1 << ha[i][A]);
}
if (ha[i][S] >= 0) {
s_add += (1 << ha[i][S]);
s_or |= (1 << ha[i][S]);
}
// Cond 2: The English man lives in the red house.
if ((ha[i][M] >= 0 && ha[i][C] >= 0) &&
((ha[i][M] == English && ha[i][C] != Red) || // Checking both
(ha[i][M] != English && ha[i][C] == Red))) // to make things quicker.
return Invalid;
// Cond 3: The Swede has a dog.
if ((ha[i][M] >= 0 && ha[i][A] >= 0) &&
((ha[i][M] == Swede && ha[i][A] != Dog) ||
(ha[i][M] != Swede && ha[i][A] == Dog)))
return Invalid;
// Cond 4: The Dane drinks tea.
if ((ha[i][M] >= 0 && ha[i][D] >= 0) &&
((ha[i][M] == Dane && ha[i][D] != Tea) ||
(ha[i][M] != Dane && ha[i][D] == Tea)))
return Invalid;
// Cond 5: The green house is immediately to the left of the white house.
if ((i > 0 && ha[i][C] >= 0 /*&& ha[i-1][C] >= 0 */ ) &&
((ha[i - 1][C] == Green && ha[i][C] != White) ||
(ha[i - 1][C] != Green && ha[i][C] == White)))
return Invalid;
// Cond 6: drink coffee in the green house.
if ((ha[i][C] >= 0 && ha[i][D] >= 0) &&
((ha[i][C] == Green && ha[i][D] != Coffee) ||
(ha[i][C] != Green && ha[i][D] == Coffee)))
return Invalid;
// Cond 7: The man who smokes Pall Mall has birds.
if ((ha[i][S] >= 0 && ha[i][A] >= 0) &&
((ha[i][S] == PallMall && ha[i][A] != Birds) ||
(ha[i][S] != PallMall && ha[i][A] == Birds)))
return Invalid;
// Cond 8: In the yellow house they smoke Dunhill.
if ((ha[i][S] >= 0 && ha[i][C] >= 0) &&
((ha[i][S] == Dunhill && ha[i][C] != Yellow) ||
(ha[i][S] != Dunhill && ha[i][C] == Yellow)))
return Invalid;
// Cond 11: The man who smokes Blend lives in the house next to the house with cats.
if (ha[i][S] == Blend) {
if (i == 0 && ha[i + 1][A] >= 0 && ha[i + 1][A] != Cats)
return Invalid;
else if (i == 4 && ha[i - 1][A] != Cats)
return Invalid;
else if (ha[i + 1][A] >= 0 && ha[i + 1][A] != Cats && ha[i - 1][A] != Cats)
return Invalid;
}
// Cond 12: In a house next to the house where they have a horse, they smoke Dunhill.
if (ha[i][S] == Dunhill) {
if (i == 0 && ha[i + 1][A] >= 0 && ha[i + 1][A] != Horse)
return Invalid;
else if (i == 4 && ha[i - 1][A] != Horse)
return Invalid;
else if (ha[i + 1][A] >= 0 && ha[i + 1][A] != Horse && ha[i - 1][A] != Horse)
return Invalid;
}
// Cond 13: The man who smokes Blue Master drinks beer.
if ((ha[i][S] >= 0 && ha[i][D] >= 0) &&
((ha[i][S] == BlueMaster && ha[i][D] != Beer) ||
(ha[i][S] != BlueMaster && ha[i][D] == Beer)))
return Invalid;
// Cond 14: The German smokes Prince
if ((ha[i][M] >= 0 && ha[i][S] >= 0) &&
((ha[i][M] == German && ha[i][S] != Prince) ||
(ha[i][M] != German && ha[i][S] == Prince)))
return Invalid;
// Cond 15: The Norwegian lives next to the blue house.
if (ha[i][M] == Norwegian &&
((i < 4 && ha[i + 1][C] >= 0 && ha[i + 1][C] != Blue) ||
(i > 0 && ha[i - 1][C] != Blue)))
return Invalid;
// Cond 16: They drink water in a house next to the house where they smoke Blend.
if (ha[i][S] == Blend) {
if (i == 0 && ha[i + 1][D] >= 0 && ha[i + 1][D] != Water)
return Invalid;
else if (i == 4 && ha[i - 1][D] != Water)
return Invalid;
else if (ha[i + 1][D] >= 0 && ha[i + 1][D] != Water && ha[i - 1][D] != Water)
return Invalid;
}
}
if ((c_add != c_or) || (m_add != m_or) || (d_add != d_or)
|| (a_add != a_or) || (s_add != s_or)) {
return Invalid;
}
if ((c_add != 0b11111) || (m_add != 0b11111) || (d_add != 0b11111)
|| (a_add != 0b11111) || (s_add != 0b11111)) {
return Underfull;
}
return Valid;
}
int bruteFill(int ha[5][5], int hno, int attr) {
int stat = checkHouses(ha);
if ((stat == Valid) || (stat == Invalid))
return stat;
int hb[5][5];
memcpy(hb, ha, sizeof(int) * 5 * 5);
for (int i = 0; i < 5; i++) {
hb[hno][attr] = i;
stat = checkHouses(hb);
if (stat != Invalid) {
int nexthno, nextattr;
if (attr < 4) {
nextattr = attr + 1;
nexthno = hno;
} else {
nextattr = 0;
nexthno = hno + 1;
}
stat = bruteFill(hb, nexthno, nextattr);
if (stat != Invalid) {
memcpy(ha, hb, sizeof(int) * 5 * 5);
return stat;
}
}
}
// We only come here if none of the attr values assigned were valid.
return Invalid;
}
int main() {
int ha[5][5] = {{-1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1}};
bruteFill(ha, 0, 0);
printHouses(ha);
return 0;
} |
http://rosettacode.org/wiki/XML/XPath | XML/XPath | Perform the following three XPath queries on the XML Document below:
//item[1]: Retrieve the first "item" element
//price/text(): Perform an action on each "price" element (print it out)
//name: Get an array of all the "name" elements
XML Document:
<inventory title="OmniCorp Store #45x10^3">
<section name="health">
<item upc="123456789" stock="12">
<name>Invisibility Cream</name>
<price>14.50</price>
<description>Makes you invisible</description>
</item>
<item upc="445322344" stock="18">
<name>Levitation Salve</name>
<price>23.99</price>
<description>Levitate yourself for up to 3 hours per application</description>
</item>
</section>
<section name="food">
<item upc="485672034" stock="653">
<name>Blork and Freen Instameal</name>
<price>4.95</price>
<description>A tasty meal in a tablet; just add water</description>
</item>
<item upc="132957764" stock="44">
<name>Grob winglets</name>
<price>3.56</price>
<description>Tender winglets of Grob. Just add water</description>
</item>
</section>
</inventory>
| #C.23 | C# | XmlReader XReader;
// Either read the xml from a string ...
XReader = XmlReader.Create(new StringReader("<inventory title=... </inventory>"));
// ... or read it from the file system.
XReader = XmlReader.Create("xmlfile.xml");
// Create a XPathDocument object (which implements the IXPathNavigable interface)
// which is optimized for XPath operation. (very fast).
IXPathNavigable XDocument = new XPathDocument(XReader);
// Create a Navigator to navigate through the document.
XPathNavigator Nav = XDocument.CreateNavigator();
Nav = Nav.SelectSingleNode("//item");
// Move to the first element of the selection. (if available).
if(Nav.MoveToFirst())
{
Console.WriteLine(Nav.OuterXml); // The outer xml of the first item element.
}
// Get an iterator to loop over multiple selected nodes.
XPathNodeIterator Iterator = XDocument.CreateNavigator().Select("//price");
while (Iterator.MoveNext())
{
Console.WriteLine(Iterator.Current.Value);
}
Iterator = XDocument.CreateNavigator().Select("//name");
// Use a generic list.
List<string> NodesValues = new List<string>();
while (Iterator.MoveNext())
{
NodesValues.Add(Iterator.Current.Value);
}
// Convert the generic list to an array and output the count of items.
Console.WriteLine(NodesValues.ToArray().Length); |
http://rosettacode.org/wiki/Yin_and_yang | Yin and yang | One well-known symbol of the philosophy of duality known as yin and yang is the taijitu.
Task
Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.
Generate and display the symbol for two different (small) sizes.
| #AWK | AWK |
# syntax: GAWK -f YIN_AND_YANG.AWK
# converted from PHL
BEGIN {
yin_and_yang(16)
yin_and_yang(8)
exit(0)
}
function yin_and_yang(radius, black,white,scale_x,scale_y,sx,sy,x,y) {
black = "#"
white = "."
scale_x = 2
scale_y = 1
for (sy = radius*scale_y; sy >= -(radius*scale_y); sy--) {
for (sx = -(radius*scale_x); sx <= radius*scale_x; sx++) {
x = sx / scale_x
y = sy / scale_y
if (in_big_circle(radius,x,y)) {
if (in_white_semi_circle(radius,x,y)) {
printf("%s",(in_small_black_circle(radius,x,y)) ? black : white)
}
else if (in_black_semi_circle(radius,x,y)) {
printf("%s",(in_small_white_circle(radius,x,y)) ? white : black)
}
else {
printf("%s",(x<0) ? white : black)
}
}
else {
printf(" ")
}
}
printf("\n")
}
}
function in_circle(center_x,center_y,radius,x,y) {
return (x-center_x)*(x-center_x)+(y-center_y)*(y-center_y) <= radius*radius
}
function in_big_circle(radius,x,y) {
return in_circle(0,0,radius,x,y)
}
function in_black_semi_circle(radius,x,y) {
return in_circle(0,0-radius/2,radius/2,x,y)
}
function in_white_semi_circle(radius,x,y) {
return in_circle(0,radius/2,radius/2,x,y)
}
function in_small_black_circle(radius,x,y) {
return in_circle(0,radius/2,radius/6,x,y)
}
function in_small_white_circle(radius,x,y) {
return in_circle(0,0-radius/2,radius/6,x,y)
}
|
http://rosettacode.org/wiki/Y_combinator | Y combinator | In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions.
This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function.
The Y combinator is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function.
The Y combinator is the simplest of the class of such functions, called fixed-point combinators.
Task
Define the stateless Y combinator and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions.
Cf
Jim Weirich: Adventures in Functional Programming
| #C | C | #include <stdio.h>
#include <stdlib.h>
/* func: our one and only data type; it holds either a pointer to
a function call, or an integer. Also carry a func pointer to
a potential parameter, to simulate closure */
typedef struct func_t *func;
typedef struct func_t {
func (*fn) (func, func);
func _;
int num;
} func_t;
func new(func(*f)(func, func), func _) {
func x = malloc(sizeof(func_t));
x->fn = f;
x->_ = _; /* closure, sort of */
x->num = 0;
return x;
}
func call(func f, func n) {
return f->fn(f, n);
}
func Y(func(*f)(func, func)) {
func g = new(f, 0);
g->_ = g;
return g;
}
func num(int n) {
func x = new(0, 0);
x->num = n;
return x;
}
func fac(func self, func n) {
int nn = n->num;
return nn > 1 ? num(nn * call(self->_, num(nn - 1))->num)
: num(1);
}
func fib(func self, func n) {
int nn = n->num;
return nn > 1
? num( call(self->_, num(nn - 1))->num +
call(self->_, num(nn - 2))->num )
: num(1);
}
void show(func n) { printf(" %d", n->num); }
int main() {
int i;
func f = Y(fac);
printf("fac: ");
for (i = 1; i < 10; i++)
show( call(f, num(i)) );
printf("\n");
f = Y(fib);
printf("fib: ");
for (i = 1; i < 10; i++)
show( call(f, num(i)) );
printf("\n");
return 0;
}
|
http://rosettacode.org/wiki/Zig-zag_matrix | Zig-zag matrix | Task
Produce a zig-zag array.
A zig-zag array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you zig-zag along the array's anti-diagonals.
For a graphical representation, see JPG zigzag (JPG uses such arrays to encode images).
For example, given 5, produce this array:
0 1 5 6 14
2 4 7 13 15
3 8 12 16 21
9 11 17 20 22
10 18 19 23 24
Related tasks
Spiral matrix
Identity matrix
Ulam spiral (for primes)
See also
Wiktionary entry: anti-diagonals
| #BBC_BASIC | BBC BASIC | Size% = 5
DIM array%(Size%-1,Size%-1)
i% = 1
j% = 1
FOR e% = 0 TO Size%^2-1
array%(i%-1,j%-1) = e%
IF ((i% + j%) AND 1) = 0 THEN
IF j% < Size% j% += 1 ELSE i% += 2
IF i% > 1 i% -= 1
ELSE
IF i% < Size% i% += 1 ELSE j% += 2
IF j% > 1 j% -= 1
ENDIF
NEXT
@% = &904
FOR row% = 0 TO Size%-1
FOR col% = 0 TO Size%-1
PRINT array%(row%,col%);
NEXT
PRINT
NEXT row% |
http://rosettacode.org/wiki/Yellowstone_sequence | Yellowstone sequence | The Yellowstone sequence, also called the Yellowstone permutation, is defined as:
For n <= 3,
a(n) = n
For n >= 4,
a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and
is not relatively prime to a(n-2).
The sequence is a permutation of the natural numbers, and gets its name from what its authors felt was a spiking, geyser like appearance of a plot of the sequence.
Example
a(4) is 4 because 4 is the smallest number following 1, 2, 3 in the sequence that is relatively prime to the entry before it (3), and is not relatively prime to the number two entries before it (2).
Task
Find and show as output the first 30 Yellowstone numbers.
Extra
Demonstrate how to plot, with x = n and y coordinate a(n), the first 100 Yellowstone numbers.
Related tasks
Greatest common divisor.
Plot coordinate pairs.
See also
The OEIS entry: A098550 The Yellowstone permutation.
Applegate et al, 2015: The Yellowstone Permutation [1].
| #Lua | Lua | function gcd(a, b)
if b == 0 then
return a
end
return gcd(b, a % b)
end
function printArray(a)
io.write('[')
for i,v in pairs(a) do
if i > 1 then
io.write(', ')
end
io.write(v)
end
io.write(']')
return nil
end
function removeAt(a, i)
local na = {}
for j,v in pairs(a) do
if j ~= i then
table.insert(na, v)
end
end
return na
end
function yellowstone(sequenceCount)
local yellow = {1, 2, 3}
local num = 4
local notYellow = {}
local yellowSize = 3
while yellowSize < sequenceCount do
local found = -1
for i,test in pairs(notYellow) do
if gcd(yellow[yellowSize - 1], test) > 1 and gcd(yellow[yellowSize - 0], test) == 1 then
found = i
break
end
end
if found >= 0 then
table.insert(yellow, notYellow[found])
notYellow = removeAt(notYellow, found)
yellowSize = yellowSize + 1
else
while true do
if gcd(yellow[yellowSize - 1], num) > 1 and gcd(yellow[yellowSize - 0], num) == 1 then
table.insert(yellow, num)
yellowSize = yellowSize + 1
num = num + 1
break
end
table.insert(notYellow, num)
num = num + 1
end
end
end
return yellow
end
function main()
print("First 30 values in the yellowstone sequence:")
printArray(yellowstone(30))
print()
end
main() |
http://rosettacode.org/wiki/Yahoo!_search_interface | Yahoo! search interface | Create a class for searching Yahoo! results.
It must implement a Next Page method, and read URL, Title and Content from results.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Manipulate[
Column[Flatten[
StringCases[
StringCases[
URLFetch[
"http://search.yahoo.com/search?p=" <> query <> "&b=" <>
ToString@page], "<ol" ~~ ___ ~~ "</ol>"],
"<a" ~~ Shortest[__] ~~ "class=\"yschttl spt\" href=\"" ~~
Shortest[url__] ~~ "\"" ~~ Shortest[__] ~~ ">" ~~
Shortest[title__] ~~
"<div class=\"abstr\">" | "<div class=\"sm-abs\">" ~~
Shortest[abstr__] ~~ "</div>" :>
Column[{Hyperlink[Style[#[[1]], Larger], #[[2]]], #[[3]],
Style[#[[2]], Smaller]} &@
StringReplace[{title, url,
abstr}, {"<" ~~ Shortest[__] ~~ ">" -> "",
"&#" ~~ n : DigitCharacter ... ~~ ";" :>
FromCharacterCode[FromDigits@n], "&" -> "&",
""" -> "\"", "<" -> "<", ">" -> ">"}]]], 1],
Spacings -> 2], {{input, "", "Yahoo!"},
InputField[Dynamic@input, String] &}, {{query, ""},
ControlType -> None}, {{page, 1}, ControlType -> None},
Row[{Button["Search", page = 1; query = input],
Button["Prev", page -= 10, Enabled -> Dynamic[page >= 10]],
Button["Next", page += 10]}]] |
http://rosettacode.org/wiki/Yahoo!_search_interface | Yahoo! search interface | Create a class for searching Yahoo! results.
It must implement a Next Page method, and read URL, Title and Content from results.
| #Nim | Nim | import httpclient, strutils, htmlparser, xmltree, strtabs
const
PageSize = 7
YahooURLPattern = "https://search.yahoo.com/search?fr=opensearch&b=$$#&pz=$#&p=".format(PageSize)
type
SearchResult = ref object
url, title, content: string
SearchInterface = ref object
client: HttpClient
urlPattern: string
page: int
results: array[PageSize+2, SearchResult]
proc newSearchInterface(question: string): SearchInterface =
new result
result.client = newHttpClient()
# result.client = newHttpClient(proxy = newProxy(
# "http://localhost:40001")) # only http_proxy supported
result.urlPattern = YahooURLPattern&question
proc search(si: SearchInterface) =
let html = parseHtml(si.client.getContent(si.urlPattern.format(
si.page*PageSize+1)))
var
i: int
attrs: XmlAttributes
for d in html.findAll("div"):
attrs = d.attrs
if attrs != nil and attrs.getOrDefault("class").startsWith("dd algo algo-sr relsrch"):
let d_inner = d.child("div")
for a in d_inner.findAll("a"):
attrs = a.attrs
if attrs != nil and attrs.getOrDefault("class") == " ac-algo fz-l ac-21th lh-24":
si.results[i] = SearchResult(url: attrs["href"], title: a.innerText,
content: d.findAll("p")[0].innerText)
i+=1
break
while i < len(si.results) and si.results[i] != nil:
si.results[i] = nil
i+=1
proc nextPage(si: SearchInterface) =
si.page+=1
si.search()
proc echoResult(si: SearchInterface) =
for res in si.results:
if res == nil:
break
echo(res[])
var searchInf = newSearchInterface("weather")
searchInf.search()
searchInf.echoResult()
echo("searching for next page...")
searchInf.nextPage()
searchInf.echoResult()
|
http://rosettacode.org/wiki/Zumkeller_numbers | Zumkeller numbers | Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that the two partition sums are equal.
E.G.
6 is a Zumkeller number; The divisors {1 2 3 6} can be partitioned into two groups {1 2 3} and {6} that both sum to 6.
10 is not a Zumkeller number; The divisors {1 2 5 10} can not be partitioned into two groups in any way that will both sum to the same value.
12 is a Zumkeller number; The divisors {1 2 3 4 6 12} can be partitioned into two groups {1 3 4 6} and {2 12} that both sum to 14.
Even Zumkeller numbers are common; odd Zumkeller numbers are much less so. For values below 10^6, there is at least one Zumkeller number in every 12 consecutive integers, and the vast majority of them are even. The odd Zumkeller numbers are very similar to the list from the task Abundant odd numbers; they are nearly the same except for the further restriction that the abundance (A(n) = sigma(n) - 2n), must be even: A(n) mod 2 == 0
Task
Write a routine (function, procedure, whatever) to find Zumkeller numbers.
Use the routine to find and display here, on this page, the first 220 Zumkeller numbers.
Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers.
Optional, stretch goal: Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers that don't end with 5.
See Also
OEIS:A083207 - Zumkeller numbers to get an impression of different partitions OEIS:A083206 Zumkeller partitions
OEIS:A174865 - Odd Zumkeller numbers
Related Tasks
Abundant odd numbers
Abundant, deficient and perfect number classifications
Proper divisors , Factors of an integer | #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Function GetDivisors(n As Integer) As List(Of Integer)
Dim divs As New List(Of Integer) From {
1, n
}
Dim i = 2
While i * i <= n
If n Mod i = 0 Then
Dim j = n \ i
divs.Add(i)
If i <> j Then
divs.Add(j)
End If
End If
i += 1
End While
Return divs
End Function
Function IsPartSum(divs As List(Of Integer), sum As Integer) As Boolean
If sum = 0 Then
Return True
End If
Dim le = divs.Count
If le = 0 Then
Return False
End If
Dim last = divs(le - 1)
Dim newDivs As New List(Of Integer)
For i = 1 To le - 1
newDivs.Add(divs(i - 1))
Next
If last > sum Then
Return IsPartSum(newDivs, sum)
End If
Return IsPartSum(newDivs, sum) OrElse IsPartSum(newDivs, sum - last)
End Function
Function IsZumkeller(n As Integer) As Boolean
Dim divs = GetDivisors(n)
Dim sum = divs.Sum()
REM if sum is odd can't be split into two partitions with equal sums
If sum Mod 2 = 1 Then
Return False
End If
REM if n is odd use 'abundant odd number' optimization
If n Mod 2 = 1 Then
Dim abundance = sum - 2 * n
Return abundance > 0 AndAlso abundance Mod 2 = 0
End If
REM if n and sum are both even check if there's a partition which totals sum / 2
Return IsPartSum(divs, sum \ 2)
End Function
Sub Main()
Console.WriteLine("The first 220 Zumkeller numbers are:")
Dim i = 2
Dim count = 0
While count < 220
If IsZumkeller(i) Then
Console.Write("{0,3} ", i)
count += 1
If count Mod 20 = 0 Then
Console.WriteLine()
End If
End If
i += 1
End While
Console.WriteLine()
Console.WriteLine("The first 40 odd Zumkeller numbers are:")
i = 3
count = 0
While count < 40
If IsZumkeller(i) Then
Console.Write("{0,5} ", i)
count += 1
If count Mod 10 = 0 Then
Console.WriteLine()
End If
End If
i += 2
End While
Console.WriteLine()
Console.WriteLine("The first 40 odd Zumkeller numbers which don't end in 5 are:")
i = 3
count = 0
While count < 40
If i Mod 10 <> 5 AndAlso IsZumkeller(i) Then
Console.Write("{0,7} ", i)
count += 1
If count Mod 8 = 0 Then
Console.WriteLine()
End If
End If
i += 2
End While
End Sub
End Module |
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included) | Arbitrary-precision integers (included) | Using the in-built capabilities of your language, calculate the integer value of:
5
4
3
2
{\displaystyle 5^{4^{3^{2}}}}
Confirm that the first and last twenty digits of the answer are:
62060698786608744707...92256259918212890625
Find and show the number of decimal digits in the answer.
Note: Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead.
Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value.
Related tasks
Long multiplication
Exponentiation order
exponentiation operator
Exponentiation with infix operators in (or operating on) the base
| #Hoon | Hoon |
=+ big=(pow 5 (pow 4 (pow 3 2)))
=+ digits=(lent (skip <big> |=(a/* ?:(=(a '.') & |))))
[digits (div big (pow 10 (sub digits 20))) (mod big (pow 10 20))]
|
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included) | Arbitrary-precision integers (included) | Using the in-built capabilities of your language, calculate the integer value of:
5
4
3
2
{\displaystyle 5^{4^{3^{2}}}}
Confirm that the first and last twenty digits of the answer are:
62060698786608744707...92256259918212890625
Find and show the number of decimal digits in the answer.
Note: Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead.
Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value.
Related tasks
Long multiplication
Exponentiation order
exponentiation operator
Exponentiation with infix operators in (or operating on) the base
| #Icon_and_Unicon | Icon and Unicon | procedure main()
x := 5^4^3^2
write("done with computation")
x := string(x)
write("5 ^ 4 ^ 3 ^ 2 has ",*x," digits")
write("The first twenty digits are ",x[1+:20])
write("The last twenty digits are ",x[0-:20])
end |
http://rosettacode.org/wiki/Zhang-Suen_thinning_algorithm | Zhang-Suen thinning algorithm | This is an algorithm used to thin a black and white i.e. one bit per pixel images.
For example, with an input image of:
################# #############
################## ################
################### ##################
######## ####### ###################
###### ####### ####### ######
###### ####### #######
################# #######
################ #######
################# #######
###### ####### #######
###### ####### #######
###### ####### ####### ######
######## ####### ###################
######## ####### ###### ################## ######
######## ####### ###### ################ ######
######## ####### ###### ############# ######
It produces the thinned output:
# ########## #######
## # #### #
# # ##
# # #
# # #
# # #
############ #
# # #
# # #
# # #
# # #
# ##
# ############
### ###
Algorithm
Assume black pixels are one and white pixels zero, and that the input image is a rectangular N by M array of ones and zeroes.
The algorithm operates on all black pixels P1 that can have eight neighbours.
The neighbours are, in order, arranged as:
P9 P2 P3
P8 P1 P4
P7 P6 P5
Obviously the boundary pixels of the image cannot have the full eight neighbours.
Define
A
(
P
1
)
{\displaystyle A(P1)}
= the number of transitions from white to black, (0 -> 1) in the sequence P2,P3,P4,P5,P6,P7,P8,P9,P2. (Note the extra P2 at the end - it is circular).
Define
B
(
P
1
)
{\displaystyle B(P1)}
= The number of black pixel neighbours of P1. ( = sum(P2 .. P9) )
Step 1
All pixels are tested and pixels satisfying all the following conditions (simultaneously) are just noted at this stage.
(0) The pixel is black and has eight neighbours
(1)
2
<=
B
(
P
1
)
<=
6
{\displaystyle 2<=B(P1)<=6}
(2) A(P1) = 1
(3) At least one of P2 and P4 and P6 is white
(4) At least one of P4 and P6 and P8 is white
After iterating over the image and collecting all the pixels satisfying all step 1 conditions, all these condition satisfying pixels are set to white.
Step 2
All pixels are again tested and pixels satisfying all the following conditions are just noted at this stage.
(0) The pixel is black and has eight neighbours
(1)
2
<=
B
(
P
1
)
<=
6
{\displaystyle 2<=B(P1)<=6}
(2) A(P1) = 1
(3) At least one of P2 and P4 and P8 is white
(4) At least one of P2 and P6 and P8 is white
After iterating over the image and collecting all the pixels satisfying all step 2 conditions, all these condition satisfying pixels are again set to white.
Iteration
If any pixels were set in this round of either step 1 or step 2 then all steps are repeated until no image pixels are so changed.
Task
Write a routine to perform Zhang-Suen thinning on an image matrix of ones and zeroes.
Use the routine to thin the following image and show the output here on this page as either a matrix of ones and zeroes, an image, or an ASCII-art image of space/non-space characters.
00000000000000000000000000000000
01111111110000000111111110000000
01110001111000001111001111000000
01110000111000001110000111000000
01110001111000001110000000000000
01111111110000001110000000000000
01110111100000001110000111000000
01110011110011101111001111011100
01110001111011100111111110011100
00000000000000000000000000000000
Reference
Zhang-Suen Thinning Algorithm, Java Implementation by Nayef Reza.
"Character Recognition Systems: A Guide for Students and Practitioners" By Mohamed Cheriet, Nawwaf Kharma, Cheng-Lin Liu, Ching Suen
| #Tcl | Tcl | # -*- coding: utf-8 -*-
set data {
00000000000000000000000000000000
01111111110000000111111110000000
01110001111000001111001111000000
01110000111000001110000111000000
01110001111000001110000000000000
01111111110000001110000000000000
01110111100000001110000111000000
01110011110011101111001111011100
01110001111011100111111110011100
00000000000000000000000000000000
}
proc zhang-suen data {
set data [string trim $data]
while 1 {
set n 0
incr n [step 1 data]
incr n [step 2 data]
if !$n break
}
return $data
}
proc step {number _data} {
upvar 1 $_data data
set xmax [string length [lindex $data 0]]
set ymax [llength $data]
switch -- $number {
1 {set cond {(!$P2 || !$P4 || !$P6) && (!$P4 || !$P6 || !$P8)}}
2 {set cond {(!$P2 || !$P4 || !$P8) && (!$P2 || !$P6 || !$P8)}}
}
set hits {}
for {set x 1} {$x < $xmax-1} {incr x} {
for {set y 1} {$y < $ymax-1} {incr y} {
if {[getpix $data $x $y] == 1} {
set b [B $data $x $y]
if {2 <= $b && $b <= 6} {
if {[A $data $x $y] == 1} {
set P2 [getpix $data $x [expr $y-1]]
set P4 [getpix $data [expr $x+1] $y]
set P6 [getpix $data $x [expr $y+1]]
set P8 [getpix $data [expr $x-1] $y]
if $cond {lappend hits $x $y}
}
}
}
}
}
foreach {x y} $hits {set data [setpix $data $x $y 0]}
return [llength $hits]
}
proc A {data x y} {
set res 0
set last [getpix $data $x [expr $y-1]]
foreach {dx dy} {1 -1 1 0 1 1 0 1 -1 1 -1 0 -1 -1 0 -1} {
set this [getpix $data [expr $x+$dx] [expr $y+$dy]]
if {$this > $last} {incr res}
set last $this
}
return $res
}
proc B {data x y} {
set res 0
foreach {dx dy} {1 -1 1 0 1 1 0 1 -1 1 -1 0 -1 -1 0 -1} {
incr res [getpix $data [expr $x+$dx] [expr $y+$dy]]
}
return $res
}
proc getpix {data x y} {
string index [lindex $data $y] $x
}
proc setpix {data x y val} {
set row [lindex $data $y]
lset data $y [string replace $row $x $x $val]
return $data
}
puts [string map {1 @ 0 .} [join [zhang-suen $data] \n]] |
http://rosettacode.org/wiki/Zeckendorf_number_representation | Zeckendorf number representation | Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series.
Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13.
The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100.
10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that no two consecutive Fibonacci numbers can be used which leads to the former unique solution.
Task
Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order.
The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task.
Also see
OEIS A014417 for the the sequence of required results.
Brown's Criterion - Numberphile
Related task
Fibonacci sequence
| #Klingphix | Klingphix | include ..\Utilitys.tlhy
:listos
%i$ "" !i$
len [ get tostr $i$ chain !i$ ] for drop
$i$
;
:Zeckendorf %n !n
%i 0 !i %c 0 !c
[
$i 8 itob listos
"11" find not (
[ ( $c ":" 9 tochar ) lprint tonum ? $c 1 + !c ]
[drop]
) if
$i 1 + !i
]
[$c $n >] until
;
20 Zeckendorf
nl "End " input |
http://rosettacode.org/wiki/Zeckendorf_number_representation | Zeckendorf number representation | Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series.
Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13.
The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100.
10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that no two consecutive Fibonacci numbers can be used which leads to the former unique solution.
Task
Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order.
The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task.
Also see
OEIS A014417 for the the sequence of required results.
Brown's Criterion - Numberphile
Related task
Fibonacci sequence
| #Kotlin | Kotlin | // version 1.0.6
const val LIMIT = 46 // to stay within range of signed 32 bit integer
val fibs = fibonacci(LIMIT)
fun fibonacci(n: Int): IntArray {
if (n !in 2..LIMIT) throw IllegalArgumentException("n must be between 2 and $LIMIT")
val fibs = IntArray(n)
fibs[0] = 1
fibs[1] = 1
for (i in 2 until n) fibs[i] = fibs[i - 1] + fibs[i - 2]
return fibs
}
fun zeckendorf(n: Int): String {
if (n < 0) throw IllegalArgumentException("n must be non-negative")
if (n < 2) return n.toString()
var lastFibIndex = 1
for (i in 2..LIMIT)
if (fibs[i] > n) {
lastFibIndex = i - 1
break
}
var nn = n - fibs[lastFibIndex--]
val zr = StringBuilder("1")
for (i in lastFibIndex downTo 1)
if (fibs[i] <= nn) {
zr.append('1')
nn -= fibs[i]
} else {
zr.append('0')
}
return zr.toString()
}
fun main(args: Array<String>) {
println(" n z")
for (i in 0..20) println("${"%2d".format(i)} : ${zeckendorf(i)}")
} |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. 100Doors.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Current-n PIC 9(3).
01 StepSize PIC 9(3).
01 DoorTable.
02 Doors PIC 9(1) OCCURS 100 TIMES.
88 ClosedDoor VALUE ZERO.
01 Idx PIC 9(3).
PROCEDURE DIVISION.
Begin.
INITIALIZE DoorTable
PERFORM VARYING StepSize FROM 1 BY 1 UNTIL StepSize > 100
PERFORM VARYING Current-n FROM StepSize BY StepSize
UNTIL Current-n > 100
SUBTRACT Doors (Current-n) FROM 1 GIVING Doors (Current-n)
END-PERFORM
END-PERFORM
PERFORM VARYING Idx FROM 1 BY 1
UNTIL Idx > 100
IF ClosedDoor (Idx)
DISPLAY Idx " is closed."
ELSE
DISPLAY Idx " is open."
END-IF
END-PERFORM
STOP RUN
. |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #Frink | Frink |
a = new array
a@0 = 10
a@1 = 20
println[a@1]
b = [1, 2, 3]
|
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part", where the imaginary part is the number to be multiplied by
i
{\displaystyle i}
.
Task
Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.)
Print the results for each operation tested.
Optional: Show complex conjugation.
By definition, the complex conjugate of
a
+
b
i
{\displaystyle a+bi}
is
a
−
b
i
{\displaystyle a-bi}
Some languages have complex number libraries available. If your language does, show the operations. If your language does not, also show the definition of this type.
| #Rust | Rust | extern crate num;
use num::complex::Complex;
fn main() {
// two valid forms of definition
let a = Complex {re:-4.0, im: 5.0};
let b = Complex::new(1.0, 1.0);
println!(" a = {}", a);
println!(" b = {}", b);
println!(" a + b = {}", a + b);
println!(" a * b = {}", a * b);
println!(" 1 / a = {}", a.inv());
println!(" -a = {}", -a);
println!("conj(a) = {}", a.conj());
} |
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part", where the imaginary part is the number to be multiplied by
i
{\displaystyle i}
.
Task
Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.)
Print the results for each operation tested.
Optional: Show complex conjugation.
By definition, the complex conjugate of
a
+
b
i
{\displaystyle a+bi}
is
a
−
b
i
{\displaystyle a-bi}
Some languages have complex number libraries available. If your language does, show the operations. If your language does not, also show the definition of this type.
| #Scala | Scala | package org.rosettacode
package object ArithmeticComplex {
val i = Complex(0, 1)
implicit def fromDouble(d: Double) = Complex(d)
implicit def fromInt(i: Int) = Complex(i.toDouble)
}
package ArithmeticComplex {
case class Complex(real: Double = 0.0, imag: Double = 0.0) {
def this(s: String) =
this("[\\d.]+(?!i)".r findFirstIn s getOrElse "0" toDouble,
"[\\d.]+(?=i)".r findFirstIn s getOrElse "0" toDouble)
def +(b: Complex) = Complex(real + b.real, imag + b.imag)
def -(b: Complex) = Complex(real - b.real, imag - b.imag)
def *(b: Complex) = Complex(real * b.real - imag * b.imag, real * b.imag + imag * b.real)
def inverse = {
val denom = real * real + imag * imag
Complex(real / denom, -imag / denom)
}
def /(b: Complex) = this * b.inverse
def unary_- = Complex(-real, -imag)
lazy val abs = math.hypot(real, imag)
override def toString = real + " + " + imag + "i"
def i = { require(imag == 0.0); Complex(imag = real) }
}
object Complex {
def apply(s: String) = new Complex(s)
def fromPolar(rho:Double, theta:Double) = Complex(rho*math.cos(theta), rho*math.sin(theta))
}
} |
http://rosettacode.org/wiki/Arithmetic/Rational | Arithmetic/Rational | Task
Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language.
Example
Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number).
Further define the appropriate rational unary operators abs and '-', with the binary operators for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠').
Define standard coercion operators for casting int to frac etc.
If space allows, define standard increment and decrement operators (e.g. '+:=' & '-:=' etc.).
Finally test the operators:
Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors.
Related task
Perfect Numbers
| #Tcl | Tcl | namespace eval rat {}
proc rat::new {args} {
if {[llength $args] == 0} {
set args {0}
}
lassign [split {*}$args] n d
if {$d == 0} {
error "divide by zero"
}
if {$d < 0} {
set n [expr {-1 * $n}]
set d [expr {abs($d)}]
}
return [normalize $n $d]
}
proc rat::split {args} {
if {[llength $args] == 1} {
lassign [::split $args /] n d
if {$d eq ""} {
set d 1
}
} else {
lassign $args n d
}
return [list $n $d]
}
proc rat::join {rat} {
lassign $rat n d
if {$n == 0} {
return 0
} elseif {$d == 1} {
return $n
} else {
return $n/$d
}
}
proc rat::normalize {n d} {
set gcd [gcd $n $d]
return [join [list [expr {$n/$gcd}] [expr {$d/$gcd}]]]
}
proc rat::gcd {a b} {
while {$b != 0} {
lassign [list $b [expr {$a % $b}]] a b
}
return $a
}
proc rat::abs {rat} {
lassign [split $rat] n d
return [join [list [expr {abs($n)}] $d]]
}
proc rat::inv {rat} {
lassign [split $rat] n d
return [normalize $d $n]
}
proc rat::+ {args} {
set n 0
set d 1
foreach arg $args {
lassign [split $arg] an ad
set n [expr {$n*$ad + $an*$d}]
set d [expr {$d * $ad}]
}
return [normalize $n $d]
}
proc rat::- {args} {
lassign [split [lindex $args 0]] n d
if {[llength $args] == 1} {
return [join [list [expr {-1 * $n}] $d]]
}
foreach arg [lrange $args 1 end] {
lassign [split $arg] an ad
set n [expr {$n*$ad - $an*$d}]
set d [expr {$d * $ad}]
}
return [normalize $n $d]
}
proc rat::* {args} {
set n 1
set d 1
foreach arg $args {
lassign [split $arg] an ad
set n [expr {$n * $an}]
set d [expr {$d * $ad}]
}
return [normalize $n $d]
}
proc rat::/ {a b} {
set r [* $a [inv $b]]
if {[string match */0 $r]} {
error "divide by zero"
}
return $r
}
proc rat::== {a b} {
return [expr {[- $a $b] == 0}]
}
proc rat::!= {a b} {
return [expr { ! [== $a $b]}]
}
proc rat::< {a b} {
lassign [split [- $a $b]] n d
return [expr {$n < 0}]
}
proc rat::> {a b} {
lassign [split [- $a $b]] n d
return [expr {$n > 0}]
}
proc rat::<= {a b} {
return [expr { ! [> $a $b]}]
}
proc rat::>= {a b} {
return [expr { ! [< $a $b]}]
}
################################################
proc is_perfect {num} {
set sum [rat::new 0]
foreach factor [all_factors $num] {
set sum [rat::+ $sum [rat::new 1/$factor]]
}
# note, all_factors includes 1, so sum should be 2
return [rat::== $sum 2]
}
proc get_perfect_numbers {} {
set t [clock seconds]
set limit [expr 2**19]
for {set num 2} {$num < $limit} {incr num} {
if {[is_perfect $num]} {
puts "perfect: $num"
}
}
puts "elapsed: [expr {[clock seconds] - $t}] seconds"
set num [expr {2**12 * (2**13 - 1)}] ;# 5th perfect number
if {[is_perfect $num]} {
puts "perfect: $num"
}
}
source primes.tcl
get_perfect_numbers |
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, you may also try something like:
x = 0
y = 0
z = x**y
say 'z=' z
Show the result here.
And of course use any symbols or notation that is supported in your computer programming language for exponentiation.
See also
The Wiki entry: Zero to the power of zero.
The Wiki entry: History of differing points of view.
The MathWorld™ entry: exponent laws.
Also, in the above MathWorld™ entry, see formula (9):
x
0
=
1
{\displaystyle x^{0}=1}
.
The OEIS entry: The special case of zero to the zeroth power
| #.D0.9C.D0.9A-61.2F52 | МК-61/52 | Сx ^ x^y С/П |
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, you may also try something like:
x = 0
y = 0
z = x**y
say 'z=' z
Show the result here.
And of course use any symbols or notation that is supported in your computer programming language for exponentiation.
See also
The Wiki entry: Zero to the power of zero.
The Wiki entry: History of differing points of view.
The MathWorld™ entry: exponent laws.
Also, in the above MathWorld™ entry, see formula (9):
x
0
=
1
{\displaystyle x^{0}=1}
.
The OEIS entry: The special case of zero to the zeroth power
| #Nanoquery | Nanoquery | println 0^0 |
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, you may also try something like:
x = 0
y = 0
z = x**y
say 'z=' z
Show the result here.
And of course use any symbols or notation that is supported in your computer programming language for exponentiation.
See also
The Wiki entry: Zero to the power of zero.
The Wiki entry: History of differing points of view.
The MathWorld™ entry: exponent laws.
Also, in the above MathWorld™ entry, see formula (9):
x
0
=
1
{\displaystyle x^{0}=1}
.
The OEIS entry: The special case of zero to the zeroth power
| #Neko | Neko | /**
Zero to the zeroth power, in Neko
*/
var math_pow = $loader.loadprim("std@math_pow", 2)
$print(math_pow(0, 0), "\n") |
http://rosettacode.org/wiki/Zebra_puzzle | Zebra puzzle | Zebra puzzle
You are encouraged to solve this task according to the task description, using any language you may know.
The Zebra puzzle, a.k.a. Einstein's Riddle,
is a logic puzzle which is to be solved programmatically.
It has several variants, one of them this:
There are five houses.
The English man lives in the red house.
The Swede has a dog.
The Dane drinks tea.
The green house is immediately to the left of the white house.
They drink coffee in the green house.
The man who smokes Pall Mall has birds.
In the yellow house they smoke Dunhill.
In the middle house they drink milk.
The Norwegian lives in the first house.
The man who smokes Blend lives in the house next to the house with cats.
In a house next to the house where they have a horse, they smoke Dunhill.
The man who smokes Blue Master drinks beer.
The German smokes Prince.
The Norwegian lives next to the blue house.
They drink water in a house next to the house where they smoke Blend.
The question is, who owns the zebra?
Additionally, list the solution for all the houses.
Optionally, show the solution is unique.
Related tasks
Dinesman's multiple-dwelling problem
Twelve statements
| #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using static System.Console;
public enum Colour { Red, Green, White, Yellow, Blue }
public enum Nationality { Englishman, Swede, Dane, Norwegian,German }
public enum Pet { Dog, Birds, Cats, Horse, Zebra }
public enum Drink { Coffee, Tea, Milk, Beer, Water }
public enum Smoke { PallMall, Dunhill, Blend, BlueMaster, Prince}
public static class ZebraPuzzle
{
private static (Colour[] colours, Drink[] drinks, Smoke[] smokes, Pet[] pets, Nationality[] nations) _solved;
static ZebraPuzzle()
{
var solve = from colours in Permute<Colour>() //r1 5 range
where (colours,Colour.White).IsRightOf(colours, Colour.Green) // r5
from nations in Permute<Nationality>()
where nations[0] == Nationality.Norwegian // r10
where (nations, Nationality.Englishman).IsSameIndex(colours, Colour.Red) //r2
where (nations,Nationality.Norwegian).IsNextTo(colours,Colour.Blue) // r15
from drinks in Permute<Drink>()
where drinks[2] == Drink.Milk //r9
where (drinks, Drink.Coffee).IsSameIndex(colours, Colour.Green) // r6
where (drinks, Drink.Tea).IsSameIndex(nations, Nationality.Dane) //r4
from pets in Permute<Pet>()
where (pets, Pet.Dog).IsSameIndex(nations, Nationality.Swede) // r3
from smokes in Permute<Smoke>()
where (smokes, Smoke.PallMall).IsSameIndex(pets, Pet.Birds) // r7
where (smokes, Smoke.Dunhill).IsSameIndex(colours, Colour.Yellow) // r8
where (smokes, Smoke.Blend).IsNextTo(pets, Pet.Cats) // r11
where (smokes, Smoke.Dunhill).IsNextTo(pets, Pet.Horse) //r12
where (smokes, Smoke.BlueMaster).IsSameIndex(drinks, Drink.Beer) //r13
where (smokes, Smoke.Prince).IsSameIndex(nations, Nationality.German) // r14
where (drinks,Drink.Water).IsNextTo(smokes,Smoke.Blend) // r16
select (colours, drinks, smokes, pets, nations);
_solved = solve.First();
}
private static int IndexOf<T>(this T[] arr, T obj) => Array.IndexOf(arr, obj);
private static bool IsRightOf<T, U>(this (T[] a, T v) right, U[] a, U v) => right.a.IndexOf(right.v) == a.IndexOf(v) + 1;
private static bool IsSameIndex<T, U>(this (T[] a, T v)x, U[] a, U v) => x.a.IndexOf(x.v) == a.IndexOf(v);
private static bool IsNextTo<T, U>(this (T[] a, T v)x, U[] a, U v) => (x.a,x.v).IsRightOf(a, v) || (a,v).IsRightOf(x.a,x.v);
// made more generic from https://codereview.stackexchange.com/questions/91808/permutations-in-c
public static IEnumerable<IEnumerable<T>> Permutations<T>(this IEnumerable<T> values)
{
if (values.Count() == 1)
return values.ToSingleton();
return values.SelectMany(v => Permutations(values.Except(v.ToSingleton())),(v, p) => p.Prepend(v));
}
public static IEnumerable<T[]> Permute<T>() => ToEnumerable<T>().Permutations().Select(p=>p.ToArray());
private static IEnumerable<T> ToSingleton<T>(this T item){ yield return item; }
private static IEnumerable<T> ToEnumerable<T>() => Enum.GetValues(typeof(T)).Cast<T>();
public static new String ToString()
{
var sb = new StringBuilder();
sb.AppendLine("House Colour Drink Nationality Smokes Pet");
sb.AppendLine("───── ────── ──────── ─────────── ────────── ─────");
var (colours, drinks, smokes, pets, nations) = _solved;
for (var i = 0; i < 5; i++)
sb.AppendLine($"{i+1,5} {colours[i],-6} {drinks[i],-8} {nations[i],-11} {smokes[i],-10} {pets[i],-10}");
return sb.ToString();
}
public static void Main(string[] arguments)
{
var owner = _solved.nations[_solved.pets.IndexOf(Pet.Zebra)];
WriteLine($"The zebra owner is {owner}");
Write(ToString());
Read();
}
} |
http://rosettacode.org/wiki/XML/XPath | XML/XPath | Perform the following three XPath queries on the XML Document below:
//item[1]: Retrieve the first "item" element
//price/text(): Perform an action on each "price" element (print it out)
//name: Get an array of all the "name" elements
XML Document:
<inventory title="OmniCorp Store #45x10^3">
<section name="health">
<item upc="123456789" stock="12">
<name>Invisibility Cream</name>
<price>14.50</price>
<description>Makes you invisible</description>
</item>
<item upc="445322344" stock="18">
<name>Levitation Salve</name>
<price>23.99</price>
<description>Levitate yourself for up to 3 hours per application</description>
</item>
</section>
<section name="food">
<item upc="485672034" stock="653">
<name>Blork and Freen Instameal</name>
<price>4.95</price>
<description>A tasty meal in a tablet; just add water</description>
</item>
<item upc="132957764" stock="44">
<name>Grob winglets</name>
<price>3.56</price>
<description>Tender winglets of Grob. Just add water</description>
</item>
</section>
</inventory>
| #C.2B.2B | C++ | #include <cassert>
#include <cstdlib>
#include <iostream>
#include <stdexcept>
#include <utility>
#include <vector>
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xmlerror.h>
#include <libxml/xmlstring.h>
#include <libxml/xmlversion.h>
#include <libxml/xpath.h>
#ifndef LIBXML_XPATH_ENABLED
# error libxml was not configured with XPath support
#endif
// Because libxml2 is a C library, we need a couple things to make it work
// well with modern C++:
// 1) a ScopeGuard-like type to handle cleanup functions; and
// 2) an exception type that transforms the library's errors.
// ScopeGuard-like type to handle C library cleanup functions.
template <typename F>
class [[nodiscard]] scope_exit
{
public:
// C++20: Constructor can (and should) be [[nodiscard]].
/*[[nodiscard]]*/ constexpr explicit scope_exit(F&& f) :
f_{std::move(f)}
{}
~scope_exit()
{
f_();
}
// Non-copyable, non-movable.
scope_exit(scope_exit const&) = delete;
scope_exit(scope_exit&&) = delete;
auto operator=(scope_exit const&) -> scope_exit& = delete;
auto operator=(scope_exit&&) -> scope_exit& = delete;
private:
F f_;
};
// Exception that gets last libxml2 error.
class libxml_error : public std::runtime_error
{
public:
libxml_error() : libxml_error(std::string{}) {}
explicit libxml_error(std::string message) :
std::runtime_error{make_message_(std::move(message))}
{}
private:
static auto make_message_(std::string message) -> std::string
{
if (auto const last_error = ::xmlGetLastError(); last_error)
{
if (not message.empty())
message += ": ";
message += last_error->message;
}
return message;
}
};
auto main() -> int
{
try
{
// Initialize libxml.
::xmlInitParser();
LIBXML_TEST_VERSION
auto const libxml_cleanup = scope_exit{[] { ::xmlCleanupParser(); }};
// Load and parse XML document.
auto const doc = ::xmlParseFile("test.xml");
if (not doc)
throw libxml_error{"failed to load document"};
auto const doc_cleanup = scope_exit{[doc] { ::xmlFreeDoc(doc); }};
// Create XPath context for document.
auto const xpath_context = ::xmlXPathNewContext(doc);
if (not xpath_context)
throw libxml_error{"failed to create XPath context"};
auto const xpath_context_cleanup = scope_exit{[xpath_context]
{ ::xmlXPathFreeContext(xpath_context); }};
// Task 1 ============================================================
{
std::cout << "Task 1:\n";
auto const xpath =
reinterpret_cast<::xmlChar const*>(u8"//item[1]");
// Create XPath object (same for every task).
auto xpath_obj = ::xmlXPathEvalExpression(xpath, xpath_context);
if (not xpath_obj)
throw libxml_error{"failed to evaluate XPath"};
auto const xpath_obj_cleanup = scope_exit{[xpath_obj]
{ ::xmlXPathFreeObject(xpath_obj); }};
// 'result' a xmlNode* to the desired node, or nullptr if it
// doesn't exist. If not nullptr, the node is owned by 'doc'.
auto const result = xmlXPathNodeSetItem(xpath_obj->nodesetval, 0);
if (result)
std::cout << '\t' << "node found" << '\n';
else
std::cout << '\t' << "node not found" << '\n';
}
// Task 2 ============================================================
{
std::cout << "Task 2:\n";
auto const xpath =
reinterpret_cast<::xmlChar const*>(u8"//price/text()");
// Create XPath object (same for every task).
auto xpath_obj = ::xmlXPathEvalExpression(xpath, xpath_context);
if (not xpath_obj)
throw libxml_error{"failed to evaluate XPath"};
auto const xpath_obj_cleanup = scope_exit{[xpath_obj]
{ ::xmlXPathFreeObject(xpath_obj); }};
// Printing the results.
auto const count =
xmlXPathNodeSetGetLength(xpath_obj->nodesetval);
for (auto i = decltype(count){0}; i < count; ++i)
{
auto const node =
xmlXPathNodeSetItem(xpath_obj->nodesetval, i);
assert(node);
auto const content = XML_GET_CONTENT(node);
assert(content);
// Note that reinterpret_cast here is a Bad Idea, because
// 'content' is UTF-8 encoded, which may or may not be the
// encoding cout expects. A *PROPER* solution would translate
// content to the correct encoding (or at least verify that
// UTF-8 *is* the correct encoding).
//
// But this "works" well enough for illustration.
std::cout << "\n\t" << reinterpret_cast<char const*>(content);
}
std::cout << '\n';
}
// Task 3 ============================================================
{
std::cout << "Task 3:\n";
auto const xpath =
reinterpret_cast<::xmlChar const*>(u8"//name");
// Create XPath object (same for every task).
auto xpath_obj = ::xmlXPathEvalExpression(xpath, xpath_context);
if (not xpath_obj)
throw libxml_error{"failed to evaluate XPath"};
auto const xpath_obj_cleanup = scope_exit{[xpath_obj]
{ ::xmlXPathFreeObject(xpath_obj); }};
// 'results' is a vector of pointers to the result nodes. The
// nodes pointed to are owned by 'doc'.
auto const results = [ns=xpath_obj->nodesetval]()
{
auto v = std::vector<::xmlNode*>{};
if (ns && ns->nodeTab)
v.assign(ns->nodeTab, ns->nodeTab + ns->nodeNr);
return v;
}();
std::cout << '\t' << "set of " << results.size()
<< " node(s) found" << '\n';
}
}
catch (std::exception const& x)
{
std::cerr << "ERROR: " << x.what() << '\n';
return EXIT_FAILURE;
}
}
|
http://rosettacode.org/wiki/Yin_and_yang | Yin and yang | One well-known symbol of the philosophy of duality known as yin and yang is the taijitu.
Task
Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.
Generate and display the symbol for two different (small) sizes.
| #BASIC | BASIC | pi=3.141592
s=.5
xp=320:yp=100:size=150
GOSUB DrawYY
xp=500:yp=40:size=50
GOSUB DrawYY
END
DrawYY:
CIRCLE (xp,yp),size,,,,s
CIRCLE (xp,yp+size/4),size/8,,,,s
CIRCLE (xp,yp-size/4),size/8,,,,s
CIRCLE (xp,yp+size/4),size/2,,.5*pi,1.5*pi,s
CIRCLE (xp,yp-size/4),size/2,,1.5*pi,2*pi,s
CIRCLE (xp,yp-size/4),size/2,,0,.5*pi,s
PAINT (xp,yp-size/4)
PSET (xp,yp)
PAINT (xp+size/4,yp)
RETURN |
http://rosettacode.org/wiki/Yin_and_yang | Yin and yang | One well-known symbol of the philosophy of duality known as yin and yang is the taijitu.
Task
Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.
Generate and display the symbol for two different (small) sizes.
| #BCPL | BCPL | get "libhdr"
let circle(x, y, c, r) = (r*r) >= (x/2) * (x/2) + (y-c) * (y-c)
let pixel(x, y, r) =
circle(x, y, -r/2, r/6) -> '#',
circle(x, y, r/2, r/6) -> '.',
circle(x, y, -r/2, r/2) -> '.',
circle(x, y, r/2, r/2) -> '#',
circle(x, y, 0, r) -> x<0 -> '.', '#',
' '
let yinyang(r) be
for y = -r to r
$( for x = -2*r to 2*r do
wrch(pixel(x,y,r))
wrch('*N')
$)
let start() be
$( yinyang(4)
yinyang(8)
$) |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.