How to resolve the algorithm Hofstadter Q sequence step by step in the Raku programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Hofstadter Q sequence step by step in the Raku programming language
Table of Contents
Problem Statement
It is defined like the Fibonacci sequence, but whereas the next term in the Fibonacci sequence is the sum of the previous two terms, in the Q sequence the previous two terms tell you how far to go back in the Q sequence to find the two numbers to sum to make the next term of the sequence.
(This point is to ensure that caching and/or recursion limits, if it is a concern, is correctly handled).
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Hofstadter Q sequence step by step in the Raku programming language
Source code in the raku programming language
class Hofstadter {
has @!c = 1,1;
method AT-POS ($me: Int $i) {
@!c.push($me[@!c.elems-$me[@!c.elems-1]] +
$me[@!c.elems-$me[@!c.elems-2]]) until @!c[$i]:exists;
return @!c[$i];
}
}
# Testing:
my Hofstadter $Q .= new();
say "first ten: $Q[^10]";
say "1000th: $Q[999]";
my $count = 0;
$count++ if $Q[$_ +1 ] < $Q[$_] for ^99_999;
say "In the first 100_000 terms, $count terms are less than their preceding terms";
my @Q = 1, 1, -> $a, $b {
(state $n = 1)++;
@Q[$n - $a] + @Q[$n - $b]
} ... *;
# Testing:
say "first ten: ", @Q[^10];
say "1000th: ", @Q[999];
say "In the first 100_000 terms, ",
[+](@Q[1..100000] Z< @Q[0..99999]),
" terms are less than their preceding terms";
You may also check:How to resolve the algorithm Knuth shuffle step by step in the Scheme programming language
You may also check:How to resolve the algorithm Loops/Nested step by step in the Kotlin programming language
You may also check:How to resolve the algorithm De Bruijn sequences step by step in the Python programming language
You may also check:How to resolve the algorithm Polymorphism step by step in the Objective-C programming language
You may also check:How to resolve the algorithm GUI component interaction step by step in the Kotlin programming language