Hofstadter Q sequence: Difference between revisions
Content added Content deleted
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
|||
Line 24: | Line 24: | ||
{{trans|C}} |
{{trans|C}} |
||
< |
<syntaxhighlight lang="11l">V qseq = [0] * 100001 |
||
qseq[1] = 1 |
qseq[1] = 1 |
||
qseq[2] = 1 |
qseq[2] = 1 |
||
Line 38: | Line 38: | ||
I qseq[i] < qseq[i-1] |
I qseq[i] < qseq[i-1] |
||
less_than_preceding++ |
less_than_preceding++ |
||
print(‘Times a member of the sequence is less than its preceding term: ’less_than_preceding)</ |
print(‘Times a member of the sequence is less than its preceding term: ’less_than_preceding)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 49: | Line 49: | ||
=={{header|360 Assembly}}== |
=={{header|360 Assembly}}== |
||
{{trans|PL/I}} |
{{trans|PL/I}} |
||
< |
<syntaxhighlight lang="360asm">* Hofstrader q sequence for any n - 18/10/2015 |
||
HOFSTRAD CSECT |
HOFSTRAD CSECT |
||
USING HOFSTRAD,R15 set base register |
USING HOFSTRAD,R15 set base register |
||
Line 99: | Line 99: | ||
Q DS 1000F array q(1000) |
Q DS 1000F array q(1000) |
||
YREGS |
YREGS |
||
END HOFSTRAD</ |
END HOFSTRAD</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre style="height:16ex"> |
<pre style="height:16ex"> |
||
Line 117: | Line 117: | ||
=={{header|8080 Assembly}}== |
=={{header|8080 Assembly}}== |
||
< |
<syntaxhighlight lang="8080asm">puts: equ 9 ; CP/M call to print a string |
||
org 100h |
org 100h |
||
;;; Generate the first 1000 members of the Q sequence |
;;; Generate the first 1000 members of the Q sequence |
||
Line 238: | Line 238: | ||
db '*****' ; Placeholder for number |
db '*****' ; Placeholder for number |
||
num: db ' $' |
num: db ' $' |
||
qq: dw 1,1 ; Q sequence stored here, starting with 1, 1</ |
qq: dw 1,1 ; Q sequence stored here, starting with 1, 1</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 247: | Line 247: | ||
=={{header|8086 Assembly}}== |
=={{header|8086 Assembly}}== |
||
< |
<syntaxhighlight lang="asm">puts: equ 9 ; MS-DOS syscall to print a string |
||
cpu 8086 |
cpu 8086 |
||
org 100h |
org 100h |
||
Line 307: | Line 307: | ||
num: db ' $' |
num: db ' $' |
||
Q: dw 1,1 |
Q: dw 1,1 |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 315: | Line 315: | ||
=={{header|Action!}}== |
=={{header|Action!}}== |
||
< |
<syntaxhighlight lang="action!">PROC Main() |
||
DEFINE MAX="1000" |
DEFINE MAX="1000" |
||
INT ARRAY q(MAX+1) |
INT ARRAY q(MAX+1) |
||
Line 331: | Line 331: | ||
OD |
OD |
||
PrintF("%I: %I%E",MAX,q(MAX)) |
PrintF("%I: %I%E",MAX,q(MAX)) |
||
RETURN</ |
RETURN</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Hofstadter_Q_sequence.png Screenshot from Atari 8-bit computer] |
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Hofstadter_Q_sequence.png Screenshot from Atari 8-bit computer] |
||
Line 349: | Line 349: | ||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
< |
<syntaxhighlight lang="ada">with Ada.Text_IO; |
||
procedure Hofstadter_Q_Sequence is |
procedure Hofstadter_Q_Sequence is |
||
Line 407: | Line 407: | ||
-- how many times a member of the sequence is less than its preceding term |
-- how many times a member of the sequence is less than its preceding term |
||
-- for terms up to and including the 100,000'th term |
-- for terms up to and including the 100,000'th term |
||
end Hofstadter_Q_Sequence;</ |
end Hofstadter_Q_Sequence;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 420: | Line 420: | ||
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''.}} |
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''.}} |
||
'''File: Hofstadter_Q_sequence.a68'''< |
'''File: Hofstadter_Q_sequence.a68'''<syntaxhighlight lang="algol68">#!/usr/local/bin/a68g --script # |
||
INT n = 100000; |
INT n = 100000; |
||
Line 443: | Line 443: | ||
printf(($"flips: "g(0)l$, flip)) |
printf(($"flips: "g(0)l$, flip)) |
||
)</ |
)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 452: | Line 452: | ||
=={{header|ALGOL-M}}== |
=={{header|ALGOL-M}}== |
||
< |
<syntaxhighlight lang="algolm">begin |
||
integer array Q[1:1000]; |
integer array Q[1:1000]; |
||
integer n; |
integer n; |
||
Line 465: | Line 465: | ||
write("The 1000th term is:", Q[1000]); |
write("The 1000th term is:", Q[1000]); |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>The first 10 terms are: |
<pre>The first 10 terms are: |
||
Line 472: | Line 472: | ||
=={{header|ALGOL W}}== |
=={{header|ALGOL W}}== |
||
< |
<syntaxhighlight lang="algolw">begin % find elements of the Hofstader Q sequence Q(1) = Q(2) = 1 % |
||
% Q(n) = Q( n - Q( n - 1 ) ) + Q( n - Q( n - 2 ) ) for n > 2 % |
% Q(n) = Q( n - Q( n - 1 ) ) + Q( n - Q( n - 2 ) ) for n > 2 % |
||
integer MAX_Q; |
integer MAX_Q; |
||
Line 510: | Line 510: | ||
write( i_w := 1, s_w := 0, "Q(n) < Q(n-1) ", ltCount," times for n up to ", MAX_Q ) |
write( i_w := 1, s_w := 0, "Q(n) < Q(n-1) ", ltCount," times for n up to ", MAX_Q ) |
||
end |
end |
||
end.</ |
end.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 521: | Line 521: | ||
=={{header|APL}}== |
=={{header|APL}}== |
||
< |
<syntaxhighlight lang="apl">∇ Q_sequence;seq;size |
||
size←100000 |
size←100000 |
||
seq←{⍵,+/⍵[(1+⍴⍵)-¯2↑⍵]}⍣(size-2)⊢1 1 |
seq←{⍵,+/⍵[(1+⍴⍵)-¯2↑⍵]}⍣(size-2)⊢1 1 |
||
Line 528: | Line 528: | ||
⎕←'The 1000th term is:', seq[1000] |
⎕←'The 1000th term is:', seq[1000] |
||
⎕←(+/ 2>/seq),'terms were preceded by a larger term.' |
⎕←(+/ 2>/seq),'terms were preceded by a larger term.' |
||
∇</ |
∇</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 539: | Line 539: | ||
=={{header|ARM Assembly}}== |
=={{header|ARM Assembly}}== |
||
<lang>.text |
<syntaxhighlight lang="text">.text |
||
.global _start |
.global _start |
||
_start: ldr r6,=qs @ R6 = base register for Q array |
_start: ldr r6,=qs @ R6 = base register for Q array |
||
Line 652: | Line 652: | ||
.align 4 |
.align 4 |
||
.space 8 @ Buffer for number output |
.space 8 @ Buffer for number output |
||
qs: .space 4 * 100001 @ One word per term</ |
qs: .space 4 * 100001 @ One word per term</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 662: | Line 662: | ||
=={{header|Arturo}}== |
=={{header|Arturo}}== |
||
< |
<syntaxhighlight lang="rebol">q: new [1 1] |
||
n: 2 |
n: 2 |
||
while [n<1001][ |
while [n<1001][ |
||
Line 670: | Line 670: | ||
print ["First ten items:" first.n: 10 q] |
print ["First ten items:" first.n: 10 q] |
||
print ["1000th item:" q\[999]]</ |
print ["1000th item:" q\[999]]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 678: | Line 678: | ||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
< |
<syntaxhighlight lang="autohotkey">SetBatchLines, -1 |
||
Q := HofsQSeq(100000) |
Q := HofsQSeq(100000) |
||
Line 697: | Line 697: | ||
} |
} |
||
return Q |
return Q |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>First ten: 1, 1, 2, 3, 3, 4, 5, 5, 6, 6, |
<pre>First ten: 1, 1, 2, 3, 3, 4, 5, 5, 6, 6, |
||
Line 704: | Line 704: | ||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
< |
<syntaxhighlight lang="awk">#!/usr/bin/awk -f |
||
BEGIN { |
BEGIN { |
||
N = 100000 |
N = 100000 |
||
Line 725: | Line 725: | ||
} |
} |
||
return seq |
return seq |
||
} </ |
} </syntaxhighlight> |
||
<pre>Q-sequence(1..10) : 1 1 2 3 3 4 5 5 6 6 |
<pre>Q-sequence(1..10) : 1 1 2 3 3 4 5 5 6 6 |
||
Line 733: | Line 733: | ||
=={{header|BASIC256}}== |
=={{header|BASIC256}}== |
||
{{trans|FreeBASIC}} |
{{trans|FreeBASIC}} |
||
<syntaxhighlight lang="basic256"> |
|||
<lang BASIC256> |
|||
limite = 100000 |
limite = 100000 |
||
dim Q[limite+1] |
dim Q[limite+1] |
||
Line 751: | Line 751: | ||
print "Término número 1000: "; Q[1000] |
print "Término número 1000: "; Q[1000] |
||
print "Términos menores que los anteriores: "; cont |
print "Términos menores que los anteriores: "; cont |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 758: | Line 758: | ||
=={{header|BBC BASIC}}== |
=={{header|BBC BASIC}}== |
||
< |
<syntaxhighlight lang="bbcbasic"> PRINT "First 10 terms of Q = " ; |
||
FOR i% = 1 TO 10 : PRINT ;FNq(i%, c%) " "; : NEXT : PRINT |
FOR i% = 1 TO 10 : PRINT ;FNq(i%, c%) " "; : NEXT : PRINT |
||
PRINT "1000th term = " ; FNq(1000, c%) |
PRINT "1000th term = " ; FNq(1000, c%) |
||
Line 775: | Line 775: | ||
IF q%(i%) < q%(i%-1) THEN c% += 1 |
IF q%(i%) < q%(i%-1) THEN c% += 1 |
||
NEXT |
NEXT |
||
= q%(n%)</ |
= q%(n%)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 785: | Line 785: | ||
=={{header|Bracmat}}== |
=={{header|Bracmat}}== |
||
< |
<syntaxhighlight lang="bracmat">( 0:?memocells |
||
& tbl$(memo,!memocells+1) { allocate array } |
& tbl$(memo,!memocells+1) { allocate array } |
||
& ( Q |
& ( Q |
||
Line 816: | Line 816: | ||
) |
) |
||
& out$!lessThan |
& out$!lessThan |
||
);</ |
);</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>1 1 2 3 3 4 5 5 6 6 |
<pre>1 1 2 3 3 4 5 5 6 6 |
||
Line 823: | Line 823: | ||
=={{header|BCPL}}== |
=={{header|BCPL}}== |
||
< |
<syntaxhighlight lang="bcpl">get "libhdr" |
||
let start() be |
let start() be |
||
Line 837: | Line 837: | ||
writef("*NThe 1000th term is: %N*N", Q!1000) |
writef("*NThe 1000th term is: %N*N", Q!1000) |
||
$)</ |
$)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>The first 10 terms are: 1 1 2 3 3 4 5 5 6 6 |
<pre>The first 10 terms are: 1 1 2 3 3 4 5 5 6 6 |
||
Line 843: | Line 843: | ||
=={{header|C}}== |
=={{header|C}}== |
||
< |
<syntaxhighlight lang="c">#include <stdio.h> |
||
#include <stdlib.h> |
#include <stdlib.h> |
||
Line 866: | Line 866: | ||
printf("flips: %d\n", flip); |
printf("flips: %d\n", flip); |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>1 1 2 3 3 4 5 5 6 6 |
<pre>1 1 2 3 3 4 5 5 6 6 |
||
Line 875: | Line 875: | ||
=={{header|C sharp}}== |
=={{header|C sharp}}== |
||
< |
<syntaxhighlight lang="c sharp">using System; |
||
using System.Collections.Generic; |
using System.Collections.Generic; |
||
Line 938: | Line 938: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 957: | Line 957: | ||
solution modeled after Perl solution |
solution modeled after Perl solution |
||
< |
<syntaxhighlight lang="cpp">#include <iostream> |
||
int main() { |
int main() { |
||
Line 976: | Line 976: | ||
std::cout << less_than_preceding << " times a number was preceded by a greater number!" << std::endl; |
std::cout << less_than_preceding << " times a number was preceded by a greater number!" << std::endl; |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>The first 10 numbers are: 1 1 2 3 3 4 5 5 6 6 |
<pre>The first 10 numbers are: 1 1 2 3 3 4 5 5 6 6 |
||
Line 986: | Line 986: | ||
The subsequences are vectors for efficient indexing. |
The subsequences are vectors for efficient indexing. |
||
''qfirst'' iterates ''qs'' so the nth iteration is Q{1..n]. |
''qfirst'' iterates ''qs'' so the nth iteration is Q{1..n]. |
||
< |
<syntaxhighlight lang="clojure">(defn qs [q] |
||
(let [n (count q)] |
(let [n (count q)] |
||
(condp = n |
(condp = n |
||
Line 998: | Line 998: | ||
(println "first 10:" (qfirst 10)) |
(println "first 10:" (qfirst 10)) |
||
(println "1000th:" (last (qfirst 1000))) |
(println "1000th:" (last (qfirst 1000))) |
||
(println "extra credit:" (->> (qfirst 100000) (partition 2 1) (filter #(apply > %)) count))</ |
(println "extra credit:" (->> (qfirst 100000) (partition 2 1) (filter #(apply > %)) count))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<lang>first 10: [1 1 2 3 3 4 5 5 6 6] |
<syntaxhighlight lang="text">first 10: [1 1 2 3 3 4 5 5 6 6] |
||
1000th: 502 |
1000th: 502 |
||
extra credit: 49798</ |
extra credit: 49798</syntaxhighlight> |
||
=={{header|CLU}}== |
=={{header|CLU}}== |
||
< |
<syntaxhighlight lang="clu">q_seq = proc (n: int) returns (sequence[int]) |
||
q: array[int] := array[int]$[1,1] |
q: array[int] := array[int]$[1,1] |
||
for i: int in int$from_to(3,n) do |
for i: int in int$from_to(3,n) do |
||
Line 1,030: | Line 1,030: | ||
stream$putl(po, "\nflips: " || int$unparse(flips)) |
stream$putl(po, "\nflips: " || int$unparse(flips)) |
||
end start_up</ |
end start_up</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>First 10 terms: 1 1 2 3 3 4 5 5 6 6 |
<pre>First 10 terms: 1 1 2 3 3 4 5 5 6 6 |
||
Line 1,038: | Line 1,038: | ||
=={{header|CoffeeScript}}== |
=={{header|CoffeeScript}}== |
||
{{trans|JavaScript}} |
{{trans|JavaScript}} |
||
< |
<syntaxhighlight lang="coffeescript">hofstadterQ = do -> |
||
memo = [ 1 ,1, 1] |
memo = [ 1 ,1, 1] |
||
Q = (n) -> |
Q = (n) -> |
||
Line 1,048: | Line 1,048: | ||
# some results: |
# some results: |
||
console.log 'Q(' + i + ') = ' + hofstadterQ(i) for i in [1..10] |
console.log 'Q(' + i + ') = ' + hofstadterQ(i) for i in [1..10] |
||
console.log 'Q(1000) = ' + hofstadterQ(1000)</ |
console.log 'Q(1000) = ' + hofstadterQ(1000)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Q(1) = 1 |
<pre>Q(1) = 1 |
||
Line 1,063: | Line 1,063: | ||
=={{header|COBOL}}== |
=={{header|COBOL}}== |
||
< |
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION. |
||
PROGRAM-ID. Q-SEQ. |
PROGRAM-ID. Q-SEQ. |
||
Line 1,102: | Line 1,102: | ||
MOVE N TO IX. |
MOVE N TO IX. |
||
MOVE Q(N) TO ITEM. |
MOVE Q(N) TO ITEM. |
||
DISPLAY 'Q(' IX ') = ' ITEM.</ |
DISPLAY 'Q(' IX ') = ' ITEM.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Q( 1) = 1 |
<pre>Q( 1) = 1 |
||
Line 1,117: | Line 1,117: | ||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
< |
<syntaxhighlight lang="lisp">(defparameter *mm* (make-hash-table :test #'equal)) |
||
;;; generic memoization macro |
;;; generic memoization macro |
||
Line 1,143: | Line 1,143: | ||
(if (< next-q last-q) (incf c)) |
(if (< next-q last-q) (incf c)) |
||
(setf last-q next-q)) |
(setf last-q next-q)) |
||
finally (return c)))</ |
finally (return c)))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>First of Q: (1 1 2 3 3 4 5 5 6 6) |
<pre>First of Q: (1 1 2 3 3 4 5 5 6 6) |
||
Line 1,149: | Line 1,149: | ||
Bumps up to 100000: 49798</pre> |
Bumps up to 100000: 49798</pre> |
||
Although the above definition of <code>q</code> is more general, for this specific problem the following is faster:< |
Although the above definition of <code>q</code> is more general, for this specific problem the following is faster:<syntaxhighlight lang="lisp">(let ((cc (make-array 3 :element-type 'integer |
||
:initial-element 1 |
:initial-element 1 |
||
:adjustable t |
:adjustable t |
||
Line 1,160: | Line 1,160: | ||
(aref cc (- n (aref cc (- n 2))))) |
(aref cc (- n (aref cc (- n 2))))) |
||
cc)) |
cc)) |
||
(aref cc n)))</ |
(aref cc n)))</syntaxhighlight> |
||
=={{header|Cowgol}}== |
=={{header|Cowgol}}== |
||
< |
<syntaxhighlight lang="cowgol">include "cowgol.coh"; |
||
# Generate 1000 terms of the Q sequence |
# Generate 1000 terms of the Q sequence |
||
Line 1,189: | Line 1,189: | ||
print("The 1000th term is: "); |
print("The 1000th term is: "); |
||
print_i16(Q[1000]); |
print_i16(Q[1000]); |
||
print_nl();</ |
print_nl();</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,197: | Line 1,197: | ||
=={{header|D}}== |
=={{header|D}}== |
||
< |
<syntaxhighlight lang="d">import std.stdio, std.algorithm, std.functional, std.range; |
||
int Q(in int n) nothrow |
int Q(in int n) nothrow |
||
Line 1,216: | Line 1,216: | ||
iota(2, 100_001).count!(i => Q(i) < Q(i - 1))); |
iota(2, 100_001).count!(i => Q(i) < Q(i - 1))); |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre>Q(n) for n = [1..10] is: [1, 1, 2, 3, 3, 4, 5, 5, 6, 6] |
<pre>Q(n) for n = [1..10] is: [1, 1, 2, 3, 3, 4, 5, 5, 6, 6] |
||
Line 1,226: | Line 1,226: | ||
{{trans|Python}} |
{{trans|Python}} |
||
Same output. |
Same output. |
||
< |
<syntaxhighlight lang="d">import std.stdio, std.algorithm, std.range, std.array; |
||
uint Q(in int n) nothrow |
uint Q(in int n) nothrow |
||
Line 1,245: | Line 1,245: | ||
iota(2, 100_001).count!(i => Q(i) < Q(i - 1))); |
iota(2, 100_001).count!(i => Q(i) < Q(i - 1))); |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
===Even Faster Version=== |
===Even Faster Version=== |
||
This code is here to show that you don't have to use all fancy features of D. Straightforward simple code is often clearer, and faster. |
This code is here to show that you don't have to use all fancy features of D. Straightforward simple code is often clearer, and faster. |
||
<syntaxhighlight lang="d"> |
|||
<lang d> |
|||
import std.stdio; |
import std.stdio; |
||
Line 1,282: | Line 1,282: | ||
writefln("Q(i) is less than Q(i-1) for i [2..100_000] %d times.", lt); |
writefln("Q(i) is less than Q(i-1) for i [2..100_000] %d times.", lt); |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Dart}}== |
=={{header|Dart}}== |
||
Naive version using only recursion (Q(1000) fails due to browser script runtime restrictions) |
Naive version using only recursion (Q(1000) fails due to browser script runtime restrictions) |
||
< |
<syntaxhighlight lang="dart">int Q(int n) => n>2 ? Q(n-Q(n-1))+Q(n-Q(n-2)) : 1; |
||
main() { |
main() { |
||
Line 1,293: | Line 1,293: | ||
} |
} |
||
print("Q(1000)=${Q(1000)}"); |
print("Q(1000)=${Q(1000)}"); |
||
}</ |
}</syntaxhighlight> |
||
Version featuring caching. |
Version featuring caching. |
||
< |
<syntaxhighlight lang="dart">class Q { |
||
Map<int,int> _table; |
Map<int,int> _table; |
||
Line 1,337: | Line 1,337: | ||
} |
} |
||
print("value is smaller than previous $count times"); |
print("value is smaller than previous $count times"); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Q(1)=1 |
<pre>Q(1)=1 |
||
Line 1,353: | Line 1,353: | ||
If the maximum number is known, filling an array is probably the fastest solution. |
If the maximum number is known, filling an array is probably the fastest solution. |
||
< |
<syntaxhighlight lang="dart">main() { |
||
List<int> q=new List<int>(100001); |
List<int> q=new List<int>(100001); |
||
q[1]=q[2]=1; |
q[1]=q[2]=1; |
||
Line 1,369: | Line 1,369: | ||
print("Q(1000)=${q[1000]}"); |
print("Q(1000)=${q[1000]}"); |
||
print("value is smaller than previous $count times"); |
print("value is smaller than previous $count times"); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Draco}}== |
=={{header|Draco}}== |
||
< |
<syntaxhighlight lang="draco">proc nonrec make_Q([*] word q) void: |
||
word n; |
word n; |
||
q[1] := 1; |
q[1] := 1; |
||
Line 1,391: | Line 1,391: | ||
writeln(); |
writeln(); |
||
writeln("The 1000th term is: ", q[1000]) |
writeln("The 1000th term is: ", q[1000]) |
||
corp</ |
corp</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>The first 10 terms are: 1 1 2 3 3 4 5 5 6 6 |
<pre>The first 10 terms are: 1 1 2 3 3 4 5 5 6 6 |
||
Line 1,397: | Line 1,397: | ||
=={{header|EchoLisp}}== |
=={{header|EchoLisp}}== |
||
< |
<syntaxhighlight lang="scheme"> |
||
(define RECURSE_BUMP 500) ;; minimum of chrome:500 safari:1000 firefox:2000 |
(define RECURSE_BUMP 500) ;; minimum of chrome:500 safari:1000 firefox:2000 |
||
Line 1,421: | Line 1,421: | ||
(Q 1000) → 502 |
(Q 1000) → 502 |
||
(flips 100000) → 49798 |
(flips 100000) → 49798 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Eiffel}}== |
=={{header|Eiffel}}== |
||
<syntaxhighlight lang="eiffel"> |
|||
<lang Eiffel> |
|||
class |
class |
||
APPLICATION |
APPLICATION |
||
Line 1,486: | Line 1,486: | ||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,500: | Line 1,500: | ||
{{trans|Erlang}} |
{{trans|Erlang}} |
||
changed collection (Erlang array => Map) |
changed collection (Erlang array => Map) |
||
< |
<syntaxhighlight lang="elixir">defmodule Hofstadter do |
||
defp flip(v2, v1) when v1 > v2, do: 1 |
defp flip(v2, v1) when v1 > v2, do: 1 |
||
defp flip(_v2, _v1), do: 0 |
defp flip(_v2, _v1), do: 0 |
||
Line 1,523: | Line 1,523: | ||
end |
end |
||
Hofstadter.main</ |
Hofstadter.main</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,533: | Line 1,533: | ||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
< |
<syntaxhighlight lang="erlang">%% @author Jan Willem Luiten <jwl@secondmove.com> |
||
%% Hofstadter Q Sequence for Rosetta Code |
%% Hofstadter Q Sequence for Rosetta Code |
||
Line 1,563: | Line 1,563: | ||
Acc = array:set(1, 1, Tmp), |
Acc = array:set(1, 1, Tmp), |
||
hofstadter(?MAX, 2, Acc, 0). |
hofstadter(?MAX, 2, Acc, 0). |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,573: | Line 1,573: | ||
=={{header|ERRE}}== |
=={{header|ERRE}}== |
||
{{output|ERRE}} |
{{output|ERRE}} |
||
<syntaxhighlight lang="erre"> |
|||
<lang ERRE> |
|||
PROGRAM HOFSTADER_Q |
PROGRAM HOFSTADER_Q |
||
Line 1,609: | Line 1,609: | ||
PRINT("Number of Q(n)<Q(n+1) for n<=10000 : ";NN) |
PRINT("Number of Q(n)<Q(n+1) for n<=10000 : ";NN) |
||
END PROGRAM |
END PROGRAM |
||
</syntaxhighlight> |
|||
</lang> |
|||
Note: The extra credit was limited to 10000 because memory addressable range is limited to 64K. |
Note: The extra credit was limited to 10000 because memory addressable range is limited to 64K. |
||
If you want to implement extra credit for 100,000 you must use external file for array Q%[]. |
If you want to implement extra credit for 100,000 you must use external file for array Q%[]. |
||
Line 1,615: | Line 1,615: | ||
=={{header|F_Sharp|F#}}== |
=={{header|F_Sharp|F#}}== |
||
===The function=== |
===The function=== |
||
< |
<syntaxhighlight lang="fsharp"> |
||
// Populate an array with values of Hofstadter Q sequence. Nigel Galloway: August 26th., 2020 |
// Populate an array with values of Hofstadter Q sequence. Nigel Galloway: August 26th., 2020 |
||
let fQ N=let g=Array.length N in N.[0]<-1; N.[1]<-1;(for g in 2..g-1 do N.[g]<-N.[g-N.[g-1]]+N.[g-N.[g-2]]) |
let fQ N=let g=Array.length N in N.[0]<-1; N.[1]<-1;(for g in 2..g-1 do N.[g]<-N.[g-N.[g-1]]+N.[g-N.[g-2]]) |
||
</syntaxhighlight> |
|||
</lang> |
|||
===The Tasks=== |
===The Tasks=== |
||
< |
<syntaxhighlight lang="fsharp"> |
||
let Q=Array.zeroCreate<int>10 in fQ Q; printfn "%A" Q |
let Q=Array.zeroCreate<int>10 in fQ Q; printfn "%A" Q |
||
let Q=Array.zeroCreate<int>1000 in fQ Q; printfn "%d" (Array.last Q) |
let Q=Array.zeroCreate<int>1000 in fQ Q; printfn "%d" (Array.last Q) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,630: | Line 1,630: | ||
</pre> |
</pre> |
||
===Extra Credit=== |
===Extra Credit=== |
||
< |
<syntaxhighlight lang="fsharp"> |
||
let Q=Array.zeroCreate<int>100000 in fQ Q; printfn "%d" (Q|>Seq.pairwise|>Seq.sumBy(fun(n,g)->if n>g then 1 else 0)) |
let Q=Array.zeroCreate<int>100000 in fQ Q; printfn "%d" (Q|>Seq.pairwise|>Seq.sumBy(fun(n,g)->if n>g then 1 else 0)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,639: | Line 1,639: | ||
;What is a large number? |
;What is a large number? |
||
< |
<syntaxhighlight lang="fsharp"> |
||
let Q=Array.zeroCreate<int>2500000000 in fQ Q; printfn "%d" (Array.last Q) |
let Q=Array.zeroCreate<int>2500000000 in fQ Q; printfn "%d" (Array.last Q) |
||
let Q=Array.zeroCreate<int>5000000000 in fQ Q; printfn "%d" (Array.last Q) |
let Q=Array.zeroCreate<int>5000000000 in fQ Q; printfn "%d" (Array.last Q) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,651: | Line 1,651: | ||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
We define a method next that takes a sequence of the first n Q values and appends the next one to it. Then we perform it 1000 times on <code>{ 1 1 }</code> and show the first 10 and 999th (because the list is zero-indexed) elements. |
We define a method next that takes a sequence of the first n Q values and appends the next one to it. Then we perform it 1000 times on <code>{ 1 1 }</code> and show the first 10 and 999th (because the list is zero-indexed) elements. |
||
< |
<syntaxhighlight lang="factor">( scratchpad ) : next ( seq -- newseq ) |
||
dup 2 tail* over length [ swap - ] curry map |
dup 2 tail* over length [ swap - ] curry map |
||
[ dupd swap nth ] map 0 [ + ] reduce suffix ; |
[ dupd swap nth ] map 0 [ + ] reduce suffix ; |
||
Line 1,657: | Line 1,657: | ||
( scratchpad ) { 1 1 } 1000 [ next ] times dup 10 head . 999 swap nth . |
( scratchpad ) { 1 1 } 1000 [ next ] times dup 10 head . 999 swap nth . |
||
{ 1 1 2 3 3 4 5 5 6 6 } |
{ 1 1 2 3 3 4 5 5 6 6 } |
||
502</ |
502</syntaxhighlight> |
||
=={{header|Fermat}}== |
=={{header|Fermat}}== |
||
<lang>Func Hq(n) = if n<2 then 1 else |
<syntaxhighlight lang="text">Func Hq(n) = if n<2 then 1 else |
||
Array qq[n+1]; |
Array qq[n+1]; |
||
qq[1] := 1; |
qq[1] := 1; |
||
Line 1,672: | Line 1,672: | ||
for i=1 to 10 do !Hq(i);!' ' od; |
for i=1 to 10 do !Hq(i);!' ' od; |
||
Hq(1000)</ |
Hq(1000)</syntaxhighlight> |
||
{{out}}<pre> |
{{out}}<pre> |
||
1 1 2 3 3 4 5 5 6 6 |
1 1 2 3 3 4 5 5 6 6 |
||
Line 1,679: | Line 1,679: | ||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
{{trans|C}} |
{{trans|C}} |
||
< |
<syntaxhighlight lang="forth">100000 constant N |
||
: q ( n -- addr ) cells here + ; |
: q ( n -- addr ) cells here + ; |
||
Line 1,705: | Line 1,705: | ||
999 q @ . cr |
999 q @ . cr |
||
flips |
flips |
||
bye</ |
bye</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,717: | Line 1,717: | ||
The latter-day function COUNT(''logical expression'') could easily be replaced by a simple test-and-count in the DO-loop preparing the array. One hopes that the compiler produces sensible code rather than creating an auxiliary array of boolean results then counting the ''true'' values. Rather more clunky is the need to employ odd structure for the input loop so as to handle possible bad input (text, rather than a valid number, for example) and who knows, end-of-file might happen also. |
The latter-day function COUNT(''logical expression'') could easily be replaced by a simple test-and-count in the DO-loop preparing the array. One hopes that the compiler produces sensible code rather than creating an auxiliary array of boolean results then counting the ''true'' values. Rather more clunky is the need to employ odd structure for the input loop so as to handle possible bad input (text, rather than a valid number, for example) and who knows, end-of-file might happen also. |
||
<syntaxhighlight lang="fortran"> |
|||
<lang Fortran> |
|||
Calculate the Hofstadter Q-sequence, using a big array rather than recursion. |
Calculate the Hofstadter Q-sequence, using a big array rather than recursion. |
||
INTEGER ENUFF |
INTEGER ENUFF |
||
Line 1,748: | Line 1,748: | ||
999 WRITE (6,*) "Bye." |
999 WRITE (6,*) "Bye." |
||
END |
END |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
Line 1,762: | Line 1,762: | ||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
< |
<syntaxhighlight lang="freebasic"> |
||
Const limite = 100000 |
Const limite = 100000 |
||
Line 1,784: | Line 1,784: | ||
Print "Terminos menores que los anteriores: " &cont |
Print "Terminos menores que los anteriores: " &cont |
||
End |
End |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,802: | Line 1,802: | ||
=={{header|Go}}== |
=={{header|Go}}== |
||
Sure there are ways that run faster or handle larger numbers; for the task though, maps and recursion work just fine. |
Sure there are ways that run faster or handle larger numbers; for the task though, maps and recursion work just fine. |
||
< |
<syntaxhighlight lang="go">package main |
||
import "fmt" |
import "fmt" |
||
Line 1,847: | Line 1,847: | ||
func showQ(n int) { |
func showQ(n int) { |
||
fmt.Printf("Q(%d) = %d\n", n, q(n)) |
fmt.Printf("Q(%d) = %d\n", n, q(n)) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,866: | Line 1,866: | ||
=={{header|GW-BASIC}}== |
=={{header|GW-BASIC}}== |
||
< |
<syntaxhighlight lang="gwbasic">10 DIM Q!(1000) |
||
20 Q(1) = 1: Q(2) = 1 |
20 Q(1) = 1: Q(2) = 1 |
||
30 FOR N = 3 TO 1000 |
30 FOR N = 3 TO 1000 |
||
Line 1,874: | Line 1,874: | ||
70 PRINT Q(N) |
70 PRINT Q(N) |
||
80 NEXT N |
80 NEXT N |
||
90 PRINT Q(1000)</ |
90 PRINT Q(1000)</syntaxhighlight> |
||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
Line 1,880: | Line 1,880: | ||
The basic task: |
The basic task: |
||
< |
<syntaxhighlight lang="haskell">qSequence = tail qq where |
||
qq = 0 : 1 : 1 : map g [3..] |
qq = 0 : 1 : 1 : map g [3..] |
||
g n = qq !! (n - qq !! (n-1)) + qq !! (n - qq !! (n-2)) |
g n = qq !! (n - qq !! (n-1)) + qq !! (n - qq !! (n-2)) |
||
Line 1,887: | Line 1,887: | ||
*Main> (take 10 qSequence, qSequence !! (1000-1)) |
*Main> (take 10 qSequence, qSequence !! (1000-1)) |
||
([1,1,2,3,3,4,5,5,6,6],502) |
([1,1,2,3,3,4,5,5,6,6],502) |
||
(0.00 secs, 525044 bytes)</ |
(0.00 secs, 525044 bytes)</syntaxhighlight> |
||
Extra credit task: |
Extra credit task: |
||
< |
<syntaxhighlight lang="haskell">import Data.Array |
||
qSequence n = arr |
qSequence n = arr |
||
Line 1,911: | Line 1,911: | ||
. _S (zipWith (-)) tail . take n . elems $ arr ) |
. _S (zipWith (-)) tail . take n . elems $ arr ) |
||
_S f g x = f x (g x)</ |
_S f g x = f x (g x)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
< |
<syntaxhighlight lang="haskell">Prelude Main> qSeqTest 1000 100000 -- reversals in 100,000 |
||
([1,1,2,3,3,4,5,5,6,6],502,49798) |
([1,1,2,3,3,4,5,5,6,6],502,49798) |
||
(0.09 secs, 18879708 bytes) |
(0.09 secs, 18879708 bytes) |
||
Line 1,920: | Line 1,920: | ||
Prelude Main> qSeqTest 1000000 100000 -- 1,000,000-th item |
Prelude Main> qSeqTest 1000000 100000 -- 1,000,000-th item |
||
([1,1,2,3,3,4,5,5,6,6],512066,49798) |
([1,1,2,3,3,4,5,5,6,6],512066,49798) |
||
(2.80 secs, 87559640 bytes)</ |
(2.80 secs, 87559640 bytes)</syntaxhighlight> |
||
Using a list (more or less) seemlessly backed up by a double resizing array: |
Using a list (more or less) seemlessly backed up by a double resizing array: |
||
< |
<syntaxhighlight lang="haskell">q = qq (listArray (1,2) [1,1]) 1 where |
||
qq ar n = (arr!n) : qq arr (n+1) where |
qq ar n = (arr!n) : qq arr (n+1) where |
||
l = snd (bounds ar) |
l = snd (bounds ar) |
||
Line 1,938: | Line 1,938: | ||
putStr("1000-th: "); print (q !! 999) |
putStr("1000-th: "); print (q !! 999) |
||
putStr("flips: ") |
putStr("flips: ") |
||
print $ length $ filter id $ take 100000 (zipWith (>) q (tail q))</ |
print $ length $ filter id $ take 100000 (zipWith (>) q (tail q))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,947: | Line 1,947: | ||
List backed up by a list of arrays, with nominal constant lookup time. ''Somehow'' faster than the previous method. |
List backed up by a list of arrays, with nominal constant lookup time. ''Somehow'' faster than the previous method. |
||
< |
<syntaxhighlight lang="haskell">import Data.Array |
||
import Data.Int (Int64) |
import Data.Int (Int64) |
||
Line 1,967: | Line 1,967: | ||
where |
where |
||
qqq :: [Int64] |
qqq :: [Int64] |
||
qqq = map fromIntegral $ take 3000000 q</ |
qqq = map fromIntegral $ take 3000000 q</syntaxhighlight> |
||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
< |
<syntaxhighlight lang="icon">link printf |
||
procedure main() |
procedure main() |
||
Line 2,008: | Line 2,008: | ||
runerr(500,n) |
runerr(500,n) |
||
} |
} |
||
end</ |
end</syntaxhighlight> |
||
{{libheader|Icon Programming Library}} |
{{libheader|Icon Programming Library}} |
||
Line 2,027: | Line 2,027: | ||
=={{header|IS-BASIC}}== |
=={{header|IS-BASIC}}== |
||
< |
<syntaxhighlight lang="is-basic">100 PROGRAM "QSequen.bas" |
||
110 LET LIMIT=1000 |
110 LET LIMIT=1000 |
||
120 NUMERIC Q(1 TO LIMIT) |
120 NUMERIC Q(1 TO LIMIT) |
||
Line 2,038: | Line 2,038: | ||
190 PRINT Q(I); |
190 PRINT Q(I); |
||
200 NEXT |
200 NEXT |
||
210 PRINT :PRINT "Term 1000:";Q(1000)</ |
210 PRINT :PRINT "Term 1000:";Q(1000)</syntaxhighlight> |
||
=={{header|J}}== |
=={{header|J}}== |
||
'''Solution''' (''bottom-up''):< |
'''Solution''' (''bottom-up''):<syntaxhighlight lang="j"> Qs=:0 1 1 |
||
Q=: verb define |
Q=: verb define |
||
n=. >./,y |
n=. >./,y |
||
Line 2,048: | Line 2,048: | ||
end. |
end. |
||
y{Qs |
y{Qs |
||
)</ |
)</syntaxhighlight> |
||
'''Solution''' (''top-down''):< |
'''Solution''' (''top-down''):<syntaxhighlight lang="j"> Q=: 1:`(+&$:/@:- $:@-& 1 2)@.(>&2)"0 M.</syntaxhighlight> |
||
'''Example''':< |
'''Example''':<syntaxhighlight lang="j"> Q 1+i.10 |
||
1 1 2 3 3 4 5 5 6 6 |
1 1 2 3 3 4 5 5 6 6 |
||
Q 1000 |
Q 1000 |
||
502 |
502 |
||
+/2>/\ Q 1+i.100000 |
+/2>/\ Q 1+i.100000 |
||
49798</ |
49798</syntaxhighlight> |
||
'''Note''': The bottom-up solution uses iteration and doesn't risk failure due to recursion limits or cache overflows. The top-down solution uses recursion, and likely hews closer to the spirit of the task. While this latter uses memoization/caching, at some point it will still hit a recursion limit (depends on the environment; in mine, it barfs at N=4402). We use the bottom up version for the extra credit part of this task (the expression which compares adjacent numbers and gave us the result 49798). |
'''Note''': The bottom-up solution uses iteration and doesn't risk failure due to recursion limits or cache overflows. The top-down solution uses recursion, and likely hews closer to the spirit of the task. While this latter uses memoization/caching, at some point it will still hit a recursion limit (depends on the environment; in mine, it barfs at N=4402). We use the bottom up version for the extra credit part of this task (the expression which compares adjacent numbers and gave us the result 49798). |
||
Line 2,068: | Line 2,068: | ||
[[Category:Memoization]]{{works with|Java|1.5+}} |
[[Category:Memoization]]{{works with|Java|1.5+}} |
||
This example also counts the number of times each n is used as an argument up to 100000 and reports the one that was used the most. |
This example also counts the number of times each n is used as an argument up to 100000 and reports the one that was used the most. |
||
< |
<syntaxhighlight lang="java5">import java.util.HashMap; |
||
import java.util.Map; |
import java.util.Map; |
||
Line 2,113: | Line 2,113: | ||
System.out.println("Q(" + maxN + ") was called the most with " + maxUses + " calls"); |
System.out.println("Q(" + maxN + ") was called the most with " + maxUses + " calls"); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Q(1) = 1 |
<pre>Q(1) = 1 |
||
Line 2,132: | Line 2,132: | ||
===ES5=== |
===ES5=== |
||
Based on memoization example from 'JavaScript: The Good Parts'. |
Based on memoization example from 'JavaScript: The Good Parts'. |
||
< |
<syntaxhighlight lang="javascript">var hofstadterQ = function() { |
||
var memo = [1,1,1]; |
var memo = [1,1,1]; |
||
var Q = function (n) { |
var Q = function (n) { |
||
Line 2,150: | Line 2,150: | ||
console.log('Q(1000) = ' + hofstadterQ(1000)); |
console.log('Q(1000) = ' + hofstadterQ(1000)); |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,168: | Line 2,168: | ||
===ES6=== |
===ES6=== |
||
Memoising with the accumulator of a fold |
Memoising with the accumulator of a fold |
||
< |
<syntaxhighlight lang="javascript">(() => { |
||
'use strict'; |
'use strict'; |
||
Line 2,207: | Line 2,207: | ||
.reduce((a, x, i, xs) => x < xs[i - 1] ? a + 1 : a, 0) |
.reduce((a, x, i, xs) => x < xs[i - 1] ? a + 1 : a, 0) |
||
}; |
}; |
||
})();</ |
})();</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
< |
<syntaxhighlight lang="javascript">{"firstTen":[1, 1, 2, 3, 3, 4, 5, 5, 6, 6], |
||
"thousandth":502, |
"thousandth":502, |
||
"Q<Q-1UpTo10E5":49798}</ |
"Q<Q-1UpTo10E5":49798}</syntaxhighlight> |
||
=={{header|jq}}== |
=={{header|jq}}== |
||
Line 2,220: | Line 2,220: | ||
formula also holds for n == 2, and so that we can cache Q(n) at the |
formula also holds for n == 2, and so that we can cache Q(n) at the |
||
n-th position of an array with index origin 0. |
n-th position of an array with index origin 0. |
||
<syntaxhighlight lang="jq"> |
|||
<lang jq> |
|||
# For n>=2, Q(n) = Q(n - Q(n-1)) + Q(n - Q(n-2)) |
# For n>=2, Q(n) = Q(n - Q(n-1)) + Q(n - Q(n-2)) |
||
def Q: |
def Q: |
||
Line 2,248: | Line 2,248: | ||
((range(0;11), 1000) | "Q(\(.)) = \( . | Q)"), |
((range(0;11), 1000) | "Q(\(.)) = \( . | Q)"), |
||
(100000 | "flips(\(.)) = \(flips(.))")</ |
(100000 | "flips(\(.)) = \(flips(.))")</syntaxhighlight> |
||
===Transcript=== |
===Transcript=== |
||
< |
<syntaxhighlight lang="bash"> |
||
$ uname -a |
$ uname -a |
||
Darwin Mac-mini 13.3.0 Darwin Kernel Version 13.3.0: Tue Jun 3 21:27:35 PDT 2014; root:xnu-2422.110.17~1/RELEASE_X86_64 x86_64 |
Darwin Mac-mini 13.3.0 Darwin Kernel Version 13.3.0: Tue Jun 3 21:27:35 PDT 2014; root:xnu-2422.110.17~1/RELEASE_X86_64 x86_64 |
||
Line 2,270: | Line 2,270: | ||
real 0m0.562s |
real 0m0.562s |
||
user 0m0.541s |
user 0m0.541s |
||
sys 0m0.011s</ |
sys 0m0.011s</syntaxhighlight> |
||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
The following implementation accepts an argument that is a single integer, an array of integers, or a range: |
The following implementation accepts an argument that is a single integer, an array of integers, or a range: |
||
< |
<syntaxhighlight lang="julia">function hofstQseq(n, typerst::Type=Int) |
||
nmax = maximum(n) |
nmax = maximum(n) |
||
r = Vector{typerst}(nmax) |
r = Vector{typerst}(nmax) |
||
Line 2,287: | Line 2,287: | ||
println("First ten elements of sequence: ", join(hofstQseq(1:10), ", ")) |
println("First ten elements of sequence: ", join(hofstQseq(1:10), ", ")) |
||
println("1000-th element: ", hofstQseq(1000)) |
println("1000-th element: ", hofstQseq(1000)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 2,294: | Line 2,294: | ||
And we can also count the number of times a value is less than its predecessor by, for example: |
And we can also count the number of times a value is less than its predecessor by, for example: |
||
< |
<syntaxhighlight lang="julia">seq = hofstQseq(1:100_000) |
||
cnt = count(diff(seq) .< 0) |
cnt = count(diff(seq) .< 0) |
||
println("$cnt elements are less than the preceding one.")</ |
println("$cnt elements are less than the preceding one.")</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,304: | Line 2,304: | ||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
< |
<syntaxhighlight lang="scala">// version 1.1.4 |
||
fun main(args: Array<String>) { |
fun main(args: Array<String>) { |
||
Line 2,316: | Line 2,316: | ||
val flips = (2..100_000).count { q[it] < q[it - 1] } |
val flips = (2..100_000).count { q[it] < q[it - 1] } |
||
println("\nThe number of flips for the first 100,000 terms is : $flips") |
println("\nThe number of flips for the first 100,000 terms is : $flips") |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,329: | Line 2,329: | ||
=={{header|MAD}}== |
=={{header|MAD}}== |
||
< |
<syntaxhighlight lang="mad"> NORMAL MODE IS INTEGER |
||
VECTOR VALUES FMT = $2HQ(,I4,3H) =,I4*$ |
VECTOR VALUES FMT = $2HQ(,I4,3H) =,I4*$ |
||
Line 2,342: | Line 2,342: | ||
PRINT FORMAT FMT, 1000, Q(1000) |
PRINT FORMAT FMT, 1000, Q(1000) |
||
END OF PROGRAM</ |
END OF PROGRAM</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,362: | Line 2,362: | ||
=={{header|Maple}}== |
=={{header|Maple}}== |
||
We use automatic memoisation ("option remember") in the following. The use of "option system" assures that memoised values can be garbage collected. |
We use automatic memoisation ("option remember") in the following. The use of "option system" assures that memoised values can be garbage collected. |
||
< |
<syntaxhighlight lang="maple">Q := proc( n ) |
||
option remember, system; |
option remember, system; |
||
if n = 1 or n = 2 then |
if n = 1 or n = 2 then |
||
Line 2,369: | Line 2,369: | ||
thisproc( n - thisproc( n - 1 ) ) + thisproc( n - thisproc( n - 2 ) ) |
thisproc( n - thisproc( n - 1 ) ) + thisproc( n - thisproc( n - 2 ) ) |
||
end if |
end if |
||
end proc:</ |
end proc:</syntaxhighlight> |
||
From this we get: |
From this we get: |
||
< |
<syntaxhighlight lang="maple">> seq( Q( i ), i = 1 .. 10 ); |
||
1, 1, 2, 3, 3, 4, 5, 5, 6, 6 |
1, 1, 2, 3, 3, 4, 5, 5, 6, 6 |
||
> Q( 1000 ); |
> Q( 1000 ); |
||
502</ |
502</syntaxhighlight> |
||
To determine the number of "flips", we proceed as follows. |
To determine the number of "flips", we proceed as follows. |
||
< |
<syntaxhighlight lang="maple">> flips := 0: |
||
> for i from 2 to 100000 do |
> for i from 2 to 100000 do |
||
> if L[ i ] < L[ i - 1 ] then |
> if L[ i ] < L[ i - 1 ] then |
||
Line 2,384: | Line 2,384: | ||
> end do: |
> end do: |
||
> flips; |
> flips; |
||
49798</ |
49798</syntaxhighlight> |
||
Alternatively, we can build the sequence in an array. |
Alternatively, we can build the sequence in an array. |
||
< |
<syntaxhighlight lang="maple">Qflips := proc( n ) |
||
local a := Array( 1 .. n ); |
local a := Array( 1 .. n ); |
||
a[ 1 ] := 1; |
a[ 1 ] := 1; |
||
Line 2,400: | Line 2,400: | ||
end do; |
end do; |
||
flips |
flips |
||
end proc:</ |
end proc:</syntaxhighlight> |
||
This gives the same result. |
This gives the same result. |
||
< |
<syntaxhighlight lang="maple">> Qflips( 10^5 ); |
||
49798</ |
49798</syntaxhighlight> |
||
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
||
< |
<syntaxhighlight lang="mathematica">Hofstadter[1] = Hofstadter[2] = 1; |
||
Hofstadter[n_Integer?Positive] := Hofstadter[n] = Block[{$RecursionLimit = Infinity}, |
Hofstadter[n_Integer?Positive] := Hofstadter[n] = Block[{$RecursionLimit = Infinity}, |
||
Hofstadter[n - Hofstadter[n - 1]] + Hofstadter[n - Hofstadter[n - 2]] |
Hofstadter[n - Hofstadter[n - 1]] + Hofstadter[n - Hofstadter[n - 2]] |
||
]</ |
]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
< |
<syntaxhighlight lang="mathematica">Hofstadter /@ Range[10] |
||
{1,1,2,3,3,4,5,5,6,6} |
{1,1,2,3,3,4,5,5,6,6} |
||
Hofstadter[1000] |
Hofstadter[1000] |
||
502 |
502 |
||
Count[Differences[Hofstadter /@ Range[100000]], _?Negative] |
Count[Differences[Hofstadter /@ Range[100000]], _?Negative] |
||
49798</ |
49798</syntaxhighlight> |
||
=={{header|MATLAB}} / {{header|Octave}}== |
=={{header|MATLAB}} / {{header|Octave}}== |
||
This solution pre-allocates memory and is an iterative solution, so caching or recursion limits do not apply. |
This solution pre-allocates memory and is an iterative solution, so caching or recursion limits do not apply. |
||
< |
<syntaxhighlight lang="matlab">function Q = Qsequence(N) |
||
%% zeros are used to pre-allocate memory, this is not strictly necessary but can significantly improve performance for large N |
%% zeros are used to pre-allocate memory, this is not strictly necessary but can significantly improve performance for large N |
||
Q = [1,1,zeros(1,N-2)]; |
Q = [1,1,zeros(1,N-2)]; |
||
Line 2,426: | Line 2,426: | ||
Q(n) = Q(n-Q(n-1))+Q(n-Q(n-2)); |
Q(n) = Q(n-Q(n-1))+Q(n-Q(n-2)); |
||
end; |
end; |
||
end; </ |
end; </syntaxhighlight> |
||
Confirm and display that the first ten terms of the sequence are: 1, 1, 2, 3, 3, 4, 5, 5, 6, and 6 |
Confirm and display that the first ten terms of the sequence are: 1, 1, 2, 3, 3, 4, 5, 5, 6, and 6 |
||
<pre>>> Qsequence(10) |
<pre>>> Qsequence(10) |
||
Line 2,442: | Line 2,442: | ||
=={{header|Modula-2}}== |
=={{header|Modula-2}}== |
||
< |
<syntaxhighlight lang="modula2">MODULE QSequence; |
||
FROM InOut IMPORT WriteString, WriteCard, WriteLn; |
FROM InOut IMPORT WriteString, WriteCard, WriteLn; |
||
Line 2,464: | Line 2,464: | ||
WriteCard(Q[1000],4); |
WriteCard(Q[1000],4); |
||
WriteLn(); |
WriteLn(); |
||
END QSequence.</ |
END QSequence.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>The first 10 terms are: 1 1 2 3 3 4 5 5 6 6 |
<pre>The first 10 terms are: 1 1 2 3 3 4 5 5 6 6 |
||
Line 2,470: | Line 2,470: | ||
=={{header|MiniScript}}== |
=={{header|MiniScript}}== |
||
< |
<syntaxhighlight lang="miniscript">cache = {1:1, 2:1} |
||
Q = function(n) |
Q = function(n) |
||
Line 2,483: | Line 2,483: | ||
print "Q(" + i + ") = " + Q(i) |
print "Q(" + i + ") = " + Q(i) |
||
end for |
end for |
||
print "Q(1000) = " + Q(1000)</ |
print "Q(1000) = " + Q(1000)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Q(1) = 1 |
<pre>Q(1) = 1 |
||
Line 2,498: | Line 2,498: | ||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
< |
<syntaxhighlight lang="nim">var q = @[1, 1] |
||
for n in 2 ..< 100_000: q.add q[n-q[n-1]] + q[n-q[n-2]] |
for n in 2 ..< 100_000: q.add q[n-q[n-1]] + q[n-q[n-2]] |
||
Line 2,511: | Line 2,511: | ||
if q[n] < q[n-1]: |
if q[n] < q[n-1]: |
||
inc lessCount |
inc lessCount |
||
echo lessCount</ |
echo lessCount</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>@[1, 1, 2, 3, 3, 4, 5, 5, 6, 6] |
<pre>@[1, 1, 2, 3, 3, 4, 5, 5, 6, 6] |
||
Line 2,519: | Line 2,519: | ||
=={{header|Oberon-2}}== |
=={{header|Oberon-2}}== |
||
Works with oo2c version 2 |
Works with oo2c version 2 |
||
< |
<syntaxhighlight lang="oberon2"> |
||
MODULE Hofstadter; |
MODULE Hofstadter; |
||
IMPORT |
IMPORT |
||
Line 2,556: | Line 2,556: | ||
Out.String("terms less than the previous: ");Out.LongInt(count,4);Out.Ln |
Out.String("terms less than the previous: ");Out.LongInt(count,4);Out.Ln |
||
END Hofstadter. |
END Hofstadter. |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 2,575: | Line 2,575: | ||
=={{header|Oforth}}== |
=={{header|Oforth}}== |
||
< |
<syntaxhighlight lang="oforth">: QSeqTask |
||
| q i | |
| q i | |
||
ListBuffer newSize(100000) dup add(1) dup add(1) ->q |
ListBuffer newSize(100000) dup add(1) dup add(1) ->q |
||
Line 2,582: | Line 2,582: | ||
q at(i) q at(i 1-) < ifTrue: [ 1+ ] |
q at(i) q at(i 1-) < ifTrue: [ 1+ ] |
||
] |
] |
||
q left(10) println q at(1000) println println ; </ |
q left(10) println q at(1000) println println ; </syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,593: | Line 2,593: | ||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
Straightforward, unoptimized version; about 1 ms. |
Straightforward, unoptimized version; about 1 ms. |
||
< |
<syntaxhighlight lang="parigp">Q=vector(1000);Q[1]=Q[2]=1;for(n=3,#Q,Q[n]=Q[n-Q[n-1]]+Q[n-Q[n-2]]); |
||
Q1=vecextract(Q,"1..10"); |
Q1=vecextract(Q,"1..10"); |
||
print("First 10 terms: "Q1,if(Q1==[1, 1, 2, 3, 3, 4, 5, 5, 6, 6]," (as expected)"," (in error)")); |
print("First 10 terms: "Q1,if(Q1==[1, 1, 2, 3, 3, 4, 5, 5, 6, 6]," (as expected)"," (in error)")); |
||
print("1000-th term: "Q[1000],if(Q[1000]==502," (as expected)"," (in error)"));</ |
print("1000-th term: "Q[1000],if(Q[1000]==502," (as expected)"," (in error)"));</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,603: | Line 2,603: | ||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
< |
<syntaxhighlight lang="pascal">Program HofstadterQSequence (output); |
||
const |
const |
||
Line 2,626: | Line 2,626: | ||
inc(flips); |
inc(flips); |
||
writeln('Flips: ', flips); |
writeln('Flips: ', flips); |
||
end.</ |
end.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>:> ./HofstadterQSequence |
<pre>:> ./HofstadterQSequence |
||
Line 2,636: | Line 2,636: | ||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
< |
<syntaxhighlight lang="perl">my @Q = (0,1,1); |
||
push @Q, $Q[-$Q[-1]] + $Q[-$Q[-2]] for 1..100_000; |
push @Q, $Q[-$Q[-1]] + $Q[-$Q[-2]] for 1..100_000; |
||
say "First 10 terms: [@Q[1..10]]"; |
say "First 10 terms: [@Q[1..10]]"; |
||
say "Term 1000: $Q[1000]"; |
say "Term 1000: $Q[1000]"; |
||
say "Terms less than preceding in first 100k: ",scalar(grep { $Q[$_] < $Q[$_-1] } 2..100000);</ |
say "Terms less than preceding in first 100k: ",scalar(grep { $Q[$_] < $Q[$_-1] } 2..100000);</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>First 10 terms: [1 1 2 3 3 4 5 5 6 6] |
<pre>First 10 terms: [1 1 2 3 3 4 5 5 6 6] |
||
Line 2,647: | Line 2,647: | ||
A more verbose and less idiomatic solution: |
A more verbose and less idiomatic solution: |
||
< |
<syntaxhighlight lang="perl">#!/usr/bin/perl |
||
use warnings; |
use warnings; |
||
use strict; |
use strict; |
||
Line 2,668: | Line 2,668: | ||
print "Up to and including the 100000'th term, $less_than_preceding terms are less " . |
print "Up to and including the 100000'th term, $less_than_preceding terms are less " . |
||
"than their preceding terms!\n"; |
"than their preceding terms!\n"; |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre>1 |
<pre>1 |
||
Line 2,688: | Line 2,688: | ||
I could have chosen to do recursion instead of iteration, as perl has no limit on how deeply one may recurse, but did not see the benefit of doing so. |
I could have chosen to do recursion instead of iteration, as perl has no limit on how deeply one may recurse, but did not see the benefit of doing so. |
||
< |
<syntaxhighlight lang="perl">#!perl |
||
use strict; |
use strict; |
||
use warnings; |
use warnings; |
||
Line 2,723: | Line 2,723: | ||
} |
} |
||
print "Extra credit: $count\n"; |
print "Extra credit: $count\n"; |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,734: | Line 2,734: | ||
Just to be flash, I also (on the desktop only) calculated the 100 millionth term - the only limiting factor here is the length of Q |
Just to be flash, I also (on the desktop only) calculated the 100 millionth term - the only limiting factor here is the length of Q |
||
(theoretically 402,653,177 on 32 bit). |
(theoretically 402,653,177 on 32 bit). |
||
<!--< |
<!--<syntaxhighlight lang="phix">(phixonline)--> |
||
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
||
<span style="color: #004080;">sequence</span> <span style="color: #000000;">Q</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">}</span> |
<span style="color: #004080;">sequence</span> <span style="color: #000000;">Q</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">}</span> |
||
Line 2,760: | Line 2,760: | ||
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"100,000,000th: %,d (%3.2fs)\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">q</span><span style="color: #0000FF;">(</span><span style="color: #000000;">100_000_000</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">time</span><span style="color: #0000FF;">()-</span><span style="color: #000000;">t0</span><span style="color: #0000FF;">})</span> |
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"100,000,000th: %,d (%3.2fs)\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">q</span><span style="color: #0000FF;">(</span><span style="color: #000000;">100_000_000</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">time</span><span style="color: #0000FF;">()-</span><span style="color: #000000;">t0</span><span style="color: #0000FF;">})</span> |
||
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span> |
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,772: | Line 2,772: | ||
=={{header|Picat}}== |
=={{header|Picat}}== |
||
< |
<syntaxhighlight lang="picat">go => |
||
println([q(I) : I in 1..10]), |
println([q(I) : I in 1..10]), |
||
println(q1000=q(1000)), |
println(q1000=q(1000)), |
||
Line 2,782: | Line 2,782: | ||
q(1) = 1. |
q(1) = 1. |
||
q(2) = 1. |
q(2) = 1. |
||
q(N) = q(N-q(N-1)) + q(N-q(N-2)).</ |
q(N) = q(N-q(N-1)) + q(N-q(N-2)).</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,790: | Line 2,790: | ||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
< |
<syntaxhighlight lang="picolisp">(de q (N) |
||
(cache '(NIL) N |
(cache '(NIL) N |
||
(if (>= 2 N) |
(if (>= 2 N) |
||
Line 2,796: | Line 2,796: | ||
(+ |
(+ |
||
(q (- N (q (dec N)))) |
(q (- N (q (dec N)))) |
||
(q (- N (q (- N 2)))) ) ) ) )</ |
(q (- N (q (- N 2)))) ) ) ) )</syntaxhighlight> |
||
Test: |
Test: |
||
< |
<syntaxhighlight lang="picolisp">: (mapcar q (range 1 10)) |
||
-> (1 1 2 3 3 4 5 5 6 6) |
-> (1 1 2 3 3 4 5 5 6 6) |
||
Line 2,806: | Line 2,806: | ||
: (let L (mapcar q (range 1 100000)) |
: (let L (mapcar q (range 1 100000)) |
||
(cnt < (cdr L) L) ) |
(cnt < (cdr L) L) ) |
||
-> 49798</ |
-> 49798</syntaxhighlight> |
||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
<syntaxhighlight lang="pl/i"> |
|||
<lang PL/I> |
|||
/* Hofstrader Q sequence for any "n". */ |
/* Hofstrader Q sequence for any "n". */ |
||
Line 2,830: | Line 2,830: | ||
end; |
end; |
||
end H; |
end H; |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,862: | Line 2,862: | ||
</pre> |
</pre> |
||
Bonus to produce the count of unordered values: |
Bonus to produce the count of unordered values: |
||
<lang> |
<syntaxhighlight lang="text"> |
||
declare tally fixed binary (31) initial (0); |
declare tally fixed binary (31) initial (0); |
||
Line 2,869: | Line 2,869: | ||
end; |
end; |
||
put skip data (tally); |
put skip data (tally); |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,877: | Line 2,877: | ||
=={{header|PL/M}}== |
=={{header|PL/M}}== |
||
< |
<syntaxhighlight lang="plm">100H: |
||
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS; |
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS; |
||
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT; |
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT; |
||
Line 2,911: | Line 2,911: | ||
CALL PRINT$NUMBER(Q(1000)); |
CALL PRINT$NUMBER(Q(1000)); |
||
CALL EXIT; |
CALL EXIT; |
||
EOF</ |
EOF</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>THE FIRST 10 TERMS ARE: 1 1 2 3 3 4 5 5 6 6 |
<pre>THE FIRST 10 TERMS ARE: 1 1 2 3 3 4 5 5 6 6 |
||
Line 2,917: | Line 2,917: | ||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
< |
<syntaxhighlight lang="purebasic">If Not OpenConsole("Hofstadter Q sequence") |
||
End 1 |
End 1 |
||
EndIf |
EndIf |
||
Line 2,938: | Line 2,938: | ||
PrintN(~"Flips:\t\t" + Str(flip)) |
PrintN(~"Flips:\t\t" + Str(flip)) |
||
Input() |
Input() |
||
End</ |
End</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>First ten: 1 1 2 3 3 4 5 5 6 6 |
<pre>First ten: 1 1 2 3 3 4 5 5 6 6 |
||
Line 2,945: | Line 2,945: | ||
=={{header|Python}}== |
=={{header|Python}}== |
||
< |
<syntaxhighlight lang="python">def q(n): |
||
if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1") |
if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1") |
||
try: |
try: |
||
Line 2,960: | Line 2,960: | ||
print("Q(n) for n = [1..10] is:", ', '.join(str(i) for i in first10)) |
print("Q(n) for n = [1..10] is:", ', '.join(str(i) for i in first10)) |
||
assert q(1000) == 502, "Q(1000) value error" |
assert q(1000) == 502, "Q(1000) value error" |
||
print("Q(1000) =", q(1000))</ |
print("Q(1000) =", q(1000))</syntaxhighlight> |
||
;Extra credit: |
;Extra credit: |
||
Line 2,968: | Line 2,968: | ||
The following code is to be concatenated to the code above: |
The following code is to be concatenated to the code above: |
||
< |
<syntaxhighlight lang="python">from sys import getrecursionlimit |
||
def q1(n): |
def q1(n): |
||
Line 2,986: | Line 2,986: | ||
tmp = q1(100000) |
tmp = q1(100000) |
||
print("Q(i+1) < Q(i) for i [1..100000] is true %i times." % |
print("Q(i+1) < Q(i) for i [1..100000] is true %i times." % |
||
sum(k1 < k0 for k0, k1 in zip(q.seq[1:], q.seq[2:])))</ |
sum(k1 < k0 for k0, k1 in zip(q.seq[1:], q.seq[2:])))</syntaxhighlight> |
||
{{out|Combined output}} |
{{out|Combined output}} |
||
Line 2,994: | Line 2,994: | ||
===Alternative=== |
===Alternative=== |
||
< |
<syntaxhighlight lang="python">def q(n): |
||
l = len(q.seq) |
l = len(q.seq) |
||
while l <= n: |
while l <= n: |
||
Line 3,006: | Line 3,006: | ||
q(100000) |
q(100000) |
||
print("Q(i+1) < Q(i) for i [1..100000] is true %i times." % |
print("Q(i+1) < Q(i) for i [1..100000] is true %i times." % |
||
sum([q.seq[i] > q.seq[i + 1] for i in range(1, 100000)]))</ |
sum([q.seq[i] > q.seq[i + 1] for i in range(1, 100000)]))</syntaxhighlight> |
||
=={{header|Quackery}}== |
=={{header|Quackery}}== |
||
< |
<syntaxhighlight lang="quackery">[ 2dup swap size dup negate swap within |
||
not if |
not if |
||
[ drop size 1+ number$ |
[ drop size 1+ number$ |
||
Line 3,041: | Line 3,041: | ||
say " decreasing terms" ] |
say " decreasing terms" ] |
||
bailed if |
bailed if |
||
[ message take cr echo$ cr ]</ |
[ message take cr echo$ cr ]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,049: | Line 3,049: | ||
=={{header|R}}== |
=={{header|R}}== |
||
< |
<syntaxhighlight lang="rsplus"> |
||
cache <- vector("integer", 0) |
cache <- vector("integer", 0) |
||
cache[1] <- 1 |
cache[1] <- 1 |
||
Line 3,077: | Line 3,077: | ||
} |
} |
||
cat(count,"terms is less than its preceding term\n") |
cat(count,"terms is less than its preceding term\n") |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,086: | Line 3,086: | ||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
< |
<syntaxhighlight lang="racket"> |
||
#lang racket |
#lang racket |
||
Line 3,103: | Line 3,103: | ||
;; extra credit |
;; extra credit |
||
(for/sum ([i 100000]) (if (< (Q (add1 i)) (Q i)) 1 0)) |
(for/sum ([i 100000]) (if (< (Q (add1 i)) (Q i)) 1 0)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 3,119: | Line 3,119: | ||
Similar concept as the perl5 solution, except that the cache is only filled on demand. |
Similar concept as the perl5 solution, except that the cache is only filled on demand. |
||
<lang |
<syntaxhighlight lang="raku" line>class Hofstadter { |
||
has @!c = 1,1; |
has @!c = 1,1; |
||
method AT-POS ($me: Int $i) { |
method AT-POS ($me: Int $i) { |
||
Line 3,137: | Line 3,137: | ||
my $count = 0; |
my $count = 0; |
||
$count++ if $Q[$_ +1 ] < $Q[$_] for ^99_999; |
$count++ if $Q[$_ +1 ] < $Q[$_] for ^99_999; |
||
say "In the first 100_000 terms, $count terms are less than their preceding terms";</ |
say "In the first 100_000 terms, $count terms are less than their preceding terms";</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>first ten: 1 1 2 3 3 4 5 5 6 6 |
<pre>first ten: 1 1 2 3 3 4 5 5 6 6 |
||
Line 3,146: | Line 3,146: | ||
{{Works with|rakudo|2015-11-22}} |
{{Works with|rakudo|2015-11-22}} |
||
With a lazily generated array, we automatically get caching. |
With a lazily generated array, we automatically get caching. |
||
<lang |
<syntaxhighlight lang="raku" line>my @Q = 1, 1, -> $a, $b { |
||
(state $n = 1)++; |
(state $n = 1)++; |
||
@Q[$n - $a] + @Q[$n - $b] |
@Q[$n - $a] + @Q[$n - $b] |
||
Line 3,157: | Line 3,157: | ||
say "In the first 100_000 terms, ", |
say "In the first 100_000 terms, ", |
||
[+](@Q[1..100000] Z< @Q[0..99999]), |
[+](@Q[1..100000] Z< @Q[0..99999]), |
||
" terms are less than their preceding terms";</ |
" terms are less than their preceding terms";</syntaxhighlight> |
||
(Same output.) |
(Same output.) |
||
Line 3,163: | Line 3,163: | ||
===non-recursive=== |
===non-recursive=== |
||
The REXX language doesn't allow expressions for stemmed array indices, so a temporary variable must be used. |
The REXX language doesn't allow expressions for stemmed array indices, so a temporary variable must be used. |
||
< |
<syntaxhighlight lang="rexx">/*REXX program generates the Hofstadter Q sequence for any specified N. */ |
||
parse arg a b c d . /*obtain optional arguments from the CL*/ |
parse arg a b c d . /*obtain optional arguments from the CL*/ |
||
if a=='' | a=="," then a= 10 /*Not specified? Then use the default.*/ |
if a=='' | a=="," then a= 10 /*Not specified? Then use the default.*/ |
||
Line 3,196: | Line 3,196: | ||
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
||
commas: parse arg _; do ?=length(_)-3 to 1 by -3; _=insert(',', _, ?); end; return _ |
commas: parse arg _; do ?=length(_)-3 to 1 by -3; _=insert(',', _, ?); end; return _ |
||
th: procedure; #=abs(arg(1)); return word('th st nd rd',1+#//10*(#//100%10\==1)*(#//10<4))</ |
th: procedure; #=abs(arg(1)); return word('th st nd rd',1+#//10*(#//100%10\==1)*(#//10<4))</syntaxhighlight> |
||
{{out|output|text= when using the internal default inputs:}} |
{{out|output|text= when using the internal default inputs:}} |
||
<pre> |
<pre> |
||
Line 3,220: | Line 3,220: | ||
This REXX example is identical to the first version |
This REXX example is identical to the first version |
||
except that it uses a function to retrieve array elements which may have index expressions. |
except that it uses a function to retrieve array elements which may have index expressions. |
||
< |
<syntaxhighlight lang="rexx">/*REXX program generates the Hofstadter Q sequence for any specified N. */ |
||
parse arg a b c d . /*obtain optional arguments from the CL*/ |
parse arg a b c d . /*obtain optional arguments from the CL*/ |
||
if a=='' | a=="," then a= 10 /*Not specified? Then use the default.*/ |
if a=='' | a=="," then a= 10 /*Not specified? Then use the default.*/ |
||
Line 3,251: | Line 3,251: | ||
@: parse arg ?; return @.? /*return value of @.? to invoker.*/ |
@: parse arg ?; return @.? /*return value of @.? to invoker.*/ |
||
th: procedure; #=abs(arg(1)); return word('th st nd rd',1+#//10*(#//100%10\==1)*(#//10<4)) |
th: procedure; #=abs(arg(1)); return word('th st nd rd',1+#//10*(#//100%10\==1)*(#//10<4)) |
||
commas: parse arg _; do ?=length(_)-3 to 1 by -3; _=insert(',', _, ?); end; return _</ |
commas: parse arg _; do ?=length(_)-3 to 1 by -3; _=insert(',', _, ?); end; return _</syntaxhighlight> |
||
{{out|output|text= is identical to the 1<sup>st</sup> REXX version.}} |
{{out|output|text= is identical to the 1<sup>st</sup> REXX version.}} |
||
Line 3,257: | Line 3,257: | ||
===recursive=== |
===recursive=== |
||
< |
<syntaxhighlight lang="rexx">/*REXX program generates the Hofstadter Q sequence for any specified N. */ |
||
parse arg a b c d . /*obtain optional arguments from the CL*/ |
parse arg a b c d . /*obtain optional arguments from the CL*/ |
||
if a=='' | a=="," then a= 10 /*Not specified? Then use the default.*/ |
if a=='' | a=="," then a= 10 /*Not specified? Then use the default.*/ |
||
Line 3,291: | Line 3,291: | ||
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
||
th: procedure; #=abs(arg(1)); return word('th st nd rd',1+#//10*(#//100%10\==1)*(#//10<4)) |
th: procedure; #=abs(arg(1)); return word('th st nd rd',1+#//10*(#//100%10\==1)*(#//10<4)) |
||
commas: parse arg _; do ?=length(_)-3 to 1 by -3; _=insert(',', _, ?); end; return _</ |
commas: parse arg _; do ?=length(_)-3 to 1 by -3; _=insert(',', _, ?); end; return _</syntaxhighlight> |
||
{{out|output|text= is identical to the 1<sup>st</sup> REXX version.}} |
{{out|output|text= is identical to the 1<sup>st</sup> REXX version.}} |
||
Line 3,297: | Line 3,297: | ||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang="ring"> |
||
n = 20 |
n = 20 |
||
aList = list(n) |
aList = list(n) |
||
Line 3,306: | Line 3,306: | ||
if i <= 20 see "n = " + string(i) + " : "+ aList[i] + nl ok |
if i <= 20 see "n = " + string(i) + " : "+ aList[i] + nl ok |
||
next |
next |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
< |
<syntaxhighlight lang="ruby">@cache = [] |
||
def Q(n) |
def Q(n) |
||
if @cache[n].nil? |
if @cache[n].nil? |
||
Line 3,330: | Line 3,330: | ||
prev = q |
prev = q |
||
end |
end |
||
puts "number of times in the first 100,000 terms where Q(i)<Q(i-1): #{count}"</ |
puts "number of times in the first 100,000 terms where Q(i)<Q(i-1): #{count}"</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>first 10 numbers in the sequence: [1, 1, 2, 3, 3, 4, 5, 5, 6, 6] |
<pre>first 10 numbers in the sequence: [1, 1, 2, 3, 3, 4, 5, 5, 6, 6] |
||
Line 3,337: | Line 3,337: | ||
=={{header|Run BASIC}}== |
=={{header|Run BASIC}}== |
||
< |
<syntaxhighlight lang="runbasic">input "How many values do you want? :";n |
||
dim Q(n) |
dim Q(n) |
||
Q(1) = 1 |
Q(1) = 1 |
||
Line 3,347: | Line 3,347: | ||
if i > 20 then print "n=";using("####",i);using("####",Q(i)) |
if i > 20 then print "n=";using("####",i);using("####",Q(i)) |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,378: | Line 3,378: | ||
Rust doesn't allow static Vec's (but there's lazy_static crate), thus memoization storage is allocated in <code>main</code>. |
Rust doesn't allow static Vec's (but there's lazy_static crate), thus memoization storage is allocated in <code>main</code>. |
||
< |
<syntaxhighlight lang="rust">fn hofq(q: &mut Vec<u32>, x : u32) -> u32 { |
||
let cur_len=q.len()-1; |
let cur_len=q.len()-1; |
||
let i=x as usize; |
let i=x as usize; |
||
Line 3,404: | Line 3,404: | ||
println!("Term is less than preceding term {} times", nless); |
println!("Term is less than preceding term {} times", nless); |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,426: | Line 3,426: | ||
Naive but elegant version using only recursion doesn't work |
Naive but elegant version using only recursion doesn't work |
||
because runtime is excessive increasing ... |
because runtime is excessive increasing ... |
||
< |
<syntaxhighlight lang="scala">object HofstadterQseq extends App { |
||
val Q: Int => Int = n => { |
val Q: Int => Int = n => { |
||
if (n <= 2) 1 |
if (n <= 2) 1 |
||
Line 3,433: | Line 3,433: | ||
(1 to 10).map(i=>(i,Q(i))).foreach(t=>println("Q("+t._1+") = "+t._2)) |
(1 to 10).map(i=>(i,Q(i))).foreach(t=>println("Q("+t._1+") = "+t._2)) |
||
println("Q("+1000+") = "+Q(1000)) |
println("Q("+1000+") = "+Q(1000)) |
||
}</ |
}</syntaxhighlight> |
||
Line 3,440: | Line 3,440: | ||
Thus we are forced to use a caching featured version. |
Thus we are forced to use a caching featured version. |
||
< |
<syntaxhighlight lang="scala">object HofstadterQseq extends App { |
||
val HofQ = scala.collection.mutable.Map((1->1),(2->1)) |
val HofQ = scala.collection.mutable.Map((1->1),(2->1)) |
||
Line 3,458: | Line 3,458: | ||
println("Q("+1000+") = "+Q(1000)) |
println("Q("+1000+") = "+Q(1000)) |
||
println((3 to 100000).filter(i=>Q(i)<Q(i-1)).size) |
println((3 to 100000).filter(i=>Q(i)<Q(i-1)).size) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Q(1) = 1 |
<pre>Q(1) = 1 |
||
Line 3,477: | Line 3,477: | ||
or to resize arrays, or to do formated output--anything to make the code |
or to resize arrays, or to do formated output--anything to make the code |
||
less silly looking while still run under more than one interpreter. |
less silly looking while still run under more than one interpreter. |
||
< |
<syntaxhighlight lang="lisp">(define qc '#(0 1 1)) |
||
(define filled 3) |
(define filled 3) |
||
(define len 3) |
(define len 3) |
||
Line 3,523: | Line 3,523: | ||
(if (>= i 100000) s |
(if (>= i 100000) s |
||
(loop (+ s (if (> (q i) (q (+ 1 i))) 1 0)) (+ 1 i))))) |
(loop (+ s (if (> (q i) (q (+ 1 i))) 1 0)) (+ 1 i))))) |
||
(newline)</ |
(newline)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Q(1 .. 10): 1 1 2 3 3 4 5 5 6 6 |
<pre>Q(1 .. 10): 1 1 2 3 3 4 5 5 6 6 |
||
Line 3,530: | Line 3,530: | ||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
< |
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i"; |
||
const type: intHash is hash [integer] integer; |
const type: intHash is hash [integer] integer; |
||
Line 3,567: | Line 3,567: | ||
end for; |
end for; |
||
writeln("q(n) < q(n-1) for n = 2 .. 100000: " <& less_than_preceding); |
writeln("q(n) < q(n-1) for n = 2 .. 100000: " <& less_than_preceding); |
||
end func;</ |
end func;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,579: | Line 3,579: | ||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
Using a memoized function: |
Using a memoized function: |
||
< |
<syntaxhighlight lang="ruby">func Q(n) is cached { |
||
n <= 2 ? 1 |
n <= 2 ? 1 |
||
: Q(n - Q(n-1))+Q(n-Q(n-2)) |
: Q(n - Q(n-1))+Q(n-Q(n-2)) |
||
Line 3,586: | Line 3,586: | ||
say "First 10 terms: #{ {|n| Q(n) }.map(1..10) }" |
say "First 10 terms: #{ {|n| Q(n) }.map(1..10) }" |
||
say "Term 1000: #{Q(1000)}" |
say "Term 1000: #{Q(1000)}" |
||
say "Terms less than preceding in first 100k: #{2..100000->count{|i|Q(i)<Q(i-1)}}"</ |
say "Terms less than preceding in first 100k: #{2..100000->count{|i|Q(i)<Q(i-1)}}"</syntaxhighlight> |
||
Using an array: |
Using an array: |
||
< |
<syntaxhighlight lang="ruby">var Q = [0, 1, 1] |
||
100_000.times { |
100_000.times { |
||
Q << (Q[-Q[-1]] + Q[-Q[-2]]) |
Q << (Q[-Q[-1]] + Q[-Q[-2]]) |
||
Line 3,596: | Line 3,596: | ||
say "First 10 terms: #{Q.ft(1, 10)}" |
say "First 10 terms: #{Q.ft(1, 10)}" |
||
say "Term 1000: #{Q[1000]}" |
say "Term 1000: #{Q[1000]}" |
||
say "Terms less than preceding in first 100k: #{2..100000->count{|i|Q[i]<Q[i-1]}}"</ |
say "Terms less than preceding in first 100k: #{2..100000->count{|i|Q[i]<Q[i-1]}}"</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,606: | Line 3,606: | ||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
{{trans|C}} |
{{trans|C}} |
||
< |
<syntaxhighlight lang="swift">let n = 100000 |
||
var q = Array(repeating: 0, count: n) |
var q = Array(repeating: 0, count: n) |
||
Line 3,625: | Line 3,625: | ||
} |
} |
||
} |
} |
||
print("Number of times a member of the sequence is less than the preceding term for terms up to and including the 100,000th term: \(count)")</ |
print("Number of times a member of the sequence is less than the preceding term for terms up to and including the 100,000th term: \(count)")</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,635: | Line 3,635: | ||
=={{header|Tailspin}}== |
=={{header|Tailspin}}== |
||
< |
<syntaxhighlight lang="tailspin"> |
||
templates q |
templates q |
||
def outputFrom: $(1); |
def outputFrom: $(1); |
||
Line 3,664: | Line 3,664: | ||
[[1, 100000] -> q] -> countDownSteps -> 'Less than previous $; times' -> !OUT::write |
[[1, 100000] -> q] -> countDownSteps -> 'Less than previous $; times' -> !OUT::write |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,673: | Line 3,673: | ||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
< |
<syntaxhighlight lang="tcl">package require Tcl 8.5 |
||
# Index 0 is not used, but putting it in makes the code a bit shorter |
# Index 0 is not used, but putting it in makes the code a bit shorter |
||
Line 3,696: | Line 3,696: | ||
incr count [expr {$q > [set q [expr {Q($i)}]]}] |
incr count [expr {$q > [set q [expr {Q($i)}]]}] |
||
} |
} |
||
puts "Q(i)<Q(i-1) for i \[2..100000\] is true $count times"</ |
puts "Q(i)<Q(i-1) for i \[2..100000\] is true $count times"</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,716: | Line 3,716: | ||
{{trans|BBC BASIC}} |
{{trans|BBC BASIC}} |
||
uBasic/4tH simply lacks the memory to make it through to the 1000th term. 256 is the best it can do. |
uBasic/4tH simply lacks the memory to make it through to the 1000th term. 256 is the best it can do. |
||
<lang>Print "First 10 terms of Q = " ; |
<syntaxhighlight lang="text">Print "First 10 terms of Q = " ; |
||
For i = 1 To 10 : Print FUNC(_q(i));" "; : Next : Print |
For i = 1 To 10 : Print FUNC(_q(i));" "; : Next : Print |
||
Print "256th term = ";FUNC(_q(256)) |
Print "256th term = ";FUNC(_q(256)) |
||
Line 3,736: | Line 3,736: | ||
Next |
Next |
||
Return (@(a@-1))</ |
Return (@(a@-1))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>First 10 terms of Q = 1 1 2 3 3 4 5 5 6 6 |
<pre>First 10 terms of Q = 1 1 2 3 3 4 5 5 6 6 |
||
Line 3,744: | Line 3,744: | ||
=={{header|VBA}}== |
=={{header|VBA}}== |
||
< |
<syntaxhighlight lang="vb">Public Q(100000) As Long |
||
Public Sub HofstadterQ() |
Public Sub HofstadterQ() |
||
Dim n As Long, smaller As Long |
Dim n As Long, smaller As Long |
||
Line 3,760: | Line 3,760: | ||
Debug.Print "The 1000th term is:"; Q(1000) |
Debug.Print "The 1000th term is:"; Q(1000) |
||
Debug.Print "Number of times smaller:"; smaller |
Debug.Print "Number of times smaller:"; smaller |
||
End Sub</ |
End Sub</syntaxhighlight>{{out}} |
||
<pre>First ten terms: |
<pre>First ten terms: |
||
1 1 2 3 3 4 5 5 6 6 |
1 1 2 3 3 4 5 5 6 6 |
||
Line 3,767: | Line 3,767: | ||
=={{header|VBScript}}== |
=={{header|VBScript}}== |
||
<syntaxhighlight lang="vb"> |
|||
<lang vb> |
|||
Sub q_sequence(n) |
Sub q_sequence(n) |
||
Dim Q() |
Dim Q() |
||
Line 3,795: | Line 3,795: | ||
q_sequence(100000) |
q_sequence(100000) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
Line 3,805: | Line 3,805: | ||
=={{header|Visual FoxPro}}== |
=={{header|Visual FoxPro}}== |
||
< |
<syntaxhighlight lang="vfp"> |
||
LOCAL p As Integer, i As Integer |
LOCAL p As Integer, i As Integer |
||
CLEAR |
CLEAR |
||
Line 3,834: | Line 3,834: | ||
RETURN aq[n] |
RETURN aq[n] |
||
ENDFUNC |
ENDFUNC |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,845: | Line 3,845: | ||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
< |
<syntaxhighlight lang="ecmascript">var N = 1e5 |
||
var q = List.filled(N + 1, 0) |
var q = List.filled(N + 1, 0) |
||
q[1] = 1 |
q[1] = 1 |
||
Line 3,858: | Line 3,858: | ||
if (q[n] < q[n-1]) flips = flips + 1 |
if (q[n] < q[n-1]) flips = flips + 1 |
||
} |
} |
||
System.print("\nThere are %(flips) flips in the first %(N) terms.")</ |
System.print("\nThere are %(flips) flips in the first %(N) terms.")</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,871: | Line 3,871: | ||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
< |
<syntaxhighlight lang="xpl0">code ChOut=8, CrLf=9, IntOut=11; |
||
int N, C, Q(100_001); |
int N, C, Q(100_001); |
||
[Q(1):= 1; Q(2):= 1; C:= 0; |
[Q(1):= 1; Q(2):= 1; C:= 0; |
||
Line 3,883: | Line 3,883: | ||
IntOut(0, Q(1000)); CrLf(0); |
IntOut(0, Q(1000)); CrLf(0); |
||
IntOut(0, C); CrLf(0); |
IntOut(0, C); CrLf(0); |
||
]</ |
]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,894: | Line 3,894: | ||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
{{trans|ALGOL 68}} |
{{trans|ALGOL 68}} |
||
< |
<syntaxhighlight lang="zkl">const n = 0d100_000; |
||
q:=(n+1).pump(List.createLong(n+1).write); // (0,1,2,...,n) base 1 |
q:=(n+1).pump(List.createLong(n+1).write); // (0,1,2,...,n) base 1 |
||
q[1] = q[2] = 1; |
q[1] = q[2] = 1; |
||
Line 3,905: | Line 3,905: | ||
flip := 0; |
flip := 0; |
||
foreach i in (n){ flip += (q[i] > q[i + 1]) } |
foreach i in (n){ flip += (q[i] > q[i + 1]) } |
||
println("flips: ",flip);</ |
println("flips: ",flip);</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,916: | Line 3,916: | ||
{{trans|BBC_BASIC}} |
{{trans|BBC_BASIC}} |
||
Extra credit 100000 is not implemented because of memory limitations. |
Extra credit 100000 is not implemented because of memory limitations. |
||
< |
<syntaxhighlight lang="zxbasic">10 PRINT "First 10 terms of Q = " |
||
20 FOR i=1 TO 10: GO SUB 1000: PRINT s;" ";: NEXT i: PRINT |
20 FOR i=1 TO 10: GO SUB 1000: PRINT s;" ";: NEXT i: PRINT |
||
30 LET i=1000 |
30 LET i=1000 |
||
Line 3,933: | Line 3,933: | ||
1090 NEXT j |
1090 NEXT j |
||
1100 LET s=q(i) |
1100 LET s=q(i) |
||
1110 RETURN</ |
1110 RETURN</syntaxhighlight> |